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