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