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