1 /*******************************************************************************
2 * Copyright (c) 2012, 2016 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 * Semantum Oy - refactoring
12 *******************************************************************************/
13 package org.simantics.diagram.adapter;
15 import java.awt.BasicStroke;
16 import java.awt.Color;
17 import java.awt.Shape;
18 import java.awt.Stroke;
19 import java.awt.geom.AffineTransform;
20 import java.awt.geom.Rectangle2D;
21 import java.util.Collection;
22 import java.util.Collections;
26 import org.simantics.databoard.Bindings;
27 import org.simantics.db.ReadGraph;
28 import org.simantics.db.Resource;
29 import org.simantics.db.Session;
30 import org.simantics.db.Statement;
31 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
32 import org.simantics.db.common.request.ResourceRead2;
33 import org.simantics.db.common.request.UnaryRead;
34 import org.simantics.db.common.utils.NameUtils;
35 import org.simantics.db.exception.DatabaseException;
36 import org.simantics.diagram.connection.ConnectionVisuals;
37 import org.simantics.diagram.connection.RouteGraph;
38 import org.simantics.diagram.connection.RouteGraphConnectionClass;
39 import org.simantics.diagram.connection.RouteLine;
40 import org.simantics.diagram.connection.RouteNode;
41 import org.simantics.diagram.connection.RouteTerminal;
42 import org.simantics.diagram.connection.rendering.BasicConnectionStyle;
43 import org.simantics.diagram.connection.rendering.ConnectionStyle;
44 import org.simantics.diagram.connection.rendering.StyledRouteGraphRenderer;
45 import org.simantics.diagram.connection.rendering.arrows.ArrowLineEndStyle;
46 import org.simantics.diagram.connection.rendering.arrows.ILineEndStyle;
47 import org.simantics.diagram.connection.rendering.arrows.PlainLineEndStyle;
48 import org.simantics.diagram.content.EdgeResource;
49 import org.simantics.diagram.content.TerminalMap;
50 import org.simantics.diagram.query.DiagramRequests;
51 import org.simantics.diagram.stubs.DiagramResource;
52 import org.simantics.diagram.stubs.G2DResource;
53 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
54 import org.simantics.diagram.synchronization.graph.RouteGraphConnection;
55 import org.simantics.g2d.canvas.ICanvasContext;
56 import org.simantics.g2d.canvas.impl.CanvasContext;
57 import org.simantics.g2d.diagram.IDiagram;
58 import org.simantics.g2d.diagram.handler.Topology.Connection;
59 import org.simantics.g2d.diagram.impl.ElementDiagram;
60 import org.simantics.g2d.element.ElementUtils;
61 import org.simantics.g2d.element.IElement;
62 import org.simantics.g2d.element.handler.EdgeVisuals.EdgeEnd;
63 import org.simantics.g2d.elementclass.FlagClass.Type;
64 import org.simantics.layer0.Layer0;
65 import org.simantics.scenegraph.g2d.nodes.connection.RouteGraphChangeEvent;
66 import org.simantics.scenegraph.utils.GeometryUtils;
67 import org.simantics.structural.stubs.StructuralResource2;
68 import org.simantics.structural2.modelingRules.CPTerminal;
69 import org.simantics.structural2.modelingRules.IAttachmentRelationMap;
70 import org.simantics.structural2.modelingRules.IModelingRules;
71 import org.simantics.utils.threads.CurrentThread;
73 import gnu.trove.map.hash.THashMap;
74 import gnu.trove.set.hash.THashSet;
76 public class RouteGraphUtils {
78 public static boolean DEBUG = false;
80 public static final ILineEndStyle HEAD = new ArrowLineEndStyle("fill 2 1 0");
81 public static final ILineEndStyle TAIL = PlainLineEndStyle.INSTANCE;
83 public static RouteGraph load(ReadGraph graph, Resource diagramRuntime, Resource connection) throws DatabaseException {
84 ICanvasContext canvas = new CanvasContext(CurrentThread.getThreadAccess());
85 IDiagram diagram = new ElementDiagram(canvas);
86 return load(graph, diagramRuntime, connection, canvas, diagram);
89 public static RouteGraph load(ReadGraph graph, Resource diagramRuntime, Resource connection, ICanvasContext canvas, IDiagram diagram) throws DatabaseException {
90 Layer0 L0 = Layer0.getInstance(graph);
91 Resource diagramResource = graph.getPossibleObject(connection, L0.PartOf);
92 IModelingRules modelingRules = graph.syncRequest(DiagramRequests.getModelingRules(diagramResource, null), TransientCacheListener.<IModelingRules>instance());
93 return load(graph, diagramRuntime, connection, canvas, diagram, modelingRules, null);
96 public static RouteGraph load(ReadGraph graph, Resource diagramRuntime, Resource connection, ICanvasContext canvas, IDiagram diagram, IModelingRules modelingRules, Set<BackendConnection> backendConnections) throws DatabaseException {
98 DiagramResource DIA = DiagramResource.getInstance(graph);
99 StructuralResource2 STR = StructuralResource2.getInstance(graph);
101 RouteGraph rg = new RouteGraph();
103 // Default capacity should be enough for common cases.
104 Set<EdgeResource> links = new THashSet<EdgeResource>();
105 Map<Object, RouteNode> nodeByData = new THashMap<Object, RouteNode>();
107 // Load all route graph interior RouteNodes: route lines and points
108 for (Resource interiorNode : graph.getObjects(connection, DIA.HasInteriorRouteNode)) {
109 if (graph.isInstanceOf(interiorNode, DIA.RouteLine)) {
110 Boolean isHorizontal = graph.getRelatedValue(interiorNode, DIA.IsHorizontal, Bindings.BOOLEAN);
111 Double position = graph.getRelatedValue(interiorNode, DIA.HasPosition, Bindings.DOUBLE);
112 RouteLine line = rg.addLine(isHorizontal, position);
113 line.setData( RouteGraphConnection.serialize(graph, interiorNode) );
115 nodeByData.put( interiorNode, line );
117 for (Resource connectedTo : graph.getObjects(interiorNode, DIA.AreConnected)) {
118 links.add( new EdgeResource(interiorNode, connectedTo) );
120 } else if (graph.isInstanceOf(interiorNode, DIA.RoutePoint)) {
121 // Not supported yet. Ignore.
125 Rectangle2D bounds = new Rectangle2D.Double();
126 Map<Resource, Resource> connectorToModeledAttachment = null;
128 // Primarily the loader will believe what modeling rules say about
129 // connector attachment relations.
131 // If modeling rules decide nothing, then we simply believe what the
132 // the attachment relations in the graph say.
134 // Special case 1: connection with two (2) terminals
135 // If the attachment of one of two terminals is decided by modeling
136 // rules, the other attachment shall be the opposite of the decided
137 // attachment (see forcedAttachmentRelation below).
139 // Special case 2: connected to a flag
140 // If the attached element is a flag and modeling rules say nothing
141 // about it, believe the direction stated by the flag type.
143 Collection<Statement> toConnectorStatements = graph.getStatements(connection, DIA.HasConnector);
144 int terminalCount = 0;
146 // See if modeling rules judge any of the connection terminal attachments.
147 if (modelingRules != null) {
148 for (Statement toConnector : toConnectorStatements) {
149 Resource connector = toConnector.getObject();
151 Statement terminalStm = findTerminalStatement(graph, connection, connector, STR);
152 if (terminalStm == null)
153 // Ignore broken connector: attached to the connection but not to any terminal.
156 Resource terminalElement = terminalStm.getObject();
157 Resource connectionRelation = graph.getPossibleInverse(terminalStm.getPredicate());
158 if (connectionRelation == null)
163 IAttachmentRelationMap map = modelingRules.getAttachmentRelations(graph, connection);
164 Resource attachment = map.get(graph, new CPTerminal(terminalElement, connectionRelation));
165 if (attachment != null) {
166 // Primary: believe modeling rules
167 if (connectorToModeledAttachment == null)
168 connectorToModeledAttachment = new THashMap<Resource, Resource>(toConnectorStatements.size());
169 connectorToModeledAttachment.put(connector, attachment);
171 System.out.println("modeling rules decided attachment: " + NameUtils.getSafeName(graph, attachment, true) + " for (" + NameUtils.toString(graph, toConnector, true) + ") & (" + NameUtils.toString(graph, terminalStm, true) + ")");
172 } else if (graph.isInstanceOf(terminalElement, DIA.Flag)) {
173 // Secondary: believe flag type
174 attachment = resolveFlagAttachment(graph, connection, terminalElement, modelingRules, DIA);
175 if (attachment != null) {
176 if (connectorToModeledAttachment == null)
177 connectorToModeledAttachment = new THashMap<Resource, Resource>(toConnectorStatements.size());
178 connectorToModeledAttachment.put(connector, attachment);
180 System.out.println("flag type decided attachment: " + NameUtils.getSafeName(graph, attachment, true) + " for (" + NameUtils.toString(graph, toConnector, true) + ") & (" + NameUtils.toString(graph, terminalStm, true) + ")");
186 if (connectorToModeledAttachment == null)
187 connectorToModeledAttachment = Collections.emptyMap();
189 Resource forcedAttachmentRelation = null;
190 if (terminalCount == 2 && connectorToModeledAttachment.size() == 1) {
191 forcedAttachmentRelation = getInverseAttachment(graph, connectorToModeledAttachment.values().iterator().next(), DIA);
193 System.out.println("set forced attachment: " + NameUtils.getSafeLabel(graph, forcedAttachmentRelation));
196 Resource connectionType = graph.getPossibleObject(connection, STR.HasConnectionType);
198 // Load all node terminal connections as RouteTerminals
199 for (Statement toConnector : toConnectorStatements) {
200 Resource connector = toConnector.getObject();
201 Resource attachmentRelation = toConnector.getPredicate();
203 System.out.println("original attachment relation: " + NameUtils.getSafeLabel(graph, attachmentRelation));
205 Statement terminalStm = findTerminalStatement(graph, connection, connector, STR);
206 if (terminalStm == null)
207 // Ignore broken connector: attached to the connection but not to any terminal.
210 Resource terminalElement = terminalStm.getObject();
211 Resource terminalElementType = graph.getPossibleType(terminalElement, DIA.Element);
212 if (terminalElementType == null)
213 // Ignore non-element terminal elements
216 Resource connectionRelation = graph.getPossibleInverse(terminalStm.getPredicate());
217 if (connectionRelation == null)
220 // Discover node and terminal this connector is connected to.
221 TerminalMap terminals = graph.syncRequest(DiagramRequests.elementTypeTerminals(terminalElementType),
222 TransientCacheListener.<TerminalMap>instance());
223 Resource terminal = terminals.getTerminal(connectionRelation);
224 if (terminal == null) {
226 "RouteGraphUtils: Could not find terminal for connection point "
227 + NameUtils.getSafeName(graph, connectionRelation, true)
229 + NameUtils.getSafeName(graph, terminalElement, true));
233 double[] position = graph.getRelatedValue(connector, DIA.HasRelativeLocation, Bindings.DOUBLE_ARRAY);
234 if (position.length != 2)
235 position = new double[] { 0, 0 };
238 System.out.println("terminalStm: " + NameUtils.toString(graph, terminalStm));
239 System.out.println("terminal: " + graph.getURI(terminalStm.getPredicate()));
241 AffineTransform terminalElementTr = diagramRuntime != null ?
242 DiagramGraphUtil.getDynamicWorldTransform(graph, diagramRuntime, terminalElement) :
243 DiagramGraphUtil.getWorldTransform(graph, terminalElement);
246 System.out.println("terminalElementTr: " + terminalElementTr);
248 double x = terminalElementTr.getTranslateX();
249 double y = terminalElementTr.getTranslateY();
250 double minx = x-1, miny = y-1, maxx = x+1, maxy = y+1;
253 // Use modelingRules to ascertain the proper attachmentRelation
254 // for this terminal connection, if available.
255 Resource att = connectorToModeledAttachment.get(connector);
257 attachmentRelation = att;
259 System.out.println("modeling rules attachment: " + NameUtils.getSafeLabel(graph, attachmentRelation));
260 } else if (forcedAttachmentRelation != null) {
261 attachmentRelation = forcedAttachmentRelation;
263 System.out.println("forced rules attachment: " + NameUtils.getSafeLabel(graph, attachmentRelation));
266 System.out.println("decided attachment: " + NameUtils.getSafeLabel(graph, attachmentRelation));
268 // Get element bounds to decide allowed terminal direction(s)
269 IElement te = graph.syncRequest(DiagramRequests.getElement(canvas, diagram, terminalElement, null));
270 ElementUtils.getElementBounds(te, bounds);
272 Shape shp = org.simantics.g2d.utils.GeometryUtils.transformShape(bounds, terminalElementTr);
273 bounds.setFrame(shp.getBounds2D());
276 // Expand bounds by 2mm to make the connections enter the terminals
277 // at a straight angle and from a distance instead of coming in
279 GeometryUtils.expandRectangle(bounds, 2);
280 minx = bounds.getMinX();
281 miny = bounds.getMinY();
282 maxx = bounds.getMaxX();
283 maxy = bounds.getMaxY();
285 AffineTransform terminalPos = DiagramGraphUtil.getDynamicAffineTransform(graph, terminalElement, terminal);
286 //AffineTransform terminalPos2 = DiagramGraphUtil.getAffineTransform(graph, terminal);
287 if (terminalPos != null) {
289 System.out.println("terminalPos: " + terminalPos);
290 //System.out.println("terminalPos2: " + terminalPos2);
292 terminalElementTr.concatenate(terminalPos);
294 System.out.println("terminalElementTr: " + terminalElementTr);
295 x = terminalElementTr.getTranslateX();
296 y = terminalElementTr.getTranslateY();
299 Integer allowedDirections = graph.getPossibleRelatedValue(terminal, DIA.Terminal_AllowedDirections, Bindings.INTEGER);
300 if (allowedDirections != null) {
301 direction |= allowedDirections;
302 direction = rotateDirection(direction, terminalElementTr);
304 direction |= RouteGraphConnectionClass.shortestDirectionOutOfBounds(x, y, bounds);
306 //System.out.println("DIR(" + x + ", " + y + ", " + bounds + "): " + Integer.toHexString(direction));
308 if (backendConnections != null) {
309 backendConnections.add(
310 new BackendConnection(
311 toEdgeEnd(graph, attachmentRelation, EdgeEnd.Begin, DIA),
318 // Accept any horizontal/vertical direction if nothing is defined
321 if (graph.<Boolean>getRelatedValue(connector, DIA.Connector_straight, Bindings.BOOLEAN))
322 direction |= RouteTerminal.DIR_DIRECT;
323 // FIXME: routegraph crashes if this is done for all terminals regardless of the amount of terminals.
326 System.out.println("load line style: " + NameUtils.getSafeLabel(graph, attachmentRelation));
327 ILineEndStyle endStyle = loadLineEndStyle(graph, attachmentRelation, connectionType, TAIL);
329 RouteTerminal routeTerminal = rg.addTerminal(x, y, minx, miny, maxx, maxy, direction, endStyle);
330 routeTerminal.setData( RouteGraphConnection.serialize(graph, connector) );
332 nodeByData.put( connector, routeTerminal );
334 for (Resource connectedTo : graph.getObjects(connector, DIA.AreConnected)) {
335 links.add( new EdgeResource(connectedTo, connector) );
339 // Finish route graph loading by Linking route nodes together
340 for (EdgeResource link : links) {
341 RouteNode n1 = nodeByData.get(link.first());
342 RouteNode n2 = nodeByData.get(link.second());
343 if (n1 == null || n2 == null) {
344 System.err.println("Stray connection link found: " + link.toString(graph));
354 public static EdgeEnd toEdgeEnd(ReadGraph graph, Resource attachmentRelation, EdgeEnd defaultValue, DiagramResource DIA)
355 throws DatabaseException {
356 if (graph.isSubrelationOf(attachmentRelation, DIA.HasTailConnector))
357 return EdgeEnd.Begin;
358 if (graph.isSubrelationOf(attachmentRelation, DIA.HasHeadConnector))
363 public static Resource resolveFlagAttachment(ReadGraph graph, Resource connection, Resource flag, IModelingRules modelingRules, DiagramResource DIA) throws DatabaseException {
364 Type type = resolveFlagType(graph, connection, flag, modelingRules, DIA);
367 case In: return DIA.HasPlainConnector;
368 case Out: return DIA.HasArrowConnector;
374 private static Type resolveFlagType(ReadGraph graph, Resource connection, Resource flag, IModelingRules modelingRules, DiagramResource DIA) throws DatabaseException {
375 return readFlagType(graph, flag, DIA);
378 private static Type readFlagType(ReadGraph graph, Resource flag, DiagramResource DIA) throws DatabaseException {
379 Resource flagType = graph.getPossibleObject(flag, DIA.HasFlagType);
380 Type type = DiagramGraphUtil.toFlagType(DIA, flagType);
384 public static Statement findTerminalStatement(ReadGraph graph, Resource connection, Resource connector, StructuralResource2 STR)
385 throws DatabaseException {
386 for (Statement stm : graph.getStatements(connector, STR.Connects)) {
387 if (connection.equals(stm.getObject()))
394 public static Resource getInverseAttachment(ReadGraph graph, Resource attachmentRelation, DiagramResource DIA)
395 throws DatabaseException {
396 Resource inverse = graph.getPossibleObject(attachmentRelation, DIA.HasInverseAttachment);
399 if (graph.isSubrelationOf(attachmentRelation, DIA.HasHeadConnector))
400 return DIA.HasPlainConnector;
401 if (graph.isSubrelationOf(attachmentRelation, DIA.HasTailConnector))
402 return DIA.HasArrowConnector;
406 public static ILineEndStyle loadLineEndStyle(ReadGraph graph, Resource attachmentRelation, ILineEndStyle defaultValue)
407 throws DatabaseException {
408 ILineEndStyle style = graph.syncRequest(new LineEndStyle(attachmentRelation),
409 TransientCacheListener.<ILineEndStyle>instance());
410 return style != null ? style : defaultValue;
413 public static ILineEndStyle loadLineEndStyle(ReadGraph graph, Resource attachmentRelation, Resource connectionType, ILineEndStyle defaultValue)
414 throws DatabaseException {
415 if(connectionType != null) {
416 ILineEndStyle style = graph.syncRequest(new LineEndStyleWithType(attachmentRelation, connectionType),
417 TransientCacheListener.<ILineEndStyle>instance());
418 return style != null ? style : defaultValue;
420 ILineEndStyle style = graph.syncRequest(new LineEndStyle(attachmentRelation),
421 TransientCacheListener.<ILineEndStyle>instance());
422 return style != null ? style : defaultValue;
427 * A request for caching ILineEndStyle results.
429 public static class LineEndStyle extends UnaryRead<Resource, ILineEndStyle> {
430 public LineEndStyle(Resource attachmentRelation) {
431 super(attachmentRelation);
434 public ILineEndStyle perform(ReadGraph graph) throws DatabaseException {
435 return loadLineEndStyle0(graph, parameter);
439 public static class LineEndStyleWithType extends ResourceRead2<ILineEndStyle> {
440 public LineEndStyleWithType(Resource attachmentRelation, Resource connectionType) {
441 super(attachmentRelation, connectionType);
444 public ILineEndStyle perform(ReadGraph graph) throws DatabaseException {
445 return loadLineEndStyle0(graph, resource, resource2);
449 private static ILineEndStyle loadLineEndStyle0(ReadGraph graph, Resource attachmentRelation)
450 throws DatabaseException {
451 ILineEndStyle style = graph.getPossibleAdapter(attachmentRelation, ILineEndStyle.class);
454 DiagramResource DIA = DiagramResource.getInstance(graph);
455 if (graph.isSubrelationOf(attachmentRelation, DIA.HasHeadConnector))
457 if (graph.isSubrelationOf(attachmentRelation, DIA.HasTailConnector))
462 private static ILineEndStyle loadLineEndStyle0(ReadGraph graph, Resource attachmentRelation, Resource connectionType)
463 throws DatabaseException {
464 DiagramResource DIA = DiagramResource.getInstance(graph);
465 if (graph.isSubrelationOf(attachmentRelation, DIA.HasHeadConnector)) {
466 if(connectionType != null) {
467 G2DResource G2D = G2DResource.getInstance(graph);
468 Resource end = graph.getPossibleObject(connectionType, G2D.HasEndArrow);
470 Double size = graph.getPossibleRelatedValue(end, G2D.HasSize, Bindings.DOUBLE);
471 if(size == null) size = 0.0;
472 Double widthRatio = graph.getPossibleRelatedValue(end, G2D.HasWidthRatio, Bindings.DOUBLE);
473 if(widthRatio == null) widthRatio = 1.0;
474 Double space = graph.getPossibleRelatedValue(end, G2D.HasSpace, Bindings.DOUBLE);
475 if(space == null) space = 0.0;
477 Resource c = graph.getPossibleObject(end, G2D.HasColor);
480 float[] col = graph.getPossibleValue(c, Bindings.FLOAT_ARRAY);
481 if (col != null && col.length >= 3) {
482 color = new Color(col[0], col[1], col[2]);
486 return new ArrowLineEndStyle(size, widthRatio*size, space, color);
490 return loadLineEndStyle0(graph, attachmentRelation);
498 * @throws DatabaseException
500 public static StyledRouteGraphRenderer getRenderer(ReadGraph graph, ConnectionStyle style)
501 throws DatabaseException {
502 return graph.syncRequest(new Renderer(style),
503 TransientCacheListener.<StyledRouteGraphRenderer>instance());
507 * A request for caching StyledRouteGraphRenderer results.
509 public static class Renderer extends UnaryRead<ConnectionStyle, StyledRouteGraphRenderer> {
510 public Renderer(ConnectionStyle style) {
514 public StyledRouteGraphRenderer perform(ReadGraph graph) throws DatabaseException {
515 return new StyledRouteGraphRenderer(parameter);
522 * @param modelingRules
525 * @throws DatabaseException
527 protected static ConnectionStyle readConnectionStyle(ReadGraph graph, IModelingRules modelingRules, Resource connection, StructuralResource2 STR) throws DatabaseException {
528 Resource connectionType = null;
529 if (modelingRules != null)
530 connectionType = modelingRules.getConnectionType(graph, connection);
531 if (connectionType == null)
532 connectionType = graph.getPossibleObject(connection, STR.HasConnectionType);
533 return readConnectionStyleFromConnectionType(graph, connectionType);
536 protected static ConnectionStyle readConnectionStyleFromConnectionType(ReadGraph graph, Resource connectionType) throws DatabaseException {
537 return graph.syncRequest(new ReadConnectionStyleFromConnectionType(connectionType),
538 TransientCacheListener.<ConnectionStyle>instance());
542 * A request for caching ConnectionStyle results.
544 public static class ReadConnectionStyleFromConnectionType extends UnaryRead<Resource, ConnectionStyle> {
545 public ReadConnectionStyleFromConnectionType(Resource connectionType) {
546 super(connectionType);
549 public ConnectionStyle perform(ReadGraph graph) throws DatabaseException {
550 return readConnectionStyleFromConnectionType0(graph, parameter);
554 protected static ConnectionStyle readConnectionStyleFromConnectionType0(ReadGraph graph, Resource connectionType) throws DatabaseException {
555 ConnectionVisuals cv = null;
556 if (connectionType != null)
557 cv = graph.syncRequest(DiagramRequests.getConnectionVisuals(connectionType),
558 TransientCacheListener.<ConnectionVisuals>instance());
560 // Fixed style settings
561 Color branchPointColor = Color.BLACK;
562 double branchPointRadius = 0.5;
563 double degenerateLineLength = 0.8;
565 Color lineColor = cv != null ? cv.toColor() : null;
566 if (lineColor == null)
567 lineColor = Color.DARK_GRAY;
568 Stroke lineStroke = cv != null ? cv.stroke : null;
569 if (lineStroke == null)
570 lineStroke = new BasicStroke(0.1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10, null, 0);
571 Stroke routeLineStroke = GeometryUtils.scaleStrokeWidth(lineStroke, 2);
573 return new BasicConnectionStyle(
579 degenerateLineLength);
582 public static void scheduleSynchronize(Session session, Resource connection, RouteGraphChangeEvent event) {
583 session.asyncRequest(RouteGraphConnection.synchronizer(connection, event));
586 // ------------------------------------------------------------------------
587 // RouteGraph RouteTerminal allowed direction rotation support
588 // ------------------------------------------------------------------------
590 public static int rotateDirection(int direction, AffineTransform at) {
591 // When direct routing is enabled, no point in wasting time rotating.
592 if ((direction & RouteTerminal.DIR_DIRECT) != 0)
595 final int mask = (AffineTransform.TYPE_MASK_ROTATION | AffineTransform.TYPE_FLIP);
596 boolean rotatedOrFlipped = (at.getType() & mask) != 0;
597 if (rotatedOrFlipped) {
598 double xAxisAngle = Math.atan2( at.getShearY(), at.getScaleX() );
599 double yAxisAngle = Math.atan2( at.getScaleY(), at.getShearX() );
601 int xQuadrant = mainQuadrant(xAxisAngle);
602 int yQuadrant = mainQuadrant(yAxisAngle);
604 int xDirMask = direction & (RouteTerminal.DIR_LEFT | RouteTerminal.DIR_RIGHT);
605 int yDirMask = direction & (RouteTerminal.DIR_DOWN | RouteTerminal.DIR_UP);
607 int xDirMaskRotated = rotl4(xDirMask, xQuadrant);
608 int yDirMaskRotated = rotl4(yDirMask, yQuadrant-1);
610 direction = xDirMaskRotated | yDirMaskRotated;
617 * 4-bit rotate left without carry operation.
618 * Operates on the 4 least sensitive bits of the integer
619 * and leaves the higher bits untouched.
620 * @param x the bits to rotate
621 * @param n the amount of rotation [0..3]
624 private static int rotl4(int x, int n) {
628 int hx = x & 0xfffffff0;
630 int xh = (lx << n) & 0xf;
631 int xl = (lx >>> (4-n));
643 * @param theta angle in radians
644 * @return the quadrant based on the ASCII art above
646 private static int mainQuadrant(double theta) {
647 if (theta > -DEG_45 && theta <= DEG_45) {
649 } else if ((theta > DEG_45 && theta <= DEG_135)) {
651 } else if (theta >= -DEG_135 && theta < -DEG_45) {
657 private static final double DEG_45 = Math.PI/4.;
658 private static final double DEG_135 = Math.PI*3./4.;
660 public static class BackendConnection {
661 public final Resource node;
662 public final Resource terminal;
663 public final EdgeEnd end;
664 public final int hash;
665 public BackendConnection(EdgeEnd end, Resource node, Resource terminal) {
668 assert terminal != null;
671 this.terminal = terminal;
672 this.hash = makeHash();
675 public boolean equals(Object obj) {
678 if (!(obj instanceof Connection))
680 Connection other = (Connection) obj;
681 return other.terminal == terminal
682 && other.node == node
685 private int makeHash() {
686 final int prime = 31;
688 result = prime * result + end.hashCode();
689 result = prime * result + ((node == null) ? 0 : node.hashCode());
690 result = prime * result + ((terminal == null) ? 0 : terminal.hashCode());
694 public int hashCode() {
698 public String toString() {
699 return "BackendConnection[node=" + node + ", terminal=" + terminal + ", end=" + end + "]";