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