1 package org.simantics.plant3d.scenegraph.controlpoint;
3 import java.util.ArrayList;
4 import java.util.Collection;
7 import javax.vecmath.Point3d;
8 import javax.vecmath.Quat4d;
9 import javax.vecmath.Vector3d;
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;
22 public class PipingRules {
23 private static final boolean DEBUG = false;
24 private static final boolean DUMMY = false;
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.
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;
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
45 private static boolean enabled = true; //
46 private static boolean updating = false;
47 private static boolean allowInsertRemove = true;
48 private static boolean triedIR = false;
51 private static List<PipeControlPoint> requestUpdates = new ArrayList<PipeControlPoint>();
52 private static List<PipeControlPoint> currentUpdates = new ArrayList<PipeControlPoint>();
54 private static Object updateMutex = new Object();
55 private static Object ruleMutex = new Object();
57 public static void requestUpdate(PipeControlPoint pcp) {
58 if (!PipingRules.enabled)
60 if (DEBUG) System.out.println("PipingRules request " + pcp);
61 synchronized (updateMutex) {
62 if (!requestUpdates.contains(pcp))
63 requestUpdates.add(pcp);
67 public static boolean update() throws Exception {
68 if (!PipingRules.enabled)
71 if (requestUpdates.size() == 0)
74 List<PipeControlPoint> temp = new ArrayList<PipeControlPoint>(requestUpdates.size());
75 synchronized(updateMutex) {
76 temp.addAll(requestUpdates);
77 requestUpdates.clear();
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();
87 synchronized(updateMutex) {
88 requestUpdates.removeAll(temp);
94 public static boolean positionUpdate(PipeControlPoint pcp) throws Exception {
96 return positionUpdate(pcp, true);
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();
109 private static boolean _positionUpdate(PipeControlPoint pcp, boolean allowIR) throws Exception {
110 if (updating || !enabled)
112 if (pcp.getPipeRun() == null)
115 if (DEBUG) System.out.println("PipingRules " + pcp);
117 allowInsertRemove = allowIR;
119 validate(pcp.getPipeRun());
120 if (pcp.asPathLegEnd()) {
121 updatePathLegEndControlPoint(pcp); // FIXME: Rules won't work properly, if they are not run twice.
122 //updatePathLegEndControlPoint(pcp);
124 updateInlineControlPoint(pcp);
125 //updateInlineControlPoint(pcp);
127 validate(pcp.getPipeRun());
128 if (!allowInsertRemove)
133 // System.out.println("PipingRules done " + pcp);
137 public static void setEnabled(boolean enabled) {
138 PipingRules.enabled = enabled;
140 currentUpdates.clear();
143 public static boolean isEnabled() {
147 public static class ExpandIterInfo {
148 // these two are turn control points
149 private PipeControlPoint start;
150 private PipeControlPoint end;
153 public ExpandIterInfo() {
157 public ExpandIterInfo(PipeControlPoint tcp, int type) {
158 if (type == REMOVE_START)
165 public ExpandIterInfo(PipeControlPoint start, PipeControlPoint end) {
168 this.type = REMOVE_BOTH;
171 public PipeControlPoint getEnd() {
175 public void setEnd(PipeControlPoint end) {
179 public PipeControlPoint getStart() {
183 public void setStart(PipeControlPoint start) {
187 public int getType() {
191 public void setType(int type) {
197 private static void updatePathLegEndControlPoint(PipeControlPoint pcp) throws Exception {
199 System.out.println("PipingRules.updatePathLegEndControlPoint() " + pcp);
200 if (pcp.getNext() != null) {
201 updatePathLegNext(pcp, pcp, PathLegUpdateType.NEXT_S);
203 if (pcp.getPrevious() != null) {
204 updatePathLegPrev(pcp, pcp, PathLegUpdateType.PREV_S);
209 private static void updateInlineControlPoint(PipeControlPoint pcp) throws Exception {
211 System.out.println("PipingRules.updateInlineControlPoint() " + pcp);
212 PipeControlPoint start = pcp.findPreviousEnd();
213 updatePathLegNext(start, pcp, PathLegUpdateType.NONE);
216 private static PipeControlPoint insertElbow(PipeControlPoint pcp1, PipeControlPoint pcp2, Vector3d pos) throws Exception{
218 System.out.println("PipingRules.insertElbow() " + pcp1 + " " + pcp2 + " " + pos);
219 if (pcp1.getNext() == pcp2 && pcp2.getPrevious() == pcp1) {
221 } else if (pcp1.getNext() == pcp2 && pcp1.isDualInline() && pcp2.getPrevious() == pcp1.getDualSub()) {
222 pcp1 = pcp1.getDualSub();
223 } else if (pcp1.getPrevious() == pcp2 && pcp2.getNext() == pcp1) {
224 PipeControlPoint t = pcp1;
227 } else if (pcp2.isDualInline() && pcp1.getPrevious() == pcp2.getDualSub() && pcp2.getNext() == pcp1) {
228 PipeControlPoint t = pcp1;
229 pcp1 = pcp2.getDualSub();
232 throw new RuntimeException();
234 TurnComponent elbow = ComponentUtils.createTurn((P3DRootNode)pcp1.getRootNode());
235 PipeControlPoint pcp = elbow.getControlPoint();
236 if (pcp1.isDualInline())
237 pcp1 = pcp1.getDualSub();
238 String name = pcp1.getPipeRun().getUniqueName("Elbow");
240 pcp1.getPipeRun().addChild(elbow);
242 pcp.insert(pcp1, pcp2);
244 pcp.setWorldPosition(pos);
245 validate(pcp.getPipeRun());
249 private static PipeControlPoint insertStraight(PipeControlPoint pcp1, PipeControlPoint pcp2, Vector3d pos, double length) throws Exception {
251 System.out.println("PipingRules.insertStraight() " + pcp1 + " " + pcp2 + " " + pos);
252 if (pcp1.getNext() == pcp2 && pcp2.getPrevious() == pcp1) {
254 } else if (pcp1.getNext() == pcp2 && pcp1.isDualInline() && pcp2.getPrevious() == pcp1.getDualSub()) {
255 pcp1 = pcp1.getDualSub();
256 } else if (pcp1.getPrevious() == pcp2 && pcp2.getNext() == pcp1) {
257 PipeControlPoint t = pcp1;
260 } else if (pcp2.isDualInline() && pcp1.getPrevious() == pcp2.getDualSub() && pcp2.getNext() == pcp1) {
261 PipeControlPoint t = pcp1;
262 pcp1 = pcp2.getDualSub();
265 throw new RuntimeException();
267 InlineComponent component = ComponentUtils.createStraight((P3DRootNode)pcp1.getRootNode());
268 PipeControlPoint scp = component.getControlPoint();
269 if (pcp1.isDualInline())
270 pcp1 = pcp1.getDualSub();
271 String name = pcp1.getPipeRun().getUniqueName("Pipe");
272 component.setName(name);
273 pcp1.getPipeRun().addChild(component);
275 scp.insert(pcp1, pcp2);
277 scp.setWorldPosition(pos);
278 scp.setLength(length);
279 validate(scp.getPipeRun());
283 private static PipeControlPoint insertStraight(PipeControlPoint pcp, Direction direction , Vector3d pos, double length) throws Exception {
285 System.out.println("PipingRules.insertStraight() " + pcp + " " + direction + " " + pos);
287 InlineComponent component = ComponentUtils.createStraight((P3DRootNode)pcp.getRootNode());
288 PipeControlPoint scp = component.getControlPoint();
289 if (pcp.isDualInline() && direction == Direction.NEXT)
290 pcp = pcp.getDualSub();
291 String name = pcp.getPipeRun().getUniqueName("Pipe");
292 component.setName(name);
293 pcp.getPipeRun().addChild(component);
295 scp.insert(pcp,direction);
297 scp.setWorldPosition(pos);
298 scp.setLength(length);
299 validate(scp.getPipeRun());
303 private static void updatePathLegNext(PipeControlPoint start, PipeControlPoint updated, PathLegUpdateType lengthChange) throws Exception {
304 UpdateStruct2 us = createUS(start, Direction.NEXT, 0, new ArrayList<ExpandIterInfo>(), updated);
306 System.out.println("Null update struct " + start);
309 updatePathLeg(us, lengthChange);
312 private static void updatePathLegPrev(PipeControlPoint start, PipeControlPoint updated, PathLegUpdateType lengthChange) throws Exception {
313 UpdateStruct2 us = createUS(start, Direction.PREVIOUS, 0, new ArrayList<ExpandIterInfo>(), updated);
315 System.out.println("Null update struct " + start);
318 updatePathLeg(us, lengthChange);
321 private static class UpdateStruct2 {
322 public PipeControlPoint start;
323 public Vector3d startPoint;
324 public ArrayList<PipeControlPoint> list;
325 public PipeControlPoint end;
326 public Vector3d endPoint;
328 public Vector3d offset;
329 public boolean hasOffsets;
331 public boolean reversed;
332 public ArrayList<ExpandIterInfo> toRemove;
333 public PipeControlPoint updated;
335 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) {
336 if (start == null || end == null)
337 throw new NullPointerException();
339 this.startPoint = startPoint;
342 this.endPoint = endPoint;
344 this.offset = offset;
345 this.hasOffsets = hasOffsets;
347 this.reversed = reversed;
348 this.toRemove = toRemove;
349 this.updated = updated;
351 if (!MathTools.isValid(startPoint) ||
352 !MathTools.isValid(endPoint) ||
353 !MathTools.isValid(dir)) {
354 throw new RuntimeException();
358 public String toString() {
359 return start + " " + end+ " " + dir + " " + hasOffsets + " " + offset + " " + iter + " " + toRemove.size();
364 @SuppressWarnings("unused")
365 private static boolean calculateOffset(Vector3d startPoint, Vector3d endPoint, ArrayList<PipeControlPoint> list, Vector3d dir, Vector3d offset) {
366 boolean hasOffsets = false;
367 List<PipeControlPoint> offsets = new ArrayList<PipeControlPoint>(list.size());
368 for (PipeControlPoint icp : list) {
369 if (icp.isOffset()) {
371 } else if (icp.isDualSub())
372 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
374 if (offsets.size() == 0) {
377 double l = dir.lengthSquared();
378 if (l > MathTools.NEAR_ZERO)
379 dir.scale(1.0/Math.sqrt(l));
380 offset.set(0.0, 0.0, 0.0);
383 Vector3d sp = new Vector3d(startPoint);
384 Point3d ep = new Point3d(endPoint);
387 double l = dir.lengthSquared();
388 if (l > MathTools.NEAR_ZERO)
389 dir.scale(1.0/Math.sqrt(l));
393 offset.set(0.0, 0.0, 0.0);
395 for (PipeControlPoint icp : offsets) {
396 Vector3d v = icp.getSizeChangeOffsetVector(dir);
399 Point3d nep = new Point3d(endPoint);
401 if (nep.distance(ep) < 0.0000000001) {
407 l = dir.lengthSquared();
408 if (l > MathTools.NEAR_ZERO)
409 dir.scale(1.0/Math.sqrt(l));
414 if (DEBUG && hasOffsets)
415 System.out.println("calcOffset s:"+ startPoint + " e:" + endPoint + " d:" + dir + " o:"+offset) ;
419 private static UpdateStruct2 createUS(PipeControlPoint start, Direction direction, int iter, ArrayList<ExpandIterInfo> toRemove, PipeControlPoint updated) {
420 ArrayList<PipeControlPoint> list = new ArrayList<PipeControlPoint>();
421 PipeControlPoint end = null;
422 if (direction == Direction.NEXT) {
423 end = start.findNextEnd(list);
425 ArrayList<PipeControlPoint> prevList = new ArrayList<PipeControlPoint>();
426 PipeControlPoint tend = start.findPreviousEnd(prevList);
427 for (PipeControlPoint icp : prevList) {
428 if (icp.isDualSub()) {
429 list.add(0, icp.getParentPoint());
439 boolean hasOffsets = false;
440 Vector3d offset = new Vector3d();
441 Vector3d startPoint = start.getWorldPosition();
442 Vector3d endPoint = end.getWorldPosition();
443 Vector3d dir = new Vector3d();
444 hasOffsets = calculateOffset(startPoint, endPoint, list, dir, offset);
445 return new UpdateStruct2(start, startPoint, list, end, endPoint, dir, offset, hasOffsets, iter, direction == Direction.PREVIOUS, toRemove, updated);
448 private static boolean asDirected(PipeControlPoint pcp, Direction direction) {
449 if (pcp.isDirected())
451 if (pcp.asFixedAngle()) {
452 if (!pcp._getReversed())
453 return direction == Direction.NEXT;
455 return direction == Direction.PREVIOUS;
460 private static Vector3d direction(PipeControlPoint pcp, Direction direction) {
461 return pcp.getDirection(direction);
464 private static void updatePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
467 if (lengthChange == PathLegUpdateType.NONE) {
471 updatePathLeg(u, lengthChange, rs, re);
474 private static void updatePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange, boolean rs, boolean re) throws Exception {
476 if (asDirected(u.start, Direction.NEXT))
478 if (asDirected(u.end, Direction.PREVIOUS))
481 setErrorForce(u.start, null);
483 setErrorForce(u.end, null);
484 for (PipeControlPoint pcp : u.list)
485 setErrorForce(pcp, null);
488 updateFreePathLeg(u, lengthChange);
491 updateDirectedPathLeg(u, lengthChange);
494 updateDualDirectedPathLeg(u, lengthChange);
500 private static void updateFreePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
502 System.out.println("PipingRules.updateFreePipeRun " + u + " " + lengthChange);
503 checkExpandPathLeg(u, lengthChange);
504 if (u.start.isInline() || u.end.isInline() || u.start.asFixedAngle()|| u.end.asFixedAngle())
505 processPathLeg(u, true, false);
508 private static void updateInlineControlPoints(UpdateStruct2 u, boolean checkSizes) throws Exception{
510 System.out.println("PipingRules.updateInlineControlPoints() " + u);
512 Vector3d start = new Vector3d(u.startPoint);
513 Vector3d end = new Vector3d(u.endPoint);
516 // create offsets for leg ends.
517 if (u.start.isTurn())
518 MathTools.mad(start, u.dir, u.start.getInlineLength());
520 MathTools.mad(end, u.dir, -u.end.getInlineLength());
523 boolean recalcline = false;
525 Vector3d sp = new Vector3d(start);
526 Vector3d ep = new Vector3d(end);
530 for (PipeControlPoint icp : u.list) {
531 updateInlineControlPoint(icp, sp, ep, u.dir);
532 if (icp.isOffset()) {
533 // TODO : offset vector is already calculated and should be cached
534 Vector3d offset = icp.getSizeChangeOffsetVector(u.dir);
535 updateOffsetPoint(icp, offset);
544 // Collect all path leg points for updating variable length components. This list will also contain leg ends (usually turns)
545 ArrayList<PipeControlPoint> pathLegPoints = new ArrayList<>();
546 // Collect all fixed length components with their offsets.
547 ArrayList<Pair<PipeControlPoint,Vector3d>> fixedLengthPoints = new ArrayList<>();
549 pathLegPoints.add(u.start);
550 fixedLengthPoints.add(new Pair<PipeControlPoint, Vector3d>(u.start, new Vector3d()));
551 Vector3d off = new Vector3d();
552 for (PipeControlPoint icp : u.list) {
553 pathLegPoints.add(icp);
554 updateBranchControlPointBranches(icp);
555 if (icp.isOffset()) {
556 fixedLengthPoints.add(new Pair<PipeControlPoint, Vector3d>(icp, new Vector3d(off)));
557 Vector3d offset = icp.getSizeChangeOffsetVector(u.dir);
559 } else if (!icp.isVariableLength()) {
560 fixedLengthPoints.add(new Pair<PipeControlPoint, Vector3d>(icp, new Vector3d(off)));
563 pathLegPoints.add(u.end);
564 fixedLengthPoints.add(new Pair<PipeControlPoint, Vector3d>(u.end, new Vector3d(off)));
566 sp = new Vector3d(start);
567 ep = new Vector3d(end);
570 updateFixedLengths(fixedLengthPoints, sp, ep, u.dir);
572 for (int i = 0; i < pathLegPoints.size(); i++) {
573 PipeControlPoint icp = pathLegPoints.get(i);
575 PipeControlPoint prev = i > 0 ? pathLegPoints.get(i - 1) : null;
576 PipeControlPoint next = i < pathLegPoints.size() - 1 ? pathLegPoints.get(i + 1) : null;
578 if (prev != null && prev.isDualInline())
579 prev = prev.getDualSub();
581 if (icp.isVariableLength()) {
582 if (prev != null && next != null) {
583 recalcline = recalcline | updateVariableLength(icp, prev, next);
586 // this is variable length component at the end of the piperun.
587 // the problem is that we want to keep unconnected end of the component in the same
588 // place, but center of the component must be moved.
589 updateVariableLengthEnd(icp, prev != null ? prev : next);
591 } else if (prev != null && !prev.isVariableLength()) {
592 // If this and previous control point are not variable length pcps,
593 // we'll have to check if there is no empty space between them.
594 // I there is, we'll have to create new variable length component between them.
595 recalcline = recalcline | possibleVaribleLengthInsert(icp, prev);
597 if (icp.isOffset()) {
598 // TODO : offset vector is already calculated and should be cached
599 Vector3d offset = icp.getSizeChangeOffsetVector(u.dir);
607 u.start.findNextEnd(u.list);
610 sp = new Vector3d(u.startPoint);
611 ep = new Vector3d(u.endPoint);
613 double pathLegLength = MathTools.distance(sp, ep);
614 double availableLength = pathLegLength;
615 if (u.start.isTurn())
616 availableLength -= u.start.getInlineLength();
618 availableLength -= u.end.getInlineLength();
619 for (PipeControlPoint pcp : u.list) {
620 if (!pcp.isVariableLength())
621 availableLength-= pcp.getLength();
623 if (availableLength < 0.0) {
624 setError(u.start, "Not enough available space");
625 setError(u.end, "Not enough available space");
626 for (PipeControlPoint pcp : u.list)
627 setError(pcp, "Not enough available space");
629 // System.out.println(u.start.getPipelineComponent().toString() + " " + pathLegLength + " " + availableLength + " " + u.end.getPipelineComponent().toString() + " " + u.start.getInlineLength() + " " + u.end.getInlineLength());
633 private enum Gap{ATTACHED,OVERLAP,SPACE};
635 private static class GapObj {
639 Pair<PipeControlPoint,Vector3d> pcp1;
640 Pair<PipeControlPoint,Vector3d> pcp2;
643 private static void updateFixedLengths(List<Pair<PipeControlPoint,Vector3d>> fixedLengthPoints, Vector3d s, Vector3d e, Vector3d dir) {
644 double totalLength = MathTools.distance(s, e);
645 double reservedLength = 0.0;
646 List<Double> distances = new ArrayList<>(fixedLengthPoints.size());
648 for (int i = 1; i < fixedLengthPoints.size()-1; i++) {
649 Pair<PipeControlPoint,Vector3d> pcp = fixedLengthPoints.get(i);
650 reservedLength += pcp.first.getLength();
651 Vector3d p = pcp.first.getWorldPosition();
653 double d= MathTools.distance(s, p);
656 distances.add(totalLength);
658 if (totalLength >= reservedLength) {
659 // There is enough space for all fixed length components.
660 List<GapObj> gaps = new ArrayList<>(fixedLengthPoints.size()-1);
662 // Analyze gaps between components
663 for (int i = 0; i < fixedLengthPoints.size()-1; i++) {
664 Pair<PipeControlPoint,Vector3d> pcp1 = fixedLengthPoints.get(i);
665 Pair<PipeControlPoint,Vector3d> pcp2 = fixedLengthPoints.get(i+1);
666 double d1 = distances.get(i);
667 double d2 = distances.get(i+1);
668 double ld1 = i == 0 ? 0.0 :pcp1.first.getInlineLength();
669 double ld2 = i == fixedLengthPoints.size()-2 ? 0.0 : pcp2.first.getInlineLength();
671 double e1 = d1 + ld1; // End of comp1
672 double s2 = d2 - ld2; // Start of comp2
673 double diff =s2 - e1;
674 GapObj obj = new GapObj();
678 if (diff < -MIN_INLINE_LENGTH) {
679 obj.gap = Gap.OVERLAP;
681 } else if (diff > MIN_INLINE_LENGTH) {
684 obj.gap = Gap.ATTACHED;
688 // If there are no overlaps, there is nothing to do.
691 // Get rid of overlapping components by using closest available free spaces.
692 for (int i = 0; i < gaps.size(); i++) {
693 GapObj gapObj = gaps.get(i);
694 if (gapObj.gap != Gap.OVERLAP)
696 double curr = gapObj.d;
698 while (curr < -MIN_INLINE_LENGTH) {
699 GapObj next = i+d >= 0 ? gaps.get(i+d) : null;
700 GapObj prev = i-d >= 0 ? gaps.get(i-d) : null;
701 if (next != null && next.gap == Gap.SPACE) {
702 double move = Math.min(-curr, next.d);
705 if (next.d < MIN_INLINE_LENGTH)
706 next.gap = Gap.ATTACHED;
707 Vector3d mv = new Vector3d(dir);
710 for (int j = i ; j < i+d; j++) {
711 Pair<PipeControlPoint,Vector3d> pcp = gaps.get(j).pcp2;
712 Vector3d p = new Vector3d(pcp.first.getWorldPosition());
714 pcp.first.setWorldPosition(p);
717 if (curr < -MIN_INLINE_LENGTH && prev != null && prev.gap == Gap.SPACE) {
718 double move = Math.min(-curr, prev.d);
721 if (next.d < MIN_INLINE_LENGTH)
722 next.gap = Gap.ATTACHED;
723 Vector3d mv = new Vector3d(dir);
726 for (int j = i ; j > i-d; j--) {
727 Pair<PipeControlPoint,Vector3d> pcp = gaps.get(j).pcp1;
728 Vector3d p = new Vector3d(pcp.first.getWorldPosition());
730 pcp.first.setWorldPosition(p);
736 for (int i = 1; i < fixedLengthPoints.size()-1; i++) {
737 Pair<PipeControlPoint,Vector3d> prev = i == 0 ? null : fixedLengthPoints.get(i-1);
738 Pair<PipeControlPoint,Vector3d> curr = fixedLengthPoints.get(i);
739 Pair<PipeControlPoint,Vector3d> next = i == fixedLengthPoints.size() -1 ? null : fixedLengthPoints.get(i+1);
740 updateFixedLength(curr, prev, next, s,e, dir);
745 private static void updateFixedLength(Pair<PipeControlPoint,Vector3d> icp, Pair<PipeControlPoint,Vector3d> prev, Pair<PipeControlPoint,Vector3d> next, Vector3d s, Vector3d e, Vector3d dir) {
747 checkOverlap(prev, icp, dir,true);
750 checkOverlap(icp, next, dir,true);
753 private static boolean checkOverlap(Pair<PipeControlPoint,Vector3d> icp, Pair<PipeControlPoint,Vector3d> icp2, Vector3d dir, boolean se) {
754 Vector3d p1 = icp.first.getWorldPosition();
755 Vector3d p2 = icp2.first.getWorldPosition();
758 double u[] = new double[1];
759 MathTools.closestPointOnStraight(p2, p1, dir, u);
764 MathTools.mad(p2, dir, MIN_INLINE_LENGTH);
765 icp2.first.setWorldPosition(p2);
767 double d = MathTools.distance(p1, p2);
768 double r = icp.first.getInlineLength() + icp2.first.getInlineLength();
770 if ((d-r) < - MIN_INLINE_LENGTH) {
772 setError(icp.first, "Overlapping");
773 setError(icp2.first, "Overlapping");
781 * Overrides current error of a component
785 private static void setErrorForce(PipeControlPoint pcp, String error) {
786 PipelineComponent comp = pcp.getPipelineComponent();
789 comp.setError(error);
793 * Sets error for a component, if there is no existing error.
797 private static void setError(PipeControlPoint pcp, String error) {
798 PipelineComponent comp = pcp.getPipelineComponent();
801 if (comp.getError() != null)
803 comp.setError(error);
806 private static boolean updateVariableLength(PipeControlPoint icp, PipeControlPoint prev, PipeControlPoint next) {
807 Vector3d prevPos = prev.getWorldPosition();
808 Vector3d nextPos = next.getWorldPosition();
810 Vector3d dir = new Vector3d(nextPos);
812 double l = dir.length(); // distance between control points
813 double l2prev = prev.getInlineLength(); // distance taken by components
814 double l2next = next.getInlineLength();
815 double l2 = l2prev + l2next;
816 double length = l - l2; // true length of the variable length component
817 if (length >= MIN_INLINE_LENGTH) { // check if there is enough space for variable length component.
820 dir.scale(length * 0.5 + l2prev); // calculate center position of the component
822 icp.setWorldPosition(dir);
823 icp.setLength(length);
826 // components leave no space to the component and it must be removed
827 if (icp.isDeletable()) {
828 if (!allowInsertRemove) {
829 icp.setLength(MIN_INLINE_LENGTH);
830 setError(icp, "Not enough available space");
835 System.out.println("PipingRules.updateVariableLength removing " + icp);
839 icp.setLength(MIN_INLINE_LENGTH);
840 icp.getPipelineComponent().setError("Not enough available space");
846 private static boolean possibleVaribleLengthInsert(PipeControlPoint icp, PipeControlPoint prev) throws Exception{
847 Vector3d currentPos = icp.getWorldPosition();
848 Vector3d prevPos = prev.getWorldPosition();
849 Vector3d dir = new Vector3d(currentPos);
851 double l = dir.lengthSquared();
852 double l2prev = prev.getInlineLength();
853 double l2next = icp.getInlineLength();
854 double l2 = l2prev + l2next;
855 double l2s = l2 * l2;
857 if (allowInsertRemove) {
859 double length = Math.sqrt(l) - l2; // true length of the variable length component
860 dir.scale(length * 0.5 + l2prev); // calculate center position of the component
862 insertStraight(prev, icp, dir, length);
871 private static void updateVariableLengthEnd(PipeControlPoint icp, PipeControlPoint prev) {
872 Vector3d currentPos = icp.getWorldPosition();
873 Vector3d prevPos = prev.getWorldPosition();
875 Vector3d dir = new Vector3d();
876 dir.sub(currentPos, prevPos);
878 boolean simple = currentUpdates.contains(icp);
880 // Update based on position -> adjust length
881 double currentLength = (dir.length() - prev.getInlineLength()) * 2.0;
882 icp.setLength(currentLength);
884 // Update based on neighbour movement -> adjust length and position, so that free end stays in place.
885 double currentLength = icp.getLength();
886 if (currentLength < MathTools.NEAR_ZERO) {
887 currentLength = (dir.length() - prev.getInlineLength()) * 2.0;
890 if (dir.lengthSquared() > MathTools.NEAR_ZERO)
892 Point3d endPos = new Point3d(dir);
893 endPos.scale(currentLength * 0.5);
894 endPos.add(currentPos); // this is the free end of the component
896 double offset = prev.getInlineLength();
897 Point3d beginPos = new Point3d(dir);
898 beginPos.scale(offset);
899 beginPos.add(prevPos); // this is the connected end of the component
901 double l = beginPos.distance(endPos);
904 System.out.println("Length for " + icp + " is NaN");
907 beginPos.add(dir); // center position
910 System.out.println("PipingRules.updateInlineControlPoints() setting variable length to " + l);
913 icp.setWorldPosition(new Vector3d(beginPos));
917 private static void ppNoOffset(UpdateStruct2 u) throws Exception {
919 System.out.println("PipingRules.ppNoOffset() " + u);
920 Vector3d offset = new Vector3d();
923 for (PipeControlPoint icp : u.list) {
924 if (icp.isOffset()) {
925 offset.add(icp.getSizeChangeOffsetVector(u.dir));
926 } else if (icp.isDualSub())
927 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
931 checkExpandPathLeg(u, PathLegUpdateType.NONE);
934 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 {
936 System.out.println("PipingRules.ppNoDir() " + start + " " + end + " " + iter + " " + toRemove.size());
937 // FIXME : extra loop (dir should be calculated here)
938 Vector3d dir = new Vector3d();
939 Vector3d offset = new Vector3d();
940 hasOffsets = calculateOffset(startPoint, endPoint, list, dir, offset);
941 ppNoOffset(new UpdateStruct2(start, startPoint, list, end, endPoint, dir, null, hasOffsets, iter, reversed, toRemove, updated));
944 private static void checkExpandPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
945 checkExpandPathLeg(u, lengthChange, u.updated.isInline() && u.updated.isOffset());
948 private static void checkExpandPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange, boolean updateEnds) throws Exception {
950 System.out.println("PipingRules.checkExpandPathLeg() " + u + " " + lengthChange);
951 if (lengthChange != PathLegUpdateType.NONE) {
952 // FIXME : turns cannot be checked before inline cps are updated,
953 // since their position affects calculation of turns
954 processPathLeg(u, updateEnds, false);
955 int type = checkTurns(u, lengthChange);
956 if (type == REMOVE_NONE) {
957 processPathLeg(u, updateEnds, true);
959 expandPathLeg(u, type);
962 processPathLeg(u, updateEnds, true);
966 private static void updateDirectedPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
968 System.out.println("PipingRules.updateDirectedPipeRun() " + u + " " + lengthChange);
969 PipeControlPoint dcp;
970 PipeControlPoint other;
971 boolean canMoveOther = false;
972 boolean dcpStart = false;
973 boolean inlineEnd = false;
975 if (asDirected(u.start, Direction.NEXT)) {
978 position = u.startPoint;
982 inlineEnd = u.end.isInline();
987 position = u.endPoint;
990 inlineEnd = u.start.isInline();
993 Vector3d directedDirection = direction(dcp, dcpStart ? Direction.NEXT : Direction.PREVIOUS);
994 if (directedDirection == null) {
995 //updateTurnControlPointTurn(dcp, dcp.getPrevious(), dcp.getNext());
996 updateTurnControlPointTurn(dcp, null, null);
997 directedDirection = direction(dcp, dcpStart ? Direction.NEXT : Direction.PREVIOUS);
998 if (directedDirection == null) {
1002 Point3d directedEndPoint = new Point3d(u.endPoint);
1004 directedEndPoint.add(u.offset);
1006 double mu[] = new double[2];
1009 Vector3d t = new Vector3d();
1012 closest = MathTools.closestPointOnStraight(directedEndPoint, u.startPoint, directedDirection, mu);
1013 t.sub(closest, directedEndPoint);
1015 closest = MathTools.closestPointOnStraight(u.startPoint, directedEndPoint, directedDirection, mu);
1016 t.sub(closest, u.startPoint);
1019 double distance = t.length();
1020 boolean aligned = (distance < ALLOWED_OFFSET);
1022 if (u.start.isInline() || u.end.isInline() || u.start.asFixedAngle() || u.end.asFixedAngle())
1023 processPathLeg(u, true, false);
1024 checkExpandPathLeg(u, lengthChange, inlineEnd);
1030 PipeControlPoint nextToMoved;
1032 if (u.list.size() > 0)
1034 nextToMoved = u.list.get(0);
1036 nextToMoved = u.list.get(u.list.size() - 1);
1038 nextToMoved = u.end;
1040 nextToMoved = u.start;
1041 if (other.isVariableAngle()) {
1043 // TODO calculate needed space from next run end.
1044 double space = spaceForTurn(other);
1045 if (mu[0] < space) {
1047 closest.set(u.startPoint);
1049 closest.set(u.endPoint);
1051 Vector3d v = new Vector3d(directedDirection);
1058 System.out.println("PipingRules.updateDirectedPipeRun() moved end " + other + " to " + closest);
1059 other.setWorldPosition(closest);
1061 ppNoOffset(new UpdateStruct2(u.start, u.startPoint, u.list, u.end, new Vector3d(closest), directedDirection, null, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated));
1062 if (u.end.getNext() != null)
1063 updatePathLegNext(u.end, u.updated, PathLegUpdateType.NEXT);
1065 ppNoOffset(new UpdateStruct2(u.start, new Vector3d(closest), u.list, u.end, u.endPoint, directedDirection, null, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated));
1066 if (u.start.getPrevious() != null)
1067 updatePathLegPrev(u.start, u.updated, PathLegUpdateType.PREV);
1070 // TODO : calculate needed space from next run end.
1071 if (allowInsertRemove)
1072 insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
1077 } else if (other.isNonDirected() && other.getParentPoint() != null) {
1078 // FIXME : this code was for updating branches
1079 Vector3d bintersect = new Vector3d();
1080 PipeControlPoint bcp = other.getParentPoint();
1081 if (bcp != null && canMoveOther) {
1082 Point3d bstart = new Point3d();
1083 Point3d bend = new Point3d();
1084 Vector3d bdir = new Vector3d();
1085 bcp.getInlineControlPointEnds(bstart, bend, bdir);
1086 Vector3d nintersect = new Vector3d();
1088 MathTools.intersectStraightStraight(position, directedDirection, bend, bdir, nintersect, bintersect, mu);
1089 Vector3d dist = new Vector3d(nintersect);
1090 dist.sub(bintersect);
1091 canMoveOther = mu[1] > 0.0 && mu[1] < 1.0 && dist.lengthSquared() < 0.01;
1093 // TODO : endControlPoints are undirected: calculcate
1094 // correct position for it
1095 throw new UnsupportedOperationException("not implemented");
1099 System.out.println("PipingRules.updateDirectedPipeRun() moved end " + other + " to " + bintersect);
1100 // is required branch position is in possible range
1101 bcp.setWorldPosition(bintersect);
1103 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);
1105 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);
1108 // branch cannot be moved into right position, new turn
1109 // / elbow must be inserted
1110 if (allowInsertRemove)
1111 insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
1116 } else { // assume that control point cannot be moved, but can
1118 if (allowInsertRemove)
1119 insertElbowUpdate(u, dcp, nextToMoved, dcpStart, position, directedDirection);
1129 private static void updateDualDirectedPathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
1131 System.out.println("PipingRules.updateDualDirectedPipeRun() " + u + " " + lengthChange);
1133 PipeControlPoint dcp1 = u.start;
1134 PipeControlPoint dcp2 = u.end;
1135 Point3d position1 = new Point3d(u.startPoint);
1136 Point3d position2 = new Point3d(u.endPoint);
1137 Point3d position1offset = new Point3d(position1);
1138 position1offset.sub(u.offset);
1139 Point3d position2offset = new Point3d(position2);
1140 position2offset.add(u.offset);
1141 Vector3d dir1 = direction(dcp1, Direction.NEXT);
1142 Vector3d dir2 = direction(dcp2, Direction.PREVIOUS);
1143 Vector3d p1 = MathTools.closestPointOnStraight(position1offset, position2, dir2);
1144 Vector3d p2 = MathTools.closestPointOnStraight(position2offset, position1, dir1);
1145 double d1 = position1.distance(new Point3d(p1));
1146 double d2 = position2.distance(new Point3d(p2));
1148 boolean aligned = (d1 < ALLOWED_OFFSET && d2 < ALLOWED_OFFSET);
1154 } else if (allowInsertRemove){
1155 PipeControlPoint dcp;
1156 PipeControlPoint next;
1159 if (u.list.size() > 0)
1160 next = u.list.get(0);
1165 if (u.list.size() > 0)
1166 next = u.list.get(u.list.size() - 1);
1171 p1 = dcp.getWorldPosition();
1172 Vector3d v = new Vector3d();
1178 // Reserve space for 90 deg elbow
1179 double off = dcp1.getPipeRun().getTurnRadius();
1184 p2 = MathTools.closestPointOnStraight(new Point3d(p1), position2, dir2);
1186 p2 = MathTools.closestPointOnStraight(new Point3d(p1), position1, dir1);
1188 // By default, the elbows are placed next to each other, by using 90 deg angles.
1189 // If the distance between elbows is not enough, we must move the other elbow (and create more shallow angle elbows)
1190 if (MathTools.distance(p1, p2) < off*2.05) {
1194 PipeControlPoint tcp1 = insertElbow(dcp, next, p1);
1195 PipeControlPoint tcp2 = insertElbow(tcp1, next, p2);
1198 System.out.println("PipingRules.updateDualDirectedPipeRun() created two turns " + tcp1 + " " + tcp2);
1201 Vector3d dd = new Vector3d(p2);
1204 updatePathLegNext(u.start, u.updated, PathLegUpdateType.NONE);
1205 updatePathLegNext(tcp1, u.updated, PathLegUpdateType.NONE);
1207 updatePathLegNext(tcp2, u.updated, PathLegUpdateType.NONE);
1209 updatePathLegPrev(tcp2, u.updated, PathLegUpdateType.NONE);
1211 Vector3d dd = new Vector3d(p1);
1214 updatePathLegNext(tcp1, u.updated, PathLegUpdateType.NONE);
1215 updatePathLegNext(tcp2, u.updated, PathLegUpdateType.NONE);
1217 updatePathLegNext(u.start, u.updated, PathLegUpdateType.NONE);
1219 updatePathLegPrev(u.start, u.updated, PathLegUpdateType.NONE);
1228 private static double spaceForTurn(PipeControlPoint tcp) {
1229 // TODO : this returns now space for 90 deg turn.
1230 // The challenge: position of tcp affects the turn angle, which then affects the required space. Perhaps we need to iterate...
1231 // Additionally, if the path legs contain offset, using just positions of opposite path leg ends is not enough,
1232 return ((TurnComponent)tcp.getPipelineComponent()).getTurnRadius();
1235 private static void insertElbowUpdate(UpdateStruct2 u, PipeControlPoint dcp, PipeControlPoint next, boolean dcpStart, Vector3d position, Vector3d directedDirection) throws Exception{
1238 // Vector3d closest = new Vector3d(position);
1239 // closest.add(directedDirection);
1241 PipeControlPoint tcp = null;
1244 closest = MathTools.closestPointOnStraight(next.getWorldPosition(), position, directedDirection);
1245 tcp = insertElbow(dcp, next, closest);
1247 closest = MathTools.closestPointOnStraight(dcp.getWorldPosition(), position, directedDirection);
1248 tcp = insertElbow(next, dcp, closest);
1250 // TODO properly calculate required distance between start and inserted elbow.
1251 double d = MathTools.distance(position, closest);
1252 double s = spaceForTurn(tcp);
1255 Vector3d p = new Vector3d(directedDirection);
1265 System.out.println("PipingRules.updateDirectedPipeRun() inserted " + tcp);
1268 // update pipe run from new turn to other end
1269 ppNoDir(tcp, new Vector3d(closest), u.list, u.end, u.endPoint, u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated);
1270 // update pipe run from directed to new turn
1271 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));
1273 // update pipe run from other end to new turn
1274 ppNoDir(u.start, u.startPoint, u.list, tcp, new Vector3d(closest), u.hasOffsets, u.iter, u.reversed, u.toRemove, u.updated);
1275 // update pipe run from new turn to directed
1276 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));
1281 * Checks if turns can be removed (turn angle near zero)
1283 private static int checkTurns(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception {
1285 System.out.println("PipingRules.checkTurns() " + u.start + " " + u.end);
1286 boolean startRemoved = false;
1287 boolean endRemoved = false;
1288 if (u.start.isVariableAngle()) {
1289 // this won't work properly if inline control points are not updated
1290 PipeControlPoint startPrev = u.start.getPrevious();
1291 if (startPrev != null) {
1292 double a = updateTurnControlPointTurn(u.start, null, u.dir);
1293 if (a < MIN_TURN_ANGLE && u.start.isDeletable())
1294 startRemoved = true;
1295 else if (lengthChange == PathLegUpdateType.PREV || lengthChange == PathLegUpdateType.PREV_S) {
1296 PathLegUpdateType type;
1297 if (lengthChange == PathLegUpdateType.PREV_S)
1298 type = PathLegUpdateType.PREV;
1300 type = PathLegUpdateType.NONE;
1301 updatePathLegPrev(u.start, u.start, type);
1305 if (u.end.isVariableAngle()) {
1307 PipeControlPoint endNext = u.end.getNext();
1308 if (endNext != null) {
1309 // TODO: u.end, u.dir, null
1310 double a = updateTurnControlPointTurn(u.end, null, null);
1311 if (a < MIN_TURN_ANGLE && u.end.isDeletable())
1313 else if (lengthChange == PathLegUpdateType.NEXT || lengthChange == PathLegUpdateType.NEXT_S) {
1314 PathLegUpdateType type;
1315 if (lengthChange == PathLegUpdateType.NEXT_S)
1316 type = PathLegUpdateType.NEXT;
1318 type = PathLegUpdateType.NONE;
1319 updatePathLegNext(u.end, u.end, type);
1324 System.out.println("PipingRules.checkTurns() res " + startRemoved + " " + endRemoved);
1325 if (!startRemoved && !endRemoved)
1327 if (startRemoved && endRemoved)
1330 return REMOVE_START;
1335 * Expands piperun search over turns that are going to be removed
1338 private static void expandPathLeg(UpdateStruct2 u, int type) throws Exception {
1340 System.out.println("PipingRules.expandPipeline " + u.start + " " + u.end);
1341 ArrayList<PipeControlPoint> newList = new ArrayList<PipeControlPoint>();
1344 throw new RuntimeException("Error in piping rules");
1346 u.toRemove.add(new ExpandIterInfo(u.start, REMOVE_START));
1347 u.start = u.start.findPreviousEnd();
1348 u.startPoint = u.start.getPosition();
1349 u.start.findNextEnd(newList);
1350 newList.addAll(u.list);
1354 u.toRemove.add(new ExpandIterInfo(u.end, REMOVE_END));
1355 u.end = u.end.findNextEnd(newList);
1356 u.endPoint = u.end.getPosition();
1357 u.list.addAll(newList);
1360 u.toRemove.add(new ExpandIterInfo(u.start, u.end));
1361 u.start = u.start.findPreviousEnd();
1362 u.startPoint = u.start.getPosition();
1363 u.start.findNextEnd(newList);
1364 newList.addAll(u.list);
1366 newList = new ArrayList<PipeControlPoint>();
1367 u.end = u.end.findNextEnd(newList);
1368 u.endPoint = u.end.getPosition();
1369 u.list.addAll(newList);
1372 throw new RuntimeException("Error in piping rules");
1375 u.offset = new Vector3d();
1378 for (PipeControlPoint icp : u.list) {
1379 if (icp.isOffset()) {
1380 u.offset.add(icp.getSizeChangeOffsetVector(u.dir));
1381 } else if (icp.isDualSub())
1382 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1386 System.out.println("PipingRules.expandPipeline expanded " + u.start + " " + u.end);
1388 updatePathLeg(u, PathLegUpdateType.NONE);
1392 * reverts one iteration of turn removing back)
1394 private static void backIter(UpdateStruct2 u) throws Exception {
1397 System.out.println("PipingRules.backIter" + u.start + " " + u.end);
1399 throw new RuntimeException("Error in piping rules");
1400 ExpandIterInfo info = u.toRemove.get(u.toRemove.size() - 1);
1401 u.toRemove.remove(u.toRemove.size() - 1);
1402 if (info.getType() == REMOVE_START || info.getType() == REMOVE_BOTH) {
1403 while (u.list.size() > 0) {
1404 PipeControlPoint icp = u.list.get(0);
1405 if (icp.getPrevious().equals(info.getStart()))
1409 u.start = info.getStart();
1411 if (info.getType() == REMOVE_END || info.getType() == REMOVE_BOTH) {
1412 while (u.list.size() > 0) {
1413 PipeControlPoint icp = u.list.get(u.list.size() - 1);
1414 if (icp.getNext().equals(info.getEnd()))
1418 u.end = info.getEnd();
1420 u.offset = new Vector3d();
1423 for (PipeControlPoint icp : u.list) {
1424 if (icp.isOffset()) {
1425 u.offset.add(icp.getSizeChangeOffsetVector(u.dir));
1426 } else if (icp.isDualSub())
1427 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1435 * Processes pipe run (removes necessary turns and updates run ends)
1437 // private static void processPathLeg(PipeControlPoint start, Point3d
1438 // startPoint,ArrayList<InlineControlPoint> list, PipeControlPoint
1439 // end,Point3d endPoint, Vector3d dir,Vector3d offset, boolean
1440 // hasOffsets,int iter, boolean reversed, ArrayList<ExpandIterInfo>
1441 // toRemove) throws TransactionException {
1443 private static void processPathLeg(UpdateStruct2 u) throws Exception {
1445 System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1446 processPathLeg(u, true, true);
1449 private static void processPathLeg(UpdateStruct2 u, boolean updateEnds, boolean updateInline) throws Exception {
1451 System.out.println("PipingRules.processPathLeg " + (updateEnds ? "ends " : "") + (updateInline ? "inline " : "") + u.start + " " + u.end);
1453 if (u.toRemove.size() > 0) {
1454 for (ExpandIterInfo info : u.toRemove) {
1455 if (info.getStart() != null) {
1457 System.out.println("PipingRules.processPathLeg removing start " + info.getStart());
1458 info.getStart()._remove();
1460 if (info.getEnd() != null) {
1462 System.out.println("PipingRules.processPathLeg removing end " + info.getEnd());
1463 info.getEnd()._remove();
1466 // ControlPointTools.removeControlPoint may remove more than one CP;
1467 // we must populate inline CP list again.
1469 u.start.findNextEnd( u.list);
1471 // FIXME : inline CPs are update twice because their positions must be
1472 // updated before and after ends.
1473 updateInlineControlPoints(u, false);
1476 if (u.start.isTurn()) {
1477 //updateTurnControlPointTurn(u.start, u.start.getPrevious(), u.start.getNext());
1478 updateTurnControlPointTurn(u.start, null, null);
1479 // updatePathLegPrev(u.start, u.start, PathLegUpdateType.NONE);
1480 } else if (u.start.isEnd()) {
1481 updateEndComponentControlPoint(u.start, u.dir);
1482 } else if (u.start.isInline()) {
1483 updateControlPointOrientation(u.start, u.dir);
1485 if (u.end.isTurn()) {
1486 //updateTurnControlPointTurn(u.end, u.end.getPrevious(), u.end.getNext());
1487 updateTurnControlPointTurn(u.end, null, null);
1488 // updatePathLegNext(u.end, u.end, PathLegUpdateType.NONE);
1489 } else if (u.end.isEnd()) {
1490 updateEndComponentControlPoint(u.end, u.dir);
1491 } else if (u.end.isInline()) {
1492 updateControlPointOrientation(u.end, u.dir);
1496 if (u.start.isEnd()) {
1497 updateEndComponentControlPoint(u.start, u.dir);
1499 if (u.end.isEnd()) {
1500 updateEndComponentControlPoint(u.end, u.dir);
1504 updateInlineControlPoints(u, true);
1509 * Processes pipe run and recalculates offset
1511 // private static void processPathLeg(PipeControlPoint start, Point3d
1512 // startPoint,ArrayList<InlineControlPoint> list, PipeControlPoint
1513 // end,Point3d endPoint, Vector3d dir, boolean hasOffsets,int iter, boolean
1514 // reversed, ArrayList<ExpandIterInfo> toRemove) throws TransactionException
1516 @SuppressWarnings("unused")
1517 private static void processPathLegNoOffset(UpdateStruct2 u) throws Exception {
1519 System.out.println("PipingRules.processPathLeg " + u.start + " " + u.end);
1520 Vector3d offset = new Vector3d();
1523 for (PipeControlPoint icp : u.list) {
1524 if (icp.isOffset()) {
1525 offset.add(icp.getSizeChangeOffsetVector(u.dir));
1526 } else if (icp.isDualSub()) {
1527 ErrorLogger.defaultLogError("Updating pipe run, found offset controlpoint " + icp, new Exception("ASSERT!"));
1534 private static void updateOffsetPoint(PipeControlPoint sccp, Vector3d offset) {
1535 Vector3d world = sccp.getWorldPosition();
1537 PipeControlPoint ocp = sccp.getDualSub();
1538 ocp.setWorldPosition(world);
1542 * Updates InlineControlPoints position when straight pipe's end(s) have
1550 private static void updateInlineControlPoint(PipeControlPoint icp, Vector3d prev, Vector3d next, Vector3d dir) {
1552 System.out.println("PipingRules.updateInlineControlPoint() " + icp);
1554 Vector3d inlinePoint = icp.getWorldPosition();
1555 Vector3d prevPoint = new Vector3d(prev);
1556 Vector3d nextPoint = new Vector3d(next);
1557 if (!icp.isVariableLength()) {
1558 // Reserve space for fixed length components.
1559 MathTools.mad(prevPoint, dir, icp.getInlineLength());
1560 MathTools.mad(nextPoint, dir, -icp.getInlineLength());
1561 if (MathTools.distance(prevPoint, nextPoint) < ALLOWED_OFFSET) {
1566 boolean canCalc = MathTools.distance(prevPoint, nextPoint) > ALLOWED_OFFSET;
1568 System.out.print("InlineControlPoint update " + icp + " " + inlinePoint + " " + prevPoint + " " + nextPoint);
1569 Vector3d newInlinePoint = null;
1571 boolean branchUpdate = false;
1572 PipeControlPoint becp = null;
1573 for (PipeControlPoint pcp : icp.getChildPoints())
1574 if (pcp.isNonDirected()) {
1575 branchUpdate = true;
1580 if (DUMMY || !branchUpdate) {
1581 newInlinePoint = MathTools.closestPointOnEdge(new Vector3d(inlinePoint), prevPoint, nextPoint);
1585 // FIXME : can only handle one branch
1586 PipeControlPoint p = null;
1587 if (becp.getNext() != null) {
1588 p = becp.findNextEnd();
1589 } else if (becp.getPrevious() != null) {
1590 p = becp.findPreviousEnd();
1593 newInlinePoint = MathTools.closestPointOnEdge(new Vector3d(inlinePoint), prevPoint, nextPoint);
1594 } else if (canCalc){
1595 Vector3d branchLegEnd = p.getWorldPosition();
1596 Vector3d dir2 = new Vector3d(inlinePoint);
1597 dir2.sub(branchLegEnd);
1598 Vector3d dir1 = new Vector3d(nextPoint);
1599 dir1.sub(prevPoint);
1600 newInlinePoint = new Vector3d();
1601 double mu[] = new double[2];
1602 MathTools.intersectStraightStraight(new Vector3d(prevPoint), dir1, new Vector3d(branchLegEnd), dir2, newInlinePoint, new Vector3d(), mu);
1604 System.out.println(mu[0]);
1605 // FIXME : reserve space
1607 newInlinePoint = new Vector3d(prevPoint);
1608 } else if (mu[0] > 1.0) {
1609 newInlinePoint = new Vector3d(nextPoint);
1614 // prevPoint == nextPoint
1615 newInlinePoint = new Vector3d(prevPoint);
1618 System.out.println(" " + newInlinePoint);
1620 icp.setWorldPosition(newInlinePoint);
1621 updateControlPointOrientation(icp, dir);
1625 * Updates InlineControlPoints position when straight pipe's end(s) have
1633 private static void updateEndComponentControlPoint(PipeControlPoint ecp, Vector3d dir) throws Exception {
1635 System.out.println("PipingRules.updateEndComponentControlPoint() " + ecp);
1636 //FIXME : end control point cannot be fixed!
1637 //if (!ecp.isFixed())
1638 updateControlPointOrientation(ecp, dir);
1640 for (PipeControlPoint pcp : ecp.getChildPoints()) {
1641 // TODO update position
1642 updatePathLegEndControlPoint(pcp);
1646 private static void updateControlPointOrientation(PipeControlPoint pcp, Vector3d dir) {
1647 Double angleO = pcp.getRotationAngle();
1651 boolean reversed = pcp._getReversed();
1654 q = pcp.getControlPointOrientationQuat(dir, angle, reversed);
1656 q = pcp.getControlPointOrientationQuat(angle, reversed);
1658 pcp.setWorldOrientation(q);
1662 * Updates all branches when branch's position has been changed
1666 private static void updateBranchControlPointBranches(PipeControlPoint bcp) throws Exception {
1668 System.out.println("PipingRules.updateBranchControlPointBranches() " + bcp);
1669 if (bcp.isDualInline())
1671 Collection<PipeControlPoint> branches = bcp.getChildPoints();
1672 if (branches.size() == 0) {
1674 System.out.println("No Branches found");
1678 for (PipeControlPoint pcp : branches) {
1679 updatePathLegEndControlPoint(pcp);
1683 private static double updateTurnControlPointTurn(PipeControlPoint tcp, Vector3d prev, Vector3d next) {
1685 UpdateStruct2 us = createUS(tcp, Direction.NEXT, 0, new ArrayList<PipingRules.ExpandIterInfo>(), tcp);
1690 UpdateStruct2 us = createUS(tcp, Direction.PREVIOUS, 0, new ArrayList<PipingRules.ExpandIterInfo>(), tcp);
1696 if (!tcp.asFixedAngle()) {
1699 if (next == null || prev == null) {
1700 if (tcp.getTurnAngle() != null)
1701 return tcp.getTurnAngle();
1702 return Math.PI; // FIXME : argh
1704 double turnAngle = prev.angle(next);
1706 double angle = Math.PI - turnAngle;
1708 Vector3d turnAxis = new Vector3d();
1709 turnAxis.cross(prev, next);
1710 if (turnAxis.lengthSquared() > MathTools.NEAR_ZERO) {
1711 double elbowRadius = ((TurnComponent)tcp.getPipelineComponent()).getTurnRadius();
1712 double R = elbowRadius / Math.tan(angle * 0.5);
1714 turnAxis.normalize();
1715 tcp.setTurnAngle(turnAngle);
1716 tcp.setLength(R);// setComponentOffsetValue(R);
1717 tcp.setTurnAxis(turnAxis);
1718 // tcp.setPosition(tcp.getPosition());
1721 tcp.setTurnAngle(0.0);
1723 tcp.setTurnAxis(new Vector3d(MathTools.Y_AXIS));
1726 updateControlPointOrientation(tcp,prev);
1729 System.out.println("PipingTools.updateTurnControlPointTurn " + prev + " " + next + " " + turnAngle + " " + turnAxis);
1733 if (prev != null && next != null) {
1735 } else if (prev == null) {
1736 if (!tcp._getReversed())
1737 tcp.setReversed(true);
1738 } else if (next == null) {
1739 if (tcp._getReversed())
1740 tcp.setReversed(false);
1743 Vector3d dir = null;
1744 if (!tcp._getReversed()) {
1751 return Math.PI; // FIXME : argh
1754 Quat4d q = PipeControlPoint.getControlPointOrientationQuat(dir, tcp.getRotationAngle() != null ? tcp.getRotationAngle() : 0.0);
1755 Vector3d v = new Vector3d();
1756 MathTools.rotate(q, MathTools.Y_AXIS,v);
1758 tcp.setWorldOrientation(q);
1759 if (tcp.getTurnAngle() != null)
1760 return tcp.getTurnAngle();
1761 return Math.PI; // FIXME : argh
1767 public static List<PipeControlPoint> getControlPoints(PipeRun pipeRun) {
1768 List<PipeControlPoint> list = new ArrayList<PipeControlPoint>();
1769 if (pipeRun.getControlPoints().size() == 0)
1771 PipeControlPoint pcp = pipeRun.getControlPoints().iterator().next();
1772 while (pcp.getPrevious() != null) {
1773 PipeControlPoint prev = pcp.getPrevious();
1774 if (prev.getPipeRun() != pipeRun && prev.getPipeRun() != null) { // bypass possible corruption
1779 if (pcp.isDualSub()) {
1780 pcp = pcp.getParentPoint();
1783 while (pcp.getNext() != null) {
1784 pcp = pcp.getNext();
1785 if (pcp.getPipeRun() != pipeRun)
1792 public static void reverse(PipeRun pipeRun) {
1795 List<PipeControlPoint> points = getControlPoints(pipeRun);
1796 PipeControlPoint pcp = points.get(0);
1797 if (pcp.isSizeChange() && pcp.getChildPoints().size() > 0) {
1798 pipeRun = pcp.getPipeRun();
1803 List<PipeRun> all = new ArrayList<PipeRun>();
1804 List<List<PipeControlPoint>> pcps = new ArrayList<List<PipeControlPoint>>();
1807 List<PipeControlPoint> points = getControlPoints(pipeRun);
1809 PipeControlPoint pcp = points.get(points.size()-1);
1810 if (pcp.getChildPoints().size() > 0) {
1811 PipeRun pipeRun2 = pcp.getChildPoints().get(0).getPipeRun();
1812 if (pipeRun == pipeRun2)
1820 for (int i = 0 ; i < all.size(); i++) {
1821 List<PipeControlPoint> list = pcps.get(i);
1824 for (int i = 0 ; i < all.size(); i++) {
1825 boolean last = i == all.size() - 1;
1826 List<PipeControlPoint> list = pcps.get(i);
1829 List<PipeControlPoint> list2 = pcps.get(i+1);
1830 PipeControlPoint prev = list.get(list.size()-1);
1831 PipeControlPoint next = list2.get(0);
1832 System.out.println();
1834 // Reverse the component on the boundary.
1835 InlineComponent ic = (InlineComponent)prev.getPipelineComponent();
1836 PipeRun r1 = ic.getPipeRun();
1837 PipeRun r2 = ic.getAlternativePipeRun();
1838 if (r1 == null || r2 == null)
1839 throw new RuntimeException("Components on PipeRun changes should refer to bot PipeRuns");
1843 ic.setAlternativePipeRun(r1);
1845 throw new RuntimeException("PipeRun changes should contain shared control points");
1853 private static void _reverse(List<PipeControlPoint> list) {
1854 if (list.size() <= 1)
1855 return; // nothing to do.
1857 for (int i = 0 ; i < list.size(); i++) {
1858 boolean first = i == 0;
1859 boolean last = i == list.size() - 1;
1860 PipeControlPoint current = list.get(i);
1861 PipeControlPoint currentSub = null;
1862 if (current.isDualInline())
1863 currentSub = current.getDualSub();
1865 PipeControlPoint next = list.get(i+1);
1866 if (next.isDualInline())
1867 next = next.getDualSub();
1868 if (current.getNext() == next)
1869 current.setNext(null);
1870 current.setPrevious(next);
1871 if (currentSub != null) {
1872 if (currentSub.getNext() == next)
1873 currentSub.setNext(null);
1874 currentSub.setPrevious(next);
1877 PipeControlPoint prev = list.get(i-1);
1879 if (current.getPrevious() == prev)
1880 current.setPrevious(null);
1881 current.setNext(prev);
1883 if (currentSub != null) {
1884 if (currentSub.getPrevious() == prev)
1885 currentSub.setPrevious(null);
1886 currentSub.setNext(prev);
1889 PipeControlPoint prev = list.get(i-1);
1890 PipeControlPoint next = list.get(i+1);
1891 if (next.isDualInline())
1892 next = next.getDualSub();
1895 current.setPrevious(next);
1896 current.setNext(prev);
1898 if (currentSub != null) {
1899 currentSub.setPrevious(next);
1900 currentSub.setNext(prev);
1904 //if (current.isTurn() && current.isFixed()) {
1905 if (current.asFixedAngle()) {
1906 current.setReversed(!current._getReversed());
1908 if (current.isInline() && current.isReverse()) {
1909 current.setReversed(!current._getReversed());
1916 public static void validate(PipeRun pipeRun) {
1917 if (pipeRun == null)
1919 Collection<PipeControlPoint> pcps = pipeRun.getControlPoints();
1921 //System.out.println("Validate " + pipeRun.getName());
1922 for (PipeControlPoint pcp : pcps) {
1923 if (pcp.getParentPoint() == null || pcp.getParentPoint().getPipeRun() != pipeRun)
1926 List<PipeControlPoint> runPcps = getControlPoints(pipeRun);
1927 if (runPcps.size() != count) {
1928 System.out.println("Run " + pipeRun.getName() + " contains unconnected control points, found " + runPcps.size() + " connected, " + pcps.size() + " total.");
1929 for (PipeControlPoint pcp : pcps) {
1930 if (!runPcps.contains(pcp)) {
1931 System.out.println("Unconnected " + pcp + " " + pcp.getPipelineComponent());
1935 for (PipeControlPoint pcp : pcps) {
1936 if (pcp.getPipeRun() == null) {
1937 System.out.println("PipeRun ref missing " + pcp + " " + pcp.getPipelineComponent());
1939 if (!pcp.isDirected() && pcp.getNext() == null && pcp.getPrevious() == null)
1940 System.out.println("Orphan undirected " + pcp + " " + pcp.getPipelineComponent());
1942 for (PipeControlPoint pcp : pcps) {
1943 if (pcp.getParentPoint() == null) {
1944 PipeControlPoint sub = null;
1945 if (pcp.isDualInline())
1946 sub = pcp.getDualSub();
1947 PipeControlPoint next = pcp.getNext();
1948 PipeControlPoint prev = pcp.getPrevious();
1950 if (!(next.getPrevious() == pcp || next.getPrevious() == sub)) {
1951 System.out.println("Inconsistency between " + pcp + " -> " +next );
1955 PipeControlPoint prevParent = null;
1956 if (prev.isDualSub()) {
1957 prevParent = prev.getParentPoint();
1958 } else if (prev.isDualInline()) {
1959 System.out.println("Inconsistency between " + pcp + " <-- " +prev );
1961 if (!(prev.getNext() == pcp && (prevParent == null || prevParent.getNext() == pcp))) {
1962 System.out.println("Inconsistency between " + pcp + " <-- " +prev );
1969 public static void splitVariableLengthComponent(PipelineComponent newComponent, InlineComponent splittingComponent, boolean assignPos) throws Exception{
1970 assert(!splittingComponent.getControlPoint().isFixedLength());
1971 assert(!(newComponent instanceof InlineComponent && !newComponent.getControlPoint().isFixedLength()));
1972 PipeControlPoint newCP = newComponent.getControlPoint();
1973 PipeControlPoint splittingCP = splittingComponent.getControlPoint();
1974 PipeControlPoint nextCP = splittingCP.getNext();
1975 PipeControlPoint prevCP = splittingCP.getPrevious();
1977 /* there are many different cases to insert new component when
1978 it splits existing VariableLengthinlineComponent.
1980 1. VariableLengthComponet is connected from both sides:
1981 - insert new component between VariableLength component and component connected to it
1982 - insert new VariableLengthComponent between inserted component and component selected in previous step
1984 2. VariableLengthComponent is connected from one side
1985 - Use previous case or:
1986 - Insert new component to empty end
1987 - Insert new VariableLength component to inserted components empty end
1989 3. VariableLength is not connected to any component.
1990 - Should not be possible, at least in current implementation.
1991 - Could be done using second case
1995 if (nextCP == null && prevCP == null) {
1996 // this should not be possible
1997 throw new RuntimeException("VariableLengthComponent " + splittingComponent + " is not connected to anything.");
1999 double newLength = newComponent.getControlPoint().getLength();
2002 Point3d next = new Point3d();
2003 Point3d prev = new Point3d();
2004 splittingCP.getInlineControlPointEnds(prev, next);
2006 Vector3d newPos = null;
2008 newPos = new Vector3d(prev);
2009 Vector3d dir = new Vector3d(next);
2013 newComponent.setWorldPosition(newPos);
2015 newPos = newComponent.getWorldPosition();
2020 Vector3d dir = new Vector3d(next);
2023 dir.scale(newLength * 0.5);
2024 Point3d vn = new Point3d(newPos);
2025 Point3d vp = new Point3d(newPos);
2028 double ln = vn.distance(next);
2029 double lp = vp.distance(prev);
2030 vp.interpolate(prev, 0.5);
2031 vn.interpolate(next, 0.5);
2034 if (nextCP == null) {
2035 newCP.insert(splittingCP, Direction.NEXT);
2036 insertStraight(newCP, Direction.NEXT, new Vector3d(vn), ln);
2037 splittingCP.setWorldPosition(new Vector3d(vp));
2038 // ControlPointTools.setWorldPosition(splittingCP, vp);
2039 // splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, lp);
2040 } else if (prevCP == null) {
2041 newCP.insert(splittingCP, Direction.PREVIOUS);
2042 insertStraight(newCP, Direction.PREVIOUS, new Vector3d(vp), lp);
2043 splittingCP.setWorldPosition(new Vector3d(vn));
2044 // splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, ln);
2046 newCP.insert(splittingCP, nextCP);
2047 insertStraight(newCP, nextCP, new Vector3d(vn), ln);
2048 splittingCP.setWorldPosition(new Vector3d(vp));
2049 // splittingCP.setRelatedScalarDouble(ProcessResource.plant3Dresource.HasLength, lp);
2051 positionUpdate(newCP);
2055 public static void addSizeChange(boolean reversed, PipeRun pipeRun, PipeRun other, InlineComponent reducer, PipeControlPoint previous, PipeControlPoint next) {
2056 PipeControlPoint pcp = reducer.getControlPoint();
2057 PipeControlPoint ocp = pcp.getDualSub();
2059 String name = pipeRun.getUniqueName("Reducer");
2060 reducer.setName(name);
2061 pipeRun.addChild(reducer);
2062 other.addChild(ocp);
2063 reducer.setAlternativePipeRun(other);
2065 previous.setNext(pcp);
2066 pcp.setPrevious(previous);
2067 ocp.setPrevious(previous);
2071 next.setPrevious(ocp);
2074 String name = other.getUniqueName("Reducer");
2075 reducer.setName(name);
2076 other.addChild(reducer);
2077 pipeRun.addChild(ocp);
2078 reducer.setAlternativePipeRun(pipeRun);
2082 pcp.setPrevious(next);
2083 ocp.setPrevious(next);
2085 pcp.setNext(previous);
2086 ocp.setNext(previous);
2087 previous.setPrevious(ocp);