]> gerrit.simantics Code Review - simantics/3d.git/blob - org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/PipingRules.java
Use path leg end point check for offset legs
[simantics/3d.git] / org.simantics.plant3d / src / org / simantics / plant3d / scenegraph / controlpoint / PipingRules.java
1 package org.simantics.plant3d.scenegraph.controlpoint;
2
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import java.util.HashMap;
6 import java.util.List;
7 import java.util.Map;
8
9 import javax.vecmath.Point3d;
10 import javax.vecmath.Quat4d;
11 import javax.vecmath.Vector3d;
12
13 import org.simantics.g3d.math.MathTools;
14 import org.simantics.plant3d.scenegraph.InlineComponent;
15 import org.simantics.plant3d.scenegraph.Nozzle;
16 import org.simantics.plant3d.scenegraph.P3DRootNode;
17 import org.simantics.plant3d.scenegraph.PipeRun;
18 import org.simantics.plant3d.scenegraph.PipelineComponent;
19 import org.simantics.plant3d.scenegraph.TurnComponent;
20 import org.simantics.plant3d.scenegraph.controlpoint.PipeControlPoint.Direction;
21 import org.simantics.plant3d.utils.ComponentUtils;
22 import org.simantics.utils.ui.ErrorLogger;
23
24 public class PipingRules {
25         private static final boolean DEBUG = false;
26         private static final boolean DUMMY = false;
27
28         private static double MIN_TURN_ANGLE = 0.001; // Threshold for removing turn components.
29         private static double ALLOWED_OFFSET = 0.001; // Allowed offset for directed path legs
30
31         private static final int REMOVE_NONE = 0;
32         private static final int REMOVE_START = 1;
33         private static final int REMOVE_END = 2;
34         private static final int REMOVE_BOTH = 3;
35         
36
37         private enum PathLegUpdateType {
38                 NONE, PREV, NEXT, PREV_S, NEXT_S
39         };
40         
41         private static boolean enabled = true;
42         private static boolean updating = false;
43         private static boolean allowInsertRemove = true;
44         private static boolean triedIR = false;
45
46         
47         private static List<PipeControlPoint> updates = new ArrayList<PipeControlPoint>();
48         
49         private static Object mutex = new Object();
50         
51         public static void requestUpdate(PipeControlPoint pcp) {
52                 if (DEBUG) System.out.println("PipingRules request " + pcp);
53                 synchronized (mutex) {
54                 if (!updates.contains(pcp))
55                         updates.add(pcp);
56                 }
57         }
58         
59         public static synchronized boolean update() throws Exception {
60                 if (updates.size() == 0)
61                         return false;
62                 List<PipeControlPoint> temp = new ArrayList<PipeControlPoint>(updates.size());
63                 synchronized(mutex) {
64                         temp.addAll(updates);
65                         updates.clear();
66                 }
67                 
68                 for (PipeControlPoint pcp : temp)
69                         positionUpdate(pcp);
70                 return true;
71         }
72         
73         public static boolean positionUpdate(PipeControlPoint pcp) throws Exception {
74                 
75                 return positionUpdate(pcp, true);
76         }
77         
78         public static boolean positionUpdate(PipeControlPoint pcp, boolean allowIR) throws Exception {
79                 if (updating || !enabled)
80                         return true;
81                 if (pcp.getPipeRun() == null)
82                         return false;
83                 try {
84                         if (DEBUG) System.out.println("PipingRules " + pcp);
85                         updating = true;
86                         allowInsertRemove = allowIR;
87                         triedIR = false;
88                         validate(pcp.getPipeRun());
89                         if (pcp.isPathLegEnd()) {
90                                 updatePathLegEndControlPoint(pcp); // FIXME: Rules won't work properly, if they are not run twice.
91                                 updatePathLegEndControlPoint(pcp);
92                         } else {
93                                 updateInlineControlPoint(pcp);
94                                 updateInlineControlPoint(pcp);
95                         }
96                         validate(pcp.getPipeRun());
97                         if (!allowInsertRemove)
98                                 return !triedIR;
99                         return true;
100                 } finally {
101                         updating = false;
102 //                      System.out.println("PipingRules done " + pcp);
103                 }
104         }
105         
106         public static void setEnabled(boolean enabled) {
107                 PipingRules.enabled = enabled;
108                 if(!enabled)
109                         updates.clear();
110         }
111         
112         public static boolean isEnabled() {
113                 return enabled;
114         }
115         
116 //      private void commit() {
117 //              root.getNodeMap().commit();
118 //      }
119
120         public static class ExpandIterInfo {
121                 // these two are turn control points
122                 private PipeControlPoint start;
123                 private PipeControlPoint end;
124                 private int type;
125
126                 public ExpandIterInfo() {
127
128                 }
129
130                 public ExpandIterInfo(PipeControlPoint tcp, int type) {
131                         if (type == REMOVE_START)
132                                 start = tcp;
133                         else
134                                 end = tcp;
135                         this.type = type;
136                 }
137
138                 public ExpandIterInfo(PipeControlPoint start, PipeControlPoint end) {
139                         this.start = start;
140                         this.end = end;
141                         this.type = REMOVE_BOTH;
142                 }
143
144                 public PipeControlPoint getEnd() {
145                         return end;
146                 }
147
148                 public void setEnd(PipeControlPoint end) {
149                         this.end = end;
150                 }
151
152                 public PipeControlPoint getStart() {
153                         return start;
154                 }
155
156                 public void setStart(PipeControlPoint start) {
157                         this.start = start;
158                 }
159
160                 public int getType() {
161                         return type;
162                 }
163
164                 public void setType(int type) {
165                         this.type = type;
166                 }
167
168         }
169
170         private static void updatePathLegEndControlPoint(PipeControlPoint pcp) throws Exception {
171                 if (DEBUG)
172                         System.out.println("PipingRules.updatePathLegEndControlPoint() " + pcp);
173                 if (pcp.getNext() != null) {
174                         updatePathLegNext(pcp, pcp, PathLegUpdateType.NEXT_S);
175                 }
176                 if (pcp.getPrevious() != null) {
177                         updatePathLegPrev(pcp, pcp, PathLegUpdateType.PREV_S);
178                 }
179
180         }
181
182         private static void updateInlineControlPoint(PipeControlPoint pcp) throws Exception {
183                 if (DEBUG)
184                         System.out.println("PipingRules.updateInlineControlPoint() " + pcp);
185                 PipeControlPoint start = pcp.findPreviousEnd();
186                 updatePathLegNext(start, pcp, PathLegUpdateType.NONE);
187         }
188
189         private static PipeControlPoint insertElbow(PipeControlPoint pcp1, PipeControlPoint pcp2, Vector3d pos) throws Exception{
190                 if (DEBUG)
191                         System.out.println("PipingRules.insertElbow() " + pcp1 + " " + pcp2 + " " + pos);
192                 if (pcp1.getNext() == pcp2 && pcp2.getPrevious() == pcp1) {
193                         
194                 } else if (pcp1.getNext() == pcp2 && pcp1.isDualInline() && pcp2.getPrevious() == pcp1.getSubPoint().get(0)) {
195                         pcp1 = pcp1.getSubPoint().get(0);       
196                 } else if (pcp1.getPrevious() == pcp2 && pcp2.getNext() == pcp1) {
197                         PipeControlPoint t = pcp1;
198                         pcp1 = pcp2;
199                         pcp2 = t;
200                 } else if (pcp2.isDualInline() && pcp1.getPrevious() == pcp2.getSubPoint().get(0) && pcp2.getNext() == pcp1) {
201                         PipeControlPoint t = pcp1;
202                         pcp1 = pcp2.getSubPoint().get(0);
203                         pcp2 = t;
204                 } else {
205                         throw new RuntimeException();
206                 }
207                 TurnComponent elbow = ComponentUtils.createTurn((P3DRootNode)pcp1.getRootNode());
208                 PipeControlPoint pcp = elbow.getControlPoint();
209                 if (pcp1.isDualInline())
210                         pcp1 = pcp1.getSubPoint().get(0);
211                 String name = pcp1.getPipeRun().getUniqueName("Elbow");
212                 elbow.setName(name);
213                 pcp1.getPipeRun().addChild(elbow);
214
215                 pcp.insert(pcp1, pcp2);
216
217                 pcp.setWorldPosition(pos);
218                 validate(pcp.getPipeRun());
219                 return pcp;
220         }
221         
222         private static PipeControlPoint insertStraight(PipeControlPoint pcp1, PipeControlPoint pcp2, Vector3d pos, double length) throws Exception {
223                 if (DEBUG)
224                         System.out.println("PipingRules.insertStraight() " + pcp1 + " " + pcp2 + " " + pos);
225                 if (pcp1.getNext() == pcp2 && pcp2.getPrevious() == pcp1) {
226                         
227                 } else if (pcp1.getNext() == pcp2 && pcp1.isDualInline() && pcp2.getPrevious() == pcp1.getSubPoint().get(0)) {
228                         pcp1 = pcp1.getSubPoint().get(0);       
229                 } else if (pcp1.getPrevious() == pcp2 && pcp2.getNext() == pcp1) {
230                         PipeControlPoint t = pcp1;
231                         pcp1 = pcp2;
232                         pcp2 = t;
233                 } else if (pcp2.isDualInline() && pcp1.getPrevious() == pcp2.getSubPoint().get(0) && pcp2.getNext() == pcp1) {
234                         PipeControlPoint t = pcp1;
235                         pcp1 = pcp2.getSubPoint().get(0);
236                         pcp2 = t;
237                 } else {
238                         throw new RuntimeException();
239                 }
240                 InlineComponent component = ComponentUtils.createStraight((P3DRootNode)pcp1.getRootNode());
241                 PipeControlPoint scp = component.getControlPoint();
242                 if (pcp1.isDualInline())
243                         pcp1 = pcp1.getSubPoint().get(0);
244                 String name = pcp1.getPipeRun().getUniqueName("Pipe");
245                 component.setName(name);
246                 pcp1.getPipeRun().addChild(component);
247                 
248                 scp.insert(pcp1, pcp2);
249
250                 scp.setWorldPosition(pos);
251                 scp.setLength(length);
252                 validate(scp.getPipeRun());
253                 return scp;
254         }
255         
256         private static PipeControlPoint insertStraight(PipeControlPoint pcp, Direction direction , Vector3d pos, double length) throws Exception {
257                 if (DEBUG)
258                         System.out.println("PipingRules.insertStraight() " + pcp + " " + direction + " " + pos);
259                 
260                 InlineComponent component = ComponentUtils.createStraight((P3DRootNode)pcp.getRootNode());
261                 PipeControlPoint scp = component.getControlPoint();
262                 if (pcp.isDualInline() && direction == Direction.NEXT)
263                         pcp = pcp.getSubPoint().get(0);
264                 String name = pcp.getPipeRun().getUniqueName("Pipe");
265                 component.setName(name);
266                 pcp.getPipeRun().addChild(component);
267                 
268                 scp.insert(pcp,direction);
269
270                 scp.setWorldPosition(pos);
271                 scp.setLength(length);
272                 validate(scp.getPipeRun());
273                 return scp;
274         }
275
276         private static void updatePathLegNext(PipeControlPoint start, PipeControlPoint updated, PathLegUpdateType lengthChange) throws Exception {
277                 ArrayList<PipeControlPoint> list = new ArrayList<PipeControlPoint>();
278                 PipeControlPoint end = start.findNextEnd(list);
279                 // this is for inline cp that is also path leg end
280                 if (lengthChange == PathLegUpdateType.NONE) {
281                         if (start.equals(updated))
282                                 lengthChange = PathLegUpdateType.NEXT;
283                         else if (end.equals(updated))
284                                 lengthChange = PathLegUpdateType.PREV;
285                 }
286                 updatePathLegNext(start, list, end, updated, lengthChange);
287         }
288
289         private static void updatePathLegNext(PipeControlPoint start, ArrayList<PipeControlPoint> list, PipeControlPoint end, PipeControlPoint updated, PathLegUpdateType lengthChange) throws Exception {
290                 updatePathLeg(start, list, end, false, 0, new ArrayList<ExpandIterInfo>(), updated, lengthChange);
291         }
292         
293         private static void updatePathLegPrev(PipeControlPoint start, PipeControlPoint updated, PathLegUpdateType lengthChange) throws Exception {
294                 ArrayList<PipeControlPoint> list = new ArrayList<PipeControlPoint>();
295                 PipeControlPoint end = start.findPreviousEnd(list);
296                 // TODO: this method is not symmetric with updatePathLegNext, which may alter lengthChange parameter?
297                 updatePathLegPrev(start, list, end, updated, lengthChange);
298         }
299
300         private static void updatePathLegPrev(PipeControlPoint start, ArrayList<PipeControlPoint> list, PipeControlPoint end, PipeControlPoint updated, PathLegUpdateType lengthChange) throws Exception {
301                 // reverses the list
302                 ArrayList<PipeControlPoint> nextList = new ArrayList<PipeControlPoint>();
303                 for (PipeControlPoint icp : list) {
304                         if (icp.isDualSub()) {
305                                 nextList.add(0, icp.getParentPoint());
306                         } else {
307                                 nextList.add(0, icp);
308                         }
309                 }
310                 updatePathLeg(end, nextList, start, true, 0, new ArrayList<ExpandIterInfo>(), updated, lengthChange);
311
312         }
313
314         private static class UpdateStruct2 {
315                 public PipeControlPoint start;
316                 public Vector3d startPoint;
317                 public ArrayList<PipeControlPoint> list;
318                 public PipeControlPoint end;
319                 public Vector3d endPoint;
320                 public Vector3d dir;
321                 public Vector3d offset;
322                 public boolean hasOffsets;
323                 public int iter;
324                 public boolean reversed;
325                 public ArrayList<ExpandIterInfo> toRemove;
326                 public PipeControlPoint updated;
327
328                 public UpdateStruct2(PipeControlPoint start, Vector3d startPoint, ArrayList<PipeControlPoint> list, PipeControlPoint end, Vector3d endPoint, Vector3d dir, Vector3d offset, boolean hasOffsets, int iter, boolean reversed, ArrayList<ExpandIterInfo> toRemove, PipeControlPoint updated) {
329                         if (start == null || end == null)
330                                 throw new NullPointerException();
331                         this.start = start;
332                         this.startPoint = startPoint;
333                         this.list = list;
334                         this.end = end;
335                         this.endPoint = endPoint;
336                         this.dir = dir;
337                         this.offset = offset;
338                         this.hasOffsets = hasOffsets;
339                         this.iter = iter;
340                         this.reversed = reversed;
341                         this.toRemove = toRemove;
342                         this.updated = updated;
343                         
344                         if (!MathTools.isValid(startPoint) || 
345                                 !MathTools.isValid(endPoint) || 
346                                 !MathTools.isValid(dir)) {
347                                 throw new RuntimeException();
348                         }
349                 }
350
351                 public String toString() {
352                         return start + " " + end+ " " + dir + " " + hasOffsets + " " + offset + " " + iter + " " + toRemove.size();
353                 }
354
355         }
356
357         private static boolean calculateOffset(Vector3d startPoint, Vector3d endPoint, ArrayList<PipeControlPoint> list, Vector3d dir, Vector3d offset) {
358                 boolean hasOffsets = false;
359                 List<PipeControlPoint> offsets = new ArrayList<PipeControlPoint>(list.size());
360                 for (PipeControlPoint icp : list) {
361                         if (icp.isOffset()) {
362                                 offsets.add(icp);
363                         } else if (icp.isDualSub())
364                                 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
365                 }
366                 if (offsets.size() == 0) {
367                         dir.set(endPoint);
368                         dir.sub(startPoint);
369                         double l = dir.lengthSquared(); 
370                         if (l > MathTools.NEAR_ZERO)
371                                 dir.scale(1.0/Math.sqrt(l));
372                         offset.set(0.0, 0.0, 0.0);
373                         return false;
374                 } else {
375                         Vector3d sp = new Vector3d(startPoint);
376                         Point3d ep = new Point3d(endPoint);
377                         dir.set(ep);
378                         dir.sub(sp);
379                         double l = dir.lengthSquared(); 
380                         if (l > MathTools.NEAR_ZERO)
381                                 dir.scale(1.0/Math.sqrt(l));
382                         int iter = 100;
383                         while (iter >= 0) {
384                                 iter--;
385                                 offset.set(0.0, 0.0, 0.0);
386                                 
387                                 for (PipeControlPoint icp : offsets) {
388                                         Vector3d v = icp.getSizeChangeOffsetVector(dir);
389                                         offset.add(v);
390                                 }
391                                 Point3d nep = new Point3d(endPoint);
392                                 nep.sub(offset);
393                                 if (nep.distance(ep) < 0.0000000001) {
394                                         break;
395                                 } 
396                                 ep = nep;
397                                 dir.set(ep);
398                                 dir.sub(sp);
399                                 l = dir.lengthSquared(); 
400                                 if (l > MathTools.NEAR_ZERO)
401                                         dir.scale(1.0/Math.sqrt(l));
402                         }
403                         hasOffsets = true;
404                 }
405                 
406 //              for (PipeControlPoint icp : list) {
407 //                      if (icp.isOffset()) {
408 //                              icp.setOffset(((InlineComponent)icp.getPipelineComponent()).getOffset());
409 //                              hasOffsets = true;
410 //                              Vector3d v = icp.getSizeChangeOffsetVector(dir);
411 //                              offset.add(v);
412 //                      } else if (icp.isDualSub())
413 //                              ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
414 //              }
415                 if (DEBUG && hasOffsets)
416                         System.out.println("calcOffset s:"+ startPoint + " e:" + endPoint + " d:" + dir + " o:"+offset) ;
417                 return hasOffsets;
418         }
419
420         /**
421          * @param start
422          *            starting point of the pipe run
423          * @param list
424          *            list of inline control points in the pipe run
425          * @param end
426          *            ending point of the pipe run
427          * @param reversed
428          *            boolean flag indicating wether start or end control point was
429          *            modified (if true then end point was modified)
430          * @throws TransactionException
431          */
432         private static void updatePathLeg(PipeControlPoint start, ArrayList<PipeControlPoint> list, PipeControlPoint end, boolean reversed, int iter, ArrayList<ExpandIterInfo> toRemove, PipeControlPoint updated, PathLegUpdateType lengthChange) throws Exception {
433                 if (start == end)
434                         return;
435                 // FIXME: direction is calculated wrong way!
436                 boolean hasOffsets = false;
437                 Vector3d offset = new Vector3d();
438                 Vector3d startPoint = start.getWorldPosition();
439                 Vector3d endPoint = end.getWorldPosition();
440                 Vector3d dir = new Vector3d();
441                 hasOffsets = calculateOffset(startPoint, endPoint, list, dir, offset);
442                 updatePathLeg(new UpdateStruct2(start, startPoint, list, end, endPoint, dir, offset, hasOffsets, iter, reversed, toRemove, updated), lengthChange);
443
444         }
445
446         private static void updatePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
447                 int directed = 0;
448                 if (u.start.isDirected())
449                         directed++;
450                 if (u.end.isDirected())
451                         directed++;
452                 switch (directed) {
453                 case 0:
454                         updateFreePathLeg(u, lengthChange);
455                         break;
456                 case 1:
457                         updateDirectedPathLeg(u, lengthChange);
458                         break;
459                 case 2:
460                         updateDualDirectedPathLeg(u, lengthChange);
461                         break;
462                 }
463
464         }
465
466         private static void updateFreePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
467                 if (DEBUG)
468                         System.out.println("PipingRules.updateFreePipeRun " + u + " " + lengthChange);
469                 checkExpandPathLeg(u, lengthChange);
470                 if (u.start.isInline() || u.end.isInline())
471                         processPathLeg(u, true, false);
472         }
473
474         private static void updateInlineControlPoints(UpdateStruct2 u, boolean checkSizes) throws Exception{
475                 if (DEBUG)
476                         System.out.println("PipingRules.updateInlineControlPoints() " + u);
477
478                 Vector3d start = new Vector3d(u.startPoint);
479                 Vector3d end = new Vector3d(u.endPoint);
480                 
481                 if (checkSizes) {
482                         // create offsets for leg ends.
483                         MathTools.mad(start, u.dir, u.start.getInlineLength());
484                         MathTools.mad(end, u.dir, -u.end.getInlineLength());
485                 }
486                 
487                 boolean recalcline = false;
488                 if (!u.hasOffsets) {
489                         
490                         
491                         for (PipeControlPoint icp : u.list) {
492                                 updateInlineControlPoint(icp, start, end, u.dir);
493                                 
494                                 if (icp.isOffset()) {
495                                         // TODO : offset vector is already calculated and should be cached
496                                         Vector3d off = icp.getSizeChangeOffsetVector(u.dir);
497                                         updateOffsetPoint(icp, off);
498                                 }
499                         }
500                         if (!checkSizes)
501                                 return;                 
502
503                         ArrayList<PipeControlPoint> pathLegPoints = new ArrayList<PipeControlPoint>();
504                         pathLegPoints.add(u.start);
505                         for (PipeControlPoint icp : u.list) {
506                                 // updateInlineControlPoint(icp, u.startPoint,
507                                 // u.endPoint,u.dir);
508                                 updateBranchControlPointBranches(icp);
509                                 pathLegPoints.add(icp);
510                         }
511                         pathLegPoints.add(u.end);
512
513                         // TODO : values can be cached in the loop
514                         for (int i = 1; i < pathLegPoints.size(); i++) {
515                                 PipeControlPoint icp = pathLegPoints.get(i);
516
517                                 PipeControlPoint prev = pathLegPoints.get(i - 1);
518                                 
519
520                                 if (icp.isVariableLength()) {
521                                         if (i != pathLegPoints.size() - 1) {
522                                                 PipeControlPoint next = pathLegPoints.get(i + 1);
523                                                 recalcline = recalcline | updateVariableLength(icp,  prev, next);
524
525                                         } else {
526                                                 // this is variable length component at the end of the
527                                                 // piperun.
528                                                 // the problem is that we want to keep unconnected end
529                                                 // of the component in the same
530                                                 // place, but center of the component must be moved.
531                                                 updateVariableLengthEnd(icp, prev);
532                                         }
533
534
535                                 } else if (!prev.isVariableLength()) {
536                                         // If this and previous control point are not variable
537                                         // length pcps, we'll have to check if there is no empty
538                                         // space between them.
539                                         // I there is, we'll have to create new variable length
540                                         // component between them.
541                                         recalcline = recalcline | possibleVaribleLengthInsert(icp, prev);
542                                 }
543                         }
544                 } else { // with offset
545                         Vector3d sp = new Vector3d(start);
546                         Vector3d ep = new Vector3d(end);
547                         ep.sub(u.offset);
548                         
549                         ArrayList<PipeControlPoint> pathLegPoints = new ArrayList<PipeControlPoint>();
550                         pathLegPoints.add(u.start);
551
552                         for (PipeControlPoint icp : u.list) {
553                                 updateInlineControlPoint(icp, sp, ep, u.dir);
554                                 updateBranchControlPointBranches(icp);
555                                 pathLegPoints.add(icp);
556                                 if (icp.isOffset()) {
557                                         // TODO : offset vector is already calculated and should be
558                                         // cached
559                                         Vector3d  offset = icp.getSizeChangeOffsetVector(u.dir);
560                                         updateOffsetPoint(icp, offset);
561                                         sp.add(offset);
562                                         ep.add(offset);
563                                 }
564                         }
565                         pathLegPoints.add(u.end);
566                         
567                         if (!checkSizes)
568                                 return; 
569                         
570                         sp = new Vector3d(u.startPoint);
571                         ep = new Vector3d(u.endPoint);
572                         ep.sub(u.offset);
573                         
574                         for (int i = 1; i < pathLegPoints.size(); i++) {
575                                 PipeControlPoint icp = pathLegPoints.get(i);
576
577                                 PipeControlPoint prev = pathLegPoints.get(i - 1);
578                                 if (prev.isDualInline())
579                                         prev = prev.getSubPoint().get(0);
580                                 
581
582                                 if (icp.isVariableLength()) {
583                                         if (i != pathLegPoints.size() - 1) {
584                                                 PipeControlPoint next;
585                                                 next = pathLegPoints.get(i + 1);
586                                                 recalcline = recalcline | updateVariableLength(icp,  prev, next);
587
588                                         } else {
589                                                 // this is variable length component at the end of the
590                                                 // piperun.
591                                                 // the problem is that we want to keep unconnected end
592                                                 // of the component in the same
593                                                 // place, but center of the component must be moved.
594                                                 updateVariableLengthEnd(icp, prev);
595                                         }
596                                 } else if (!prev.isVariableLength()) {
597                                         // If this and previous control point are not variable
598                                         // length pcps, we'll have to check if there is no empty
599                                         // space between them.
600                                         // I there is, we'll have to create new variable length
601                                         // component between them.
602                                         recalcline = recalcline | possibleVaribleLengthInsert(icp, prev);
603                                 }
604                                 if (icp.isOffset()) {
605                                         // TODO : offset vector is already calculated and should be
606                                         // cached
607                                         Vector3d  offset = icp.getSizeChangeOffsetVector(u.dir);
608                                         sp.add(offset);
609                                         ep.add(offset);
610                                 }
611                         }
612                 }
613                 if (recalcline) {
614                         u.list.clear();
615                         u.start.findNextEnd(u.list);
616                 }
617         }
618         
619         private static boolean updateVariableLength(PipeControlPoint icp, PipeControlPoint prev,  PipeControlPoint next) {
620                 Vector3d prevPos = prev.getWorldPosition();
621                 Vector3d nextPos = next.getWorldPosition();
622                 
623                 Vector3d dir = new Vector3d(nextPos);
624                 dir.sub(prevPos);
625                 double l = dir.lengthSquared(); // distance between
626                                                                                 // control points
627                                                                                 // (square)
628                 double l2prev = prev.getInlineLength(); // distance
629                                                                                                                                         // taken
630                                                                                                                                         // by
631                                                                                                                                         // components
632                 double l2next = next.getInlineLength();
633                 double l2 = l2prev + l2next;
634                 double l2s = MathTools.square(l2);
635                 if (l2s < l) { // check if there is enough space for
636                                                 // variable length component.
637                         // components fit
638                         dir.normalize();
639                         double length = Math.sqrt(l) - l2; // true length of
640                                                                                                 // the variable
641                                                                                                 // length
642                                                                                                 // component
643                         dir.scale(length * 0.5 + l2prev); // calculate
644                                                                                                 // center
645                                                                                                 // position of
646                                                                                                 // the component
647                         dir.add(prevPos);
648                         icp.setWorldPosition(dir);
649                         icp.setLength(length);
650                         return false;
651                 } else {
652                         // components leave no space to the component and it
653                         // must be removed
654                         
655                         if (icp.isDeletable()) {
656                                 if (DEBUG)
657                                         System.out.println("PipingRules.updateVariableLength removing " + icp);
658                                 icp._remove();
659                                 return true;
660                         }
661                         return false;
662                 }
663         }
664         
665         private static boolean possibleVaribleLengthInsert(PipeControlPoint icp, PipeControlPoint prev) throws Exception{
666                 Vector3d currentPos = icp.getWorldPosition();
667                 Vector3d prevPos = prev.getWorldPosition();
668                 Vector3d dir = new Vector3d(currentPos);
669                 dir.sub(prevPos);
670                 double l = dir.lengthSquared();
671                 double l2prev = prev.getInlineLength();
672                 double l2next = icp.getInlineLength();
673                 double l2 = l2prev + l2next;
674                 double l2s = l2 * l2;
675                 if (l > l2s) {
676                         if (allowInsertRemove) {
677                                 dir.normalize();
678                                 double length = Math.sqrt(l) - l2; // true length of the
679                                                                                                         // variable length
680                                                                                                         // component
681                                 dir.scale(length * 0.5 + l2prev); // calculate center
682                                                                                                         // position of the
683                                                                                                         // component
684                                 dir.add(prevPos);
685                                 PipeControlPoint scp = insertStraight(prev, icp, dir, length);
686                                 return true;
687                         } else {
688                                 triedIR = true;
689                         }
690                 }
691                 return false;
692         }
693         
694         private static void updateVariableLengthEnd(PipeControlPoint icp,  PipeControlPoint prev) {
695                 double currentLength = icp.getLength();
696                 Vector3d currentPos = icp.getWorldPosition();
697                 Vector3d prevPos = prev.getWorldPosition();
698                 
699                 Vector3d dir = new Vector3d();
700                 dir.sub(currentPos, prevPos);
701                 
702                 if (currentLength < MathTools.NEAR_ZERO) {
703                         currentLength = (dir.length() - prev.getInlineLength()) * 2.0;
704                 }
705                 
706                 if (dir.lengthSquared() > MathTools.NEAR_ZERO)
707                         dir.normalize();
708                 Point3d endPos = new Point3d(dir);
709                 endPos.scale(currentLength * 0.5);
710                 endPos.add(currentPos); // this is the free end of the
711                                                                 // component
712
713                 double offset = prev.getInlineLength();
714                 Point3d beginPos = new Point3d(dir);
715                 beginPos.scale(offset);
716                 beginPos.add(prevPos); // this is the connected end of
717                                                                 // the component
718
719                 double l = beginPos.distance(endPos);
720                 
721                 if (Double.isNaN(l))
722                         System.out.println("Length for " + icp + " is NaN");
723
724                 dir.scale(l * 0.5);
725                 beginPos.add(dir); // center position
726
727                 if (DEBUG)
728                         System.out.println("PipingRules.updateInlineControlPoints() setting variable length to " + l);
729                 icp.setLength(l);
730
731                 icp.setWorldPosition(new Vector3d(beginPos));
732         }
733
734         private static void ppNoOffset(UpdateStruct2 u) throws Exception {
735                 if (DEBUG)
736                         System.out.println("PipingRules.ppNoOffset() " + u);
737                 Vector3d offset = new Vector3d();
738                 if (u.hasOffsets) {
739                         u.dir.normalize();
740                         for (PipeControlPoint icp : u.list) {
741                                 if (icp.isOffset()) {
742                                         offset.add(icp.getSizeChangeOffsetVector(u.dir));
743                                 } else if (icp.isDualSub())
744                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
745                         }
746                 }
747                 u.offset = offset;
748                 checkExpandPathLeg(u, PathLegUpdateType.NONE);
749         }
750
751         private static void ppNoDir(PipeControlPoint start, Vector3d startPoint, ArrayList<PipeControlPoint> list, PipeControlPoint end, Vector3d endPoint, boolean hasOffsets, int iter, boolean reversed, ArrayList<ExpandIterInfo> toRemove, PipeControlPoint updated) throws Exception {
752                 if (DEBUG)
753                         System.out.println("PipingRules.ppNoDir() " + start + " " + end + " " + iter + " " + toRemove.size());
754                 // FIXME : extra loop (dir should be calculated here)
755                 Vector3d dir = new Vector3d();
756                 Vector3d offset = new Vector3d();
757                 hasOffsets = calculateOffset(startPoint, endPoint, list, dir, offset);
758                 ppNoOffset(new UpdateStruct2(start, startPoint, list, end, endPoint, dir, null, hasOffsets, iter, reversed, toRemove, updated));
759         }
760
761         private static void checkExpandPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
762                 checkExpandPathLeg(u, lengthChange, u.updated.isInline() && u.updated.isOffset());
763         }
764         
765         private static void checkExpandPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange, boolean updateEnds) throws Exception {
766                 if (DEBUG)
767                         System.out.println("PipingRules.checkExpandPathLeg() " + u + " " + lengthChange);
768                 if (lengthChange != PathLegUpdateType.NONE) {
769                         // FIXME : turns cannot be checked before inline cps are updated,
770                         // since their position affects calculation of turns
771                         processPathLeg(u, updateEnds, false);
772                         int type = checkTurns(u, lengthChange);
773                         if (type == REMOVE_NONE) {
774                                 processPathLeg(u, updateEnds, true);
775                         } else {
776                                 expandPathLeg(u, type);
777                         }
778                 } else {
779                         processPathLeg(u, updateEnds, true);
780                 }
781         }
782
783         private static void updateDirectedPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
784                 if (DEBUG)
785                         System.out.println("PipingRules.updateDirectedPipeRun() " + u + " " + lengthChange);
786                 PipeControlPoint dcp;
787                 PipeControlPoint other;
788                 boolean canMoveOther = false;
789                 boolean dcpStart = false;
790                 boolean inlineEnd = false;
791                 Vector3d position;
792                 if (u.start.isDirected()) {
793                         dcp = u.start;
794                         other = u.end;
795                         position = u.startPoint;
796                         dcpStart = true;
797                         if (!u.reversed)
798                                 canMoveOther = true;
799                         inlineEnd = u.end.isInline();
800                                 
801                 } else {
802                         dcp = u.end;
803                         other = u.start;
804                         position = u.endPoint;
805                         if (u.reversed)
806                                 canMoveOther = true;
807                         inlineEnd = u.start.isInline();
808                 }
809
810                 Vector3d directedDirection = dcp.getDirection();
811                 Point3d directedEndPoint = new Point3d(u.endPoint);
812                 if (u.hasOffsets)
813                         directedEndPoint.add(u.offset);
814
815                 double mu[] = new double[2];
816
817                 Vector3d closest;
818                 Vector3d t = new Vector3d();
819
820                 if (dcpStart) {
821                         closest = MathTools.closestPointOnStraight(directedEndPoint, u.startPoint, directedDirection, mu);
822                         t.sub(closest, directedEndPoint);
823                 } else {
824                         closest = MathTools.closestPointOnStraight(u.startPoint, directedEndPoint, directedDirection, mu);
825                         t.sub(closest, u.startPoint);
826                 }
827
828                 double distance = t.length();
829                 boolean aligned = (distance < ALLOWED_OFFSET);
830                 if (aligned) {
831                         checkExpandPathLeg(u, lengthChange, inlineEnd);
832                         
833                 } else {
834                         if (u.iter > 0) {
835                                 backIter(u);
836                         } else {
837                                 PipeControlPoint nextToMoved;
838
839                                 if (u.list.size() > 0)
840                                         if (dcpStart)
841                                                 nextToMoved = u.list.get(0);
842                                         else
843                                                 nextToMoved = u.list.get(u.list.size() - 1);
844                                 else if (dcpStart)
845                                         nextToMoved = u.end;
846                                 else
847                                         nextToMoved = u.start;
848                                 if (other.isVariableAngle()) {
849
850                                         // TODO calculate needed space from next run end.
851                                         if (mu[0] < 1.0) {
852                                                 if (dcpStart) {
853                                                         closest.set(u.startPoint);
854                                                 } else {
855                                                         closest.set(u.endPoint);
856                                                 }
857                                                 Vector3d v = new Vector3d(directedDirection);
858                                                 v.scale(spaceForTurn(other));
859                                                 closest.add(v);
860                                         }
861
862                                         if (canMoveOther) {
863                                                 if (DEBUG)
864                                                         System.out.println("PipingRules.updateDirectedPipeRun() moved end " + other + " to " + closest);
865                                                 other.setWorldPosition(closest);
866                                                 if (dcpStart) {
867                                                         ppNoOffset(new UpdateStruct2(u.start, u.startPoint, u.list, u.end, new Vector3d(closest), directedDirection, null, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated));
868                                                         if (u.end.getNext() != null)
869                                                                 updatePathLegNext(u.end, u.updated, PathLegUpdateType.NEXT);
870                                                 } else {
871                                                         ppNoOffset(new UpdateStruct2(u.start, new Vector3d(closest), u.list, u.end, u.endPoint, directedDirection, null, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated));
872                                                         if (u.start.getPrevious() != null)
873                                                                 updatePathLegPrev(u.start, u.updated, PathLegUpdateType.PREV);
874                                                 }
875                                         } else {
876                                                 // TODO : calculate needed space from next run end.
877                                                 if (allowInsertRemove)
878                                                         insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
879                                                         
880                                                 else
881                                                         triedIR = true;
882                                         }
883                                 } else if (other.isNonDirected() && other.getParentPoint() != null) {
884                                         // FIXME : this code was for updating branches
885                                         Vector3d bintersect = new Vector3d();
886                                         PipeControlPoint bcp = other.getParentPoint();
887                                         if (bcp != null && canMoveOther) {
888                                                 Point3d bstart = new Point3d();
889                                                 Point3d bend = new Point3d();
890                                                 Vector3d bdir = new Vector3d();
891                                                 bcp.getInlineControlPointEnds(bstart, bend, bdir);
892                                                 Vector3d nintersect = new Vector3d();
893
894                                                 MathTools.intersectStraightStraight(position, directedDirection, bend, bdir, nintersect, bintersect, mu);
895                                                 Vector3d dist = new Vector3d(nintersect);
896                                                 dist.sub(bintersect);
897                                                 canMoveOther = mu[1] > 0.0 && mu[1] < 1.0 && dist.lengthSquared() < 0.01;
898                                         } else {
899                                                 // TODO : endControlPoints are undirected: calculcate
900                                                 // correct position for it
901                                                 throw new UnsupportedOperationException("not implemented");
902                                         }
903                                         if (canMoveOther) {
904                                                 if (DEBUG)
905                                                         System.out.println("PipingRules.updateDirectedPipeRun() moved end " + other + " to " + bintersect);
906                                                 // is required branch position is in possible range
907                                                 bcp.setWorldPosition(bintersect);
908                                                 if (dcpStart) {
909                                                         checkExpandPathLeg(new UpdateStruct2(u.start, u.startPoint, u.list, u.end, new Vector3d(bintersect), directedDirection, u.offset, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated), lengthChange);
910                                                 } else {
911                                                         checkExpandPathLeg(new UpdateStruct2(u.start, new Vector3d(bintersect), u.list, u.end, u.endPoint, directedDirection, u.offset, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated), lengthChange);
912                                                 }
913                                         } else {
914                                                 // branch cannot be moved into right position, new turn
915                                                 // / elbow must be inserted
916                                                 if (allowInsertRemove)
917                                                         insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
918                                                 else
919                                                         triedIR = true;
920                                         }
921
922                                 } else { // assume that control point cannot be moved, but can
923                                                         // be rotated
924                                         if (allowInsertRemove)
925                                                 insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
926                                         else
927                                                 triedIR = true;
928                                 }
929                         }
930                 }
931                 
932                 
933         }
934
935         private static void updateDualDirectedPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
936                 if (DEBUG)
937                         System.out.println("PipingRules.updateDualDirectedPipeRun() " + u + " " + lengthChange);
938                 
939                 PipeControlPoint dcp1 = u.start;
940                 PipeControlPoint dcp2 = u.end;
941                 Point3d position1 = new Point3d(u.startPoint);
942                 Point3d position2 = new Point3d(u.endPoint);
943                 Point3d position1offset = new Point3d(position1);
944                 position1offset.sub(u.offset);
945                 Point3d position2offset = new Point3d(position2);
946                 position2offset.add(u.offset);
947                 Vector3d dir1 = dcp1.getDirection();
948                 Vector3d dir2 = dcp2.getDirection();
949                 Vector3d p1 = MathTools.closestPointOnStraight(position1offset, position2, dir2);
950                 Vector3d p2 = MathTools.closestPointOnStraight(position2offset, position1, dir1);
951                 double d1 = position1.distance(new Point3d(p1));
952                 double d2 = position2.distance(new Point3d(p2));
953
954                 boolean aligned = (d1 < ALLOWED_OFFSET && d2 < ALLOWED_OFFSET);
955                 if (aligned) {
956                         processPathLeg(u);
957                 } else {
958                         if (u.iter > 0) {
959                                 backIter(u);
960                         } else if (allowInsertRemove){
961                                 PipeControlPoint dcp;
962                                 PipeControlPoint next;
963                                 if (!u.reversed) {
964                                         dcp = dcp1;
965                                         if (u.list.size() > 0)
966                                                 next = u.list.get(0);
967                                         else
968                                                 next = dcp2;
969                                 } else {
970                                         dcp = dcp2;
971                                         if (u.list.size() > 0)
972                                                 next = u.list.get(u.list.size() - 1);
973                                         else
974                                                 next = dcp1;
975                                 }
976                                 
977                                 p1 = dcp.getWorldPosition();
978                                 // FIXME: calculate position of the elbows properly.
979                                 if (!u.reversed)
980                                         p1.add(dir1);
981                                 else
982                                         p1.add(dir2);
983
984                                 if (!u.reversed)
985                                         p2 = MathTools.closestPointOnStraight(new Point3d(p1), position2, dir2);
986                                 else
987                                         p2 = MathTools.closestPointOnStraight(new Point3d(p1), position1, dir1);
988
989                                 
990                                 PipeControlPoint tcp1 = insertElbow(dcp, next, p1);
991                                 PipeControlPoint tcp2 = insertElbow(tcp1, next, p2);
992
993                                 if (DEBUG)
994                                         System.out.println("PipingRules.updateDualDirectedPipeRun() created two turns " + tcp1 + " " + tcp2);
995
996                                 if (!u.reversed) {
997                                         Vector3d dd = new Vector3d(p2);
998                                         dd.sub(p1);
999                                         dir2.negate();
1000                                         updatePathLegNext(u.start, u.updated, PathLegUpdateType.NONE);
1001                                         updatePathLegNext(tcp1, u.updated, PathLegUpdateType.NONE);
1002                                         if (!u.reversed)
1003                                                 updatePathLegNext(tcp2, u.updated, PathLegUpdateType.NONE);
1004                                         else
1005                                                 updatePathLegPrev(tcp2, u.updated, PathLegUpdateType.NONE);
1006                                 } else {
1007                                         Vector3d dd = new Vector3d(p1);
1008                                         dd.sub(p2);
1009                                         dir2.negate();
1010                                         updatePathLegNext(tcp1, u.updated, PathLegUpdateType.NONE);
1011                                         updatePathLegNext(tcp2, u.updated, PathLegUpdateType.NONE);
1012                                         if (!u.reversed)
1013                                                 updatePathLegNext(u.start, u.updated, PathLegUpdateType.NONE);
1014                                         else
1015                                                 updatePathLegPrev(u.start, u.updated, PathLegUpdateType.NONE);
1016                                 }
1017                         } else {
1018                                 triedIR = true;
1019                         }
1020                 }
1021                 
1022         }
1023         
1024         private static double spaceForTurn(PipeControlPoint tcp) {
1025                 // TODO : this returns now space for 90 deg turn.
1026                 // The challenge: position of tcp affects the turn angle, which then affects the required space. Perhaps we need to iterate...
1027                 // Additionally, if the path legs contain offset, using just positions of opposite path leg ends is not enough,    
1028                 return tcp.getPipeRun().getTurnRadius();
1029         }
1030
1031         private static void insertElbowUpdate(UpdateStruct2 u, PipeControlPoint dcp, PipeControlPoint next, boolean dcpStart, Vector3d position, Vector3d directedDirection) throws Exception{
1032
1033                 
1034 //              Vector3d closest = new Vector3d(position);
1035 //              closest.add(directedDirection);
1036                 
1037                 PipeControlPoint tcp = null;
1038                 Vector3d closest;
1039                 if (dcpStart) {
1040                         closest = MathTools.closestPointOnStraight(next.getWorldPosition(), position, directedDirection);
1041                         tcp = insertElbow(dcp, next, closest);
1042                 } else {
1043                         closest = MathTools.closestPointOnStraight(dcp.getWorldPosition(), position, directedDirection);
1044                         tcp = insertElbow(next, dcp, closest);
1045                 }
1046                 // TODO properly calculate required distance between start and inserted elbow.
1047                 double d = MathTools.distance(position, closest);
1048                 double s = spaceForTurn(tcp);
1049                 if (d < s)  {
1050                         d = s - d;
1051                         Vector3d p = new Vector3d(directedDirection);
1052                         p.scale(d);
1053                         p.add(closest);
1054                         tcp.setPosition(p);
1055                         closest = p;
1056                 }
1057                 
1058                 
1059
1060                 if (DEBUG)
1061                         System.out.println("PipingRules.updateDirectedPipeRun() inserted " + tcp);
1062
1063                 if (dcpStart) {
1064                         // update pipe run from new turn to other end
1065                         ppNoDir(tcp, new Vector3d(closest), u.list, u.end, u.endPoint, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated);
1066                         // update pipe run from directed to new turn
1067                         processPathLeg(new UpdateStruct2(u.start, u.startPoint, new ArrayList<PipeControlPoint>(), tcp, new Vector3d(closest), directedDirection, new Vector3d(), false, 0, false, new ArrayList<ExpandIterInfo>(), u.updated));
1068                 } else {
1069                         // update pipe run from other end to new turn
1070                         ppNoDir(u.start, u.startPoint, u.list, tcp, new Vector3d(closest), u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated);
1071                         // update pipe run from new turn to directed
1072                         processPathLeg(new UpdateStruct2(tcp, new Vector3d(closest), new ArrayList<PipeControlPoint>(), u.end, u.endPoint, directedDirection, new Vector3d(), false, 0, false, new ArrayList<ExpandIterInfo>(), u.updated));
1073                 }
1074         }
1075
1076         /**
1077          * Checks if turns can be removed (turn angle near zero)
1078          */
1079         private static int checkTurns(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
1080                 if (DEBUG)
1081                         System.out.println("PipingRules.checkTurns() " + u.start + " " + u.end);
1082                 boolean startRemoved = false;
1083                 boolean endRemoved = false;
1084                 if (u.start.isVariableAngle()) {
1085                         // this won't work properly if inline control points are not updated
1086                         PipeControlPoint startPrev = u.start.getPrevious();
1087                         if (startPrev != null) {
1088                                 double a;
1089                                 if (!u.hasOffsets) {
1090                                         a = updateTurnControlPointTurn(u.start, startPrev, u.end);
1091                                 } else {
1092                                         Vector3d ep = new Vector3d(u.endPoint);
1093                                         ep.sub(u.offset);
1094                                         a = updateTurnControlPointTurn(u.start, u.startPoint, startPrev.getPosition(), ep);
1095
1096                                 }
1097                                 if (a < MIN_TURN_ANGLE && u.start.isDeletable())
1098                                         startRemoved = true;
1099                                 else if (lengthChange == PathLegUpdateType.PREV || lengthChange == PathLegUpdateType.PREV_S) {
1100                                         PathLegUpdateType type;
1101                                         if (lengthChange == PathLegUpdateType.PREV_S)
1102                                                 type = PathLegUpdateType.PREV;
1103                                         else
1104                                                 type = PathLegUpdateType.NONE;
1105                                         updatePathLegPrev(u.start, u.start, type);
1106                                 }
1107                         }
1108                 }
1109                 if (u.end.isVariableAngle()) {
1110
1111                         PipeControlPoint endNext = u.end.getNext();
1112                         if (endNext != null) {
1113                                 double a;
1114                                 if (!u.hasOffsets) {
1115                                         a = updateTurnControlPointTurn(u.end, u.start, endNext);
1116                                 } else {
1117                                         Vector3d sp = new Vector3d(u.startPoint);
1118                                         sp.add(u.offset);
1119                                         a = updateTurnControlPointTurn(u.end, u.endPoint, sp, endNext.getPosition());
1120                                 }
1121                                 if (a < MIN_TURN_ANGLE && u.end.isDeletable())
1122                                         endRemoved = true;
1123                                 else if (lengthChange == PathLegUpdateType.NEXT || lengthChange == PathLegUpdateType.NEXT_S) {
1124                                         PathLegUpdateType type;
1125                                         if (lengthChange == PathLegUpdateType.NEXT_S)
1126                                                 type = PathLegUpdateType.NEXT;
1127                                         else
1128                                                 type = PathLegUpdateType.NONE;
1129                                         updatePathLegNext(u.end, u.end, type);
1130                                 }
1131                         }
1132                 }
1133                 if (DEBUG)
1134                         System.out.println("PipingRules.checkTurns() res " + startRemoved + " " + endRemoved);
1135                 if (!startRemoved && !endRemoved)
1136                         return REMOVE_NONE;
1137                 if (startRemoved && endRemoved)
1138                         return REMOVE_BOTH;
1139                 if (startRemoved)
1140                         return REMOVE_START;
1141                 return REMOVE_END;
1142         }
1143
1144         /**
1145          * Expands piperun search over turns that are going to be removed
1146          * 
1147          */
1148         private static void expandPathLeg(UpdateStruct2 u, int type) throws Exception {
1149                 if (DEBUG)
1150                         System.out.println("PipingRules.expandPipeline " + u.start + " " + u.end);
1151                 ArrayList<PipeControlPoint> newList = new ArrayList<PipeControlPoint>();
1152                 switch (type) {
1153                 case REMOVE_NONE:
1154                         throw new RuntimeException("Error in piping rules");
1155                 case REMOVE_START:
1156                         u.toRemove.add(new ExpandIterInfo(u.start, REMOVE_START));
1157                         u.start = u.start.findPreviousEnd();
1158                         u.startPoint = u.start.getPosition();
1159                         u.start.findNextEnd(newList);
1160                         newList.addAll(u.list);
1161                         u.list = newList;
1162                         break;
1163                 case REMOVE_END:
1164                         u.toRemove.add(new ExpandIterInfo(u.end, REMOVE_END));
1165                         u.end = u.end.findNextEnd(newList);
1166                         u.endPoint = u.end.getPosition();
1167                         u.list.addAll(newList);
1168                         break;
1169                 case REMOVE_BOTH:
1170                         u.toRemove.add(new ExpandIterInfo(u.start, u.end));
1171                         u.start = u.start.findPreviousEnd();
1172                         u.startPoint = u.start.getPosition();
1173                         u.start.findNextEnd(newList);
1174                         newList.addAll(u.list);
1175                         u.list = newList;
1176                         newList = new ArrayList<PipeControlPoint>();
1177                         u.end = u.end.findNextEnd(newList);
1178                         u.endPoint = u.end.getPosition();
1179                         u.list.addAll(newList);
1180                         break;
1181                 default:
1182                         throw new RuntimeException("Error in piping rules");
1183
1184                 }
1185                 u.offset = new Vector3d();
1186                 if (u.hasOffsets) {
1187                         u.dir.normalize();
1188                         for (PipeControlPoint icp : u.list) {
1189                                 if (icp.isOffset()) {
1190                                         u.offset.add(icp.getSizeChangeOffsetVector(u.dir));
1191                                 } else if (icp.isDualSub())
1192                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1193                         }
1194                 }
1195                 if (DEBUG)
1196                         System.out.println("PipingRules.expandPipeline expanded " + u.start + " " + u.end);
1197                 u.iter++;
1198                 updatePathLeg(u, PathLegUpdateType.NONE);
1199         }
1200
1201         /**
1202          * reverts one iteration of turn removing back)
1203          */
1204         private static void backIter(UpdateStruct2 u) throws Exception {
1205
1206                 if (DEBUG)
1207                         System.out.println("PipingRules.backIter" + u.start + " " + u.end);
1208                 if (u.iter == 0)
1209                         throw new RuntimeException("Error in piping rules");
1210                 ExpandIterInfo info = u.toRemove.get(u.toRemove.size() - 1);
1211                 u.toRemove.remove(u.toRemove.size() - 1);
1212                 if (info.getType() == REMOVE_START || info.getType() == REMOVE_BOTH) {
1213                         while (u.list.size() > 0) {
1214                                 PipeControlPoint icp = u.list.get(0);
1215                                 if (icp.getPrevious().equals(info.getStart()))
1216                                         break;
1217                                 u.list.remove(icp);
1218                         }
1219                         u.start = info.getStart();
1220                 }
1221                 if (info.getType() == REMOVE_END || info.getType() == REMOVE_BOTH) {
1222                         while (u.list.size() > 0) {
1223                                 PipeControlPoint icp = u.list.get(u.list.size() - 1);
1224                                 if (icp.getNext().equals(info.getEnd()))
1225                                         break;
1226                                 u.list.remove(icp);
1227                         }
1228                         u.end = info.getEnd();
1229                 }
1230                 u.offset = new Vector3d();
1231                 if (u.hasOffsets) {
1232                         u.dir.normalize();
1233                         for (PipeControlPoint icp : u.list) {
1234                                 if (icp.isOffset()) {
1235                                         u.offset.add(icp.getSizeChangeOffsetVector(u.dir));
1236                                 } else if (icp.isDualSub())
1237                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1238                         }
1239                 }
1240                 processPathLeg(u);
1241
1242         }
1243
1244         /**
1245          * Processes pipe run (removes necessary turns and updates run ends)
1246          */
1247         // private static void processPathLeg(PipeControlPoint start, Point3d
1248         // startPoint,ArrayList<InlineControlPoint> list, PipeControlPoint
1249         // end,Point3d endPoint, Vector3d dir,Vector3d offset, boolean
1250         // hasOffsets,int iter, boolean reversed, ArrayList<ExpandIterInfo>
1251         // toRemove) throws TransactionException {
1252
1253         private static void processPathLeg(UpdateStruct2 u) throws Exception {
1254                 if (DEBUG)
1255                         System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1256                 processPathLeg(u, true, true);
1257         }
1258
1259         private static void processPathLeg(UpdateStruct2 u, boolean updateEnds, boolean updateInline) throws Exception {
1260                 if (DEBUG)
1261                         System.out.println("PipingRules.processPathLeg " + (updateEnds ? "ends " : "") + (updateInline ? "inline " : "") + u.start + " " + u.end);
1262
1263                 if (u.toRemove.size() > 0) {
1264                         for (ExpandIterInfo info : u.toRemove) {
1265                                 if (info.getStart() != null) {
1266                                         if (DEBUG)
1267                                                 System.out.println("PipingRules.processPathLeg removing start " + info.getStart());
1268                                         info.getStart()._remove();
1269                                 }
1270                                 if (info.getEnd() != null) {
1271                                         if (DEBUG)
1272                                                 System.out.println("PipingRules.processPathLeg removing end " + info.getEnd());
1273                                         info.getEnd()._remove();
1274                                 }
1275                         }
1276                         // ControlPointTools.removeControlPoint may remove mo0re than one
1277                         // CP;
1278                         // we must populate inline CP list again.
1279                         u.list.clear();
1280                         u.start.findNextEnd( u.list);
1281                 }
1282                 // FIXME : inline CPs are update twice because their positions must be
1283                 // updated before and after ends.
1284                 updateInlineControlPoints(u, false);
1285                 
1286                 if (updateEnds) {
1287                         if (u.start.isTurn()) {
1288                                 updateTurnControlPointTurn(u.start, u.start.getPrevious(), u.start.getNext());
1289 //                              updatePathLegPrev(u.start, u.start, PathLegUpdateType.NONE);
1290                         } else if (u.start.isEnd()) {
1291                                 updateEndComponentControlPoint(u.start, u.startPoint, u.endPoint);
1292                         } else if (u.start.isInline()) {
1293                                 updateControlPointOrientation(u.start);
1294                         }
1295                         if (u.end.isTurn()) {
1296                                 updateTurnControlPointTurn(u.end, u.end.getPrevious(), u.end.getNext());
1297 //                              updatePathLegNext(u.end, u.end, PathLegUpdateType.NONE);
1298                         } else if (u.end.isEnd()) {
1299                                 updateEndComponentControlPoint(u.end, u.startPoint, u.endPoint);
1300                         } else if (u.end.isInline()) {
1301                                 updateControlPointOrientation(u.end);
1302                         }
1303
1304                 } else {
1305                         if (u.start.isEnd()) {
1306                                 updateEndComponentControlPoint(u.start, u.startPoint, u.endPoint);
1307                         }
1308                         if (u.end.isEnd()) {
1309                                 updateEndComponentControlPoint(u.end, u.startPoint, u.endPoint);
1310                         }
1311                 }
1312                 if (updateInline)
1313                         updateInlineControlPoints(u, true);
1314
1315         }
1316
1317         /**
1318          * Processes pipe run and recalculates offset
1319          */
1320         // private static void processPathLeg(PipeControlPoint start, Point3d
1321         // startPoint,ArrayList<InlineControlPoint> list, PipeControlPoint
1322         // end,Point3d endPoint, Vector3d dir, boolean hasOffsets,int iter, boolean
1323         // reversed, ArrayList<ExpandIterInfo> toRemove) throws TransactionException
1324         // {
1325         private static void processPathLegNoOffset(UpdateStruct2 u) throws Exception {
1326                 if (DEBUG)
1327                         System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1328                 Vector3d offset = new Vector3d();
1329                 if (u.hasOffsets) {
1330                         u.dir.normalize();
1331                         for (PipeControlPoint icp : u.list) {
1332                                 if (icp.isOffset()) {
1333                                         offset.add(icp.getSizeChangeOffsetVector(u.dir));
1334                                 } else if (icp.isDualSub()) {
1335                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1336                                 }
1337                         }
1338                 }
1339                 processPathLeg(u);
1340         }
1341
1342         private static void updateOffsetPoint(PipeControlPoint sccp, Vector3d offset) {
1343                 Vector3d world = sccp.getWorldPosition();
1344                 world.add(offset);
1345                 PipeControlPoint ocp = sccp.getSubPoint().iterator().next();
1346                 ocp.setWorldPosition(world);
1347         }
1348
1349         /**
1350          * Updates InlineControlPoints position when straight pipe's end(s) have
1351          * been changed)
1352          * 
1353          * @param pipeline
1354          * @param icp
1355          * @param nextPoint
1356          * @param prevPoint
1357          */
1358         private static void updateInlineControlPoint(PipeControlPoint icp, Vector3d prev, Vector3d next,  Vector3d dir) {
1359                 if (DEBUG)
1360                         System.out.println("PipingRules.updateInlineControlPoint() " + icp);
1361
1362                 Vector3d inlinePoint = icp.getWorldPosition();
1363                 Vector3d prevPoint = new Vector3d(prev);
1364                 Vector3d nextPoint = new Vector3d(next);
1365                 if (!icp.isVariableLength()) {
1366                         // Reserve space for fixed length components. 
1367                         MathTools.mad(prevPoint, dir, icp.getInlineLength());
1368                         MathTools.mad(nextPoint, dir, -icp.getInlineLength());
1369                         if (MathTools.distance(prevPoint, nextPoint) < ALLOWED_OFFSET) {
1370                                 prevPoint = prev;
1371                                 nextPoint = next;
1372                         }
1373                 }
1374                 boolean canCalc = MathTools.distance(prevPoint, nextPoint) > ALLOWED_OFFSET;
1375                 if (DEBUG)
1376                         System.out.print("InlineControlPoint update " + icp + " " + inlinePoint + " " + prevPoint + " " + nextPoint);
1377                 Vector3d newInlinePoint = null;
1378                 if (canCalc) {
1379                         boolean branchUpdate = false;
1380                         PipeControlPoint becp = null;
1381                         for (PipeControlPoint pcp : icp.getSubPoint())
1382                                 if (pcp.isNonDirected()) {
1383                                         branchUpdate = true;
1384                                         becp = pcp;
1385                                         break;
1386                                 }
1387         
1388                         if (DUMMY || !branchUpdate) {
1389                                 newInlinePoint = MathTools.closestPointOnEdge(new Vector3d(inlinePoint), prevPoint, nextPoint);
1390                                 
1391                         } else {
1392         
1393                                 // FIXME : can only handle one branch
1394                                 PipeControlPoint p = null;
1395                                 if (becp.getNext() != null) {
1396                                         p = becp.findNextEnd();
1397                                 } else if (becp.getPrevious() != null) {
1398                                         p = becp.findPreviousEnd();
1399                                 }
1400                                 if (p == null) {
1401                                         newInlinePoint = MathTools.closestPointOnEdge(new Vector3d(inlinePoint), prevPoint, nextPoint);
1402                                 } else if (canCalc){
1403                                         Vector3d branchLegEnd = p.getWorldPosition();
1404                                         Vector3d dir2 = new Vector3d(inlinePoint);
1405                                         dir2.sub(branchLegEnd);
1406                                         Vector3d dir1 = new Vector3d(nextPoint);
1407                                         dir1.sub(prevPoint);
1408                                         newInlinePoint = new Vector3d();
1409                                         double mu[] = new double[2];
1410                                         MathTools.intersectStraightStraight(new Vector3d(prevPoint), dir1, new Vector3d(branchLegEnd), dir2, newInlinePoint, new Vector3d(), mu);
1411                                         if (DEBUG)
1412                                                 System.out.println(mu[0]);
1413                                         // FIXME : reserve space
1414                                         if (mu[0] < 0.0) {
1415                                                 newInlinePoint = new Vector3d(prevPoint);
1416                                         } else if (mu[0] > 1.0) {
1417                                                 newInlinePoint = new Vector3d(nextPoint);
1418                                         }
1419                                 }
1420                         }
1421                 } else {
1422                         // prevPoint == nextPoint
1423                         newInlinePoint = new Vector3d(prevPoint);
1424                 }
1425                 if (DEBUG)
1426                         System.out.println(" " + newInlinePoint);
1427
1428                 icp.setWorldPosition(newInlinePoint);
1429                 updateControlPointOrientation(icp);
1430         }
1431
1432         /**
1433          * Updates InlineControlPoints position when straight pipe's end(s) have
1434          * been changed)
1435          * 
1436          * @param pipeline
1437          * @param icp
1438          * @param nextPoint
1439          * @param prevPoint
1440          */
1441         private static void updateEndComponentControlPoint(PipeControlPoint ecp, Vector3d start, Vector3d end) throws Exception {
1442                 if (DEBUG)
1443                         System.out.println("PipingRules.updateEndComponentControlPoint() " + ecp);
1444                 // PipeControlPoint next = ecp.getNext();
1445                 // PipeControlPoint prev = ecp.getPrevious();
1446                 // if (next != null) {
1447                 // end = G3DTools.getPoint(next.getLocalPosition());
1448                 // start = G3DTools.getPoint(ecp.getLocalPosition());
1449                 // } else if (prev != null) {
1450                 // end = G3DTools.getPoint(ecp.getLocalPosition());
1451                 // start = G3DTools.getPoint(prev.getLocalPosition());
1452                 // } else {
1453                 // // TODO : warning?
1454                 // return;
1455                 // }
1456                 // Vector3d dir = new Vector3d (end);
1457                 // dir.sub(start);
1458                 // dir.normalize();
1459                 // G3DTools.setTuple(ecp.getDirection(), dir);
1460                 if (!ecp.isFixed())
1461                         updateControlPointOrientation(ecp);
1462
1463                 for (PipeControlPoint pcp : ecp.getSubPoint()) {
1464                         // TODO update position
1465                         updatePathLegEndControlPoint(pcp);
1466                 }
1467         }
1468
1469         private static void updateControlPointOrientation(PipeControlPoint pcp) {
1470                 // FIXME : hack to bypass variable length components orientation
1471 //              if (pcp.getAtMostOneRelatedObject(ProcessResource.g3dResource.HasWorldOrientation) == null)
1472 //                      return;
1473 //              if (pcp.rotationAngle == null)
1474 //                      return;
1475                 Double angleO = pcp.getRotationAngle();
1476                 double angle = 0.0;
1477                 if (angleO != null)
1478                         angle = angleO;
1479
1480                 Quat4d q = pcp.getControlPointOrientationQuat(angle);
1481                 pcp.setWorldOrientation(q);
1482         }
1483
1484         /**
1485          * Updates all branches when branch's position has been changed
1486          * 
1487          * @param bcp
1488          */
1489         private static void updateBranchControlPointBranches(PipeControlPoint bcp) throws Exception {
1490                 if (DEBUG)
1491                         System.out.println("PipingRules.updateBranchControlPointBranches() " + bcp);
1492                 if (bcp.isDualInline())
1493                         return;
1494                 Collection<PipeControlPoint> branches = bcp.getSubPoint();
1495                 if (branches.size() == 0) {
1496                         if (DEBUG)
1497                                 System.out.println("No Branches found");
1498                         return;
1499                 }
1500                 
1501                 for (PipeControlPoint pcp : branches) {
1502                         updatePathLegEndControlPoint(pcp);
1503                 }
1504         }
1505
1506         /**
1507          * Recalculates turn control point's internal data (turn angle and offset)
1508          * 
1509          * @param tcp
1510          * @param prev
1511          * @param next
1512          */
1513         private static double updateTurnControlPointTurn(PipeControlPoint tcp, PipeControlPoint prev, PipeControlPoint next) {
1514                 if (DEBUG)
1515                         System.out.println("PipingTools.updateTurnControlPointTurn()" + tcp);
1516                 if (next == null || prev == null)
1517                         return Math.PI; // FIXME : argh
1518                 Vector3d middlePoint = tcp.getWorldPosition();
1519                 Vector3d nextPoint = next.getWorldPosition();
1520                 Vector3d prevPoint = prev.getWorldPosition();
1521                 return updateTurnControlPointTurn(tcp, middlePoint, prevPoint, nextPoint);
1522         }
1523
1524         /**
1525          * Recalculates turn control point's internal data (turn angle and offset)
1526          * 
1527          * @param tcp
1528          * @param middlePoint
1529          * @param nextPoint
1530          * @param prevPoint
1531          */
1532         private static double updateTurnControlPointTurn(PipeControlPoint tcp, Vector3d middlePoint, Vector3d prevPoint, Vector3d nextPoint) {
1533
1534                 Vector3d dir1 = new Vector3d(middlePoint);
1535                 dir1.sub(prevPoint);
1536                 Vector3d dir2 = new Vector3d(nextPoint);
1537                 dir2.sub(middlePoint);
1538                 if (DEBUG)
1539                         System.out.println("PipingTools.updateTurnControlPointTurn " + tcp + " " + prevPoint + " " + middlePoint + " " + nextPoint);
1540                 return updateTurnControlPointTurn(tcp, dir1, dir2);
1541         }
1542
1543         private static double updateTurnControlPointTurn(PipeControlPoint tcp, Vector3d dir1, Vector3d dir2) {
1544                 double turnAngle = dir1.angle(dir2);
1545
1546                 double angle = Math.PI - turnAngle;
1547
1548                 Vector3d turnAxis = new Vector3d();
1549                 turnAxis.cross(dir1, dir2);
1550                 if (turnAxis.lengthSquared() > MathTools.NEAR_ZERO) {
1551                         double elbowRadius = tcp.getPipelineComponent().getPipeRun().getTurnRadius();
1552                         double R = elbowRadius / Math.tan(angle * 0.5);
1553                         
1554                         turnAxis.normalize();
1555                         tcp.setTurnAngle(turnAngle);
1556                         tcp.setLength(R);// setComponentOffsetValue(R);
1557                         tcp.setTurnAxis(turnAxis);
1558 //                      tcp.setPosition(tcp.getPosition());
1559                 } else {
1560                         turnAngle = 0.0;
1561                         tcp.setTurnAngle(0.0);
1562                         tcp.setLength(0.0);
1563                         tcp.setTurnAxis(MathTools.Y_AXIS);
1564                 }
1565                 updateControlPointOrientation(tcp);
1566                 if (DEBUG)
1567                         System.out.println("PipingTools.updateTurnControlPointTurn " + dir1 + " " + dir2 + " " + turnAngle + " " + turnAxis);
1568                 return turnAngle;
1569         }
1570         
1571         public static List<PipeControlPoint> getControlPoints(PipeRun pipeRun) {
1572                 List<PipeControlPoint> list = new ArrayList<PipeControlPoint>();
1573                 if (pipeRun.getControlPoints().size() == 0)
1574                         return list;
1575                 PipeControlPoint pcp = pipeRun.getControlPoints().iterator().next();
1576                 while (pcp.getPrevious() != null) {
1577                         PipeControlPoint prev = pcp.getPrevious();
1578                         if (prev.getPipeRun() != pipeRun)
1579                                 break;
1580                         pcp = prev;
1581                 }
1582                 if (pcp.isDualSub()) {
1583                         pcp = pcp.getParentPoint();
1584                 }
1585                 list.add(pcp);
1586                 while (pcp.getNext() != null) {
1587                         pcp = pcp.getNext();
1588                         if (pcp.getPipeRun() != pipeRun)
1589                                 break;
1590                         list.add(pcp);
1591                 }
1592                 return list;
1593         }
1594         
1595         public static void reverse(PipeRun pipeRun) {
1596                 List<PipeControlPoint> list = getControlPoints(pipeRun);
1597                 if (list.size() <= 1)
1598                         return; // nothing to do.
1599                 
1600                 for (int i = 0 ; i < list.size(); i++) {
1601                         boolean first = i == 0;
1602                         boolean last = i == list.size() - 1;
1603                         PipeControlPoint current = list.get(i);
1604                         PipeControlPoint currentSub = null;
1605                         if (current.isDualInline())
1606                                 currentSub = current.getSubPoint().get(0);
1607                         if (first) {
1608                                 PipeControlPoint next = list.get(i+1);
1609                                 if (next.isDualInline())
1610                                         next = next.getSubPoint().get(0);
1611                                 current.setNext(null);
1612                                 current.setPrevious(next);
1613                                 if (currentSub != null) {
1614                                         currentSub.setNext(null);
1615                                         currentSub.setPrevious(next);           
1616                                 }
1617                         } else if (last) {
1618                                 PipeControlPoint prev = list.get(i-1);
1619                                 
1620                                 current.setPrevious(null);
1621                                 current.setNext(prev);
1622                                 
1623                                 if (currentSub != null) {
1624                                         currentSub.setPrevious(null);
1625                                         currentSub.setNext(prev);               
1626                                 }
1627                         } else {
1628                                 PipeControlPoint prev = list.get(i-1);
1629                                 PipeControlPoint next = list.get(i+1);
1630                                 if (next.isDualInline())
1631                                         next = next.getSubPoint().get(0);
1632                                 
1633                                 
1634                                 current.setPrevious(next);
1635                                 current.setNext(prev);
1636                                 
1637                                 if (currentSub != null) {
1638                                         currentSub.setPrevious(next);
1639                                         currentSub.setNext(prev);               
1640                                 }
1641                                 
1642                         }
1643                 }
1644         }
1645         
1646         public static void merge(PipeRun run1, PipeRun r2) {
1647                 Map<PipeControlPoint, Vector3d> positions = new HashMap<PipeControlPoint, Vector3d>();
1648                 Map<PipeControlPoint, Quat4d> orientations = new HashMap<PipeControlPoint, Quat4d>();
1649                 for (PipeControlPoint pcp : r2.getControlPoints()) {
1650                         positions.put(pcp, pcp.getWorldPosition());
1651                         orientations.put(pcp, pcp.getWorldOrientation());
1652                 }
1653                 for (PipeControlPoint pcp : r2.getControlPoints()) {
1654                         r2.deattachChild(pcp);
1655                         run1.addChild(pcp);
1656                         PipelineComponent component = pcp.getPipelineComponent();
1657                         if (component != null) {
1658                                 if (!(component instanceof Nozzle)) {
1659                                         component.deattach();
1660                                         run1.addChild(component);
1661                                 } else {
1662                                         Nozzle n = (Nozzle)component;
1663                                         n.setPipeRun(run1);
1664                                 }
1665                         }
1666                 }
1667                 r2.remove();
1668                 
1669         }
1670         
1671         public static void validate(PipeRun pipeRun) {
1672                 if (pipeRun == null)
1673                         return;
1674                 Collection<PipeControlPoint> pcps = pipeRun.getControlPoints();
1675                 int count = 0;
1676                 for (PipeControlPoint pcp : pcps) {
1677                         if (pcp.getParentPoint() == null || pcp.getParentPoint().getPipeRun() != pipeRun)
1678                                 count++;
1679                 }
1680                 List<PipeControlPoint> runPcps = getControlPoints(pipeRun);
1681                 if (runPcps.size() != count) {
1682                         System.out.println("Run is not connected");
1683                 }
1684                 for (PipeControlPoint pcp : pcps) {
1685                         if (!pcp.isDirected() && pcp.getNext() == null && pcp.getPrevious() == null)
1686                                 System.out.println("Orphan undirected " + pcp);
1687                 }
1688                 for (PipeControlPoint pcp : pcps) {
1689                         if (pcp.getParentPoint() == null) {
1690                                 PipeControlPoint sub = null;
1691                                 if (pcp.isDualInline())
1692                                         sub = pcp.getSubPoint().get(0);
1693                                 PipeControlPoint next = pcp.getNext();
1694                                 PipeControlPoint prev = pcp.getPrevious();
1695                                 if (next != null) {
1696                                         if (!(next.getPrevious() == pcp || next.getPrevious() == sub)) {
1697                                                 System.out.println("Inconsistency between " + pcp + " -> " +next );
1698                                         }
1699                                 }
1700                                 if (prev != null) {
1701                                         PipeControlPoint prevParent = null;
1702                                         if (prev.isDualSub()) {
1703                                                 prevParent = prev.getParentPoint();
1704                                         } else if (prev.isDualInline()) {
1705                                                 System.out.println("Inconsistency between " + pcp + " <-- " +prev );
1706                                         }
1707                                         if (!(prev.getNext() == pcp && (prevParent == null || prevParent.getNext() == pcp))) {
1708                                                 System.out.println("Inconsistency between " + pcp + " <-- " +prev );
1709                                         }
1710                                 }
1711                         }
1712                 }
1713         }
1714         
1715         public static void splitVariableLengthComponent(PipelineComponent newComponent, InlineComponent splittingComponent, boolean assignPos) throws Exception{
1716                 assert(!splittingComponent.getControlPoint().isFixed());
1717                 assert(!(newComponent instanceof  InlineComponent && !newComponent.getControlPoint().isFixed()));
1718                 PipeControlPoint newCP = newComponent.getControlPoint();
1719                 PipeControlPoint splittingCP = splittingComponent.getControlPoint();
1720                 PipeControlPoint nextCP = splittingCP.getNext();
1721                 PipeControlPoint prevCP = splittingCP.getPrevious();
1722                 
1723                 /* there are many different cases to insert new component when
1724                    it splits existing VariableLengthinlineComponent.
1725             
1726                1. VariableLengthComponet is connected from both sides:
1727                   - insert new component between VariableLength component and component connected to it
1728                   - insert new VariableLengthComponent between inserted component and component selected in previous step
1729                 
1730                    2. VariableLengthComponent is connected from one side
1731                      - Use previous case or:
1732                      - Insert new component to empty end
1733                      - Insert new VariableLength component to inserted components empty end
1734                      
1735                    3. VariableLength is not connected to any component.
1736                      - Should not be possible, at least in current implementation.
1737                      - Could be done using second case
1738
1739                 */
1740                 
1741                 if (nextCP == null && prevCP == null) {
1742                         // this should not be possible
1743                         throw new RuntimeException("VariableLengthComponent " + splittingComponent + " is not connected to anything.");
1744                 }
1745                 double reservedLength = splittingComponent.getControlPoint().getLength();
1746                 double newLength = newComponent.getControlPoint().getLength();
1747                 
1748                 
1749                 Point3d next = new Point3d();
1750                 Point3d prev = new Point3d();
1751                 splittingCP.getInlineControlPointEnds(prev, next);
1752                 
1753                 Vector3d newPos = null;
1754                 if (assignPos) {
1755                         newPos = new Vector3d(prev);
1756                         Vector3d dir = new Vector3d(next);
1757                         dir.sub(prev);
1758                         dir.scale(0.5);
1759                         newPos.add(dir);
1760                         newComponent.setWorldPosition(newPos);
1761                 } else {
1762                         newPos = newComponent.getWorldPosition();
1763                 }
1764                 
1765                 
1766
1767                 Vector3d dir = new Vector3d(next);
1768                 dir.sub(prev);
1769                 dir.normalize();
1770                 dir.scale(newLength * 0.5);
1771                 Point3d vn = new Point3d(newPos);
1772                 Point3d vp = new Point3d(newPos);
1773                 vn.add(dir);
1774                 vp.sub(dir);
1775                 double ln = vn.distance(next);
1776                 double lp = vp.distance(prev);
1777                 vp.interpolate(prev, 0.5);
1778                 vn.interpolate(next, 0.5);
1779                 
1780                 
1781                 PipeControlPoint newVariableLengthCP = null;//insertStraight(pcp1, pcp2, pos, length);
1782                 if (nextCP == null) {
1783                         newCP.insert(splittingCP, Direction.NEXT);
1784                         newVariableLengthCP = insertStraight(newCP, Direction.NEXT, new Vector3d(vn), ln);
1785                         splittingCP.setWorldPosition(new Vector3d(vp));
1786 //                      ControlPointTools.setWorldPosition(splittingCP, vp);
1787 //                      splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, lp);
1788                 } else if (prevCP == null) {
1789                         newCP.insert(splittingCP, Direction.PREVIOUS);
1790                         newVariableLengthCP = insertStraight(newCP, Direction.PREVIOUS, new Vector3d(vp), lp);
1791                         splittingCP.setWorldPosition(new Vector3d(vn));
1792 //                      splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, ln);
1793                 } else {
1794                         newCP.insert(splittingCP, nextCP);
1795                         newVariableLengthCP = insertStraight(newCP, nextCP, new Vector3d(vn), ln);
1796                         splittingCP.setWorldPosition(new Vector3d(vp));
1797 //                      splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, lp);
1798                 }
1799                 positionUpdate(newCP);
1800
1801         }
1802         
1803         public static void addSizeChange(boolean reversed, PipeRun pipeRun, PipeRun other, InlineComponent reducer, PipeControlPoint previous, PipeControlPoint next) {
1804                 PipeControlPoint pcp = reducer.getControlPoint();
1805                 PipeControlPoint ocp = pcp.getSubPoint().get(0);
1806                 if (!reversed) {
1807                         String name = pipeRun.getUniqueName("Reducer");
1808                         reducer.setName(name);
1809                         pipeRun.addChild(reducer);
1810                         other.addChild(ocp);
1811                         reducer.setAlternativePipeRun(other);
1812                         
1813                         previous.setNext(pcp);
1814                         pcp.setPrevious(previous);
1815                         ocp.setPrevious(previous);
1816                         if (next != null) {
1817                                 pcp.setNext(next);
1818                                 ocp.setNext(next);
1819                                 next.setPrevious(ocp);
1820                         }
1821                 } else {
1822                         String name = other.getUniqueName("Reducer");
1823                         reducer.setName(name);
1824                         other.addChild(reducer);
1825                         pipeRun.addChild(ocp);
1826                         reducer.setAlternativePipeRun(pipeRun);
1827                         
1828                         if (next != null) {
1829                                 next.setNext(pcp);
1830                                 pcp.setPrevious(next);
1831                                 ocp.setPrevious(next);
1832                         }
1833                         pcp.setNext(previous);
1834                         ocp.setNext(previous);
1835                         previous.setPrevious(ocp);
1836                 }
1837         }
1838 }