]> gerrit.simantics Code Review - simantics/3d.git/blob - org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/PipingRules.java
Handle variable length components on offset path leg
[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                 boolean recalcline = false;
479                 if (!u.hasOffsets) {
480                         
481                         Vector3d start = new Vector3d(u.startPoint);
482                         Vector3d end = new Vector3d(u.endPoint);
483                         // create offsets.
484                         MathTools.mad(start, u.dir, u.start.getInlineLength());
485                         MathTools.mad(end, u.dir, -u.end.getInlineLength());
486                         for (PipeControlPoint icp : u.list) {
487                                 updateInlineControlPoint(icp, start, end, u.dir);
488                                 
489                                 if (icp.isOffset()) {
490                                         // TODO : offset vector is already calculated and should be cached
491                                         Vector3d off = icp.getSizeChangeOffsetVector(u.dir);
492                                         updateOffsetPoint(icp, off);
493                                 }
494                         }
495                         if (!checkSizes)
496                                 return;                 
497
498                         ArrayList<PipeControlPoint> pathLegPoints = new ArrayList<PipeControlPoint>();
499                         pathLegPoints.add(u.start);
500                         for (PipeControlPoint icp : u.list) {
501                                 // updateInlineControlPoint(icp, u.startPoint,
502                                 // u.endPoint,u.dir);
503                                 updateBranchControlPointBranches(icp);
504                                 pathLegPoints.add(icp);
505                         }
506                         pathLegPoints.add(u.end);
507
508                         // TODO : values can be cached in the loop
509                         for (int i = 1; i < pathLegPoints.size(); i++) {
510                                 PipeControlPoint icp = pathLegPoints.get(i);
511
512                                 PipeControlPoint prev = pathLegPoints.get(i - 1);
513                                 
514
515                                 if (icp.isVariableLength()) {
516                                         if (i != pathLegPoints.size() - 1) {
517                                                 PipeControlPoint next = pathLegPoints.get(i + 1);
518                                                 recalcline = recalcline | updateVariableLength(icp,  prev, next);
519
520                                         } else {
521                                                 // this is variable length component at the end of the
522                                                 // piperun.
523                                                 // the problem is that we want to keep unconnected end
524                                                 // of the component in the same
525                                                 // place, but center of the component must be moved.
526                                                 updateVariableLengthEnd(icp, prev);
527                                         }
528
529
530                                 } else if (!prev.isVariableLength()) {
531                                         // If this and previous control point are not variable
532                                         // length pcps, we'll have to check if there is no empty
533                                         // space between them.
534                                         // I there is, we'll have to create new variable length
535                                         // component between them.
536                                         recalcline = recalcline | possibleVaribleLengthInsert(icp, prev);
537                                 }
538                         }
539                 } else { // with offset
540                         Vector3d sp = new Vector3d(u.startPoint);
541                         Vector3d ep = new Vector3d(u.endPoint);
542                         ep.sub(u.offset);
543                         
544                         ArrayList<PipeControlPoint> pathLegPoints = new ArrayList<PipeControlPoint>();
545                         pathLegPoints.add(u.start);
546
547                         for (PipeControlPoint icp : u.list) {
548                                 updateInlineControlPoint(icp, sp, ep, u.dir);
549                                 updateBranchControlPointBranches(icp);
550                                 pathLegPoints.add(icp);
551                                 if (icp.isOffset()) {
552                                         // TODO : offset vector is already calculated and should be
553                                         // cached
554                                         Vector3d  offset = icp.getSizeChangeOffsetVector(u.dir);
555                                         updateOffsetPoint(icp, offset);
556                                         sp.add(offset);
557                                         ep.add(offset);
558                                 }
559                         }
560                         pathLegPoints.add(u.end);
561                         
562                         if (!checkSizes)
563                                 return; 
564                         
565                         sp = new Vector3d(u.startPoint);
566                         ep = new Vector3d(u.endPoint);
567                         ep.sub(u.offset);
568                         
569                         for (int i = 1; i < pathLegPoints.size(); i++) {
570                                 PipeControlPoint icp = pathLegPoints.get(i);
571
572                                 PipeControlPoint prev = pathLegPoints.get(i - 1);
573                                 if (prev.isDualInline())
574                                         prev = prev.getSubPoint().get(0);
575                                 
576
577                                 if (icp.isVariableLength()) {
578                                         if (i != pathLegPoints.size() - 1) {
579                                                 PipeControlPoint next;
580                                                 next = pathLegPoints.get(i + 1);
581                                                 recalcline = recalcline | updateVariableLength(icp,  prev, next);
582
583                                         } else {
584                                                 // this is variable length component at the end of the
585                                                 // piperun.
586                                                 // the problem is that we want to keep unconnected end
587                                                 // of the component in the same
588                                                 // place, but center of the component must be moved.
589                                                 updateVariableLengthEnd(icp, prev);
590                                         }
591                                 } else if (!prev.isVariableLength()) {
592                                         // If this and previous control point are not variable
593                                         // length pcps, we'll have to check if there is no empty
594                                         // space between them.
595                                         // I there is, we'll have to create new variable length
596                                         // component between them.
597                                         recalcline = recalcline | possibleVaribleLengthInsert(icp, prev);
598                                 }
599                                 if (icp.isOffset()) {
600                                         // TODO : offset vector is already calculated and should be
601                                         // cached
602                                         Vector3d  offset = icp.getSizeChangeOffsetVector(u.dir);
603                                         sp.add(offset);
604                                         ep.add(offset);
605                                 }
606                         }
607                 }
608                 if (recalcline) {
609                         u.list.clear();
610                         u.start.findNextEnd(u.list);
611                 }
612         }
613         
614         private static boolean updateVariableLength(PipeControlPoint icp, PipeControlPoint prev,  PipeControlPoint next) {
615                 Vector3d prevPos = prev.getWorldPosition();
616                 Vector3d nextPos = next.getWorldPosition();
617                 
618                 Vector3d dir = new Vector3d(nextPos);
619                 dir.sub(prevPos);
620                 double l = dir.lengthSquared(); // distance between
621                                                                                 // control points
622                                                                                 // (square)
623                 double l2prev = prev.getInlineLength(); // distance
624                                                                                                                                         // taken
625                                                                                                                                         // by
626                                                                                                                                         // components
627                 double l2next = next.getInlineLength();
628                 double l2 = l2prev + l2next;
629                 double l2s = MathTools.square(l2);
630                 if (l2s < l) { // check if there is enough space for
631                                                 // variable length component.
632                         // components fit
633                         dir.normalize();
634                         double length = Math.sqrt(l) - l2; // true length of
635                                                                                                 // the variable
636                                                                                                 // length
637                                                                                                 // component
638                         dir.scale(length * 0.5 + l2prev); // calculate
639                                                                                                 // center
640                                                                                                 // position of
641                                                                                                 // the component
642                         dir.add(prevPos);
643                         icp.setWorldPosition(dir);
644                         icp.setLength(length);
645                         return false;
646                 } else {
647                         // components leave no space to the component and it
648                         // must be removed
649                         
650                         if (icp.isDeletable()) {
651                                 if (DEBUG)
652                                         System.out.println("PipingRules.updateVariableLength removing " + icp);
653                                 icp._remove();
654                                 return true;
655                         }
656                         return false;
657                 }
658         }
659         
660         private static boolean possibleVaribleLengthInsert(PipeControlPoint icp, PipeControlPoint prev) throws Exception{
661                 Vector3d currentPos = icp.getWorldPosition();
662                 Vector3d prevPos = prev.getWorldPosition();
663                 Vector3d dir = new Vector3d(currentPos);
664                 dir.sub(prevPos);
665                 double l = dir.lengthSquared();
666                 double l2prev = prev.getInlineLength();
667                 double l2next = icp.getInlineLength();
668                 double l2 = l2prev + l2next;
669                 double l2s = l2 * l2;
670                 if (l > l2s) {
671                         if (allowInsertRemove) {
672                                 dir.normalize();
673                                 double length = Math.sqrt(l) - l2; // true length of the
674                                                                                                         // variable length
675                                                                                                         // component
676                                 dir.scale(length * 0.5 + l2prev); // calculate center
677                                                                                                         // position of the
678                                                                                                         // component
679                                 dir.add(prevPos);
680                                 PipeControlPoint scp = insertStraight(prev, icp, dir, length);
681                                 return true;
682                         } else {
683                                 triedIR = true;
684                         }
685                 }
686                 return false;
687         }
688         
689         private static void updateVariableLengthEnd(PipeControlPoint icp,  PipeControlPoint prev) {
690                 double currentLength = icp.getLength();
691                 Vector3d currentPos = icp.getWorldPosition();
692                 Vector3d prevPos = prev.getWorldPosition();
693                 
694                 Vector3d dir = new Vector3d();
695                 dir.sub(currentPos, prevPos);
696                 
697                 if (currentLength < MathTools.NEAR_ZERO) {
698                         currentLength = (dir.length() - prev.getInlineLength()) * 2.0;
699                 }
700                 
701                 if (dir.lengthSquared() > MathTools.NEAR_ZERO)
702                         dir.normalize();
703                 Point3d endPos = new Point3d(dir);
704                 endPos.scale(currentLength * 0.5);
705                 endPos.add(currentPos); // this is the free end of the
706                                                                 // component
707
708                 double offset = prev.getInlineLength();
709                 Point3d beginPos = new Point3d(dir);
710                 beginPos.scale(offset);
711                 beginPos.add(prevPos); // this is the connected end of
712                                                                 // the component
713
714                 double l = beginPos.distance(endPos);
715                 
716                 if (Double.isNaN(l))
717                         System.out.println("Length for " + icp + " is NaN");
718
719                 dir.scale(l * 0.5);
720                 beginPos.add(dir); // center position
721
722                 if (DEBUG)
723                         System.out.println("PipingRules.updateInlineControlPoints() setting variable length to " + l);
724                 icp.setLength(l);
725
726                 icp.setWorldPosition(new Vector3d(beginPos));
727         }
728
729         private static void ppNoOffset(UpdateStruct2 u) throws Exception {
730                 if (DEBUG)
731                         System.out.println("PipingRules.ppNoOffset() " + u);
732                 Vector3d offset = new Vector3d();
733                 if (u.hasOffsets) {
734                         u.dir.normalize();
735                         for (PipeControlPoint icp : u.list) {
736                                 if (icp.isOffset()) {
737                                         offset.add(icp.getSizeChangeOffsetVector(u.dir));
738                                 } else if (icp.isDualSub())
739                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
740                         }
741                 }
742                 u.offset = offset;
743                 checkExpandPathLeg(u, PathLegUpdateType.NONE);
744         }
745
746         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 {
747                 if (DEBUG)
748                         System.out.println("PipingRules.ppNoDir() " + start + " " + end + " " + iter + " " + toRemove.size());
749                 // FIXME : extra loop (dir should be calculated here)
750                 Vector3d dir = new Vector3d();
751                 Vector3d offset = new Vector3d();
752                 hasOffsets = calculateOffset(startPoint, endPoint, list, dir, offset);
753                 ppNoOffset(new UpdateStruct2(start, startPoint, list, end, endPoint, dir, null, hasOffsets, iter, reversed, toRemove, updated));
754         }
755
756         private static void checkExpandPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
757                 checkExpandPathLeg(u, lengthChange, u.updated.isInline() && u.updated.isOffset());
758         }
759         
760         private static void checkExpandPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange, boolean updateEnds) throws Exception {
761                 if (DEBUG)
762                         System.out.println("PipingRules.checkExpandPathLeg() " + u + " " + lengthChange);
763                 if (lengthChange != PathLegUpdateType.NONE) {
764                         // FIXME : turns cannot be checked before inline cps are updated,
765                         // since their position affects calculation of turns
766                         processPathLeg(u, updateEnds, false);
767                         int type = checkTurns(u, lengthChange);
768                         if (type == REMOVE_NONE) {
769                                 processPathLeg(u, updateEnds, true);
770                         } else {
771                                 expandPathLeg(u, type);
772                         }
773                 } else {
774                         processPathLeg(u, updateEnds, true);
775                 }
776         }
777
778         private static void updateDirectedPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
779                 if (DEBUG)
780                         System.out.println("PipingRules.updateDirectedPipeRun() " + u + " " + lengthChange);
781                 PipeControlPoint dcp;
782                 PipeControlPoint other;
783                 boolean canMoveOther = false;
784                 boolean dcpStart = false;
785                 boolean inlineEnd = false;
786                 Vector3d position;
787                 if (u.start.isDirected()) {
788                         dcp = u.start;
789                         other = u.end;
790                         position = u.startPoint;
791                         dcpStart = true;
792                         if (!u.reversed)
793                                 canMoveOther = true;
794                         inlineEnd = u.end.isInline();
795                                 
796                 } else {
797                         dcp = u.end;
798                         other = u.start;
799                         position = u.endPoint;
800                         if (u.reversed)
801                                 canMoveOther = true;
802                         inlineEnd = u.start.isInline();
803                 }
804
805                 Vector3d directedDirection = dcp.getDirection();
806                 Point3d directedEndPoint = new Point3d(u.endPoint);
807                 if (u.hasOffsets)
808                         directedEndPoint.add(u.offset);
809
810                 double mu[] = new double[2];
811
812                 Vector3d closest;
813                 Vector3d t = new Vector3d();
814
815                 if (dcpStart) {
816                         closest = MathTools.closestPointOnStraight(directedEndPoint, u.startPoint, directedDirection, mu);
817                         t.sub(closest, directedEndPoint);
818                 } else {
819                         closest = MathTools.closestPointOnStraight(u.startPoint, directedEndPoint, directedDirection, mu);
820                         t.sub(closest, u.startPoint);
821                 }
822
823                 double distance = t.length();
824                 boolean aligned = (distance < ALLOWED_OFFSET);
825                 if (aligned) {
826                         checkExpandPathLeg(u, lengthChange, inlineEnd);
827                         
828                 } else {
829                         if (u.iter > 0) {
830                                 backIter(u);
831                         } else {
832                                 PipeControlPoint nextToMoved;
833
834                                 if (u.list.size() > 0)
835                                         if (dcpStart)
836                                                 nextToMoved = u.list.get(0);
837                                         else
838                                                 nextToMoved = u.list.get(u.list.size() - 1);
839                                 else if (dcpStart)
840                                         nextToMoved = u.end;
841                                 else
842                                         nextToMoved = u.start;
843                                 if (other.isVariableAngle()) {
844
845                                         // TODO calculate needed space from next run end.
846                                         if (mu[0] < 1.0) {
847                                                 if (dcpStart) {
848                                                         closest.set(u.startPoint);
849                                                 } else {
850                                                         closest.set(u.endPoint);
851                                                 }
852                                                 Vector3d v = new Vector3d(directedDirection);
853                                                 v.scale(spaceForTurn(other));
854                                                 closest.add(v);
855                                         }
856
857                                         if (canMoveOther) {
858                                                 if (DEBUG)
859                                                         System.out.println("PipingRules.updateDirectedPipeRun() moved end " + other + " to " + closest);
860                                                 other.setWorldPosition(closest);
861                                                 if (dcpStart) {
862                                                         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));
863                                                         if (u.end.getNext() != null)
864                                                                 updatePathLegNext(u.end, u.updated, PathLegUpdateType.NEXT);
865                                                 } else {
866                                                         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));
867                                                         if (u.start.getPrevious() != null)
868                                                                 updatePathLegPrev(u.start, u.updated, PathLegUpdateType.PREV);
869                                                 }
870                                         } else {
871                                                 // TODO : calculate needed space from next run end.
872                                                 if (allowInsertRemove)
873                                                         insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
874                                                         
875                                                 else
876                                                         triedIR = true;
877                                         }
878                                 } else if (other.isNonDirected() && other.getParentPoint() != null) {
879                                         // FIXME : this code was for updating branches
880                                         Vector3d bintersect = new Vector3d();
881                                         PipeControlPoint bcp = other.getParentPoint();
882                                         if (bcp != null && canMoveOther) {
883                                                 Point3d bstart = new Point3d();
884                                                 Point3d bend = new Point3d();
885                                                 Vector3d bdir = new Vector3d();
886                                                 bcp.getInlineControlPointEnds(bstart, bend, bdir);
887                                                 Vector3d nintersect = new Vector3d();
888
889                                                 MathTools.intersectStraightStraight(position, directedDirection, bend, bdir, nintersect, bintersect, mu);
890                                                 Vector3d dist = new Vector3d(nintersect);
891                                                 dist.sub(bintersect);
892                                                 canMoveOther = mu[1] > 0.0 && mu[1] < 1.0 && dist.lengthSquared() < 0.01;
893                                         } else {
894                                                 // TODO : endControlPoints are undirected: calculcate
895                                                 // correct position for it
896                                                 throw new UnsupportedOperationException("not implemented");
897                                         }
898                                         if (canMoveOther) {
899                                                 if (DEBUG)
900                                                         System.out.println("PipingRules.updateDirectedPipeRun() moved end " + other + " to " + bintersect);
901                                                 // is required branch position is in possible range
902                                                 bcp.setWorldPosition(bintersect);
903                                                 if (dcpStart) {
904                                                         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);
905                                                 } else {
906                                                         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);
907                                                 }
908                                         } else {
909                                                 // branch cannot be moved into right position, new turn
910                                                 // / elbow must be inserted
911                                                 if (allowInsertRemove)
912                                                         insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
913                                                 else
914                                                         triedIR = true;
915                                         }
916
917                                 } else { // assume that control point cannot be moved, but can
918                                                         // be rotated
919                                         if (allowInsertRemove)
920                                                 insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
921                                         else
922                                                 triedIR = true;
923                                 }
924                         }
925                 }
926                 
927                 
928         }
929
930         private static void updateDualDirectedPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
931                 if (DEBUG)
932                         System.out.println("PipingRules.updateDualDirectedPipeRun() " + u + " " + lengthChange);
933                 
934                 PipeControlPoint dcp1 = u.start;
935                 PipeControlPoint dcp2 = u.end;
936                 Point3d position1 = new Point3d(u.startPoint);
937                 Point3d position2 = new Point3d(u.endPoint);
938                 Point3d position1offset = new Point3d(position1);
939                 position1offset.sub(u.offset);
940                 Point3d position2offset = new Point3d(position2);
941                 position2offset.add(u.offset);
942                 Vector3d dir1 = dcp1.getDirection();
943                 Vector3d dir2 = dcp2.getDirection();
944                 Vector3d p1 = MathTools.closestPointOnStraight(position1offset, position2, dir2);
945                 Vector3d p2 = MathTools.closestPointOnStraight(position2offset, position1, dir1);
946                 double d1 = position1.distance(new Point3d(p1));
947                 double d2 = position2.distance(new Point3d(p2));
948
949                 boolean aligned = (d1 < ALLOWED_OFFSET && d2 < ALLOWED_OFFSET);
950                 if (aligned) {
951                         processPathLeg(u);
952                 } else {
953                         if (u.iter > 0) {
954                                 backIter(u);
955                         } else if (allowInsertRemove){
956                                 PipeControlPoint dcp;
957                                 PipeControlPoint next;
958                                 if (!u.reversed) {
959                                         dcp = dcp1;
960                                         if (u.list.size() > 0)
961                                                 next = u.list.get(0);
962                                         else
963                                                 next = dcp2;
964                                 } else {
965                                         dcp = dcp2;
966                                         if (u.list.size() > 0)
967                                                 next = u.list.get(u.list.size() - 1);
968                                         else
969                                                 next = dcp1;
970                                 }
971                                 
972                                 p1 = dcp.getWorldPosition();
973                                 // FIXME: calculate position of the elbows properly.
974                                 if (!u.reversed)
975                                         p1.add(dir1);
976                                 else
977                                         p1.add(dir2);
978
979                                 if (!u.reversed)
980                                         p2 = MathTools.closestPointOnStraight(new Point3d(p1), position2, dir2);
981                                 else
982                                         p2 = MathTools.closestPointOnStraight(new Point3d(p1), position1, dir1);
983
984                                 
985                                 PipeControlPoint tcp1 = insertElbow(dcp, next, p1);
986                                 PipeControlPoint tcp2 = insertElbow(tcp1, next, p2);
987
988                                 if (DEBUG)
989                                         System.out.println("PipingRules.updateDualDirectedPipeRun() created two turns " + tcp1 + " " + tcp2);
990
991                                 if (!u.reversed) {
992                                         Vector3d dd = new Vector3d(p2);
993                                         dd.sub(p1);
994                                         dir2.negate();
995                                         updatePathLegNext(u.start, u.updated, PathLegUpdateType.NONE);
996                                         updatePathLegNext(tcp1, u.updated, PathLegUpdateType.NONE);
997                                         if (!u.reversed)
998                                                 updatePathLegNext(tcp2, u.updated, PathLegUpdateType.NONE);
999                                         else
1000                                                 updatePathLegPrev(tcp2, u.updated, PathLegUpdateType.NONE);
1001                                 } else {
1002                                         Vector3d dd = new Vector3d(p1);
1003                                         dd.sub(p2);
1004                                         dir2.negate();
1005                                         updatePathLegNext(tcp1, u.updated, PathLegUpdateType.NONE);
1006                                         updatePathLegNext(tcp2, u.updated, PathLegUpdateType.NONE);
1007                                         if (!u.reversed)
1008                                                 updatePathLegNext(u.start, u.updated, PathLegUpdateType.NONE);
1009                                         else
1010                                                 updatePathLegPrev(u.start, u.updated, PathLegUpdateType.NONE);
1011                                 }
1012                         } else {
1013                                 triedIR = true;
1014                         }
1015                 }
1016                 
1017         }
1018         
1019         private static double spaceForTurn(PipeControlPoint tcp) {
1020                 // TODO : this returns now space for 90 deg turn.
1021                 // The challenge: position of tcp affects the turn angle, which then affects the required space. Perhaps we need to iterate...
1022                 // Additionally, if the path legs contain offset, using just positions of opposite path leg ends is not enough,    
1023                 return tcp.getPipeRun().getTurnRadius();
1024         }
1025
1026         private static void insertElbowUpdate(UpdateStruct2 u, PipeControlPoint dcp, PipeControlPoint next, boolean dcpStart, Vector3d position, Vector3d directedDirection) throws Exception{
1027
1028                 
1029 //              Vector3d closest = new Vector3d(position);
1030 //              closest.add(directedDirection);
1031                 
1032                 PipeControlPoint tcp = null;
1033                 Vector3d closest;
1034                 if (dcpStart) {
1035                         closest = MathTools.closestPointOnStraight(next.getWorldPosition(), position, directedDirection);
1036                         tcp = insertElbow(dcp, next, closest);
1037                 } else {
1038                         closest = MathTools.closestPointOnStraight(dcp.getWorldPosition(), position, directedDirection);
1039                         tcp = insertElbow(next, dcp, closest);
1040                 }
1041                 // TODO properly calculate required distance between start and inserted elbow.
1042                 double d = MathTools.distance(position, closest);
1043                 double s = spaceForTurn(tcp);
1044                 if (d < s)  {
1045                         d = s - d;
1046                         Vector3d p = new Vector3d(directedDirection);
1047                         p.scale(d);
1048                         p.add(closest);
1049                         tcp.setPosition(p);
1050                         closest = p;
1051                 }
1052                 
1053                 
1054
1055                 if (DEBUG)
1056                         System.out.println("PipingRules.updateDirectedPipeRun() inserted " + tcp);
1057
1058                 if (dcpStart) {
1059                         // update pipe run from new turn to other end
1060                         ppNoDir(tcp, new Vector3d(closest), u.list, u.end, u.endPoint, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated);
1061                         // update pipe run from directed to new turn
1062                         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));
1063                 } else {
1064                         // update pipe run from other end to new turn
1065                         ppNoDir(u.start, u.startPoint, u.list, tcp, new Vector3d(closest), u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated);
1066                         // update pipe run from new turn to directed
1067                         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));
1068                 }
1069         }
1070
1071         /**
1072          * Checks if turns can be removed (turn angle near zero)
1073          */
1074         private static int checkTurns(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
1075                 if (DEBUG)
1076                         System.out.println("PipingRules.checkTurns() " + u.start + " " + u.end);
1077                 boolean startRemoved = false;
1078                 boolean endRemoved = false;
1079                 if (u.start.isVariableAngle()) {
1080                         // this won't work properly if inline control points are not updated
1081                         PipeControlPoint startPrev = u.start.getPrevious();
1082                         if (startPrev != null) {
1083                                 double a;
1084                                 if (!u.hasOffsets) {
1085                                         a = updateTurnControlPointTurn(u.start, startPrev, u.end);
1086                                 } else {
1087                                         Vector3d ep = new Vector3d(u.endPoint);
1088                                         ep.sub(u.offset);
1089                                         a = updateTurnControlPointTurn(u.start, u.startPoint, startPrev.getPosition(), ep);
1090
1091                                 }
1092                                 if (a < MIN_TURN_ANGLE && u.start.isDeletable())
1093                                         startRemoved = true;
1094                                 else if (lengthChange == PathLegUpdateType.PREV || lengthChange == PathLegUpdateType.PREV_S) {
1095                                         PathLegUpdateType type;
1096                                         if (lengthChange == PathLegUpdateType.PREV_S)
1097                                                 type = PathLegUpdateType.PREV;
1098                                         else
1099                                                 type = PathLegUpdateType.NONE;
1100                                         updatePathLegPrev(u.start, u.start, type);
1101                                 }
1102                         }
1103                 }
1104                 if (u.end.isVariableAngle()) {
1105
1106                         PipeControlPoint endNext = u.end.getNext();
1107                         if (endNext != null) {
1108                                 double a;
1109                                 if (!u.hasOffsets) {
1110                                         a = updateTurnControlPointTurn(u.end, u.start, endNext);
1111                                 } else {
1112                                         Vector3d sp = new Vector3d(u.startPoint);
1113                                         sp.add(u.offset);
1114                                         a = updateTurnControlPointTurn(u.end, u.endPoint, sp, endNext.getPosition());
1115                                 }
1116                                 if (a < MIN_TURN_ANGLE && u.end.isDeletable())
1117                                         endRemoved = true;
1118                                 else if (lengthChange == PathLegUpdateType.NEXT || lengthChange == PathLegUpdateType.NEXT_S) {
1119                                         PathLegUpdateType type;
1120                                         if (lengthChange == PathLegUpdateType.NEXT_S)
1121                                                 type = PathLegUpdateType.NEXT;
1122                                         else
1123                                                 type = PathLegUpdateType.NONE;
1124                                         updatePathLegNext(u.end, u.end, type);
1125                                 }
1126                         }
1127                 }
1128                 if (DEBUG)
1129                         System.out.println("PipingRules.checkTurns() res " + startRemoved + " " + endRemoved);
1130                 if (!startRemoved && !endRemoved)
1131                         return REMOVE_NONE;
1132                 if (startRemoved && endRemoved)
1133                         return REMOVE_BOTH;
1134                 if (startRemoved)
1135                         return REMOVE_START;
1136                 return REMOVE_END;
1137         }
1138
1139         /**
1140          * Expands piperun search over turns that are going to be removed
1141          * 
1142          */
1143         private static void expandPathLeg(UpdateStruct2 u, int type) throws Exception {
1144                 if (DEBUG)
1145                         System.out.println("PipingRules.expandPipeline " + u.start + " " + u.end);
1146                 ArrayList<PipeControlPoint> newList = new ArrayList<PipeControlPoint>();
1147                 switch (type) {
1148                 case REMOVE_NONE:
1149                         throw new RuntimeException("Error in piping rules");
1150                 case REMOVE_START:
1151                         u.toRemove.add(new ExpandIterInfo(u.start, REMOVE_START));
1152                         u.start = u.start.findPreviousEnd();
1153                         u.startPoint = u.start.getPosition();
1154                         u.start.findNextEnd(newList);
1155                         newList.addAll(u.list);
1156                         u.list = newList;
1157                         break;
1158                 case REMOVE_END:
1159                         u.toRemove.add(new ExpandIterInfo(u.end, REMOVE_END));
1160                         u.end = u.end.findNextEnd(newList);
1161                         u.endPoint = u.end.getPosition();
1162                         u.list.addAll(newList);
1163                         break;
1164                 case REMOVE_BOTH:
1165                         u.toRemove.add(new ExpandIterInfo(u.start, u.end));
1166                         u.start = u.start.findPreviousEnd();
1167                         u.startPoint = u.start.getPosition();
1168                         u.start.findNextEnd(newList);
1169                         newList.addAll(u.list);
1170                         u.list = newList;
1171                         newList = new ArrayList<PipeControlPoint>();
1172                         u.end = u.end.findNextEnd(newList);
1173                         u.endPoint = u.end.getPosition();
1174                         u.list.addAll(newList);
1175                         break;
1176                 default:
1177                         throw new RuntimeException("Error in piping rules");
1178
1179                 }
1180                 u.offset = new Vector3d();
1181                 if (u.hasOffsets) {
1182                         u.dir.normalize();
1183                         for (PipeControlPoint icp : u.list) {
1184                                 if (icp.isOffset()) {
1185                                         u.offset.add(icp.getSizeChangeOffsetVector(u.dir));
1186                                 } else if (icp.isDualSub())
1187                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1188                         }
1189                 }
1190                 if (DEBUG)
1191                         System.out.println("PipingRules.expandPipeline expanded " + u.start + " " + u.end);
1192                 u.iter++;
1193                 updatePathLeg(u, PathLegUpdateType.NONE);
1194         }
1195
1196         /**
1197          * reverts one iteration of turn removing back)
1198          */
1199         private static void backIter(UpdateStruct2 u) throws Exception {
1200
1201                 if (DEBUG)
1202                         System.out.println("PipingRules.backIter" + u.start + " " + u.end);
1203                 if (u.iter == 0)
1204                         throw new RuntimeException("Error in piping rules");
1205                 ExpandIterInfo info = u.toRemove.get(u.toRemove.size() - 1);
1206                 u.toRemove.remove(u.toRemove.size() - 1);
1207                 if (info.getType() == REMOVE_START || info.getType() == REMOVE_BOTH) {
1208                         while (u.list.size() > 0) {
1209                                 PipeControlPoint icp = u.list.get(0);
1210                                 if (icp.getPrevious().equals(info.getStart()))
1211                                         break;
1212                                 u.list.remove(icp);
1213                         }
1214                         u.start = info.getStart();
1215                 }
1216                 if (info.getType() == REMOVE_END || info.getType() == REMOVE_BOTH) {
1217                         while (u.list.size() > 0) {
1218                                 PipeControlPoint icp = u.list.get(u.list.size() - 1);
1219                                 if (icp.getNext().equals(info.getEnd()))
1220                                         break;
1221                                 u.list.remove(icp);
1222                         }
1223                         u.end = info.getEnd();
1224                 }
1225                 u.offset = new Vector3d();
1226                 if (u.hasOffsets) {
1227                         u.dir.normalize();
1228                         for (PipeControlPoint icp : u.list) {
1229                                 if (icp.isOffset()) {
1230                                         u.offset.add(icp.getSizeChangeOffsetVector(u.dir));
1231                                 } else if (icp.isDualSub())
1232                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1233                         }
1234                 }
1235                 processPathLeg(u);
1236
1237         }
1238
1239         /**
1240          * Processes pipe run (removes necessary turns and updates run ends)
1241          */
1242         // private static void processPathLeg(PipeControlPoint start, Point3d
1243         // startPoint,ArrayList<InlineControlPoint> list, PipeControlPoint
1244         // end,Point3d endPoint, Vector3d dir,Vector3d offset, boolean
1245         // hasOffsets,int iter, boolean reversed, ArrayList<ExpandIterInfo>
1246         // toRemove) throws TransactionException {
1247
1248         private static void processPathLeg(UpdateStruct2 u) throws Exception {
1249                 if (DEBUG)
1250                         System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1251                 processPathLeg(u, true, true);
1252         }
1253
1254         private static void processPathLeg(UpdateStruct2 u, boolean updateEnds, boolean updateInline) throws Exception {
1255                 if (DEBUG)
1256                         System.out.println("PipingRules.processPathLeg " + (updateEnds ? "ends " : "") + (updateInline ? "inline " : "") + u.start + " " + u.end);
1257
1258                 if (u.toRemove.size() > 0) {
1259                         for (ExpandIterInfo info : u.toRemove) {
1260                                 if (info.getStart() != null) {
1261                                         if (DEBUG)
1262                                                 System.out.println("PipingRules.processPathLeg removing start " + info.getStart());
1263                                         info.getStart()._remove();
1264                                 }
1265                                 if (info.getEnd() != null) {
1266                                         if (DEBUG)
1267                                                 System.out.println("PipingRules.processPathLeg removing end " + info.getEnd());
1268                                         info.getEnd()._remove();
1269                                 }
1270                         }
1271                         // ControlPointTools.removeControlPoint may remove mo0re than one
1272                         // CP;
1273                         // we must populate inline CP list again.
1274                         u.list.clear();
1275                         u.start.findNextEnd( u.list);
1276                 }
1277                 // FIXME : inline CPs are update twice because their positions must be
1278                 // updated before and after ends.
1279                 updateInlineControlPoints(u, false);
1280                 
1281                 if (updateEnds) {
1282                         if (u.start.isTurn()) {
1283                                 updateTurnControlPointTurn(u.start, u.start.getPrevious(), u.start.getNext());
1284 //                              updatePathLegPrev(u.start, u.start, PathLegUpdateType.NONE);
1285                         } else if (u.start.isEnd()) {
1286                                 updateEndComponentControlPoint(u.start, u.startPoint, u.endPoint);
1287                         } else if (u.start.isInline()) {
1288                                 updateControlPointOrientation(u.start);
1289                         }
1290                         if (u.end.isTurn()) {
1291                                 updateTurnControlPointTurn(u.end, u.end.getPrevious(), u.end.getNext());
1292 //                              updatePathLegNext(u.end, u.end, PathLegUpdateType.NONE);
1293                         } else if (u.end.isEnd()) {
1294                                 updateEndComponentControlPoint(u.end, u.startPoint, u.endPoint);
1295                         } else if (u.end.isInline()) {
1296                                 updateControlPointOrientation(u.end);
1297                         }
1298
1299                 } else {
1300                         if (u.start.isEnd()) {
1301                                 updateEndComponentControlPoint(u.start, u.startPoint, u.endPoint);
1302                         }
1303                         if (u.end.isEnd()) {
1304                                 updateEndComponentControlPoint(u.end, u.startPoint, u.endPoint);
1305                         }
1306                 }
1307                 if (updateInline)
1308                         updateInlineControlPoints(u, true);
1309
1310         }
1311
1312         /**
1313          * Processes pipe run and recalculates offset
1314          */
1315         // private static void processPathLeg(PipeControlPoint start, Point3d
1316         // startPoint,ArrayList<InlineControlPoint> list, PipeControlPoint
1317         // end,Point3d endPoint, Vector3d dir, boolean hasOffsets,int iter, boolean
1318         // reversed, ArrayList<ExpandIterInfo> toRemove) throws TransactionException
1319         // {
1320         private static void processPathLegNoOffset(UpdateStruct2 u) throws Exception {
1321                 if (DEBUG)
1322                         System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1323                 Vector3d offset = new Vector3d();
1324                 if (u.hasOffsets) {
1325                         u.dir.normalize();
1326                         for (PipeControlPoint icp : u.list) {
1327                                 if (icp.isOffset()) {
1328                                         offset.add(icp.getSizeChangeOffsetVector(u.dir));
1329                                 } else if (icp.isDualSub()) {
1330                                         ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1331                                 }
1332                         }
1333                 }
1334                 processPathLeg(u);
1335         }
1336
1337         private static void updateOffsetPoint(PipeControlPoint sccp, Vector3d offset) {
1338                 Vector3d world = sccp.getWorldPosition();
1339                 world.add(offset);
1340                 PipeControlPoint ocp = sccp.getSubPoint().iterator().next();
1341                 ocp.setWorldPosition(world);
1342         }
1343
1344         /**
1345          * Updates InlineControlPoints position when straight pipe's end(s) have
1346          * been changed)
1347          * 
1348          * @param pipeline
1349          * @param icp
1350          * @param nextPoint
1351          * @param prevPoint
1352          */
1353         private static void updateInlineControlPoint(PipeControlPoint icp, Vector3d prev, Vector3d next,  Vector3d dir) {
1354                 if (DEBUG)
1355                         System.out.println("PipingRules.updateInlineControlPoint() " + icp);
1356
1357                 Vector3d inlinePoint = icp.getWorldPosition();
1358                 Vector3d prevPoint = new Vector3d(prev);
1359                 Vector3d nextPoint = new Vector3d(next);
1360                 if (!icp.isVariableLength()) {
1361                         // Reserve space for fixed length components. 
1362                         MathTools.mad(prevPoint, dir, icp.getInlineLength());
1363                         MathTools.mad(nextPoint, dir, -icp.getInlineLength());
1364                         if (MathTools.distance(prevPoint, nextPoint) < ALLOWED_OFFSET) {
1365                                 prevPoint = prev;
1366                                 nextPoint = next;
1367                         }
1368                 }
1369                 boolean canCalc = MathTools.distance(prevPoint, nextPoint) > ALLOWED_OFFSET;
1370                 if (DEBUG)
1371                         System.out.print("InlineControlPoint update " + icp + " " + inlinePoint + " " + prevPoint + " " + nextPoint);
1372                 Vector3d newInlinePoint = null;
1373                 if (canCalc) {
1374                         boolean branchUpdate = false;
1375                         PipeControlPoint becp = null;
1376                         for (PipeControlPoint pcp : icp.getSubPoint())
1377                                 if (pcp.isNonDirected()) {
1378                                         branchUpdate = true;
1379                                         becp = pcp;
1380                                         break;
1381                                 }
1382         
1383                         if (DUMMY || !branchUpdate) {
1384                                 newInlinePoint = MathTools.closestPointOnEdge(new Vector3d(inlinePoint), prevPoint, nextPoint);
1385                                 
1386                         } else {
1387         
1388                                 // FIXME : can only handle one branch
1389                                 PipeControlPoint p = null;
1390                                 if (becp.getNext() != null) {
1391                                         p = becp.findNextEnd();
1392                                 } else if (becp.getPrevious() != null) {
1393                                         p = becp.findPreviousEnd();
1394                                 }
1395                                 if (p == null) {
1396                                         newInlinePoint = MathTools.closestPointOnEdge(new Vector3d(inlinePoint), prevPoint, nextPoint);
1397                                 } else if (canCalc){
1398                                         Vector3d branchLegEnd = p.getWorldPosition();
1399                                         Vector3d dir2 = new Vector3d(inlinePoint);
1400                                         dir2.sub(branchLegEnd);
1401                                         Vector3d dir1 = new Vector3d(nextPoint);
1402                                         dir1.sub(prevPoint);
1403                                         newInlinePoint = new Vector3d();
1404                                         double mu[] = new double[2];
1405                                         MathTools.intersectStraightStraight(new Vector3d(prevPoint), dir1, new Vector3d(branchLegEnd), dir2, newInlinePoint, new Vector3d(), mu);
1406                                         if (DEBUG)
1407                                                 System.out.println(mu[0]);
1408                                         // FIXME : reserve space
1409                                         if (mu[0] < 0.0) {
1410                                                 newInlinePoint = new Vector3d(prevPoint);
1411                                         } else if (mu[0] > 1.0) {
1412                                                 newInlinePoint = new Vector3d(nextPoint);
1413                                         }
1414                                 }
1415                         }
1416                 } else {
1417                         // prevPoint == nextPoint
1418                         newInlinePoint = new Vector3d(prevPoint);
1419                 }
1420                 if (DEBUG)
1421                         System.out.println(" " + newInlinePoint);
1422
1423                 icp.setWorldPosition(newInlinePoint);
1424                 updateControlPointOrientation(icp);
1425         }
1426
1427         /**
1428          * Updates InlineControlPoints position when straight pipe's end(s) have
1429          * been changed)
1430          * 
1431          * @param pipeline
1432          * @param icp
1433          * @param nextPoint
1434          * @param prevPoint
1435          */
1436         private static void updateEndComponentControlPoint(PipeControlPoint ecp, Vector3d start, Vector3d end) throws Exception {
1437                 if (DEBUG)
1438                         System.out.println("PipingRules.updateEndComponentControlPoint() " + ecp);
1439                 // PipeControlPoint next = ecp.getNext();
1440                 // PipeControlPoint prev = ecp.getPrevious();
1441                 // if (next != null) {
1442                 // end = G3DTools.getPoint(next.getLocalPosition());
1443                 // start = G3DTools.getPoint(ecp.getLocalPosition());
1444                 // } else if (prev != null) {
1445                 // end = G3DTools.getPoint(ecp.getLocalPosition());
1446                 // start = G3DTools.getPoint(prev.getLocalPosition());
1447                 // } else {
1448                 // // TODO : warning?
1449                 // return;
1450                 // }
1451                 // Vector3d dir = new Vector3d (end);
1452                 // dir.sub(start);
1453                 // dir.normalize();
1454                 // G3DTools.setTuple(ecp.getDirection(), dir);
1455                 if (!ecp.isFixed())
1456                         updateControlPointOrientation(ecp);
1457
1458                 for (PipeControlPoint pcp : ecp.getSubPoint()) {
1459                         // TODO update position
1460                         updatePathLegEndControlPoint(pcp);
1461                 }
1462         }
1463
1464         private static void updateControlPointOrientation(PipeControlPoint pcp) {
1465                 // FIXME : hack to bypass variable length components orientation
1466 //              if (pcp.getAtMostOneRelatedObject(ProcessResource.g3dResource.HasWorldOrientation) == null)
1467 //                      return;
1468 //              if (pcp.rotationAngle == null)
1469 //                      return;
1470                 Double angleO = pcp.getRotationAngle();
1471                 double angle = 0.0;
1472                 if (angleO != null)
1473                         angle = angleO;
1474
1475                 Quat4d q = pcp.getControlPointOrientationQuat(angle);
1476                 pcp.setWorldOrientation(q);
1477         }
1478
1479         /**
1480          * Updates all branches when branch's position has been changed
1481          * 
1482          * @param bcp
1483          */
1484         private static void updateBranchControlPointBranches(PipeControlPoint bcp) throws Exception {
1485                 if (DEBUG)
1486                         System.out.println("PipingRules.updateBranchControlPointBranches() " + bcp);
1487                 if (bcp.isDualInline())
1488                         return;
1489                 Collection<PipeControlPoint> branches = bcp.getSubPoint();
1490                 if (branches.size() == 0) {
1491                         if (DEBUG)
1492                                 System.out.println("No Branches found");
1493                         return;
1494                 }
1495                 
1496                 for (PipeControlPoint pcp : branches) {
1497                         updatePathLegEndControlPoint(pcp);
1498                 }
1499         }
1500
1501         /**
1502          * Recalculates turn control point's internal data (turn angle and offset)
1503          * 
1504          * @param tcp
1505          * @param prev
1506          * @param next
1507          */
1508         private static double updateTurnControlPointTurn(PipeControlPoint tcp, PipeControlPoint prev, PipeControlPoint next) {
1509                 if (DEBUG)
1510                         System.out.println("PipingTools.updateTurnControlPointTurn()" + tcp);
1511                 if (next == null || prev == null)
1512                         return Math.PI; // FIXME : argh
1513                 Vector3d middlePoint = tcp.getWorldPosition();
1514                 Vector3d nextPoint = next.getWorldPosition();
1515                 Vector3d prevPoint = prev.getWorldPosition();
1516                 return updateTurnControlPointTurn(tcp, middlePoint, prevPoint, nextPoint);
1517         }
1518
1519         /**
1520          * Recalculates turn control point's internal data (turn angle and offset)
1521          * 
1522          * @param tcp
1523          * @param middlePoint
1524          * @param nextPoint
1525          * @param prevPoint
1526          */
1527         private static double updateTurnControlPointTurn(PipeControlPoint tcp, Vector3d middlePoint, Vector3d prevPoint, Vector3d nextPoint) {
1528
1529                 Vector3d dir1 = new Vector3d(middlePoint);
1530                 dir1.sub(prevPoint);
1531                 Vector3d dir2 = new Vector3d(nextPoint);
1532                 dir2.sub(middlePoint);
1533                 if (DEBUG)
1534                         System.out.println("PipingTools.updateTurnControlPointTurn " + tcp + " " + prevPoint + " " + middlePoint + " " + nextPoint);
1535                 return updateTurnControlPointTurn(tcp, dir1, dir2);
1536         }
1537
1538         private static double updateTurnControlPointTurn(PipeControlPoint tcp, Vector3d dir1, Vector3d dir2) {
1539                 double turnAngle = dir1.angle(dir2);
1540
1541                 double angle = Math.PI - turnAngle;
1542
1543                 Vector3d turnAxis = new Vector3d();
1544                 turnAxis.cross(dir1, dir2);
1545                 if (turnAxis.lengthSquared() > MathTools.NEAR_ZERO) {
1546                         double elbowRadius = tcp.getPipelineComponent().getPipeRun().getTurnRadius();
1547                         double R = elbowRadius / Math.tan(angle * 0.5);
1548                         
1549                         turnAxis.normalize();
1550                         tcp.setTurnAngle(turnAngle);
1551                         tcp.setLength(R);// setComponentOffsetValue(R);
1552                         tcp.setTurnAxis(turnAxis);
1553 //                      tcp.setPosition(tcp.getPosition());
1554                 } else {
1555                         turnAngle = 0.0;
1556                         tcp.setTurnAngle(0.0);
1557                         tcp.setLength(0.0);
1558                         tcp.setTurnAxis(MathTools.Y_AXIS);
1559                 }
1560                 updateControlPointOrientation(tcp);
1561                 if (DEBUG)
1562                         System.out.println("PipingTools.updateTurnControlPointTurn " + dir1 + " " + dir2 + " " + turnAngle + " " + turnAxis);
1563                 return turnAngle;
1564         }
1565         
1566         public static List<PipeControlPoint> getControlPoints(PipeRun pipeRun) {
1567                 List<PipeControlPoint> list = new ArrayList<PipeControlPoint>();
1568                 if (pipeRun.getControlPoints().size() == 0)
1569                         return list;
1570                 PipeControlPoint pcp = pipeRun.getControlPoints().iterator().next();
1571                 while (pcp.getPrevious() != null) {
1572                         PipeControlPoint prev = pcp.getPrevious();
1573                         if (prev.getPipeRun() != pipeRun)
1574                                 break;
1575                         pcp = prev;
1576                 }
1577                 if (pcp.isDualSub()) {
1578                         pcp = pcp.getParentPoint();
1579                 }
1580                 list.add(pcp);
1581                 while (pcp.getNext() != null) {
1582                         pcp = pcp.getNext();
1583                         if (pcp.getPipeRun() != pipeRun)
1584                                 break;
1585                         list.add(pcp);
1586                 }
1587                 return list;
1588         }
1589         
1590         public static void reverse(PipeRun pipeRun) {
1591                 List<PipeControlPoint> list = getControlPoints(pipeRun);
1592                 if (list.size() <= 1)
1593                         return; // nothing to do.
1594                 
1595                 for (int i = 0 ; i < list.size(); i++) {
1596                         boolean first = i == 0;
1597                         boolean last = i == list.size() - 1;
1598                         PipeControlPoint current = list.get(i);
1599                         PipeControlPoint currentSub = null;
1600                         if (current.isDualInline())
1601                                 currentSub = current.getSubPoint().get(0);
1602                         if (first) {
1603                                 PipeControlPoint next = list.get(i+1);
1604                                 if (next.isDualInline())
1605                                         next = next.getSubPoint().get(0);
1606                                 current.setNext(null);
1607                                 current.setPrevious(next);
1608                                 if (currentSub != null) {
1609                                         currentSub.setNext(null);
1610                                         currentSub.setPrevious(next);           
1611                                 }
1612                         } else if (last) {
1613                                 PipeControlPoint prev = list.get(i-1);
1614                                 
1615                                 current.setPrevious(null);
1616                                 current.setNext(prev);
1617                                 
1618                                 if (currentSub != null) {
1619                                         currentSub.setPrevious(null);
1620                                         currentSub.setNext(prev);               
1621                                 }
1622                         } else {
1623                                 PipeControlPoint prev = list.get(i-1);
1624                                 PipeControlPoint next = list.get(i+1);
1625                                 if (next.isDualInline())
1626                                         next = next.getSubPoint().get(0);
1627                                 
1628                                 
1629                                 current.setPrevious(next);
1630                                 current.setNext(prev);
1631                                 
1632                                 if (currentSub != null) {
1633                                         currentSub.setPrevious(next);
1634                                         currentSub.setNext(prev);               
1635                                 }
1636                                 
1637                         }
1638                 }
1639         }
1640         
1641         public static void merge(PipeRun run1, PipeRun r2) {
1642                 Map<PipeControlPoint, Vector3d> positions = new HashMap<PipeControlPoint, Vector3d>();
1643                 Map<PipeControlPoint, Quat4d> orientations = new HashMap<PipeControlPoint, Quat4d>();
1644                 for (PipeControlPoint pcp : r2.getControlPoints()) {
1645                         positions.put(pcp, pcp.getWorldPosition());
1646                         orientations.put(pcp, pcp.getWorldOrientation());
1647                 }
1648                 for (PipeControlPoint pcp : r2.getControlPoints()) {
1649                         r2.deattachChild(pcp);
1650                         run1.addChild(pcp);
1651                         PipelineComponent component = pcp.getPipelineComponent();
1652                         if (component != null) {
1653                                 if (!(component instanceof Nozzle)) {
1654                                         component.deattach();
1655                                         run1.addChild(component);
1656                                 } else {
1657                                         Nozzle n = (Nozzle)component;
1658                                         n.setPipeRun(run1);
1659                                 }
1660                         }
1661                 }
1662                 r2.remove();
1663                 
1664         }
1665         
1666         public static void validate(PipeRun pipeRun) {
1667                 if (pipeRun == null)
1668                         return;
1669                 Collection<PipeControlPoint> pcps = pipeRun.getControlPoints();
1670                 int count = 0;
1671                 for (PipeControlPoint pcp : pcps) {
1672                         if (pcp.getParentPoint() == null || pcp.getParentPoint().getPipeRun() != pipeRun)
1673                                 count++;
1674                 }
1675                 List<PipeControlPoint> runPcps = getControlPoints(pipeRun);
1676                 if (runPcps.size() != count) {
1677                         System.out.println("Run is not connected");
1678                 }
1679                 for (PipeControlPoint pcp : pcps) {
1680                         if (!pcp.isDirected() && pcp.getNext() == null && pcp.getPrevious() == null)
1681                                 System.out.println("Orphan undirected " + pcp);
1682                 }
1683                 for (PipeControlPoint pcp : pcps) {
1684                         if (pcp.getParentPoint() == null) {
1685                                 PipeControlPoint sub = null;
1686                                 if (pcp.isDualInline())
1687                                         sub = pcp.getSubPoint().get(0);
1688                                 PipeControlPoint next = pcp.getNext();
1689                                 PipeControlPoint prev = pcp.getPrevious();
1690                                 if (next != null) {
1691                                         if (!(next.getPrevious() == pcp || next.getPrevious() == sub)) {
1692                                                 System.out.println("Inconsistency between " + pcp + " -> " +next );
1693                                         }
1694                                 }
1695                                 if (prev != null) {
1696                                         PipeControlPoint prevParent = null;
1697                                         if (prev.isDualSub()) {
1698                                                 prevParent = prev.getParentPoint();
1699                                         } else if (prev.isDualInline()) {
1700                                                 System.out.println("Inconsistency between " + pcp + " <-- " +prev );
1701                                         }
1702                                         if (!(prev.getNext() == pcp && (prevParent == null || prevParent.getNext() == pcp))) {
1703                                                 System.out.println("Inconsistency between " + pcp + " <-- " +prev );
1704                                         }
1705                                 }
1706                         }
1707                 }
1708         }
1709         
1710         public static void splitVariableLengthComponent(PipelineComponent newComponent, InlineComponent splittingComponent, boolean assignPos) throws Exception{
1711                 assert(!splittingComponent.getControlPoint().isFixed());
1712                 assert(!(newComponent instanceof  InlineComponent && !newComponent.getControlPoint().isFixed()));
1713                 PipeControlPoint newCP = newComponent.getControlPoint();
1714                 PipeControlPoint splittingCP = splittingComponent.getControlPoint();
1715                 PipeControlPoint nextCP = splittingCP.getNext();
1716                 PipeControlPoint prevCP = splittingCP.getPrevious();
1717                 
1718                 /* there are many different cases to insert new component when
1719                    it splits existing VariableLengthinlineComponent.
1720             
1721                1. VariableLengthComponet is connected from both sides:
1722                   - insert new component between VariableLength component and component connected to it
1723                   - insert new VariableLengthComponent between inserted component and component selected in previous step
1724                 
1725                    2. VariableLengthComponent is connected from one side
1726                      - Use previous case or:
1727                      - Insert new component to empty end
1728                      - Insert new VariableLength component to inserted components empty end
1729                      
1730                    3. VariableLength is not connected to any component.
1731                      - Should not be possible, at least in current implementation.
1732                      - Could be done using second case
1733
1734                 */
1735                 
1736                 if (nextCP == null && prevCP == null) {
1737                         // this should not be possible
1738                         throw new RuntimeException("VariableLengthComponent " + splittingComponent + " is not connected to anything.");
1739                 }
1740                 double reservedLength = splittingComponent.getControlPoint().getLength();
1741                 double newLength = newComponent.getControlPoint().getLength();
1742                 
1743                 
1744                 Point3d next = new Point3d();
1745                 Point3d prev = new Point3d();
1746                 splittingCP.getInlineControlPointEnds(prev, next);
1747                 
1748                 Vector3d newPos = null;
1749                 if (assignPos) {
1750                         newPos = new Vector3d(prev);
1751                         Vector3d dir = new Vector3d(next);
1752                         dir.sub(prev);
1753                         dir.scale(0.5);
1754                         newPos.add(dir);
1755                         newComponent.setWorldPosition(newPos);
1756                 } else {
1757                         newPos = newComponent.getWorldPosition();
1758                 }
1759                 
1760                 
1761
1762                 Vector3d dir = new Vector3d(next);
1763                 dir.sub(prev);
1764                 dir.normalize();
1765                 dir.scale(newLength * 0.5);
1766                 Point3d vn = new Point3d(newPos);
1767                 Point3d vp = new Point3d(newPos);
1768                 vn.add(dir);
1769                 vp.sub(dir);
1770                 double ln = vn.distance(next);
1771                 double lp = vp.distance(prev);
1772                 vp.interpolate(prev, 0.5);
1773                 vn.interpolate(next, 0.5);
1774                 
1775                 
1776                 PipeControlPoint newVariableLengthCP = null;//insertStraight(pcp1, pcp2, pos, length);
1777                 if (nextCP == null) {
1778                         newCP.insert(splittingCP, Direction.NEXT);
1779                         newVariableLengthCP = insertStraight(newCP, Direction.NEXT, new Vector3d(vn), ln);
1780                         splittingCP.setWorldPosition(new Vector3d(vp));
1781 //                      ControlPointTools.setWorldPosition(splittingCP, vp);
1782 //                      splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, lp);
1783                 } else if (prevCP == null) {
1784                         newCP.insert(splittingCP, Direction.PREVIOUS);
1785                         newVariableLengthCP = insertStraight(newCP, Direction.PREVIOUS, new Vector3d(vp), lp);
1786                         splittingCP.setWorldPosition(new Vector3d(vn));
1787 //                      splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, ln);
1788                 } else {
1789                         newCP.insert(splittingCP, nextCP);
1790                         newVariableLengthCP = insertStraight(newCP, nextCP, new Vector3d(vn), ln);
1791                         splittingCP.setWorldPosition(new Vector3d(vp));
1792 //                      splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, lp);
1793                 }
1794                 positionUpdate(newCP);
1795
1796         }
1797         
1798         public static void addSizeChange(boolean reversed, PipeRun pipeRun, PipeRun other, InlineComponent reducer, PipeControlPoint previous, PipeControlPoint next) {
1799                 PipeControlPoint pcp = reducer.getControlPoint();
1800                 PipeControlPoint ocp = pcp.getSubPoint().get(0);
1801                 if (!reversed) {
1802                         String name = pipeRun.getUniqueName("Reducer");
1803                         reducer.setName(name);
1804                         pipeRun.addChild(reducer);
1805                         other.addChild(ocp);
1806                         reducer.setAlternativePipeRun(other);
1807                         
1808                         previous.setNext(pcp);
1809                         pcp.setPrevious(previous);
1810                         ocp.setPrevious(previous);
1811                         if (next != null) {
1812                                 pcp.setNext(next);
1813                                 ocp.setNext(next);
1814                                 next.setPrevious(ocp);
1815                         }
1816                 } else {
1817                         String name = other.getUniqueName("Reducer");
1818                         reducer.setName(name);
1819                         other.addChild(reducer);
1820                         pipeRun.addChild(ocp);
1821                         reducer.setAlternativePipeRun(pipeRun);
1822                         
1823                         if (next != null) {
1824                                 next.setNext(pcp);
1825                                 pcp.setPrevious(next);
1826                                 ocp.setPrevious(next);
1827                         }
1828                         pcp.setNext(previous);
1829                         ocp.setNext(previous);
1830                         previous.setPrevious(ocp);
1831                 }
1832         }
1833 }