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