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