]> gerrit.simantics Code Review - simantics/3d.git/blob - org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/PipeControlPoint.java
Allow insertion of reducers in the middle of pipe runs
[simantics/3d.git] / org.simantics.plant3d / src / org / simantics / plant3d / scenegraph / controlpoint / PipeControlPoint.java
1 package org.simantics.plant3d.scenegraph.controlpoint;
2
3 import java.util.ArrayList;
4 import java.util.Arrays;
5 import java.util.Collection;
6 import java.util.List;
7
8 import javax.vecmath.AxisAngle4d;
9 import javax.vecmath.Matrix3d;
10 import javax.vecmath.Point3d;
11 import javax.vecmath.Quat4d;
12 import javax.vecmath.Tuple3d;
13 import javax.vecmath.Vector3d;
14
15 import org.simantics.g3d.math.MathTools;
16 import org.simantics.g3d.property.annotations.GetPropertyValue;
17 import org.simantics.g3d.scenegraph.G3DNode;
18 import org.simantics.g3d.scenegraph.base.ParentNode;
19 import org.simantics.plant3d.scenegraph.IP3DNode;
20 import org.simantics.plant3d.scenegraph.Nozzle;
21 import org.simantics.plant3d.scenegraph.P3DRootNode;
22 import org.simantics.plant3d.scenegraph.PipeRun;
23 import org.simantics.plant3d.scenegraph.PipelineComponent;
24
25 import vtk.vtkRenderer;
26
27
28 public class PipeControlPoint extends G3DNode implements IP3DNode {
29
30         private static boolean DEBUG = false;
31
32         public enum PointType{INLINE,TURN,END};
33         public enum Direction{NEXT,PREVIOUS};
34         public enum PositionType {SPLIT,NEXT,PREVIOUS,PORT}
35
36         private PipelineComponent component;
37
38         private PointType type;
39         private boolean isFixed = true;        // In-line: fixed-length Turn: fixed-angle
40         private boolean isMod = false;         // Can user modify fixed value manually 
41         private boolean isRotate = false;      // rotates around path leg axis.
42         private boolean isReverse = false;     // definition direction can be swapped
43         private boolean isDeletable = true;    // can be removed by rules
44         private boolean isSizeChange = false;  // changes size of the pipe. The next control point / component is on different PipeRun
45         private boolean isSub = false;         // child point for offset / size change
46
47         private boolean disposed = false;
48         
49         public PipeControlPoint(PipelineComponent component) {
50                 this.component = component;
51                 if (component.getPipeRun() != null)
52                         component.getPipeRun().addChild(this);
53
54         }
55
56         public PipeControlPoint(PipelineComponent component, PipeRun piperun) {
57                 this.component = component;
58                 piperun.addChild(this);
59         }
60
61         @Override
62         public void update(vtkRenderer ren) {
63                 try {
64                         PipingRules.requestUpdate(this);
65                 } catch (Exception e) {
66                         e.printStackTrace();
67                 }
68
69         }
70
71         public PipeRun getPipeRun() {
72                 return (PipeRun)getParent();
73         }
74
75         public PipelineComponent getPipelineComponent() {
76                 return component;
77         }
78
79         public PointType getType() {
80                 return type;
81         }
82
83         public void setType(PointType type) {
84                 this.type = type;
85         }
86
87         @GetPropertyValue(name="Fixed",tabId="Debug",value="fixed")
88         public boolean isFixed() {
89                 return isFixed;
90         }
91
92         public void setFixed(boolean fixed) {
93                 this.isFixed = fixed;
94         }
95         
96         @GetPropertyValue(name="Mod",tabId="Debug",value="mod")
97         public boolean isMod() {
98         return isMod;
99     }
100     
101     public void setMod(boolean isMod) {
102         this.isMod = isMod;
103     }
104
105         @GetPropertyValue(name="Rotate",tabId="Debug",value="rotate")
106         public boolean isRotate() {
107                 return isRotate;
108         }
109
110         public void setRotate(boolean rotate) {
111                 this.isRotate = rotate;
112         }
113
114         @GetPropertyValue(name="Reverse",tabId="Debug",value="reverse")
115         public boolean isReverse() {
116                 return isReverse;
117         }
118
119         public void setReverse(boolean reverse) {
120                 this.isReverse = reverse;
121         }
122
123         public void setSub(boolean sub) {
124                 this.isSub = sub;
125         }
126
127         @GetPropertyValue(name="Deletable",tabId="Debug",value="deletable")
128         public boolean isDeletable() {
129                 return isDeletable;
130         }
131
132         public void setDeletable(boolean deletable) {
133                 this.isDeletable = deletable;
134         }
135
136         public boolean isPathLegEnd() {
137                 return type != PointType.INLINE;
138         }
139
140         public boolean isEnd() {
141                 return type == PointType.END;
142         }
143
144         public boolean isTurn() {
145                 return type == PointType.TURN;
146         }
147
148         public boolean isInline() {
149                 return type == PointType.INLINE;
150         }
151         
152         public boolean asPathLegEnd() {
153             // Ends and Turns are path leg ends by default, but also unconnected inline are path leg ends.
154             return isPathLegEnd() || getNext() == null || getPrevious() == null;
155         }
156
157         /**
158          * True for end components, if control point defines absolute position direction, which rules cannot modify. 
159          * This is typical for nozzles.
160          * @return
161          */
162         public boolean isDirected() {
163                 return isFixed && isEnd();
164         }
165
166         /**
167      * True for end components, if control is opposite to directed, and rules can modify position and orientation.
168      * This is typical for caps, and other end components.
169      * @return
170      */
171         public boolean isNonDirected() {
172                 return !isFixed && isEnd();
173         }
174
175         public boolean isVariableLength() {
176                 return !isFixed && isInline();
177         }
178         
179         /**
180          * Fixed length in-line component is such that piping rules cannot modify the length.
181          * @return
182          */
183         public boolean isFixedLength() {
184         return isFixed && isInline();
185     }
186
187         public boolean isVariableAngle() {
188                 return !isFixed && isTurn();
189         }
190         
191         /**
192          * Fixed angle turn component is such that piping rules cannot modify the angle.
193          * @return
194          */
195         public boolean isFixedAngle() {
196         return isFixed && isTurn();
197     }
198         
199         /**
200          * Does the turn behave like fixed angle?
201          * For variable angle turns, the turn angle is defined by connected components, and without them, we must handle the component as fixed angle. 
202          * @return
203          */
204         public boolean asFixedAngle() {
205         return isTurn() && (isFixed || next == null || previous == null);
206     }
207
208         public boolean isBranchEnd() {
209                 return isDeletable && isEnd();
210         }
211
212         public boolean isOffset() {
213                 return offset != null;
214         }
215
216         public boolean isDualSub() {
217                 return parent != null && isSub;
218         }
219
220         public boolean isDualInline() {
221                 return children.size() == 1 && children.get(0).isDualSub();
222         }
223
224         public boolean isAxial() {
225                 return isInline() && !isDualInline();
226         }
227
228         public boolean isSizeChange() {
229                 return isSizeChange;
230                 //              if (children.size() == 0)
231                 //                      return false;
232                 //              if (!isDualInline())
233                 //                      return false;
234                 //              return getPipeRun() != children.get(0).getPipeRun();
235         }
236
237         public void setSizeChange(boolean isSizeChange) {
238                 this.isSizeChange = isSizeChange;
239         }
240
241
242         private PipeControlPoint next;
243         private PipeControlPoint previous;
244
245         public PipeControlPoint getNext() {
246                 return next;
247         }
248
249         public PipeControlPoint getPrevious() {
250                 return previous;
251         }
252
253         public void setNext(PipeControlPoint next) {
254             if (isSub) {
255                 getParentPoint().setNext(next);
256                 return;
257             }
258             if (next != null && next.isDualSub())
259                 next = next.parent;
260             if (_setNext(next)) {
261                 for (PipeControlPoint pcp : children) {
262                 if (pcp.isSub)
263                     pcp._setNext(next);
264             }
265                 updateSubPoint();
266             }
267         }
268         
269         public void setPrevious(PipeControlPoint prev) {
270         if (isSub) {
271             getParentPoint().setPrevious(prev);
272             return;
273         }
274         if (prev != null && prev.isDualInline())
275             prev = prev.children.get(0);
276         if (_setPrevious(prev)) {
277             for (PipeControlPoint pcp : children) {
278                 if (pcp.isSub)
279                     pcp._setPrevious(prev);
280             }
281             updateSubPoint();
282         }
283     }
284         
285         protected boolean _setNext(PipeControlPoint next) {
286                 if (isEnd() && previous != null && next != null)
287                         throw new RuntimeException("End control points are allowed to have only one connection");
288                 if (next == this)
289                         throw new RuntimeException("Cannot connect to self");
290                 if (this.next == next)
291                         return false;
292                 if (DEBUG) System.out.println(this + " next " + next);
293                 if (next == null && isVariableAngle() && previous != null && !isRemoved()) {
294                     convertVariableAngleToFixed(Direction.NEXT);
295                 }
296                 this.next = next;
297                 if (component != null) {
298                         if (parent == null || isSub)
299                                 component.setNext(next != null ? next.component : null);
300                         else
301                                 component.setBranch0(next != null ? next.component : null);
302                         
303                 }
304                 return true;
305         }
306
307         protected boolean _setPrevious(PipeControlPoint previous) {
308                 if (isEnd() && next != null && previous != null)
309                         throw new RuntimeException("End control points are allowed to have only one connection");
310                 if (previous == this)
311                         throw new RuntimeException("Cannot connect to self");
312                 if (this.previous == previous)
313                         return false;
314                 if (DEBUG) System.out.println(this + " previous " + previous);
315                 if (previous == null && isVariableAngle() && next != null && !isRemoved()) {
316             convertVariableAngleToFixed(Direction.PREVIOUS);
317         }
318                 this.previous = previous;
319                 if (component != null) {
320                         if (parent == null || isSub)
321                                 component.setPrevious(previous != null ? previous.component : null);
322                         else
323                                 component.setBranch0(previous != null ? previous.component : null);
324                         updateSubPoint();
325                 }
326                 return true;
327         }
328         
329         private void convertVariableAngleToFixed(Direction direction) {
330             // We are removing reference, which transforms variable angle to fixed angle.
331         // Since fixed angle is defined differently, we need to calculate fixed angle parameters based on current data
332         // We need to calculate turnAngle and rotationAngle
333             Vector3d dirOut = getPathLegDirection(direction == Direction.NEXT ? Direction.NEXT : Direction.PREVIOUS);
334         Vector3d dir = getPathLegDirection(direction == Direction.NEXT ? Direction.PREVIOUS : Direction.NEXT);
335         if (dir == null || dirOut == null)
336             return;
337         dir.negate();
338         double angle = dir.angle(dirOut);
339         //super._setNext(null);
340         if (direction == Direction.NEXT)
341             next = null;
342         else
343             previous = null;
344         setRotationAngle(0.0);
345         setReversed(direction == Direction.NEXT ? false : true);
346         Vector3d dirOutN = getPathLegDirection(direction == Direction.NEXT ? Direction.NEXT : Direction.PREVIOUS);
347         dirOutN.normalize();
348         AxisAngle4d aa = new AxisAngle4d();
349         if (MathTools.createRotation(dirOutN, dirOut, dir, aa)) {
350             setRotationAngle(aa.angle);
351             setTurnAngle(angle);
352             if (DEBUG) System.out.println("convertToFixed " + dir + " " + dirOut + " " +dirOutN + " " +angle + " "+ aa.angle);
353         }
354         }
355
356         public PipeControlPoint parent;
357         public List<PipeControlPoint> children = new ArrayList<PipeControlPoint>();
358
359         public List<PipeControlPoint> getChildPoints() {
360                 return children;
361         }
362
363         public PipeControlPoint getParentPoint() {
364                 return parent;
365         }
366
367
368         private double length;
369         private Double turnAngle;
370         private Vector3d turnAxis;
371
372         private Double offset;
373         private Double rotationAngle;
374         private Boolean reversed;
375
376         @GetPropertyValue(name="Length",tabId="Debug",value="length")
377         public double getLength() {
378                 return length;
379         }
380
381         public void setLength(double l) {
382                 if (Double.isInfinite(l) || Double.isNaN(l)) {
383                         return;
384                 }
385                 if (Math.abs(this.length-l) < MathTools.NEAR_ZERO)
386                         return;
387                 this.length = l;
388                 firePropertyChanged("length");
389                 if (isDualInline())
390                     getDualSub().setLength(l);
391         }
392
393         @GetPropertyValue(name="Turn Angle",tabId="Debug",value="turnAngle")
394         public Double getTurnAngle() {
395                 return turnAngle;
396         }
397
398         @GetPropertyValue(name="Turn Axis",tabId="Debug",value="turnAxis")
399         public Vector3d getTurnAxis() {
400                 return turnAxis;
401         }
402
403         @GetPropertyValue(name="Offset",tabId="Debug",value="offset")
404         public Double getOffset() {
405                 return offset;
406         }
407
408         @GetPropertyValue(name="Rotation Angle",tabId="Debug",value="rotationAngle")
409         public Double getRotationAngle() {
410             if (isRotate || asFixedAngle())
411                 return rotationAngle;
412             return null;
413         }
414
415         @GetPropertyValue(name="Reversed",tabId="Debug",value="reversed")
416         public Boolean getReversed() {
417                 return reversed;
418         }
419
420         public boolean _getReversed() {
421                 if (reversed == null)
422                         return false;
423                 return reversed;
424         }
425
426         public void setTurnAngle(Double turnAngle) {
427                 if (turnAngle == null || Double.isInfinite(turnAngle) || Double.isNaN(turnAngle)) {
428                         return;
429                 }
430                 if (this.turnAngle != null && Math.abs(this.turnAngle-turnAngle) < MathTools.NEAR_ZERO)
431                         return;
432                 this.turnAngle = turnAngle;
433                 firePropertyChanged("turnAngle");
434         }
435
436         public void setTurnAxis(Vector3d turnAxis) {
437                 if (this.turnAxis != null && MathTools.equals(turnAxis, this.turnAxis))
438                         return;
439                 this.turnAxis = turnAxis;
440                 firePropertyChanged("turnAxis");
441         }
442
443         public void setOffset(Double offset) {
444                 if (Double.isInfinite(offset) || Double.isNaN(offset)) {
445                         return;
446                 }
447                 if (this.offset != null && Math.abs(this.offset-offset) < MathTools.NEAR_ZERO)
448                         return;
449                 this.offset = offset;
450                 firePropertyChanged("offset");
451         }
452
453         public void setRotationAngle(Double rotationAngle) {
454                 if (Double.isInfinite(rotationAngle) || Double.isNaN(rotationAngle)) {
455                         return;
456                 }
457                 if (this.rotationAngle != null && Math.abs(this.rotationAngle-rotationAngle) < MathTools.NEAR_ZERO)
458                         return;
459                 this.rotationAngle = rotationAngle;
460                 firePropertyChanged("rotationAngle");
461         }
462
463         public void setReversed(Boolean reversed) {
464                 this.reversed = reversed;
465                 firePropertyChanged("reversed");
466         }
467
468         public Vector3d getSizeChangeOffsetVector(Vector3d dir) {
469                 Quat4d q;
470                 if (rotationAngle == null)
471                         q = getControlPointOrientationQuat(dir, 0.0);
472                 else
473                         q = getControlPointOrientationQuat(dir, rotationAngle);
474                 Vector3d v = new Vector3d(0.0,offset,0.0);
475                 Vector3d offset = new Vector3d();
476                 MathTools.rotate(q, v, offset);
477                 return offset;
478         }
479
480         public Vector3d getSizeChangeOffsetVector() {
481                 Quat4d q;
482                 if (rotationAngle == null)
483                         q = getControlPointOrientationQuat(0.0);
484                 else
485                         q = getControlPointOrientationQuat(rotationAngle);
486                 Vector3d v = new Vector3d(0.0,offset,0.0);
487                 Vector3d offset = new Vector3d();
488                 MathTools.rotate(q, v, offset);
489                 return offset;
490         }
491
492         @GetPropertyValue(name="Next",tabId="Debug",value="next")
493         private String getNextString() {
494                 if (next == null)
495                         return null;
496                 return next.toString();
497         }
498
499         @GetPropertyValue(name="Previous",tabId="Debug",value="previous")
500         private String getPrevString() {
501                 if (previous == null)
502                         return null;
503                 return previous.toString();
504         }
505
506         @GetPropertyValue(name="Sub",tabId="Debug",value="sub")
507         private String getSubString() {
508                 if (children.size() == 0)
509                         return "";
510                 return Arrays.toString(children.toArray());
511         }
512
513         @GetPropertyValue(name="Type",tabId="Debug",value="type")
514         public String getTypeString() {
515                 return type.name();
516         }
517
518         public Quat4d getControlPointOrientationQuat(double angle) {
519
520                 if (turnAxis == null) {
521                         Vector3d dir = getPathLegDirection(Direction.NEXT);
522                         if (dir.lengthSquared() > MathTools.NEAR_ZERO)
523                                 dir.normalize();
524                         return getControlPointOrientationQuat(dir, angle);
525                 } else {
526                         Vector3d dir = getPathLegDirection(Direction.PREVIOUS);
527                         dir.negate();
528                         if (dir.lengthSquared() > MathTools.NEAR_ZERO)
529                                 dir.normalize();
530                         return getControlPointOrientationQuat(dir, turnAxis, angle);
531                 }
532         }
533         
534         public Quat4d getControlPointOrientationQuat(Vector3d dir, double angle, boolean reversed) {
535             if (turnAxis == null) {
536             if (dir.lengthSquared() > MathTools.NEAR_ZERO)
537                 dir.normalize();
538             Quat4d q =  getControlPointOrientationQuat(dir, angle);
539             if (reversed) {
540                 Quat4d q2 = new Quat4d();
541                 q2.set(new AxisAngle4d(MathTools.Y_AXIS, Math.PI));
542                 q.mulInverse(q2);
543             }
544             return q;
545         } else {
546             if (dir.lengthSquared() > MathTools.NEAR_ZERO)
547                 dir.normalize();
548             return getControlPointOrientationQuat(dir, turnAxis, angle);
549         }
550         }
551
552         public Quat4d getControlPointOrientationQuat(double angle, boolean reversed) {
553
554                 if (turnAxis == null) {
555                         Vector3d dir = getPathLegDirection(Direction.NEXT);
556                         return getControlPointOrientationQuat(dir, angle, reversed);
557                 } else {
558                         Vector3d dir = getPathLegDirection(Direction.PREVIOUS);
559                         dir.negate();
560                         return getControlPointOrientationQuat(dir, angle, reversed);
561                 }
562         }
563
564
565
566         public static Quat4d getControlPointOrientationQuat(Vector3d dir, double angle) {
567                 if (dir.lengthSquared() < MathTools.NEAR_ZERO)
568                         return MathTools.getIdentityQuat();
569
570
571                 Vector3d up = new Vector3d(0.0, 1.0, 0.0);
572                 double a = up.angle(dir);
573                 if (a < 0.1 || (Math.PI - a) < 0.1) {
574                         up.set(1.0, 0.0, 0.0);
575                 }
576
577
578                 return getControlPointOrientationQuat(dir, up, angle);
579         }
580
581         public static Quat4d getControlPointOrientationQuat(Vector3d dir, Vector3d up,  double angle) {
582                 if (dir.lengthSquared() < MathTools.NEAR_ZERO)
583                         return MathTools.getIdentityQuat();
584
585                 final Vector3d front = new Vector3d(1.0,0.0,0.0);
586
587                 Quat4d q1 = new Quat4d();
588
589
590                 Vector3d right = new Vector3d();
591
592                 right.cross(dir, up);
593                 up.cross(right, dir);
594                 right.normalize();
595                 up.normalize();
596
597                 Matrix3d m = new Matrix3d();
598                 m.m00 = dir.x;
599                 m.m10 = dir.y;
600                 m.m20 = dir.z;
601                 m.m01 = up.x;
602                 m.m11 = up.y;
603                 m.m21 = up.z;
604                 m.m02 = right.x;
605                 m.m12 = right.y;
606                 m.m22 = right.z;
607
608                 //q1.set(m); MathTools contains more stable conversion
609                 MathTools.getQuat(m, q1);
610
611                 //                      if (DEBUG) System.out.println("PipingTools.getPipeComponentOrientationQuat() " + dir+ " " + up + " " + right);
612
613                 Quat4d q2 = new Quat4d();
614                 q2.set(new AxisAngle4d(front, angle));
615                 q1.mul(q2);
616                 return q1;
617         }
618
619         public void insert(PipeControlPoint previous, PipeControlPoint next) {
620                 // inserting an offsetpoint is error, 
621                 if (isDualSub())
622                         throw new RuntimeException("Dual sub points cannot be inserted.");
623                 // size change control point cannot be inserted this way, because it ends PipeRun
624 //              if (isSizeChange())
625 //                      throw new RuntimeException("Size change points cannot be inserted.");
626                 PipeRun piperun = previous.getPipeRun();
627                 // and just to make sure that control point structure is not corrupted
628                 if (getPipeRun() != null) {
629                         if (piperun != getPipeRun() || piperun != next.getPipeRun())
630                                 throw new RuntimeException("All controls points must be located on the same pipe run");
631                 } else {
632                         piperun.addChild(this);
633                 }
634
635                 // insert new BranchControlPoint between straight's control points
636                 PipeControlPoint previousNext = previous.getNext();
637                 PipeControlPoint previousPrevious = previous.getPrevious();
638
639                 PipeControlPoint offsetCP = null;
640                 if (isOffset()) {
641                         offsetCP = getDualSub();
642                 }
643                 if (previousNext != null && previousNext == next) {
644                         if (previous.isDualInline()) {
645                                 throw new RuntimeException();
646                         }
647                         if (next.isDualSub()) {
648                                 throw new RuntimeException();
649                         }
650                         previous.setNext(this);
651                         this.setPrevious(previous);
652                         if (previous.isDualSub()) {
653                                 previous.getParentPoint().setNext(this);
654                         }
655                         this.setNext(next);
656
657                         if (offsetCP == null) {
658                                 next.setPrevious(this);
659                         } else {
660                                 next.setPrevious(offsetCP);
661                                 offsetCP.setNext(next);
662                                 offsetCP.setPrevious(previous);
663                         }
664
665                         if (next.isDualInline()) {
666                                 next.getDualSub().setPrevious(this);
667                         }
668                 } else if (previousPrevious != null && previousPrevious == next) {
669                         // control point were given in reverse order 
670                         if (next.isDualInline())
671                                 throw new RuntimeException();
672                         if (previous.isDualSub())
673                                 throw new RuntimeException();
674
675                         this.setNext(previous);
676                         if (offsetCP == null) {
677                                 previous.setNext(this);
678                         } else {
679                                 previous.setPrevious(offsetCP);
680                                 offsetCP.setNext(previous);
681                                 offsetCP.setPrevious(next);
682                         }
683                         if (previous.isDualInline()) {
684                                 previous.getDualSub().setPrevious(this);
685                         }
686                         this.setPrevious(next);
687                         next.setNext(this);
688                         if (next.isDualSub()) {
689                                 next.getParentPoint().setNext(this);
690                         }
691
692                 } else {
693                         throw new RuntimeException();
694                 }       
695
696                 PipingRules.validate(piperun);
697         }
698
699
700
701         public void insert(PipeControlPoint pcp, Direction direction) {
702                 if (isDualSub())
703                         throw new RuntimeException();
704                 if (direction == Direction.NEXT) {
705                         // if direction is next, user must have given OffsetPoint
706                         if (pcp.isDualInline())
707                                 throw new RuntimeException();
708                         // basic next/prev links
709                         pcp.setNext(this);
710                         this.setPrevious(pcp);
711                         // and last take care of sizechange / offset points
712                         if (pcp.isDualSub()) {
713                                 pcp.getParentPoint().setNext(this);
714                         }
715                         if (isDualInline()) {
716                             getDualSub().setPrevious(this);
717                         }
718                 } else {
719                         // if direction is previous, user must have given sizechange
720                         if (pcp.isDualSub())
721                                 throw new RuntimeException();
722                         // previous direction is more complicated, since if newCP is SizeChangeControlPoint,
723                         // we must link pcp to newCP's OffsetPoint
724                         PipeControlPoint nocp = null;
725                         if (isDualInline()) {
726                                 nocp = getDualSub();
727                                 nocp.setNext(pcp);
728                         }
729                         if (nocp == null) {
730                                 pcp.setPrevious(this);
731                         } else {
732                                 pcp.setPrevious(nocp);
733                         }
734                         this.setNext(pcp);
735                         if (pcp.isDualInline()) {
736                                 PipeControlPoint ocp = pcp.getDualSub();
737                                 if (nocp == null)
738                                         ocp.setPrevious(this);
739                                 else
740                                         ocp.setPrevious(nocp);
741                         }
742
743                 }
744                 PipingRules.validate(getPipeRun());
745         }
746
747         public Vector3d getDirectedControlPointDirection() {
748                 assert (isDirected());
749                 Vector3d dir = new Vector3d();
750                 MathTools.rotate(getWorldOrientation(), new Vector3d(1.0, 0.0, 0.0), dir);
751                 dir.normalize();
752                 return dir;
753         }
754         
755         /**
756          * Returns direction vector. 
757          * 
758          * For directed control points, always returns outwards pointing vector.
759          * 
760          * @param direction
761          * @return normalized vector, or null
762          */
763         public Vector3d getDirection(Direction direction) {
764         if (isDirected())
765             return getDirectedControlPointDirection();
766         if (isTurn() && asFixedAngle()) {
767             if (direction == Direction.NEXT) {
768                 if (previous != null) {
769                     PipeControlPoint pcp = this;
770                     Vector3d dir = new Vector3d();
771                     dir.sub(pcp.getWorldPosition(),previous.getWorldPosition());
772                     if (dir.lengthSquared() > MathTools.NEAR_ZERO)
773                         dir.normalize();
774                     else
775                         return null;
776                     Quat4d q = getControlPointOrientationQuat(dir, pcp.getRotationAngle() != null ? pcp.getRotationAngle() : 0.0);
777                     AxisAngle4d aa = new AxisAngle4d(MathTools.Y_AXIS,pcp.getTurnAngle() == null ? 0.0 : pcp.getTurnAngle());
778                     Quat4d q2 = MathTools.getQuat(aa);
779                     Vector3d v = new Vector3d(1.,0.,0.);
780                     Vector3d offset = new Vector3d();
781                     MathTools.rotate(q2, v, offset);
782                     MathTools.rotate(q, offset, dir);
783                     dir.normalize();
784                     return dir;
785                 }
786             } else {
787                 if (next != null) {
788                     PipeControlPoint pcp = this;
789                     Vector3d dir = new Vector3d();
790                     dir.sub(next.getWorldPosition(),pcp.getWorldPosition());
791                     if (dir.lengthSquared() > MathTools.NEAR_ZERO)
792                         dir.normalize();
793                     else
794                         return null;
795                     Quat4d q = getControlPointOrientationQuat(dir, pcp.getRotationAngle() != null ? pcp.getRotationAngle() : 0.0);
796                     AxisAngle4d aa = new AxisAngle4d(MathTools.Y_AXIS,pcp.getTurnAngle() == null ? 0.0 : pcp.getTurnAngle());
797                     Quat4d q2 = MathTools.getQuat(aa);
798                     Vector3d v = new Vector3d(1.,0.,0.);
799                     Vector3d offset = new Vector3d();
800                     MathTools.rotate(q2, v, offset);
801                     MathTools.rotate(q, offset, dir);
802                     dir.normalize();
803                     return dir;
804                 }
805             }
806         }
807         return null;
808     }
809
810         /**
811          * Returns path leg direction of the control point.
812          * 
813          * This method differs from getDirection by also returning inward pointing vectors for directed control points.
814          * 
815          * @param direction
816          * @return
817          */
818         public Vector3d getPathLegDirection(Direction direction) {
819                 if (direction == Direction.NEXT) {
820                         if (next != null) {
821                                 PipeControlPoint pcp = this;
822                                 if (pcp.isDualInline()) {
823                                         pcp = pcp.getDualSub();
824                                 }
825                                 Vector3d v = new Vector3d();
826                                 v.sub(next.getWorldPosition(),pcp.getWorldPosition());
827                                 if (v.lengthSquared() > MathTools.NEAR_ZERO)
828                     v.normalize();
829                 else
830                     return null;
831                                 return v;
832                         } else {
833                                 if (previous == null) {
834                                         if (!isDirected())
835                                                 throw new RuntimeException("Cannot calculate path leg direction for unconnected control point " + this);
836                                         return getDirectedControlPointDirection();
837
838                                 } else {
839                                         if (isVariableAngle() && !asFixedAngle())
840                                                 throw new RuntimeException("Cannot calculate path leg direction for unconnected variable angle control point " + this);
841                                         if (isInline()) {
842                                                 PipeControlPoint pcp = this;
843                                                 if (pcp.isDualSub()) {
844                                                         pcp = pcp.getParentPoint();
845                                                 }
846                                                 Vector3d v = new Vector3d();
847                                                 v.sub(pcp.getWorldPosition(),previous.getWorldPosition());
848                                                 if (v.lengthSquared() > MathTools.NEAR_ZERO)
849                                 v.normalize();
850                                                 else
851                                                     return null;
852                                                 return v;
853                                         } else if (isDirected()) {
854                                                 return getDirectedControlPointDirection();
855                                         } else if (isEnd()) {
856                                                 Vector3d v = new Vector3d();
857                                                 v.sub(getWorldPosition(),previous.getWorldPosition());
858                                                 if (v.lengthSquared() > MathTools.NEAR_ZERO)
859                             v.normalize();
860                         else
861                             return null;
862                                                 return v;
863                                         } else if (isTurn() && asFixedAngle() && !_getReversed()) {
864                                                 return getDirection(Direction.NEXT);
865                                         }
866                                         throw new RuntimeException("Missing implementation " + this);
867                                 }
868                         }
869                 } else {
870                         if (previous != null) {
871                                 PipeControlPoint pcp = this;
872                                 if (isDualSub()) 
873                                         pcp = getParentPoint();
874                                 Vector3d v = new Vector3d();
875                                 v.sub(previous.getWorldPosition(),pcp.getWorldPosition());
876                                 if (v.lengthSquared() > MathTools.NEAR_ZERO)
877                     v.normalize();
878                 else
879                     return null;
880                                 return v;
881                         } else {
882                                 if (next == null)  {
883                                         if (!isDirected())
884                                                 throw new RuntimeException("Cannot calculate path leg direction for unconnected control point " + this);
885                                         Vector3d v = getDirectedControlPointDirection();
886                                         v.negate();
887                                         return v;
888                                 } else {
889                                         if (isVariableAngle() && !asFixedAngle())
890                                                 throw new RuntimeException("Cannot calculate path leg direction for unconnected variable angle control point " + this);
891                                         if (isInline()) {
892                                                 PipeControlPoint pcp = this;
893                                                 if (pcp.isDualInline()) {
894                                                         pcp = pcp.getDualSub();
895                                                 }
896                                                 Vector3d v = new Vector3d();
897                                                 v.sub(pcp.getWorldPosition(),next.getWorldPosition());
898                                                 if (v.lengthSquared() > MathTools.NEAR_ZERO)
899                             v.normalize();
900                         else
901                             return null;
902                                                 return v;
903                                         } else if (isDirected()) {
904                                                 Vector3d v = getDirectedControlPointDirection();
905                                                 v.negate();
906                                                 return v;
907                                         } else if (isEnd()) {
908                                                 Vector3d v = new Vector3d();
909                                                 v.sub(getWorldPosition(),next.getWorldPosition());
910                                                 if (v.lengthSquared() > MathTools.NEAR_ZERO)
911                             v.normalize();
912                         else
913                             return null;
914                                                 return v;
915                                         } else if (isTurn() && asFixedAngle() && _getReversed()) {
916                                                 return getDirection(Direction.PREVIOUS);
917                                         }
918                                         throw new RuntimeException("Missing implementation " + this);
919                                 }
920                         }
921                 }
922         }
923
924         public void getInlineControlPointEnds(Tuple3d p1, Tuple3d p2) {
925                 assert (isInline());
926
927                 PipeControlPoint sub = isAxial() ? this : getDualSub();
928                 Vector3d pos = getWorldPosition(), pos2 = sub == this ? pos : sub.getWorldPosition();
929                 Vector3d dir = sub.getPathLegDirection(Direction.NEXT);
930                 
931                 dir.normalize();
932                 dir.scale(length * 0.5);
933                 p1.set(pos);
934                 p2.set(pos2);
935                 p1.sub(dir);
936                 p2.add(dir);
937         }
938
939         public void getControlPointEnds(Tuple3d p1, Tuple3d p2) {
940                 PipeControlPoint sub = isAxial() || isDirected() || isTurn() ? this : getChildPoints().get(0);
941                 Vector3d pos = getWorldPosition(), pos2 = sub == this ? pos : sub.getWorldPosition();
942                 
943                 Vector3d dir1 = getPathLegDirection(Direction.PREVIOUS);
944                 Vector3d dir2 = sub.getPathLegDirection(Direction.NEXT);
945                 if (isInline()) {
946                         dir1.scale(length * 0.5);
947                         dir2.scale(length * 0.5);
948                 } else {
949                         dir1.scale(length);
950                         dir2.scale(length);
951                 }
952                 p1.set(pos);
953                 p2.set(pos2);
954                 p1.add(dir1);
955                 p2.add(dir2);
956         }
957
958         public void getEndDirections(Tuple3d v1, Tuple3d v2) {
959                 PipeControlPoint sub = isAxial() ? this : getDualSub();
960                 
961                 Vector3d dir1 = getPathLegDirection(Direction.PREVIOUS);
962                 Vector3d dir2 = sub.getPathLegDirection(Direction.NEXT);
963                 v1.set(dir1);
964                 v2.set(dir2);
965         }
966
967         public void getInlineControlPointEnds(Tuple3d p1, Tuple3d p2, Vector3d dir) {
968                 assert (isInline());
969
970                 Vector3d pos = getWorldPosition();
971                 dir.set(getPathLegDirection(Direction.NEXT));
972                 dir.normalize();
973                 dir.scale(length * 0.5);
974                 p1.set(pos);
975                 p2.set(pos);
976                 p1.sub(dir);
977                 p2.add(dir);
978         }
979
980         public void getInlineControlPointEnds(Tuple3d center, Tuple3d p1, Tuple3d p2, Vector3d dir) {
981                 assert (isInline());
982
983                 Vector3d pos = getWorldPosition();
984                 center.set(pos);
985                 dir.set(getPathLegDirection(Direction.NEXT));
986                 dir.normalize();
987                 dir.scale(length * 0.5);
988                 p1.set(pos);
989                 p2.set(pos);
990                 p1.sub(dir);
991                 p2.add(dir);
992         }
993
994         public double getInlineLength() {
995                 if (type == PointType.TURN)
996                         return length;
997                 else if (type == PointType.INLINE)
998                         return length * 0.5;
999                 return 0;
1000         }
1001
1002         public Vector3d getRealPosition(PositionType type) {
1003                 Vector3d pos = getWorldPosition();
1004                 switch (type) {
1005                 case NEXT: {
1006                         Vector3d dir = getPathLegDirection(Direction.NEXT);
1007                         double length = getInlineLength();
1008                         dir.normalize();
1009                         dir.scale(length);
1010                         pos.add(dir);
1011                         break;
1012                 }
1013                 case PREVIOUS: {
1014                         Vector3d dir = getPathLegDirection(Direction.PREVIOUS);
1015                         double length = getInlineLength();
1016                         dir.normalize();
1017                         dir.scale(length);
1018                         pos.add(dir);
1019                         break;
1020                 }
1021                 case PORT:
1022                         // IEntity portDir = pcp.getSingleRelatedObject(ProcessResource.plant3Dresource.HasDirection);
1023                         // TODO : how we calculated needed space for a port; does it has an offset from control point's position or not?
1024                         break;
1025                 case SPLIT:
1026                         // do nothing
1027                         break;
1028
1029                 }
1030                 return pos;
1031         }
1032
1033         public void getInlineMovement(Tuple3d start, Tuple3d end) {
1034                 // FIXME : check type of neighbor components and allow movement on top of variable length components,
1035                 //         find proper range for movement (pcp's position is not)
1036                 PipeControlPoint p = previous.getPrevious();
1037                 PipeControlPoint n = next.getNext();
1038                 start.set(p.getWorldPosition());
1039                 end.set(n.getWorldPosition());
1040         }
1041
1042         public PipeControlPoint findNextEnd() {
1043                 ArrayList<PipeControlPoint> t = new ArrayList<PipeControlPoint>();
1044                 return findNextEnd( t);
1045         }
1046
1047         public PipeControlPoint findPreviousEnd() {
1048                 ArrayList<PipeControlPoint> t = new ArrayList<PipeControlPoint>();
1049                 return findPreviousEnd(t);
1050         }
1051
1052         public PipeControlPoint findNextEnd(List<PipeControlPoint> nextList) {
1053                 while (true) {
1054                         PipeControlPoint pcp = null;
1055                         PipeControlPoint p = null;
1056                         if (nextList.size() == 0)
1057                                 p = this;
1058
1059                         else
1060                                 p = nextList.get(nextList.size() - 1);
1061
1062                         pcp = p.getNext();
1063                         if (pcp == null) {
1064                                 pcp = p;
1065                                 if (nextList.size() > 0)
1066                                         nextList.remove(nextList.size() - 1);
1067                                 //              if (DEBUG) System.out.println(" " + pcp.getResource() + " not full");
1068                                 return pcp;
1069                                 //break;
1070                         }
1071                         if (pcp.isPathLegEnd()) {
1072                                 //if (DEBUG) System.out.println(" " + pcp.getResource());
1073                                 return pcp;
1074                         } else {
1075                                 nextList.add(pcp);
1076                                 // if (DEBUG) System.out.print(" " + pcp.getResource());
1077                         }
1078                 }
1079         }
1080
1081         public PipeControlPoint findPreviousEnd(List<PipeControlPoint> prevList) {
1082                 while (true) {
1083                         PipeControlPoint pcp = null;
1084                         PipeControlPoint p = null;
1085                         if (prevList.size() == 0)
1086                                 p = this;
1087
1088                         else
1089                                 p = prevList.get(prevList.size() - 1);
1090
1091                         pcp = p.getPrevious();
1092                         if (pcp == null) {
1093                                 pcp = p;
1094                                 if (prevList.size() > 0)
1095                                         prevList.remove(prevList.size() - 1);
1096                                 //                              if (DEBUG) System.out.println(" " + pcp.getResource() + " not full");
1097                                 return pcp;
1098                         }
1099                         if (pcp.isPathLegEnd()) {
1100                                 //                              if (DEBUG)      System.out.println(" " + pcp.getResource());
1101                                 return pcp;
1102                         } else {
1103                                 prevList.add(pcp);
1104                                 //                              if (DEBUG)System.out.print(" " + pcp.getResource());
1105                         }
1106                 }
1107         }
1108         
1109         public void _remove() {
1110             _remove(true);
1111         }
1112         
1113         
1114         public PipeControlPoint getDualSub() {
1115             if (isDualInline())
1116                 return getChildPoints().get(0);
1117             else
1118                 throw new IllegalStateException("Current control point is not dual inline");
1119         }
1120         
1121
1122         public void _remove(boolean renconnect) {
1123             if (disposed)
1124                 return;
1125                 
1126             if (DEBUG) System.out.println(this + " Remove " + renconnect);
1127
1128                 if (getParentPoint() != null) {
1129                     getParentPoint()._remove(renconnect);
1130                     return;
1131                 }
1132                 PipeRun pipeRun = getPipeRun();
1133 //              PipeRUn removal has been changed, so pipeRun may be null.
1134 //              if (pipeRun == null)
1135 //                      return;
1136
1137                 PipeControlPoint additionalRemove = null;
1138                 if (!PipingRules.isEnabled()) {
1139                     component = null;
1140                         setPrevious(null);
1141                         setNext(null);
1142                 } else {
1143
1144                         PipeControlPoint currentPrev = previous;
1145                         PipeControlPoint currentNext = next;
1146                         if (currentNext == null && currentPrev == null) {
1147                                 removeComponent();
1148                                 if (pipeRun != null) {
1149                                     pipeRun.remChild(this);
1150                                     checkRemove(pipeRun);
1151                                 }
1152                                 return;
1153                         }
1154                         if (currentNext != null && currentPrev != null) {
1155                                 boolean link = renconnect;
1156                                 if (currentNext.isBranchEnd()) {
1157                                         link = false;
1158                                         currentNext.remove();
1159                                         currentNext = null;
1160                                         setNext(null);
1161                                 }
1162                                 if (currentPrev.isBranchEnd()) {
1163                                         link = false;
1164                                         currentPrev.remove();
1165                                         currentPrev = null;
1166                                         setPrevious(null);
1167                                 }
1168                                 if (link) {
1169                                     if (currentPrev.isDirected() && currentNext.isDirected())
1170                                         link = false;
1171                                     else if (this.isDualInline()) {
1172                                         link = false;
1173                                     } else if (this.isDualSub()) {
1174                                         throw new RuntimeException("_remove() is called for parent point, somehow got to child point. " + this);
1175                                     }
1176                                 }
1177                                 if (currentNext == null) {
1178                                         // Nothing to do
1179                                 } else if (currentNext.isDualInline()) {
1180                                         PipeControlPoint sccp = currentNext;
1181                                         PipeControlPoint ocp = currentNext.getDualSub();
1182                                         if (ocp == null) {
1183                                                 throw new RuntimeException("Removing PipeControlPoint " + this+ " structure damaged, no offset control point");
1184                                         }
1185                                         if (link) {
1186                                                 sccp.setPrevious(currentPrev);
1187                                                 //ocp.setPrevious(currentPrev);
1188                                                 assert(ocp.getPrevious() == currentPrev);
1189                                         } else {
1190                                                 sccp.setPrevious(null);
1191                                                 //ocp.setPrevious(null);
1192                                                 assert(ocp.getPrevious() == null);
1193                                         }
1194                                         setNext(null);
1195                                 } else if (currentNext.isDualSub()) {
1196                                         throw new RuntimeException("Removing PipeControlPoint " + this + " structure damaged, next control point is offset control point");
1197                                 } else if (currentNext.previous == this) {
1198                                         if (link) {
1199                                                 currentNext.setPrevious(currentPrev);
1200                                         } else {
1201                                                 currentNext.setPrevious(null);
1202                                         }
1203                                         setNext(null);
1204                                 } else if (isDualInline()) {
1205                                     if (currentNext.previous != getDualSub()) {
1206                                         throw new RuntimeException("Removing PipeControlPoint "+ this+ " structure damaged");
1207                                     }
1208                                     if (link) {
1209                         currentNext.setPrevious(currentPrev);
1210                     } else {
1211                         currentNext.setPrevious(null);
1212                     }
1213                     setNext(null);
1214                                 } else {
1215                                         throw new RuntimeException("Removing PipeControlPoint "+ this+ " structure damaged");
1216                                 }
1217                                 if (currentPrev == null) {
1218                                         // Nothing to do
1219                                 } else if (currentPrev.isDualInline()) {
1220                                         throw new RuntimeException("Removing PipeControlPoint " + this + " structure damaged, previous control point is size change control point");
1221                                 } else if (currentPrev.isDualSub()) {
1222                                         PipeControlPoint ocp = currentPrev;
1223                                         PipeControlPoint sccp = currentPrev.getParentPoint();
1224                                         if (sccp == null)
1225                                                 throw new RuntimeException("Removing PipeControlPoint " + this + " structure damaged, no size change control point");
1226                                         if (link) {
1227                                                 //ocp.setNext(currentNext);
1228                                                 sccp.setNext(currentNext);
1229                                                 assert(ocp.getNext() == currentNext);
1230                                         } else {
1231                                                 //ocp.setNext(null);
1232                                                 sccp.setNext(null);
1233                                                 assert(ocp.getNext() == null);
1234                                         }
1235                                         setPrevious(null);
1236                                 } else if (currentPrev.next == this) {
1237                                         if (link)
1238                                                 currentPrev.setNext(currentNext);
1239                                         else
1240                                                 currentPrev.setNext(null);
1241
1242                                         setPrevious(null);
1243                                 } else {
1244                                         throw new RuntimeException("Removing PipeControlPoint " + this + " structure damaged");
1245                                 }
1246                                 if (link) {
1247                                         if (currentNext.isVariableLength() && currentPrev.isVariableLength()) {
1248                                                 // we have to join them into single variable length component.
1249                                                 additionalRemove = currentPrev;
1250                                                 // combine lengths and set the location of remaining control point to the center.
1251                                                 Point3d ps = new Point3d();
1252                                                 Point3d pe = new Point3d();
1253                                                 Point3d ns = new Point3d();
1254                                                 Point3d ne = new Point3d();
1255                                                 currentPrev.getInlineControlPointEnds(ps, pe);
1256                                                 currentNext.getInlineControlPointEnds(ns, ne);
1257                                                 double l = currentPrev.getLength() + currentNext.getLength();
1258                                                 Vector3d cp = new Vector3d();
1259                                                 cp.add(ps, ne);
1260                                                 cp.scale(0.5);
1261                                                 currentNext.setLength(l);
1262                                                 currentNext.setWorldPosition(cp);
1263                                         }
1264                                 } else {
1265                                         // FIXME : pipe run must be split into two parts, since the control point structure is no more continuous. 
1266                                 }
1267                         } else if (currentNext != null) {
1268                                 if (currentNext.isDualInline()) {
1269                                         PipeControlPoint sccp = currentNext;
1270                                         PipeControlPoint ocp = currentNext.getDualSub();
1271                                         if (ocp == null) {
1272                                                 throw new RuntimeException("Removing PipeControlPoint " + this+ " structure damaged, no offset control point");
1273                                         }
1274                                         sccp.setPrevious(null);
1275                                         assert(ocp.getPrevious() == null);
1276                                         //ocp.setPrevious(null);
1277                                 } else if (currentNext.isDualSub()) {
1278                                         throw new RuntimeException("Removing PipeControlPoint " + this + " structure damaged, next control point is offset control point");
1279                                 } else if (currentNext.previous == this) {
1280                                     currentNext.setPrevious(null);
1281                                 }  else if (isDualInline()) {
1282                     if (currentNext.previous != getDualSub()) {
1283                         throw new RuntimeException("Removing PipeControlPoint "+ this+ " structure damaged");
1284                     }
1285                     currentNext.setPrevious(null);
1286                                 } else {
1287                                         throw new RuntimeException("Removing PipeControlPoint "+ this+ " structure damaged");
1288                                 }
1289                                 setNext(null);
1290                         } else {  //(previous != null)
1291                                 if(currentPrev.isDualInline()) {
1292                                         throw new RuntimeException("Removing PipeControlPoint " + this + " structure damaged, previous control point is size change control point");
1293                                 } else if (currentPrev.isDualSub()) {
1294                                         PipeControlPoint ocp = currentPrev;
1295                                         PipeControlPoint sccp = currentPrev.getParentPoint();
1296                                         if (sccp == null) {
1297                                                 throw new RuntimeException("Removing PipeControlPoint " + this + " structure damaged, no size change control point");
1298                                         }
1299                                         sccp.setNext(null);
1300                                         assert(ocp.getNext() == null);
1301                                 } else if (currentPrev.next == this) {
1302                                     currentPrev.setNext(null);
1303                                 } else {
1304                                         throw new RuntimeException("Removing PipeControlPoint "+ this+ " structure damaged");
1305                                 }
1306                                 setPrevious(null);
1307                         }
1308                         if (children.size() > 0 ) {
1309                                 removeSubPoints();
1310                         } else if (parent!= null) {
1311                                 removeParentPoint();
1312                         }
1313
1314                 }
1315
1316                 removeComponent();
1317                 if (pipeRun != null) {
1318                 pipeRun.remChild(this);
1319                 checkRemove(pipeRun);
1320                 if (PipingRules.isEnabled() && pipeRun.getParent() != null && pipeRun.getControlPoints().size() > 0)
1321                         PipingRules.validate(pipeRun);
1322                 }
1323                 if (additionalRemove != null)
1324                         additionalRemove.remove();
1325                 disposed = true;
1326         }
1327
1328         /**
1329          * Removes control point and attempts to reconnect next/prev
1330          * 
1331          * If this point is size change (PipeRuns are different on both sides), then reconnection cannot be made.
1332          */
1333         public void remove() {
1334                 PipeControlPoint currentPrev = previous;
1335                 PipeControlPoint currentNext = next;
1336                 _remove();
1337                 try {
1338                         if (currentNext != null)
1339                             if (!currentNext.checkRemove())
1340                                 PipingRules.requestUpdate(currentNext);
1341                         if (currentPrev != null)
1342                             if (!currentPrev.checkRemove())
1343                                 PipingRules.requestUpdate(currentPrev);
1344                 } catch (Exception e) {
1345                         e.printStackTrace();
1346                 }
1347         }
1348         
1349         
1350         /**
1351          * Removes control point without attempting to reconnect next/prev.
1352          * This usually leads to creation of another PipeRun for the control points after this point. 
1353          */
1354         public void removeAndSplit() {
1355         PipeControlPoint currentPrev = previous;
1356         PipeControlPoint currentNext = next;
1357         
1358         if (next != null && previous != null) {
1359             P3DRootNode root = (P3DRootNode)getPipelineComponent().getRootNode();
1360             PipeRun nextPipeRun = new PipeRun();
1361             nextPipeRun.setName(root.getUniqueName("PipeRun"));
1362             root.addChild(nextPipeRun);
1363             
1364             PipeRun previousRun = previous.getPipeRun();
1365             nextPipeRun.setPipeDiameter(previousRun.getPipeDiameter());
1366             nextPipeRun.setTurnRadiusArray(previousRun.getTurnRadiusArray());
1367             
1368             PipelineComponent n = next.getPipelineComponent();
1369             while (n != null) {
1370                 if (n.getPipeRun() != previousRun)
1371                     break;
1372                 if (! (n instanceof Nozzle)) {
1373                     n.deattach();
1374                     nextPipeRun.addChild(n);
1375                 } else
1376                     n.setPipeRun(nextPipeRun);
1377                 n = n.getNext();
1378             }
1379         }
1380         _remove(false);
1381         try {
1382             if (currentNext != null)
1383                 if (!currentNext.checkRemove())
1384                     PipingRules.requestUpdate(currentNext);
1385             if (currentPrev != null)
1386                 if (!currentPrev.checkRemove())
1387                     PipingRules.requestUpdate(currentPrev);
1388         } catch (Exception e) {
1389             e.printStackTrace();
1390         }
1391     }
1392         
1393         /**
1394          * This is called when adjacent control point is removed.
1395          * 
1396          * This call should remove the give point, if the point cannot exist alone. 
1397          * At the moment there is one such case: branch.
1398          * 
1399          * @return
1400          */
1401         protected boolean checkRemove() {
1402             if (getParentPoint() != null) {
1403                 return getParentPoint().checkRemove();
1404             } else {
1405                 if (getPipelineComponent() == null)
1406                     return true; // already removed
1407             if (getPipelineComponent().getType().equals("Plant3D.URIs.Builtin_BranchSplitComponent")) {
1408                 if (getChildPoints().get(0).getNext() == null && getChildPoints().get(0).getPrevious() == null) {
1409                         remove();
1410                         return true;
1411                 }
1412             }
1413             return checkRemove(getPipeRun());
1414             }
1415     }
1416
1417         private boolean checkRemove(PipeRun pipeRun) {
1418             if (pipeRun == null)
1419                 return false;
1420                 Collection<PipeControlPoint> points = pipeRun.getControlPoints();
1421                 if (points.size() == 0) {
1422                         pipeRun.remove();
1423                         return true;
1424                 } else if (points.size() == 1) {
1425                         PipeControlPoint pcp = points.iterator().next();
1426                         if (pcp.isDeletable() && pcp.getNext() == null && pcp.getPrevious() == null) {
1427                                 pcp._remove(); // This call will recursively call also this method...
1428                                 return true;
1429                         }
1430                 } else if (points.size() == 2) {
1431                     
1432                 }
1433                 return false;
1434         }
1435
1436         private void removeSubPoints() {
1437                 for (PipeControlPoint p : children) {
1438                         p.parent = null;
1439                         p.component = null;
1440                         //p._remove();
1441                         PipeControlPoint currentNext = p.getNext();
1442                         PipeControlPoint currentPrev = p.getPrevious();
1443                         p._setNext(null);
1444                         p._setPrevious(null);
1445                         PipeRun run = p.getPipeRun();
1446                         if (run != null) {
1447                             run.remChild(p);
1448                             checkRemove(run);
1449                         }
1450                         if (currentNext != null)
1451                 if (!currentNext.checkRemove())
1452                     PipingRules.requestUpdate(currentNext);
1453             if (currentPrev != null)
1454                 if (!currentPrev.checkRemove())
1455                     PipingRules.requestUpdate(currentPrev);
1456             
1457                 }
1458                 children.clear();
1459         }
1460
1461         private void removeParentPoint() {
1462                 throw new RuntimeException("Child points cannot be removed directly");
1463         }
1464         
1465         public boolean isRemoved() {
1466             return component == null;
1467         }
1468
1469         private void removeComponent() {
1470                 if (component == null)
1471                         return;
1472                 PipelineComponent next = component.getNext();
1473                 PipelineComponent prev = component.getPrevious();
1474                 PipelineComponent br0 = component.getBranch0();
1475                 component.setNext(null);
1476                 component.setPrevious(null);
1477                 component.setBranch0(null);
1478                 if (next != null) {
1479                         if (next.getNext() == component)
1480                                 next.setNext(null);
1481                         else if (next.getPrevious() == component)
1482                                 next.setPrevious(null);
1483                         else if (next.getBranch0() == component)
1484                                 next.setBranch0(null);
1485                 }
1486                 if (prev != null) {
1487                         if (prev.getNext() == component)
1488                                 prev.setNext(null);
1489                         else if (prev.getPrevious() == component)
1490                                 prev.setPrevious(null);
1491                         else if (prev.getBranch0() == component)
1492                                 prev.setBranch0(null);
1493                 }
1494                 if (br0 != null) {
1495                         if (br0.getNext() == component)
1496                                 br0.setNext(null);
1497                         else if (br0.getPrevious() == component)
1498                                 br0.setPrevious(null);
1499                         else if (br0.getBranch0() == component)
1500                                 br0.setBranch0(null);
1501                 }
1502                 PipelineComponent comp = component;
1503                 component = null;
1504
1505                 comp.remove();
1506         }
1507
1508         @Override
1509         public void setOrientation(Quat4d orientation) {
1510                 if (MathTools.equals(orientation, getOrientation()))
1511                         return;
1512                 if (getPipelineComponent() != null && (getPipelineComponent() instanceof Nozzle))
1513                     System.out.println();
1514                 super.setOrientation(orientation);
1515                 if (getParentPoint() == null && component != null)
1516                         component._setWorldOrientation(getWorldOrientation());
1517                 updateSubPoint();
1518         }
1519
1520         @Override
1521         public void setPosition(Vector3d position) {
1522                 if (MathTools.equals(position, getPosition()))
1523                         return;
1524                 if (Double.isNaN(position.x) || Double.isNaN(position.y) || Double.isNaN(position.z))
1525                         throw new IllegalArgumentException("NaN is not supported");
1526                 super.setPosition(position);
1527                 if (getParentPoint() == null && component != null)
1528                         component._setWorldPosition(getWorldPosition());
1529                 updateSubPoint();
1530         }
1531
1532         private void updateSubPoint() {
1533                 if (isOffset()) {
1534                         if (next == null && previous == null) {
1535                                 for (PipeControlPoint sub : getChildPoints()) {
1536                                         sub.setWorldPosition(getWorldPosition());
1537                                         sub.setWorldOrientation(getWorldOrientation());
1538                                 }
1539                                 return;
1540                         }
1541                         for (PipeControlPoint sub : getChildPoints()) {
1542                                 Vector3d wp = getWorldPosition();
1543                                 wp.add(getSizeChangeOffsetVector());
1544                                 sub.setWorldPosition(wp);
1545                                 sub.setWorldOrientation(getWorldOrientation());
1546                         }
1547                 } else {
1548                         for (PipeControlPoint sub : getChildPoints()) {
1549                                 sub.setWorldPosition(getWorldPosition());
1550                                 sub.setWorldOrientation(getWorldOrientation());
1551                         }
1552                 }
1553         }
1554
1555
1556         public void _setWorldPosition(Vector3d position) {
1557                 Vector3d localPos = getLocalPosition(position);
1558                 super.setPosition(localPos);
1559                 updateSubPoint();
1560         }
1561
1562         public void _setWorldOrientation(Quat4d orientation) {
1563                 Quat4d localOr = getLocalOrientation(orientation);
1564                 super.setOrientation(localOr);
1565                 updateSubPoint();
1566         }
1567
1568         @Override
1569         public String toString() {
1570                 return getClass().getName() + "@" + Integer.toHexString(hashCode());
1571         }
1572
1573 }