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