]> gerrit.simantics Code Review - simantics/3d.git/blob - org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/PipingRules.java
Merge "Improve elbow placement when dual directed pathleg is no loner aligned"
[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 boolean asDirected(PipeControlPoint pcp, Direction direction) {
447             if (pcp.isDirected())
448                 return true;
449             if (pcp.isTurn() && pcp.isFixed()) {
450                if (!pcp._getReversed())
451                    return direction == Direction.NEXT;
452                else
453                    return direction == Direction.PREVIOUS;
454             }
455             return false;
456         }
457         
458         private static Vector3d direction(PipeControlPoint pcp, Direction direction) {
459             return pcp.getDirection(direction);
460         }
461  
462         private static void updatePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
463                 int directed = 0;
464                 if (asDirected(u.start, Direction.NEXT))
465                         directed++;
466                 if (asDirected(u.end, Direction.PREVIOUS))
467                         directed++;
468                 switch (directed) {
469                 case 0:
470                         updateFreePathLeg(u, lengthChange);
471                         break;
472                 case 1:
473                         updateDirectedPathLeg(u, lengthChange);
474                         break;
475                 case 2:
476                         updateDualDirectedPathLeg(u, lengthChange);
477                         break;
478                 }
479
480         }
481
482         private static void updateFreePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
483                 if (DEBUG)
484                         System.out.println("PipingRules.updateFreePipeRun " + u + " " + lengthChange);
485                 checkExpandPathLeg(u, lengthChange);
486                 if (u.start.isInline() || u.end.isInline() || u.start.isFixed() || u.end.isFixed())
487                         processPathLeg(u, true, false);
488         }
489
490         private static void updateInlineControlPoints(UpdateStruct2 u, boolean checkSizes) throws Exception{
491                 if (DEBUG)
492                         System.out.println("PipingRules.updateInlineControlPoints() " + u);
493
494                 Vector3d start = new Vector3d(u.startPoint);
495                 Vector3d end = new Vector3d(u.endPoint);
496                 
497                 if (checkSizes) {
498                         // create offsets for leg ends.
499                         MathTools.mad(start, u.dir, u.start.getInlineLength());
500                         MathTools.mad(end, u.dir, -u.end.getInlineLength());
501                 }
502                 
503                 boolean recalcline = false;
504                 if (!u.hasOffsets) {
505                         
506                         
507                         for (PipeControlPoint icp : u.list) {
508                                 updateInlineControlPoint(icp, start, end, u.dir);
509                                 
510                                 if (icp.isOffset()) {
511                                         // TODO : offset vector is already calculated and should be cached
512                                         Vector3d off = icp.getSizeChangeOffsetVector(u.dir);
513                                         updateOffsetPoint(icp, off);
514                                 }
515                         }
516                         if (!checkSizes)
517                                 return;                 
518
519                         ArrayList<PipeControlPoint> pathLegPoints = new ArrayList<PipeControlPoint>();
520                         pathLegPoints.add(u.start);
521                         for (PipeControlPoint icp : u.list) {
522                                 // updateInlineControlPoint(icp, u.startPoint,
523                                 // u.endPoint,u.dir);
524                                 updateBranchControlPointBranches(icp);
525                                 pathLegPoints.add(icp);
526                         }
527                         pathLegPoints.add(u.end);
528
529                         // TODO : values can be cached in the loop
530                         for (int i = 0; i < pathLegPoints.size(); i++) {
531                                 PipeControlPoint icp = pathLegPoints.get(i);
532
533                                 PipeControlPoint prev = i > 0 ? pathLegPoints.get(i - 1) : null;
534                                 PipeControlPoint next = i < pathLegPoints.size() - 1 ? pathLegPoints.get(i + 1) : null;
535
536                                 if (icp.isVariableLength()) {
537                                         if (prev != null && next != null) {
538                                                 
539                                                 recalcline = recalcline | updateVariableLength(icp,  prev, next);
540
541                                         } else {
542                                                 // this is variable length component at the end of the
543                                                 // piperun.
544                                                 // the problem is that we want to keep unconnected end
545                                                 // of the component in the same
546                                                 // place, but center of the component must be moved.
547                                                 updateVariableLengthEnd(icp, prev != null ? prev : next);
548                                         }
549
550
551                                 } else if (prev != null && !prev.isVariableLength()) {
552                                         // If this and previous control point are not variable
553                                         // length pcps, we'll have to check if there is no empty
554                                         // space between them.
555                                         // I there is, we'll have to create new variable length
556                                         // component between them.
557                                         recalcline = recalcline | possibleVaribleLengthInsert(icp, prev);
558                                 }
559                         }
560                 } else { // with offset
561                         Vector3d sp = new Vector3d(start);
562                         Vector3d ep = new Vector3d(end);
563                         ep.sub(u.offset);
564                         
565                         ArrayList<PipeControlPoint> pathLegPoints = new ArrayList<PipeControlPoint>();
566                         pathLegPoints.add(u.start);
567
568                         for (PipeControlPoint icp : u.list) {
569                                 updateInlineControlPoint(icp, sp, ep, u.dir);
570                                 updateBranchControlPointBranches(icp);
571                                 pathLegPoints.add(icp);
572                                 if (icp.isOffset()) {
573                                         // TODO : offset vector is already calculated and should be
574                                         // cached
575                                         Vector3d  offset = icp.getSizeChangeOffsetVector(u.dir);
576                                         updateOffsetPoint(icp, offset);
577                                         sp.add(offset);
578                                         ep.add(offset);
579                                 }
580                         }
581                         pathLegPoints.add(u.end);
582                         
583                         if (!checkSizes)
584                                 return; 
585                         
586                         sp = new Vector3d(u.startPoint);
587                         ep = new Vector3d(u.endPoint);
588                         ep.sub(u.offset);
589                         
590                         for (int i = 0; i < pathLegPoints.size(); i++) {
591                                 PipeControlPoint icp = pathLegPoints.get(i);
592
593                                 PipeControlPoint prev = i > 0 ? pathLegPoints.get(i - 1) : null;
594                 PipeControlPoint next = i < pathLegPoints.size() - 1 ? pathLegPoints.get(i + 1) : null;
595                 
596                                 if (prev != null && prev.isDualInline())
597                                         prev = prev.getSubPoint().get(0);
598                                 
599
600                                 if (icp.isVariableLength()) {
601                                         if (prev != null && next != null) {
602                                                 recalcline = recalcline | updateVariableLength(icp,  prev, next);
603
604                                         } else {
605                                                 // this is variable length component at the end of the
606                                                 // piperun.
607                                                 // the problem is that we want to keep unconnected end
608                                                 // of the component in the same
609                                                 // place, but center of the component must be moved.
610                                                 updateVariableLengthEnd(icp, prev != null ? prev : next);
611                                         }
612                                 } else if (prev != null && !prev.isVariableLength()) {
613                                         // If this and previous control point are not variable
614                                         // length pcps, we'll have to check if there is no empty
615                                         // space between them.
616                                         // I there is, we'll have to create new variable length
617                                         // component between them.
618                                         recalcline = recalcline | possibleVaribleLengthInsert(icp, prev);
619                                 }
620                                 if (icp.isOffset()) {
621                                         // TODO : offset vector is already calculated and should be
622                                         // cached
623                                         Vector3d  offset = icp.getSizeChangeOffsetVector(u.dir);
624                                         sp.add(offset);
625                                         ep.add(offset);
626                                 }
627                         }
628                 }
629                 if (recalcline) {
630                         u.list.clear();
631                         u.start.findNextEnd(u.list);
632                 }
633         }
634         
635         private static boolean updateVariableLength(PipeControlPoint icp, PipeControlPoint prev,  PipeControlPoint next) {
636                 Vector3d prevPos = prev.getWorldPosition();
637                 Vector3d nextPos = next.getWorldPosition();
638                 
639                 Vector3d dir = new Vector3d(nextPos);
640                 dir.sub(prevPos);
641                 double l = dir.lengthSquared(); // distance between
642                                                                                 // control points
643                                                                                 // (square)
644                 double l2prev = prev.getInlineLength(); // distance
645                                                                                                                                         // taken
646                                                                                                                                         // by
647                                                                                                                                         // components
648                 double l2next = next.getInlineLength();
649                 double l2 = l2prev + l2next;
650                 double l2s = MathTools.square(l2);
651                 if (l2s < l) { // check if there is enough space for
652                                                 // variable length component.
653                         // components fit
654                         dir.normalize();
655                         double length = Math.sqrt(l) - l2; // true length of
656                                                                                                 // the variable
657                                                                                                 // length
658                                                                                                 // component
659                         dir.scale(length * 0.5 + l2prev); // calculate
660                                                                                                 // center
661                                                                                                 // position of
662                                                                                                 // the component
663                         dir.add(prevPos);
664                         icp.setWorldPosition(dir);
665                         icp.setLength(length);
666                         return false;
667                 } else {
668                         // components leave no space to the component and it
669                         // must be removed
670                         
671                         if (icp.isDeletable()) {
672                                 if (DEBUG)
673                                         System.out.println("PipingRules.updateVariableLength removing " + icp);
674                                 icp._remove();
675                                 return true;
676                         }
677                         return false;
678                 }
679         }
680         
681         private static boolean possibleVaribleLengthInsert(PipeControlPoint icp, PipeControlPoint prev) throws Exception{
682                 Vector3d currentPos = icp.getWorldPosition();
683                 Vector3d prevPos = prev.getWorldPosition();
684                 Vector3d dir = new Vector3d(currentPos);
685                 dir.sub(prevPos);
686                 double l = dir.lengthSquared();
687                 double l2prev = prev.getInlineLength();
688                 double l2next = icp.getInlineLength();
689                 double l2 = l2prev + l2next;
690                 double l2s = l2 * l2;
691                 if (l > l2s) {
692                         if (allowInsertRemove) {
693                                 dir.normalize();
694                                 double length = Math.sqrt(l) - l2; // true length of the
695                                                                                                         // variable length
696                                                                                                         // component
697                                 dir.scale(length * 0.5 + l2prev); // calculate center
698                                                                                                         // position of the
699                                                                                                         // component
700                                 dir.add(prevPos);
701                                 PipeControlPoint scp = insertStraight(prev, icp, dir, length);
702                                 return true;
703                         } else {
704                                 triedIR = true;
705                         }
706                 }
707                 return false;
708         }
709         
710         private static void updateVariableLengthEnd(PipeControlPoint icp,  PipeControlPoint prev) {
711             Vector3d currentPos = icp.getWorldPosition();
712         Vector3d prevPos = prev.getWorldPosition();
713         
714         Vector3d dir = new Vector3d();
715         dir.sub(currentPos, prevPos);
716         
717             boolean simple = true;
718             if (simple) {
719                 double currentLength = (dir.length() - prev.getInlineLength()) * 2.0;
720                 icp.setLength(currentLength);
721             } else {
722                 double currentLength = icp.getLength();
723                 if (currentLength < MathTools.NEAR_ZERO) {
724                         currentLength = (dir.length() - prev.getInlineLength()) * 2.0;
725                 }
726                 
727                 if (dir.lengthSquared() > MathTools.NEAR_ZERO)
728                         dir.normalize();
729                 Point3d endPos = new Point3d(dir);
730                 endPos.scale(currentLength * 0.5);
731                 endPos.add(currentPos); // this is the free end of the component
732     
733                 double offset = prev.getInlineLength();
734                 Point3d beginPos = new Point3d(dir);
735                 beginPos.scale(offset);
736                 beginPos.add(prevPos); // this is the connected end of the component
737     
738                 double l = beginPos.distance(endPos);
739                 
740                 if (Double.isNaN(l))
741                         System.out.println("Length for " + icp + " is NaN");
742     
743                 dir.scale(l * 0.5);
744                 beginPos.add(dir); // center position
745     
746                 if (DEBUG)
747                         System.out.println("PipingRules.updateInlineControlPoints() setting variable length to " + l);
748                 icp.setLength(l);
749     
750                 icp.setWorldPosition(new Vector3d(beginPos));
751             }
752         }
753
754         private static void ppNoOffset(UpdateStruct2 u) throws Exception {
755                 if (DEBUG)
756                         System.out.println("PipingRules.ppNoOffset() " + u);
757                 Vector3d offset = new Vector3d();
758                 if (u.hasOffsets) {
759                         u.dir.normalize();
760                         for (PipeControlPoint icp : u.list) {
761                                 if (icp.isOffset()) {
762                                         offset.add(icp.getSizeChangeOffsetVector(u.dir));
763                                 } else if (icp.isDualSub())
764                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
765                         }
766                 }
767                 u.offset = offset;
768                 checkExpandPathLeg(u, PathLegUpdateType.NONE);
769         }
770
771         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 {
772                 if (DEBUG)
773                         System.out.println("PipingRules.ppNoDir() " + start + " " + end + " " + iter + " " + toRemove.size());
774                 // FIXME : extra loop (dir should be calculated here)
775                 Vector3d dir = new Vector3d();
776                 Vector3d offset = new Vector3d();
777                 hasOffsets = calculateOffset(startPoint, endPoint, list, dir, offset);
778                 ppNoOffset(new UpdateStruct2(start, startPoint, list, end, endPoint, dir, null, hasOffsets, iter, reversed, toRemove, updated));
779         }
780
781         private static void checkExpandPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
782                 checkExpandPathLeg(u, lengthChange, u.updated.isInline() && u.updated.isOffset());
783         }
784         
785         private static void checkExpandPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange, boolean updateEnds) throws Exception {
786                 if (DEBUG)
787                         System.out.println("PipingRules.checkExpandPathLeg() " + u + " " + lengthChange);
788                 if (lengthChange != PathLegUpdateType.NONE) {
789                         // FIXME : turns cannot be checked before inline cps are updated,
790                         // since their position affects calculation of turns
791                         processPathLeg(u, updateEnds, false);
792                         int type = checkTurns(u, lengthChange);
793                         if (type == REMOVE_NONE) {
794                                 processPathLeg(u, updateEnds, true);
795                         } else {
796                                 expandPathLeg(u, type);
797                         }
798                 } else {
799                         processPathLeg(u, updateEnds, true);
800                 }
801         }
802
803         private static void updateDirectedPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
804                 if (DEBUG)
805                         System.out.println("PipingRules.updateDirectedPipeRun() " + u + " " + lengthChange);
806                 PipeControlPoint dcp;
807                 PipeControlPoint other;
808                 boolean canMoveOther = false;
809                 boolean dcpStart = false;
810                 boolean inlineEnd = false;
811                 Vector3d position;
812                 if (asDirected(u.start, Direction.NEXT)) {
813                         dcp = u.start;
814                         other = u.end;
815                         position = u.startPoint;
816                         dcpStart = true;
817                         if (!u.reversed)
818                                 canMoveOther = true;
819                         inlineEnd = u.end.isInline();
820                                 
821                 } else {
822                         dcp = u.end;
823                         other = u.start;
824                         position = u.endPoint;
825                         if (u.reversed)
826                                 canMoveOther = true;
827                         inlineEnd = u.start.isInline();
828                 }
829
830                 Vector3d directedDirection = direction(dcp, dcpStart ? Direction.NEXT : Direction.PREVIOUS);
831                 if (directedDirection == null) {
832                     updateTurnControlPointTurn(dcp, dcp.getPrevious(), dcp.getNext());
833                     directedDirection = direction(dcp, dcpStart ? Direction.NEXT : Direction.PREVIOUS);
834                     if (directedDirection == null) {
835                         return;
836                     }
837                 }
838                 Point3d directedEndPoint = new Point3d(u.endPoint);
839                 if (u.hasOffsets)
840                         directedEndPoint.add(u.offset);
841
842                 double mu[] = new double[2];
843
844                 Vector3d closest;
845                 Vector3d t = new Vector3d();
846
847                 if (dcpStart) {
848                         closest = MathTools.closestPointOnStraight(directedEndPoint, u.startPoint, directedDirection, mu);
849                         t.sub(closest, directedEndPoint);
850                 } else {
851                         closest = MathTools.closestPointOnStraight(u.startPoint, directedEndPoint, directedDirection, mu);
852                         t.sub(closest, u.startPoint);
853                 }
854
855                 double distance = t.length();
856                 boolean aligned = (distance < ALLOWED_OFFSET);
857                 if (aligned) {
858                     if (u.start.isInline() || u.end.isInline() || u.start.isFixed() || u.end.isFixed())
859                     processPathLeg(u, true, false);
860                         checkExpandPathLeg(u, lengthChange, inlineEnd);
861                         
862                 } else {
863                         if (u.iter > 0) {
864                                 backIter(u);
865                         } else {
866                                 PipeControlPoint nextToMoved;
867
868                                 if (u.list.size() > 0)
869                                         if (dcpStart)
870                                                 nextToMoved = u.list.get(0);
871                                         else
872                                                 nextToMoved = u.list.get(u.list.size() - 1);
873                                 else if (dcpStart)
874                                         nextToMoved = u.end;
875                                 else
876                                         nextToMoved = u.start;
877                                 if (other.isVariableAngle()) {
878
879                                         // TODO calculate needed space from next run end.
880                                         if (mu[0] < 1.0) {
881                                                 if (dcpStart) {
882                                                         closest.set(u.startPoint);
883                                                 } else {
884                                                         closest.set(u.endPoint);
885                                                 }
886                                                 Vector3d v = new Vector3d(directedDirection);
887                                                 v.scale(spaceForTurn(other));
888                                                 closest.add(v);
889                                         }
890
891                                         if (canMoveOther) {
892                                                 if (DEBUG)
893                                                         System.out.println("PipingRules.updateDirectedPipeRun() moved end " + other + " to " + closest);
894                                                 other.setWorldPosition(closest);
895                                                 if (dcpStart) {
896                                                         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));
897                                                         if (u.end.getNext() != null)
898                                                                 updatePathLegNext(u.end, u.updated, PathLegUpdateType.NEXT);
899                                                 } else {
900                                                         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));
901                                                         if (u.start.getPrevious() != null)
902                                                                 updatePathLegPrev(u.start, u.updated, PathLegUpdateType.PREV);
903                                                 }
904                                         } else {
905                                                 // TODO : calculate needed space from next run end.
906                                                 if (allowInsertRemove)
907                                                         insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
908                                                         
909                                                 else
910                                                         triedIR = true;
911                                         }
912                                 } else if (other.isNonDirected() && other.getParentPoint() != null) {
913                                         // FIXME : this code was for updating branches
914                                         Vector3d bintersect = new Vector3d();
915                                         PipeControlPoint bcp = other.getParentPoint();
916                                         if (bcp != null && canMoveOther) {
917                                                 Point3d bstart = new Point3d();
918                                                 Point3d bend = new Point3d();
919                                                 Vector3d bdir = new Vector3d();
920                                                 bcp.getInlineControlPointEnds(bstart, bend, bdir);
921                                                 Vector3d nintersect = new Vector3d();
922
923                                                 MathTools.intersectStraightStraight(position, directedDirection, bend, bdir, nintersect, bintersect, mu);
924                                                 Vector3d dist = new Vector3d(nintersect);
925                                                 dist.sub(bintersect);
926                                                 canMoveOther = mu[1] > 0.0 && mu[1] < 1.0 && dist.lengthSquared() < 0.01;
927                                         } else {
928                                                 // TODO : endControlPoints are undirected: calculcate
929                                                 // correct position for it
930                                                 throw new UnsupportedOperationException("not implemented");
931                                         }
932                                         if (canMoveOther) {
933                                                 if (DEBUG)
934                                                         System.out.println("PipingRules.updateDirectedPipeRun() moved end " + other + " to " + bintersect);
935                                                 // is required branch position is in possible range
936                                                 bcp.setWorldPosition(bintersect);
937                                                 if (dcpStart) {
938                                                         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);
939                                                 } else {
940                                                         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);
941                                                 }
942                                         } else {
943                                                 // branch cannot be moved into right position, new turn
944                                                 // / elbow must be inserted
945                                                 if (allowInsertRemove)
946                                                         insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
947                                                 else
948                                                         triedIR = true;
949                                         }
950
951                                 } else { // assume that control point cannot be moved, but can
952                                                         // be rotated
953                                         if (allowInsertRemove)
954                                                 insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
955                                         else
956                                                 triedIR = true;
957                                 }
958                         }
959                 }
960                 
961                 
962         }
963
964         private static void updateDualDirectedPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
965                 if (DEBUG)
966                         System.out.println("PipingRules.updateDualDirectedPipeRun() " + u + " " + lengthChange);
967                 
968                 PipeControlPoint dcp1 = u.start;
969                 PipeControlPoint dcp2 = u.end;
970                 Point3d position1 = new Point3d(u.startPoint);
971                 Point3d position2 = new Point3d(u.endPoint);
972                 Point3d position1offset = new Point3d(position1);
973                 position1offset.sub(u.offset);
974                 Point3d position2offset = new Point3d(position2);
975                 position2offset.add(u.offset);
976                 Vector3d dir1 = direction(dcp1, Direction.NEXT);
977                 Vector3d dir2 = direction(dcp2, Direction.PREVIOUS);
978                 Vector3d p1 = MathTools.closestPointOnStraight(position1offset, position2, dir2);
979                 Vector3d p2 = MathTools.closestPointOnStraight(position2offset, position1, dir1);
980                 double d1 = position1.distance(new Point3d(p1));
981                 double d2 = position2.distance(new Point3d(p2));
982
983                 boolean aligned = (d1 < ALLOWED_OFFSET && d2 < ALLOWED_OFFSET);
984                 if (aligned) {
985                         processPathLeg(u);
986                 } else {
987                         if (u.iter > 0) {
988                                 backIter(u);
989                         } else if (allowInsertRemove){
990                                 PipeControlPoint dcp;
991                                 PipeControlPoint next;
992                                 if (!u.reversed) {
993                                         dcp = dcp1;
994                                         if (u.list.size() > 0)
995                                                 next = u.list.get(0);
996                                         else
997                                                 next = dcp2;
998                                 } else {
999                                         dcp = dcp2;
1000                                         if (u.list.size() > 0)
1001                                                 next = u.list.get(u.list.size() - 1);
1002                                         else
1003                                                 next = dcp1;
1004                                 }
1005                                 
1006                                 p1 = dcp.getWorldPosition();
1007                                 Vector3d v = new Vector3d();
1008                                 if (!u.reversed)
1009                                     v.set(dir1);
1010                                 else
1011                                         v.set(dir2);
1012                                 
1013                                 // Reserve space for 90 deg elbow
1014                                 double off = dcp1.getPipeRun().getTurnRadius();
1015                                 v.scale(off);
1016                                 p1.add(v);
1017
1018                                 if (!u.reversed)
1019                                         p2 = MathTools.closestPointOnStraight(new Point3d(p1), position2, dir2);
1020                                 else
1021                                         p2 = MathTools.closestPointOnStraight(new Point3d(p1), position1, dir1);
1022
1023                                 // By default, the elbows are placed next to each other, by using 90 deg angles.
1024                                 // If the distance between elbows is not enough, we must move the other elbow (and create more shallow angle elbows)
1025                                 if (MathTools.distance(p1, p2) < off*2.05) {
1026                                     p2.add(v);
1027                                 }
1028                                 
1029                                 PipeControlPoint tcp1 = insertElbow(dcp, next, p1);
1030                                 PipeControlPoint tcp2 = insertElbow(tcp1, next, p2);
1031
1032                                 if (DEBUG)
1033                                         System.out.println("PipingRules.updateDualDirectedPipeRun() created two turns " + tcp1 + " " + tcp2);
1034
1035                                 if (!u.reversed) {
1036                                         Vector3d dd = new Vector3d(p2);
1037                                         dd.sub(p1);
1038                                         dir2.negate();
1039                                         updatePathLegNext(u.start, u.updated, PathLegUpdateType.NONE);
1040                                         updatePathLegNext(tcp1, u.updated, PathLegUpdateType.NONE);
1041                                         if (!u.reversed)
1042                                                 updatePathLegNext(tcp2, u.updated, PathLegUpdateType.NONE);
1043                                         else
1044                                                 updatePathLegPrev(tcp2, u.updated, PathLegUpdateType.NONE);
1045                                 } else {
1046                                         Vector3d dd = new Vector3d(p1);
1047                                         dd.sub(p2);
1048                                         dir2.negate();
1049                                         updatePathLegNext(tcp1, u.updated, PathLegUpdateType.NONE);
1050                                         updatePathLegNext(tcp2, u.updated, PathLegUpdateType.NONE);
1051                                         if (!u.reversed)
1052                                                 updatePathLegNext(u.start, u.updated, PathLegUpdateType.NONE);
1053                                         else
1054                                                 updatePathLegPrev(u.start, u.updated, PathLegUpdateType.NONE);
1055                                 }
1056                         } else {
1057                                 triedIR = true;
1058                         }
1059                 }
1060                 
1061         }
1062         
1063         private static double spaceForTurn(PipeControlPoint tcp) {
1064                 // TODO : this returns now space for 90 deg turn.
1065                 // The challenge: position of tcp affects the turn angle, which then affects the required space. Perhaps we need to iterate...
1066                 // Additionally, if the path legs contain offset, using just positions of opposite path leg ends is not enough,    
1067                 return tcp.getPipeRun().getTurnRadius();
1068         }
1069
1070         private static void insertElbowUpdate(UpdateStruct2 u, PipeControlPoint dcp, PipeControlPoint next, boolean dcpStart, Vector3d position, Vector3d directedDirection) throws Exception{
1071
1072                 
1073 //              Vector3d closest = new Vector3d(position);
1074 //              closest.add(directedDirection);
1075                 
1076                 PipeControlPoint tcp = null;
1077                 Vector3d closest;
1078                 if (dcpStart) {
1079                         closest = MathTools.closestPointOnStraight(next.getWorldPosition(), position, directedDirection);
1080                         tcp = insertElbow(dcp, next, closest);
1081                 } else {
1082                         closest = MathTools.closestPointOnStraight(dcp.getWorldPosition(), position, directedDirection);
1083                         tcp = insertElbow(next, dcp, closest);
1084                 }
1085                 // TODO properly calculate required distance between start and inserted elbow.
1086                 double d = MathTools.distance(position, closest);
1087                 double s = spaceForTurn(tcp);
1088                 if (d < s)  {
1089                         d = s - d;
1090                         Vector3d p = new Vector3d(directedDirection);
1091                         p.scale(d);
1092                         p.add(closest);
1093                         tcp.setPosition(p);
1094                         closest = p;
1095                 }
1096                 
1097                 
1098
1099                 if (DEBUG)
1100                         System.out.println("PipingRules.updateDirectedPipeRun() inserted " + tcp);
1101
1102                 if (dcpStart) {
1103                         // update pipe run from new turn to other end
1104                         ppNoDir(tcp, new Vector3d(closest), u.list, u.end, u.endPoint, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated);
1105                         // update pipe run from directed to new turn
1106                         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));
1107                 } else {
1108                         // update pipe run from other end to new turn
1109                         ppNoDir(u.start, u.startPoint, u.list, tcp, new Vector3d(closest), u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated);
1110                         // update pipe run from new turn to directed
1111                         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));
1112                 }
1113         }
1114
1115         /**
1116          * Checks if turns can be removed (turn angle near zero)
1117          */
1118         private static int checkTurns(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
1119                 if (DEBUG)
1120                         System.out.println("PipingRules.checkTurns() " + u.start + " " + u.end);
1121                 boolean startRemoved = false;
1122                 boolean endRemoved = false;
1123                 if (u.start.isVariableAngle()) {
1124                         // this won't work properly if inline control points are not updated
1125                         PipeControlPoint startPrev = u.start.getPrevious();
1126                         if (startPrev != null) {
1127                                 double a;
1128                                 if (!u.hasOffsets) {
1129                                         a = updateTurnControlPointTurn(u.start, startPrev, u.end);
1130                                 } else {
1131                                         Vector3d ep = new Vector3d(u.endPoint);
1132                                         ep.sub(u.offset);
1133                                         a = updateTurnControlPointTurn(u.start, u.startPoint, startPrev.getPosition(), ep);
1134
1135                                 }
1136                                 if (a < MIN_TURN_ANGLE && u.start.isDeletable())
1137                                         startRemoved = true;
1138                                 else if (lengthChange == PathLegUpdateType.PREV || lengthChange == PathLegUpdateType.PREV_S) {
1139                                         PathLegUpdateType type;
1140                                         if (lengthChange == PathLegUpdateType.PREV_S)
1141                                                 type = PathLegUpdateType.PREV;
1142                                         else
1143                                                 type = PathLegUpdateType.NONE;
1144                                         updatePathLegPrev(u.start, u.start, type);
1145                                 }
1146                         }
1147                 }
1148                 if (u.end.isVariableAngle()) {
1149
1150                         PipeControlPoint endNext = u.end.getNext();
1151                         if (endNext != null) {
1152                                 double a;
1153                                 if (!u.hasOffsets) {
1154                                         a = updateTurnControlPointTurn(u.end, u.start, endNext);
1155                                 } else {
1156                                         Vector3d sp = new Vector3d(u.startPoint);
1157                                         sp.add(u.offset);
1158                                         a = updateTurnControlPointTurn(u.end, u.endPoint, sp, endNext.getPosition());
1159                                 }
1160                                 if (a < MIN_TURN_ANGLE && u.end.isDeletable())
1161                                         endRemoved = true;
1162                                 else if (lengthChange == PathLegUpdateType.NEXT || lengthChange == PathLegUpdateType.NEXT_S) {
1163                                         PathLegUpdateType type;
1164                                         if (lengthChange == PathLegUpdateType.NEXT_S)
1165                                                 type = PathLegUpdateType.NEXT;
1166                                         else
1167                                                 type = PathLegUpdateType.NONE;
1168                                         updatePathLegNext(u.end, u.end, type);
1169                                 }
1170                         }
1171                 }
1172                 if (DEBUG)
1173                         System.out.println("PipingRules.checkTurns() res " + startRemoved + " " + endRemoved);
1174                 if (!startRemoved && !endRemoved)
1175                         return REMOVE_NONE;
1176                 if (startRemoved && endRemoved)
1177                         return REMOVE_BOTH;
1178                 if (startRemoved)
1179                         return REMOVE_START;
1180                 return REMOVE_END;
1181         }
1182
1183         /**
1184          * Expands piperun search over turns that are going to be removed
1185          * 
1186          */
1187         private static void expandPathLeg(UpdateStruct2 u, int type) throws Exception {
1188                 if (DEBUG)
1189                         System.out.println("PipingRules.expandPipeline " + u.start + " " + u.end);
1190                 ArrayList<PipeControlPoint> newList = new ArrayList<PipeControlPoint>();
1191                 switch (type) {
1192                 case REMOVE_NONE:
1193                         throw new RuntimeException("Error in piping rules");
1194                 case REMOVE_START:
1195                         u.toRemove.add(new ExpandIterInfo(u.start, REMOVE_START));
1196                         u.start = u.start.findPreviousEnd();
1197                         u.startPoint = u.start.getPosition();
1198                         u.start.findNextEnd(newList);
1199                         newList.addAll(u.list);
1200                         u.list = newList;
1201                         break;
1202                 case REMOVE_END:
1203                         u.toRemove.add(new ExpandIterInfo(u.end, REMOVE_END));
1204                         u.end = u.end.findNextEnd(newList);
1205                         u.endPoint = u.end.getPosition();
1206                         u.list.addAll(newList);
1207                         break;
1208                 case REMOVE_BOTH:
1209                         u.toRemove.add(new ExpandIterInfo(u.start, u.end));
1210                         u.start = u.start.findPreviousEnd();
1211                         u.startPoint = u.start.getPosition();
1212                         u.start.findNextEnd(newList);
1213                         newList.addAll(u.list);
1214                         u.list = newList;
1215                         newList = new ArrayList<PipeControlPoint>();
1216                         u.end = u.end.findNextEnd(newList);
1217                         u.endPoint = u.end.getPosition();
1218                         u.list.addAll(newList);
1219                         break;
1220                 default:
1221                         throw new RuntimeException("Error in piping rules");
1222
1223                 }
1224                 u.offset = new Vector3d();
1225                 if (u.hasOffsets) {
1226                         u.dir.normalize();
1227                         for (PipeControlPoint icp : u.list) {
1228                                 if (icp.isOffset()) {
1229                                         u.offset.add(icp.getSizeChangeOffsetVector(u.dir));
1230                                 } else if (icp.isDualSub())
1231                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1232                         }
1233                 }
1234                 if (DEBUG)
1235                         System.out.println("PipingRules.expandPipeline expanded " + u.start + " " + u.end);
1236                 u.iter++;
1237                 updatePathLeg(u, PathLegUpdateType.NONE);
1238         }
1239
1240         /**
1241          * reverts one iteration of turn removing back)
1242          */
1243         private static void backIter(UpdateStruct2 u) throws Exception {
1244
1245                 if (DEBUG)
1246                         System.out.println("PipingRules.backIter" + u.start + " " + u.end);
1247                 if (u.iter == 0)
1248                         throw new RuntimeException("Error in piping rules");
1249                 ExpandIterInfo info = u.toRemove.get(u.toRemove.size() - 1);
1250                 u.toRemove.remove(u.toRemove.size() - 1);
1251                 if (info.getType() == REMOVE_START || info.getType() == REMOVE_BOTH) {
1252                         while (u.list.size() > 0) {
1253                                 PipeControlPoint icp = u.list.get(0);
1254                                 if (icp.getPrevious().equals(info.getStart()))
1255                                         break;
1256                                 u.list.remove(icp);
1257                         }
1258                         u.start = info.getStart();
1259                 }
1260                 if (info.getType() == REMOVE_END || info.getType() == REMOVE_BOTH) {
1261                         while (u.list.size() > 0) {
1262                                 PipeControlPoint icp = u.list.get(u.list.size() - 1);
1263                                 if (icp.getNext().equals(info.getEnd()))
1264                                         break;
1265                                 u.list.remove(icp);
1266                         }
1267                         u.end = info.getEnd();
1268                 }
1269                 u.offset = new Vector3d();
1270                 if (u.hasOffsets) {
1271                         u.dir.normalize();
1272                         for (PipeControlPoint icp : u.list) {
1273                                 if (icp.isOffset()) {
1274                                         u.offset.add(icp.getSizeChangeOffsetVector(u.dir));
1275                                 } else if (icp.isDualSub())
1276                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1277                         }
1278                 }
1279                 processPathLeg(u);
1280
1281         }
1282
1283         /**
1284          * Processes pipe run (removes necessary turns and updates run ends)
1285          */
1286         // private static void processPathLeg(PipeControlPoint start, Point3d
1287         // startPoint,ArrayList<InlineControlPoint> list, PipeControlPoint
1288         // end,Point3d endPoint, Vector3d dir,Vector3d offset, boolean
1289         // hasOffsets,int iter, boolean reversed, ArrayList<ExpandIterInfo>
1290         // toRemove) throws TransactionException {
1291
1292         private static void processPathLeg(UpdateStruct2 u) throws Exception {
1293                 if (DEBUG)
1294                         System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1295                 processPathLeg(u, true, true);
1296         }
1297
1298         private static void processPathLeg(UpdateStruct2 u, boolean updateEnds, boolean updateInline) throws Exception {
1299                 if (DEBUG)
1300                         System.out.println("PipingRules.processPathLeg " + (updateEnds ? "ends " : "") + (updateInline ? "inline " : "") + u.start + " " + u.end);
1301
1302                 if (u.toRemove.size() > 0) {
1303                         for (ExpandIterInfo info : u.toRemove) {
1304                                 if (info.getStart() != null) {
1305                                         if (DEBUG)
1306                                                 System.out.println("PipingRules.processPathLeg removing start " + info.getStart());
1307                                         info.getStart()._remove();
1308                                 }
1309                                 if (info.getEnd() != null) {
1310                                         if (DEBUG)
1311                                                 System.out.println("PipingRules.processPathLeg removing end " + info.getEnd());
1312                                         info.getEnd()._remove();
1313                                 }
1314                         }
1315                         // ControlPointTools.removeControlPoint may remove more than one CP;
1316                         // we must populate inline CP list again.
1317                         u.list.clear();
1318                         u.start.findNextEnd( u.list);
1319                 }
1320                 // FIXME : inline CPs are update twice because their positions must be
1321                 // updated before and after ends.
1322                 updateInlineControlPoints(u, false);
1323                 
1324                 if (updateEnds) {
1325                         if (u.start.isTurn()) {
1326                                 updateTurnControlPointTurn(u.start, u.start.getPrevious(), u.start.getNext());
1327 //                              updatePathLegPrev(u.start, u.start, PathLegUpdateType.NONE);
1328                         } else if (u.start.isEnd()) {
1329                                 updateEndComponentControlPoint(u.start, u.startPoint, u.endPoint);
1330                         } else if (u.start.isInline()) {
1331                                 updateControlPointOrientation(u.start);
1332                         }
1333                         if (u.end.isTurn()) {
1334                                 updateTurnControlPointTurn(u.end, u.end.getPrevious(), u.end.getNext());
1335 //                              updatePathLegNext(u.end, u.end, PathLegUpdateType.NONE);
1336                         } else if (u.end.isEnd()) {
1337                                 updateEndComponentControlPoint(u.end, u.startPoint, u.endPoint);
1338                         } else if (u.end.isInline()) {
1339                                 updateControlPointOrientation(u.end);
1340                         }
1341
1342                 } else {
1343                         if (u.start.isEnd()) {
1344                                 updateEndComponentControlPoint(u.start, u.startPoint, u.endPoint);
1345                         }
1346                         if (u.end.isEnd()) {
1347                                 updateEndComponentControlPoint(u.end, u.startPoint, u.endPoint);
1348                         }
1349                 }
1350                 if (updateInline)
1351                         updateInlineControlPoints(u, true);
1352
1353         }
1354
1355         /**
1356          * Processes pipe run and recalculates offset
1357          */
1358         // private static void processPathLeg(PipeControlPoint start, Point3d
1359         // startPoint,ArrayList<InlineControlPoint> list, PipeControlPoint
1360         // end,Point3d endPoint, Vector3d dir, boolean hasOffsets,int iter, boolean
1361         // reversed, ArrayList<ExpandIterInfo> toRemove) throws TransactionException
1362         // {
1363         private static void processPathLegNoOffset(UpdateStruct2 u) throws Exception {
1364                 if (DEBUG)
1365                         System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1366                 Vector3d offset = new Vector3d();
1367                 if (u.hasOffsets) {
1368                         u.dir.normalize();
1369                         for (PipeControlPoint icp : u.list) {
1370                                 if (icp.isOffset()) {
1371                                         offset.add(icp.getSizeChangeOffsetVector(u.dir));
1372                                 } else if (icp.isDualSub()) {
1373                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1374                                 }
1375                         }
1376                 }
1377                 processPathLeg(u);
1378         }
1379
1380         private static void updateOffsetPoint(PipeControlPoint sccp, Vector3d offset) {
1381                 Vector3d world = sccp.getWorldPosition();
1382                 world.add(offset);
1383                 PipeControlPoint ocp = sccp.getSubPoint().iterator().next();
1384                 ocp.setWorldPosition(world);
1385         }
1386
1387         /**
1388          * Updates InlineControlPoints position when straight pipe's end(s) have
1389          * been changed)
1390          * 
1391          * @param pipeline
1392          * @param icp
1393          * @param nextPoint
1394          * @param prevPoint
1395          */
1396         private static void updateInlineControlPoint(PipeControlPoint icp, Vector3d prev, Vector3d next,  Vector3d dir) {
1397                 if (DEBUG)
1398                         System.out.println("PipingRules.updateInlineControlPoint() " + icp);
1399
1400                 Vector3d inlinePoint = icp.getWorldPosition();
1401                 Vector3d prevPoint = new Vector3d(prev);
1402                 Vector3d nextPoint = new Vector3d(next);
1403                 if (!icp.isVariableLength()) {
1404                         // Reserve space for fixed length components. 
1405                         MathTools.mad(prevPoint, dir, icp.getInlineLength());
1406                         MathTools.mad(nextPoint, dir, -icp.getInlineLength());
1407                         if (MathTools.distance(prevPoint, nextPoint) < ALLOWED_OFFSET) {
1408                                 prevPoint = prev;
1409                                 nextPoint = next;
1410                         }
1411                 }
1412                 boolean canCalc = MathTools.distance(prevPoint, nextPoint) > ALLOWED_OFFSET;
1413                 if (DEBUG)
1414                         System.out.print("InlineControlPoint update " + icp + " " + inlinePoint + " " + prevPoint + " " + nextPoint);
1415                 Vector3d newInlinePoint = null;
1416                 if (canCalc) {
1417                         boolean branchUpdate = false;
1418                         PipeControlPoint becp = null;
1419                         for (PipeControlPoint pcp : icp.getSubPoint())
1420                                 if (pcp.isNonDirected()) {
1421                                         branchUpdate = true;
1422                                         becp = pcp;
1423                                         break;
1424                                 }
1425         
1426                         if (DUMMY || !branchUpdate) {
1427                                 newInlinePoint = MathTools.closestPointOnEdge(new Vector3d(inlinePoint), prevPoint, nextPoint);
1428                                 
1429                         } else {
1430         
1431                                 // FIXME : can only handle one branch
1432                                 PipeControlPoint p = null;
1433                                 if (becp.getNext() != null) {
1434                                         p = becp.findNextEnd();
1435                                 } else if (becp.getPrevious() != null) {
1436                                         p = becp.findPreviousEnd();
1437                                 }
1438                                 if (p == null) {
1439                                         newInlinePoint = MathTools.closestPointOnEdge(new Vector3d(inlinePoint), prevPoint, nextPoint);
1440                                 } else if (canCalc){
1441                                         Vector3d branchLegEnd = p.getWorldPosition();
1442                                         Vector3d dir2 = new Vector3d(inlinePoint);
1443                                         dir2.sub(branchLegEnd);
1444                                         Vector3d dir1 = new Vector3d(nextPoint);
1445                                         dir1.sub(prevPoint);
1446                                         newInlinePoint = new Vector3d();
1447                                         double mu[] = new double[2];
1448                                         MathTools.intersectStraightStraight(new Vector3d(prevPoint), dir1, new Vector3d(branchLegEnd), dir2, newInlinePoint, new Vector3d(), mu);
1449                                         if (DEBUG)
1450                                                 System.out.println(mu[0]);
1451                                         // FIXME : reserve space
1452                                         if (mu[0] < 0.0) {
1453                                                 newInlinePoint = new Vector3d(prevPoint);
1454                                         } else if (mu[0] > 1.0) {
1455                                                 newInlinePoint = new Vector3d(nextPoint);
1456                                         }
1457                                 }
1458                         }
1459                 } else {
1460                         // prevPoint == nextPoint
1461                         newInlinePoint = new Vector3d(prevPoint);
1462                 }
1463                 if (DEBUG)
1464                         System.out.println(" " + newInlinePoint);
1465
1466                 icp.setWorldPosition(newInlinePoint);
1467                 updateControlPointOrientation(icp);
1468         }
1469
1470         /**
1471          * Updates InlineControlPoints position when straight pipe's end(s) have
1472          * been changed)
1473          * 
1474          * @param pipeline
1475          * @param icp
1476          * @param nextPoint
1477          * @param prevPoint
1478          */
1479         private static void updateEndComponentControlPoint(PipeControlPoint ecp, Vector3d start, Vector3d end) throws Exception {
1480                 if (DEBUG)
1481                         System.out.println("PipingRules.updateEndComponentControlPoint() " + ecp);
1482                 // PipeControlPoint next = ecp.getNext();
1483                 // PipeControlPoint prev = ecp.getPrevious();
1484                 // if (next != null) {
1485                 // end = G3DTools.getPoint(next.getLocalPosition());
1486                 // start = G3DTools.getPoint(ecp.getLocalPosition());
1487                 // } else if (prev != null) {
1488                 // end = G3DTools.getPoint(ecp.getLocalPosition());
1489                 // start = G3DTools.getPoint(prev.getLocalPosition());
1490                 // } else {
1491                 // // TODO : warning?
1492                 // return;
1493                 // }
1494                 // Vector3d dir = new Vector3d (end);
1495                 // dir.sub(start);
1496                 // dir.normalize();
1497                 // G3DTools.setTuple(ecp.getDirection(), dir);
1498                 if (!ecp.isFixed())
1499                         updateControlPointOrientation(ecp);
1500
1501                 for (PipeControlPoint pcp : ecp.getSubPoint()) {
1502                         // TODO update position
1503                         updatePathLegEndControlPoint(pcp);
1504                 }
1505         }
1506
1507         private static void updateControlPointOrientation(PipeControlPoint pcp) {
1508                 // FIXME : hack to bypass variable length components orientation
1509 //              if (pcp.getAtMostOneRelatedObject(ProcessResource.g3dResource.HasWorldOrientation) == null)
1510 //                      return;
1511 //              if (pcp.rotationAngle == null)
1512 //                      return;
1513                 Double angleO = pcp.getRotationAngle();
1514                 double angle = 0.0;
1515                 if (angleO != null)
1516                         angle = angleO;
1517                 Boolean reversedO = pcp.getReversed();
1518                 boolean reversed = false;
1519                 if (reversedO != null)
1520                         reversed = reversedO;
1521                 Quat4d q = pcp.getControlPointOrientationQuat(angle, reversed);
1522                 pcp.setWorldOrientation(q);
1523         }
1524
1525         /**
1526          * Updates all branches when branch's position has been changed
1527          * 
1528          * @param bcp
1529          */
1530         private static void updateBranchControlPointBranches(PipeControlPoint bcp) throws Exception {
1531                 if (DEBUG)
1532                         System.out.println("PipingRules.updateBranchControlPointBranches() " + bcp);
1533                 if (bcp.isDualInline())
1534                         return;
1535                 Collection<PipeControlPoint> branches = bcp.getSubPoint();
1536                 if (branches.size() == 0) {
1537                         if (DEBUG)
1538                                 System.out.println("No Branches found");
1539                         return;
1540                 }
1541                 
1542                 for (PipeControlPoint pcp : branches) {
1543                         updatePathLegEndControlPoint(pcp);
1544                 }
1545         }
1546
1547         /**
1548          * Recalculates turn control point's internal data (turn angle and offset)
1549          * 
1550          * @param tcp
1551          * @param prev
1552          * @param next
1553          */
1554         private static double updateTurnControlPointTurn(PipeControlPoint tcp, PipeControlPoint prev, PipeControlPoint next) {
1555                 if (DEBUG)
1556                         System.out.println("PipingTools.updateTurnControlPointTurn()" + tcp);
1557                 
1558                 if (!tcp.isFixed()) {
1559                     if (next == null || prev == null)
1560                     return tcp.getTurnAngle();
1561                 Vector3d middlePoint = tcp.getWorldPosition();
1562                 Vector3d nextPoint = next.getWorldPosition();
1563                 Vector3d prevPoint = prev.getWorldPosition();
1564                 return updateTurnControlPointTurn(tcp, middlePoint, prevPoint, nextPoint);
1565                 } else {
1566                     // Verify that fixed turn is properly defined.
1567                     // TODO : when reversed flag is changed, rotation angle should be recalculated, otherwise the orientation will change.
1568                     // TODO : should reverse flag toggle to be done already when we are removing defining side?
1569                     if (prev != null && next != null) {
1570                         // Nothing to do
1571                     } else if (prev == null) {
1572                         if (!tcp._getReversed())
1573                             tcp.setReversed(true);
1574                     } else if (next == null) {
1575                         if (tcp._getReversed())
1576                             tcp.setReversed(false);
1577                     }
1578                     
1579                     Vector3d dir;
1580                     if (!tcp._getReversed()) {
1581                     if (prev == null)
1582                     return Math.PI; // FIXME : argh
1583                     
1584                     Vector3d middlePoint = tcp.getWorldPosition();
1585                     Vector3d prevPoint = prev.getWorldPosition();
1586                     dir = new Vector3d();
1587                     dir.sub(middlePoint, prevPoint);        
1588                    
1589                     } else {
1590                         if (next == null)
1591                     return Math.PI; // FIXME : argh
1592                 
1593                 Vector3d middlePoint = tcp.getWorldPosition();
1594                 Vector3d nextPoint = next.getWorldPosition();
1595                 dir = new Vector3d();
1596                 dir.sub(middlePoint, nextPoint);
1597                     }
1598                     dir.normalize();
1599             
1600             Quat4d q = PipeControlPoint.getControlPointOrientationQuat(dir, tcp.getRotationAngle() != null ? tcp.getRotationAngle() : 0.0);
1601             Vector3d v = new Vector3d();
1602             MathTools.rotate(q, MathTools.Y_AXIS,v);
1603             tcp.setTurnAxis(v);
1604             tcp.setWorldOrientation(q);
1605             return tcp.getTurnAngle();
1606                 }
1607         }
1608
1609         /**
1610          * Recalculates turn control point's internal data (turn angle and offset)
1611          * 
1612          * @param tcp
1613          * @param middlePoint
1614          * @param nextPoint
1615          * @param prevPoint
1616          */
1617         private static double updateTurnControlPointTurn(PipeControlPoint tcp, Vector3d middlePoint, Vector3d prevPoint, Vector3d nextPoint) {
1618
1619                 Vector3d dir1 = new Vector3d(middlePoint);
1620                 dir1.sub(prevPoint);
1621                 Vector3d dir2 = new Vector3d(nextPoint);
1622                 dir2.sub(middlePoint);
1623                 if (DEBUG)
1624                         System.out.println("PipingTools.updateTurnControlPointTurn " + tcp + " " + prevPoint + " " + middlePoint + " " + nextPoint);
1625                 return updateTurnControlPointTurn(tcp, dir1, dir2);
1626         }
1627
1628         private static double updateTurnControlPointTurn(PipeControlPoint tcp, Vector3d dir1, Vector3d dir2) {
1629                 double turnAngle = dir1.angle(dir2);
1630
1631                 double angle = Math.PI - turnAngle;
1632
1633                 Vector3d turnAxis = new Vector3d();
1634                 turnAxis.cross(dir1, dir2);
1635                 if (turnAxis.lengthSquared() > MathTools.NEAR_ZERO) {
1636                         double elbowRadius = tcp.getPipelineComponent().getPipeRun().getTurnRadius();
1637                         double R = elbowRadius / Math.tan(angle * 0.5);
1638                         
1639                         turnAxis.normalize();
1640                         tcp.setTurnAngle(turnAngle);
1641                         tcp.setLength(R);// setComponentOffsetValue(R);
1642                         tcp.setTurnAxis(turnAxis);
1643 //                      tcp.setPosition(tcp.getPosition());
1644                 } else {
1645                         turnAngle = 0.0;
1646                         tcp.setTurnAngle(0.0);
1647                         tcp.setLength(0.0);
1648                         tcp.setTurnAxis(new Vector3d(MathTools.Y_AXIS));
1649                 }
1650                 updateControlPointOrientation(tcp);
1651                 if (DEBUG)
1652                         System.out.println("PipingTools.updateTurnControlPointTurn " + dir1 + " " + dir2 + " " + turnAngle + " " + turnAxis);
1653                 return turnAngle;
1654         }
1655         
1656         public static List<PipeControlPoint> getControlPoints(PipeRun pipeRun) {
1657                 List<PipeControlPoint> list = new ArrayList<PipeControlPoint>();
1658                 if (pipeRun.getControlPoints().size() == 0)
1659                         return list;
1660                 PipeControlPoint pcp = pipeRun.getControlPoints().iterator().next();
1661                 while (pcp.getPrevious() != null) {
1662                         PipeControlPoint prev = pcp.getPrevious();
1663                         if (prev.getPipeRun() != pipeRun)
1664                                 break;
1665                         pcp = prev;
1666                 }
1667                 if (pcp.isDualSub()) {
1668                         pcp = pcp.getParentPoint();
1669                 }
1670                 list.add(pcp);
1671                 while (pcp.getNext() != null) {
1672                         pcp = pcp.getNext();
1673                         if (pcp.getPipeRun() != pipeRun)
1674                                 break;
1675                         list.add(pcp);
1676                 }
1677                 return list;
1678         }
1679         
1680         public static void reverse(PipeRun pipeRun) {
1681                 List<PipeControlPoint> list = getControlPoints(pipeRun);
1682                 if (list.size() <= 1)
1683                         return; // nothing to do.
1684                 
1685                 for (int i = 0 ; i < list.size(); i++) {
1686                         boolean first = i == 0;
1687                         boolean last = i == list.size() - 1;
1688                         PipeControlPoint current = list.get(i);
1689                         PipeControlPoint currentSub = null;
1690                         if (current.isDualInline())
1691                                 currentSub = current.getSubPoint().get(0);
1692                         if (first) {
1693                                 PipeControlPoint next = list.get(i+1);
1694                                 if (next.isDualInline())
1695                                         next = next.getSubPoint().get(0);
1696                                 current.setNext(null);
1697                                 current.setPrevious(next);
1698                                 if (currentSub != null) {
1699                                         currentSub.setNext(null);
1700                                         currentSub.setPrevious(next);           
1701                                 }
1702                         } else if (last) {
1703                                 PipeControlPoint prev = list.get(i-1);
1704                                 
1705                                 current.setPrevious(null);
1706                                 current.setNext(prev);
1707                                 
1708                                 if (currentSub != null) {
1709                                         currentSub.setPrevious(null);
1710                                         currentSub.setNext(prev);               
1711                                 }
1712                         } else {
1713                                 PipeControlPoint prev = list.get(i-1);
1714                                 PipeControlPoint next = list.get(i+1);
1715                                 if (next.isDualInline())
1716                                         next = next.getSubPoint().get(0);
1717                                 
1718                                 
1719                                 current.setPrevious(next);
1720                                 current.setNext(prev);
1721                                 
1722                                 if (currentSub != null) {
1723                                         currentSub.setPrevious(next);
1724                                         currentSub.setNext(prev);               
1725                                 }
1726                                 
1727                         }
1728                         if (current.isTurn() && current.isFixed()) {
1729                             current.setReversed(!current._getReversed());
1730                         }
1731                         if (current.isInline() && current.isReverse()) {
1732                             current.setReversed(!current._getReversed());
1733                         }   
1734                 }
1735         }
1736         
1737         public static void merge(PipeRun run1, PipeRun r2) {
1738                 Map<PipeControlPoint, Vector3d> positions = new HashMap<PipeControlPoint, Vector3d>();
1739                 Map<PipeControlPoint, Quat4d> orientations = new HashMap<PipeControlPoint, Quat4d>();
1740                 for (PipeControlPoint pcp : r2.getControlPoints()) {
1741                         positions.put(pcp, pcp.getWorldPosition());
1742                         orientations.put(pcp, pcp.getWorldOrientation());
1743                 }
1744                 for (PipeControlPoint pcp : r2.getControlPoints()) {
1745                         r2.deattachChild(pcp);
1746                         run1.addChild(pcp);
1747                         PipelineComponent component = pcp.getPipelineComponent();
1748                         if (component != null) {
1749                                 if (!(component instanceof Nozzle)) {
1750                                         component.deattach();
1751                                         run1.addChild(component);
1752                                 } else {
1753                                         Nozzle n = (Nozzle)component;
1754                                         n.setPipeRun(run1);
1755                                 }
1756                         }
1757                 }
1758                 r2.remove();
1759                 
1760         }
1761         
1762         public static void validate(PipeRun pipeRun) {
1763                 if (pipeRun == null)
1764                         return;
1765                 Collection<PipeControlPoint> pcps = pipeRun.getControlPoints();
1766                 int count = 0;
1767                 //System.out.println("Validate " + pipeRun.getName());
1768                 for (PipeControlPoint pcp : pcps) {
1769                         if (pcp.getParentPoint() == null || pcp.getParentPoint().getPipeRun() != pipeRun)
1770                                 count++;
1771                 }
1772                 List<PipeControlPoint> runPcps = getControlPoints(pipeRun);
1773                 if (runPcps.size() != count) {
1774                         System.out.println("Run " + pipeRun.getName() + " contains unconnected control points");
1775                 }
1776                 for (PipeControlPoint pcp : pcps) {
1777                         if (!pcp.isDirected() && pcp.getNext() == null && pcp.getPrevious() == null)
1778                                 System.out.println("Orphan undirected " + pcp);
1779                 }
1780                 for (PipeControlPoint pcp : pcps) {
1781                         if (pcp.getParentPoint() == null) {
1782                                 PipeControlPoint sub = null;
1783                                 if (pcp.isDualInline())
1784                                         sub = pcp.getSubPoint().get(0);
1785                                 PipeControlPoint next = pcp.getNext();
1786                                 PipeControlPoint prev = pcp.getPrevious();
1787                                 if (next != null) {
1788                                         if (!(next.getPrevious() == pcp || next.getPrevious() == sub)) {
1789                                                 System.out.println("Inconsistency between " + pcp + " -> " +next );
1790                                         }
1791                                 }
1792                                 if (prev != null) {
1793                                         PipeControlPoint prevParent = null;
1794                                         if (prev.isDualSub()) {
1795                                                 prevParent = prev.getParentPoint();
1796                                         } else if (prev.isDualInline()) {
1797                                                 System.out.println("Inconsistency between " + pcp + " <-- " +prev );
1798                                         }
1799                                         if (!(prev.getNext() == pcp && (prevParent == null || prevParent.getNext() == pcp))) {
1800                                                 System.out.println("Inconsistency between " + pcp + " <-- " +prev );
1801                                         }
1802                                 }
1803                         }
1804                 }
1805         }
1806         
1807         public static void splitVariableLengthComponent(PipelineComponent newComponent, InlineComponent splittingComponent, boolean assignPos) throws Exception{
1808                 assert(!splittingComponent.getControlPoint().isFixed());
1809                 assert(!(newComponent instanceof  InlineComponent && !newComponent.getControlPoint().isFixed()));
1810                 PipeControlPoint newCP = newComponent.getControlPoint();
1811                 PipeControlPoint splittingCP = splittingComponent.getControlPoint();
1812                 PipeControlPoint nextCP = splittingCP.getNext();
1813                 PipeControlPoint prevCP = splittingCP.getPrevious();
1814                 
1815                 /* there are many different cases to insert new component when
1816                    it splits existing VariableLengthinlineComponent.
1817             
1818                1. VariableLengthComponet is connected from both sides:
1819                   - insert new component between VariableLength component and component connected to it
1820                   - insert new VariableLengthComponent between inserted component and component selected in previous step
1821                 
1822                    2. VariableLengthComponent is connected from one side
1823                      - Use previous case or:
1824                      - Insert new component to empty end
1825                      - Insert new VariableLength component to inserted components empty end
1826                      
1827                    3. VariableLength is not connected to any component.
1828                      - Should not be possible, at least in current implementation.
1829                      - Could be done using second case
1830
1831                 */
1832                 
1833                 if (nextCP == null && prevCP == null) {
1834                         // this should not be possible
1835                         throw new RuntimeException("VariableLengthComponent " + splittingComponent + " is not connected to anything.");
1836                 }
1837                 double reservedLength = splittingComponent.getControlPoint().getLength();
1838                 double newLength = newComponent.getControlPoint().getLength();
1839                 
1840                 
1841                 Point3d next = new Point3d();
1842                 Point3d prev = new Point3d();
1843                 splittingCP.getInlineControlPointEnds(prev, next);
1844                 
1845                 Vector3d newPos = null;
1846                 if (assignPos) {
1847                         newPos = new Vector3d(prev);
1848                         Vector3d dir = new Vector3d(next);
1849                         dir.sub(prev);
1850                         dir.scale(0.5);
1851                         newPos.add(dir);
1852                         newComponent.setWorldPosition(newPos);
1853                 } else {
1854                         newPos = newComponent.getWorldPosition();
1855                 }
1856                 
1857                 
1858
1859                 Vector3d dir = new Vector3d(next);
1860                 dir.sub(prev);
1861                 dir.normalize();
1862                 dir.scale(newLength * 0.5);
1863                 Point3d vn = new Point3d(newPos);
1864                 Point3d vp = new Point3d(newPos);
1865                 vn.add(dir);
1866                 vp.sub(dir);
1867                 double ln = vn.distance(next);
1868                 double lp = vp.distance(prev);
1869                 vp.interpolate(prev, 0.5);
1870                 vn.interpolate(next, 0.5);
1871                 
1872                 
1873                 PipeControlPoint newVariableLengthCP = null;//insertStraight(pcp1, pcp2, pos, length);
1874                 if (nextCP == null) {
1875                         newCP.insert(splittingCP, Direction.NEXT);
1876                         newVariableLengthCP = insertStraight(newCP, Direction.NEXT, new Vector3d(vn), ln);
1877                         splittingCP.setWorldPosition(new Vector3d(vp));
1878 //                      ControlPointTools.setWorldPosition(splittingCP, vp);
1879 //                      splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, lp);
1880                 } else if (prevCP == null) {
1881                         newCP.insert(splittingCP, Direction.PREVIOUS);
1882                         newVariableLengthCP = insertStraight(newCP, Direction.PREVIOUS, new Vector3d(vp), lp);
1883                         splittingCP.setWorldPosition(new Vector3d(vn));
1884 //                      splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, ln);
1885                 } else {
1886                         newCP.insert(splittingCP, nextCP);
1887                         newVariableLengthCP = insertStraight(newCP, nextCP, new Vector3d(vn), ln);
1888                         splittingCP.setWorldPosition(new Vector3d(vp));
1889 //                      splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, lp);
1890                 }
1891                 positionUpdate(newCP);
1892
1893         }
1894         
1895         public static void addSizeChange(boolean reversed, PipeRun pipeRun, PipeRun other, InlineComponent reducer, PipeControlPoint previous, PipeControlPoint next) {
1896                 PipeControlPoint pcp = reducer.getControlPoint();
1897                 PipeControlPoint ocp = pcp.getSubPoint().get(0);
1898                 if (!reversed) {
1899                         String name = pipeRun.getUniqueName("Reducer");
1900                         reducer.setName(name);
1901                         pipeRun.addChild(reducer);
1902                         other.addChild(ocp);
1903                         reducer.setAlternativePipeRun(other);
1904                         
1905                         previous.setNext(pcp);
1906                         pcp.setPrevious(previous);
1907                         ocp.setPrevious(previous);
1908                         if (next != null) {
1909                                 pcp.setNext(next);
1910                                 ocp.setNext(next);
1911                                 next.setPrevious(ocp);
1912                         }
1913                 } else {
1914                         String name = other.getUniqueName("Reducer");
1915                         reducer.setName(name);
1916                         other.addChild(reducer);
1917                         pipeRun.addChild(ocp);
1918                         reducer.setAlternativePipeRun(pipeRun);
1919                         
1920                         if (next != null) {
1921                                 next.setNext(pcp);
1922                                 pcp.setPrevious(next);
1923                                 ocp.setPrevious(next);
1924                         }
1925                         pcp.setNext(previous);
1926                         ocp.setNext(previous);
1927                         previous.setPrevious(ocp);
1928                 }
1929         }
1930 }