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