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