From 53d55c24c779745f188bdb18d32f71d20acb61b2 Mon Sep 17 00:00:00 2001 From: Reino Ruusu Date: Tue, 15 Oct 2019 12:55:53 +0300 Subject: [PATCH] White space clean-up Change-Id: Ib53a7e9a2613bbe664e1af5068c3fc7248707e1c --- .../org/simantics/g3d/csg/ontology/CSG.java | 450 +++---- .../simantics/g3d/csg/editor/CSGEditor2.java | 78 +- .../simantics/g3d/csg/editor/CSGNodeMap.java | 4 +- .../g3d/csg/wizard/CSGBRepExportWizard.java | 2 +- .../g3d/csg/wizard/CSGBrepModelExporter.java | 26 +- .../g3d/csg/wizard/CSGExportModel.java | 22 +- .../g3d/csg/wizard/CSGExportPage.java | 22 +- .../src/org/simantics/g3d/ontology/G3D.java | 258 ++-- .../g3d/vtk/awt/InteractiveVtkPanel.java | 36 +- .../simantics/g3d/vtk/awt/RotateAction.java | 554 ++++---- .../g3d/vtk/awt/TranslateAction.java | 218 ++-- .../vtk/awt/vtkCameraAndSelectorAction.java | 288 ++--- .../g3d/vtk/common/AbstractVTKNodeMap.java | 1108 ++++++++-------- .../g3d/vtk/gizmo/TranslateGizmo.java | 24 +- .../org/simantics/g3d/vtk/gizmo/vtkGizmo.java | 58 +- .../vtk/handlers/CameraPositionHandler.java | 38 +- .../handlers/ParallelPerspectiveHandler.java | 34 +- .../vtk/preferences/VTKPreferencePage.java | 4 +- .../simantics/g3d/vtk/shape/MeshActor.java | 140 +- .../org/simantics/g3d/vtk/shape/vtkShape.java | 32 +- .../g3d/vtk/swt/InteractiveVtkComposite.java | 40 +- .../simantics/g3d/vtk/swt/RotateAction.java | 562 ++++----- .../g3d/vtk/swt/TranslateAction.java | 224 ++-- .../vtk/swt/vtkCameraAndSelectorAction.java | 702 +++++------ .../simantics/g3d/vtk/utils/AxesDisplay.java | 54 +- .../simantics/g3d/vtk/utils/vtkEffect.java | 6 +- .../org/simantics/g3d/vtk/utils/vtkUtil.java | 20 +- .../src/org/simantics/g3d/gizmo/Gizmo.java | 4 +- .../src/org/simantics/g3d/math/MathTools.java | 1076 ++++++++-------- ...nnotatedPropertyTabContributorFactory.java | 136 +- .../simantics/g3d/scenegraph/base/INode.java | 74 +- .../simantics/g3d/scenegraph/base/Node.java | 92 +- .../g3d/scenegraph/base/ParentNode.java | 4 +- .../scenegraph/structural/ComponentNode.java | 54 +- .../structural/G3DComponentNode.java | 54 +- .../structural/StructuralParentNode.java | 2 +- .../src/org/simantics/g3d/scl/SCLUtil.java | 116 +- .../org/simantics/g3d/scl/ScriptNodeMap.java | 934 +++++++------- .../org/simantics/g3d/shape/ArcCylinder.java | 6 +- .../src/org/simantics/g3d/shape/Mesh.java | 42 +- .../src/org/simantics/g3d/shape/Tube.java | 6 +- .../g3d/toolbar/ToolBarCommandRegistry.java | 6 +- .../g3d/toolbar/ToolbarContributor.java | 64 +- .../simantics/g3d/tools/AdaptationUtils.java | 86 +- .../g3d/tools/ConstraintDetector.java | 632 +++++----- .../org/simantics/g3d/tools/NodeTools.java | 28 +- .../org/simantics/g3d/tools/PluginTools.java | 28 +- .../simantics/g3d/ui/SceneGraphDebugger.java | 226 ++-- .../g3d/wizard/ModelExportWizard.java | 228 ++-- .../g3d/wizard/ModelExportWizardPage.java | 236 ++-- .../opencascade/vtk/EdgePointsFilter.java | 4 +- .../simantics/opencascade/vtk/VTKOCCTool.java | 1122 ++++++++--------- .../opencascade/vtk/vtkSolidObject.java | 418 +++--- .../org/simantics/opencascade/OCCTTool.java | 304 ++--- .../opencascade/OccTriangulator.java | 614 ++++----- .../plant3d/actions/AddComponentAction.java | 54 +- .../plant3d/actions/AddNozzleAction.java | 6 +- .../plant3d/actions/RoutePipeAction.java | 1078 ++++++++-------- .../actions/TranslateInlineAction.java | 22 +- .../dialog/ComponentSelectionDialog.java | 244 ++-- .../plant3d/editor/P3DContentOutlinePage.java | 32 +- .../simantics/plant3d/editor/P3DNodeMap.java | 4 +- .../plant3d/editor/Plant3DEditor.java | 78 +- .../geometry/ElbowGeometryProvider.java | 10 +- .../plant3d/geometry/FixedNozzleProvider.java | 8 +- .../geometry/PumpGeometryProvider.java | 34 +- .../plant3d/project/P3DProjectFeature.java | 8 +- .../property/P3DSelectionProcessor.java | 166 +-- .../plant3d/scenegraph/Equipment.java | 52 +- .../plant3d/scenegraph/InlineComponent.java | 2 +- .../simantics/plant3d/scenegraph/Nozzle.java | 28 +- .../plant3d/scenegraph/P3DParentNode.java | 2 +- .../plant3d/scenegraph/PipelineComponent.java | 124 +- .../plant3d/scenegraph/TurnComponent.java | 134 +- .../controlpoint/ControlPointFactory.java | 2 +- .../controlpoint/PipeControlPoint.java | 676 +++++----- .../scenegraph/controlpoint/PipingRules.java | 624 ++++----- .../plant3d/scl/P3DScriptNodeMap.java | 282 ++--- .../org/simantics/plant3d/scl/SCLUtil.java | 104 +- .../plant3d/utils/ComponentUtils.java | 790 ++++++------ .../org/simantics/plant3d/utils/P3DUtil.java | 110 +- 81 files changed, 8133 insertions(+), 8141 deletions(-) diff --git a/org.simantics.g3d.csg.ontology/src/org/simantics/g3d/csg/ontology/CSG.java b/org.simantics.g3d.csg.ontology/src/org/simantics/g3d/csg/ontology/CSG.java index 558522e3..05dce399 100644 --- a/org.simantics.g3d.csg.ontology/src/org/simantics/g3d/csg/ontology/CSG.java +++ b/org.simantics.g3d.csg.ontology/src/org/simantics/g3d/csg/ontology/CSG.java @@ -9,230 +9,230 @@ import org.simantics.db.exception.DatabaseException; import org.simantics.db.service.QueryControl; public class CSG { - - public final Resource Barrel; - public final Resource BooleanOperation; - public final Resource Box; - public final Resource CSGBrowseContext; - public final Resource CSGBrowseContext_ActiveLabelDecorationRule; - public final Resource CSGBrowseContext_RunLabelRule; - public final Resource CSGBrowseContext_ShapeTabContribution; - public final Resource Cone; - public final Resource Cylinder; - public final Resource Difference; - public final Resource EllipticCylinder; - public final Resource HasBottomRadius; - public final Resource HasBottomRadius_Inverse; - public final Resource HasCorners; - public final Resource HasCorners_Inverse; - public final Resource HasHeight; - public final Resource HasHeight_Inverse; - public final Resource HasMajorRadius; - public final Resource HasMajorRadius_Inverse; - public final Resource HasMinorRadius; - public final Resource HasMinorRadius_Inverse; - public final Resource HasRadius; - public final Resource HasRadius_Inverse; - public final Resource HasSizingProperty; - public final Resource HasSizingProperty_Inverse; - public final Resource HasTopRadius; - public final Resource HasTopRadius_Inverse; - public final Resource HasXAxisMaximumSize; - public final Resource HasXAxisMaximumSize_Inverse; - public final Resource HasXAxisMinimumSize; - public final Resource HasXAxisMinimumSize_Inverse; - public final Resource HasXAxisSize; - public final Resource HasXAxisSize_Inverse; - public final Resource HasYAxisSize; - public final Resource HasYAxisSize_Inverse; - public final Resource HasZAxisMaximumSize; - public final Resource HasZAxisMaximumSize_Inverse; - public final Resource HasZAxisMinimumSize; - public final Resource HasZAxisMinimumSize_Inverse; - public final Resource HasZAxisSize; - public final Resource HasZAxisSize_Inverse; - public final Resource Images; - public final Resource Images_Difference; - public final Resource Images_Intersection; - public final Resource Images_Ruby; - public final Resource Images_Union; - public final Resource Intersection; - public final Resource Model; - public final Resource Primitive; - public final Resource RectangularSolid; - public final Resource RegularPrism; - public final Resource Shape; - public final Resource Sphere; - public final Resource Torus; - public final Resource Union; - public final Resource hasChildShape; - public final Resource hasChildShape_Inverse; - public final Resource hasPrimaryShape; - public final Resource hasPrimaryShape_Inverse; - public final Resource hasSecondaryShape; - public final Resource hasSecondaryShape_Inverse; - - public static class URIs { - public static final String Barrel = "http://www.simantics.org/CSG-0.1/Barrel"; - public static final String BooleanOperation = "http://www.simantics.org/CSG-0.1/BooleanOperation"; - public static final String Box = "http://www.simantics.org/CSG-0.1/Box"; - public static final String CSGBrowseContext = "http://www.simantics.org/CSG-0.1/CSGBrowseContext"; - public static final String CSGBrowseContext_ActiveLabelDecorationRule = "http://www.simantics.org/CSG-0.1/CSGBrowseContext/ActiveLabelDecorationRule"; - public static final String CSGBrowseContext_RunLabelRule = "http://www.simantics.org/CSG-0.1/CSGBrowseContext/RunLabelRule"; - public static final String CSGBrowseContext_ShapeTabContribution = "http://www.simantics.org/CSG-0.1/CSGBrowseContext/ShapeTabContribution"; - public static final String Cone = "http://www.simantics.org/CSG-0.1/Cone"; - public static final String Cylinder = "http://www.simantics.org/CSG-0.1/Cylinder"; - public static final String Difference = "http://www.simantics.org/CSG-0.1/Difference"; - public static final String EllipticCylinder = "http://www.simantics.org/CSG-0.1/EllipticCylinder"; - public static final String HasBottomRadius = "http://www.simantics.org/CSG-0.1/HasBottomRadius"; - public static final String HasBottomRadius_Inverse = "http://www.simantics.org/CSG-0.1/HasBottomRadius/Inverse"; - public static final String HasCorners = "http://www.simantics.org/CSG-0.1/HasCorners"; - public static final String HasCorners_Inverse = "http://www.simantics.org/CSG-0.1/HasCorners/Inverse"; - public static final String HasHeight = "http://www.simantics.org/CSG-0.1/HasHeight"; - public static final String HasHeight_Inverse = "http://www.simantics.org/CSG-0.1/HasHeight/Inverse"; - public static final String HasMajorRadius = "http://www.simantics.org/CSG-0.1/HasMajorRadius"; - public static final String HasMajorRadius_Inverse = "http://www.simantics.org/CSG-0.1/HasMajorRadius/Inverse"; - public static final String HasMinorRadius = "http://www.simantics.org/CSG-0.1/HasMinorRadius"; - public static final String HasMinorRadius_Inverse = "http://www.simantics.org/CSG-0.1/HasMinorRadius/Inverse"; - public static final String HasRadius = "http://www.simantics.org/CSG-0.1/HasRadius"; - public static final String HasRadius_Inverse = "http://www.simantics.org/CSG-0.1/HasRadius/Inverse"; - public static final String HasSizingProperty = "http://www.simantics.org/CSG-0.1/HasSizingProperty"; - public static final String HasSizingProperty_Inverse = "http://www.simantics.org/CSG-0.1/HasSizingProperty/Inverse"; - public static final String HasTopRadius = "http://www.simantics.org/CSG-0.1/HasTopRadius"; - public static final String HasTopRadius_Inverse = "http://www.simantics.org/CSG-0.1/HasTopRadius/Inverse"; - public static final String HasXAxisMaximumSize = "http://www.simantics.org/CSG-0.1/HasXAxisMaximumSize"; - public static final String HasXAxisMaximumSize_Inverse = "http://www.simantics.org/CSG-0.1/HasXAxisMaximumSize/Inverse"; - public static final String HasXAxisMinimumSize = "http://www.simantics.org/CSG-0.1/HasXAxisMinimumSize"; - public static final String HasXAxisMinimumSize_Inverse = "http://www.simantics.org/CSG-0.1/HasXAxisMinimumSize/Inverse"; - public static final String HasXAxisSize = "http://www.simantics.org/CSG-0.1/HasXAxisSize"; - public static final String HasXAxisSize_Inverse = "http://www.simantics.org/CSG-0.1/HasXAxisSize/Inverse"; - public static final String HasYAxisSize = "http://www.simantics.org/CSG-0.1/HasYAxisSize"; - public static final String HasYAxisSize_Inverse = "http://www.simantics.org/CSG-0.1/HasYAxisSize/Inverse"; - public static final String HasZAxisMaximumSize = "http://www.simantics.org/CSG-0.1/HasZAxisMaximumSize"; - public static final String HasZAxisMaximumSize_Inverse = "http://www.simantics.org/CSG-0.1/HasZAxisMaximumSize/Inverse"; - public static final String HasZAxisMinimumSize = "http://www.simantics.org/CSG-0.1/HasZAxisMinimumSize"; - public static final String HasZAxisMinimumSize_Inverse = "http://www.simantics.org/CSG-0.1/HasZAxisMinimumSize/Inverse"; - public static final String HasZAxisSize = "http://www.simantics.org/CSG-0.1/HasZAxisSize"; - public static final String HasZAxisSize_Inverse = "http://www.simantics.org/CSG-0.1/HasZAxisSize/Inverse"; - public static final String Images = "http://www.simantics.org/CSG-0.1/Images"; - public static final String Images_Difference = "http://www.simantics.org/CSG-0.1/Images/Difference"; - public static final String Images_Intersection = "http://www.simantics.org/CSG-0.1/Images/Intersection"; - public static final String Images_Ruby = "http://www.simantics.org/CSG-0.1/Images/Ruby"; - public static final String Images_Union = "http://www.simantics.org/CSG-0.1/Images/Union"; - public static final String Intersection = "http://www.simantics.org/CSG-0.1/Intersection"; - public static final String Model = "http://www.simantics.org/CSG-0.1/Model"; - public static final String Primitive = "http://www.simantics.org/CSG-0.1/Primitive"; - public static final String RectangularSolid = "http://www.simantics.org/CSG-0.1/RectangularSolid"; - public static final String RegularPrism = "http://www.simantics.org/CSG-0.1/RegularPrism"; - public static final String Shape = "http://www.simantics.org/CSG-0.1/Shape"; - public static final String Sphere = "http://www.simantics.org/CSG-0.1/Sphere"; - public static final String Torus = "http://www.simantics.org/CSG-0.1/Torus"; - public static final String Union = "http://www.simantics.org/CSG-0.1/Union"; - public static final String hasChildShape = "http://www.simantics.org/CSG-0.1/hasChildShape"; - public static final String hasChildShape_Inverse = "http://www.simantics.org/CSG-0.1/hasChildShape/Inverse"; - public static final String hasPrimaryShape = "http://www.simantics.org/CSG-0.1/hasPrimaryShape"; - public static final String hasPrimaryShape_Inverse = "http://www.simantics.org/CSG-0.1/hasPrimaryShape/Inverse"; - public static final String hasSecondaryShape = "http://www.simantics.org/CSG-0.1/hasSecondaryShape"; - public static final String hasSecondaryShape_Inverse = "http://www.simantics.org/CSG-0.1/hasSecondaryShape/Inverse"; - } - - public static Resource getResourceOrNull(ReadGraph graph, String uri) { - try { - return graph.getResource(uri); - } catch(DatabaseException e) { - System.err.println(e.getMessage()); - return null; - } - } - - public CSG(ReadGraph graph) { - Barrel = getResourceOrNull(graph, URIs.Barrel); - BooleanOperation = getResourceOrNull(graph, URIs.BooleanOperation); - Box = getResourceOrNull(graph, URIs.Box); - CSGBrowseContext = getResourceOrNull(graph, URIs.CSGBrowseContext); - CSGBrowseContext_ActiveLabelDecorationRule = getResourceOrNull(graph, URIs.CSGBrowseContext_ActiveLabelDecorationRule); - CSGBrowseContext_RunLabelRule = getResourceOrNull(graph, URIs.CSGBrowseContext_RunLabelRule); - CSGBrowseContext_ShapeTabContribution = getResourceOrNull(graph, URIs.CSGBrowseContext_ShapeTabContribution); - Cone = getResourceOrNull(graph, URIs.Cone); - Cylinder = getResourceOrNull(graph, URIs.Cylinder); - Difference = getResourceOrNull(graph, URIs.Difference); - EllipticCylinder = getResourceOrNull(graph, URIs.EllipticCylinder); - HasBottomRadius = getResourceOrNull(graph, URIs.HasBottomRadius); - HasBottomRadius_Inverse = getResourceOrNull(graph, URIs.HasBottomRadius_Inverse); - HasCorners = getResourceOrNull(graph, URIs.HasCorners); - HasCorners_Inverse = getResourceOrNull(graph, URIs.HasCorners_Inverse); - HasHeight = getResourceOrNull(graph, URIs.HasHeight); - HasHeight_Inverse = getResourceOrNull(graph, URIs.HasHeight_Inverse); - HasMajorRadius = getResourceOrNull(graph, URIs.HasMajorRadius); - HasMajorRadius_Inverse = getResourceOrNull(graph, URIs.HasMajorRadius_Inverse); - HasMinorRadius = getResourceOrNull(graph, URIs.HasMinorRadius); - HasMinorRadius_Inverse = getResourceOrNull(graph, URIs.HasMinorRadius_Inverse); - HasRadius = getResourceOrNull(graph, URIs.HasRadius); - HasRadius_Inverse = getResourceOrNull(graph, URIs.HasRadius_Inverse); - HasSizingProperty = getResourceOrNull(graph, URIs.HasSizingProperty); - HasSizingProperty_Inverse = getResourceOrNull(graph, URIs.HasSizingProperty_Inverse); - HasTopRadius = getResourceOrNull(graph, URIs.HasTopRadius); - HasTopRadius_Inverse = getResourceOrNull(graph, URIs.HasTopRadius_Inverse); - HasXAxisMaximumSize = getResourceOrNull(graph, URIs.HasXAxisMaximumSize); - HasXAxisMaximumSize_Inverse = getResourceOrNull(graph, URIs.HasXAxisMaximumSize_Inverse); - HasXAxisMinimumSize = getResourceOrNull(graph, URIs.HasXAxisMinimumSize); - HasXAxisMinimumSize_Inverse = getResourceOrNull(graph, URIs.HasXAxisMinimumSize_Inverse); - HasXAxisSize = getResourceOrNull(graph, URIs.HasXAxisSize); - HasXAxisSize_Inverse = getResourceOrNull(graph, URIs.HasXAxisSize_Inverse); - HasYAxisSize = getResourceOrNull(graph, URIs.HasYAxisSize); - HasYAxisSize_Inverse = getResourceOrNull(graph, URIs.HasYAxisSize_Inverse); - HasZAxisMaximumSize = getResourceOrNull(graph, URIs.HasZAxisMaximumSize); - HasZAxisMaximumSize_Inverse = getResourceOrNull(graph, URIs.HasZAxisMaximumSize_Inverse); - HasZAxisMinimumSize = getResourceOrNull(graph, URIs.HasZAxisMinimumSize); - HasZAxisMinimumSize_Inverse = getResourceOrNull(graph, URIs.HasZAxisMinimumSize_Inverse); - HasZAxisSize = getResourceOrNull(graph, URIs.HasZAxisSize); - HasZAxisSize_Inverse = getResourceOrNull(graph, URIs.HasZAxisSize_Inverse); - Images = getResourceOrNull(graph, URIs.Images); - Images_Difference = getResourceOrNull(graph, URIs.Images_Difference); - Images_Intersection = getResourceOrNull(graph, URIs.Images_Intersection); - Images_Ruby = getResourceOrNull(graph, URIs.Images_Ruby); - Images_Union = getResourceOrNull(graph, URIs.Images_Union); - Intersection = getResourceOrNull(graph, URIs.Intersection); - Model = getResourceOrNull(graph, URIs.Model); - Primitive = getResourceOrNull(graph, URIs.Primitive); - RectangularSolid = getResourceOrNull(graph, URIs.RectangularSolid); - RegularPrism = getResourceOrNull(graph, URIs.RegularPrism); - Shape = getResourceOrNull(graph, URIs.Shape); - Sphere = getResourceOrNull(graph, URIs.Sphere); - Torus = getResourceOrNull(graph, URIs.Torus); - Union = getResourceOrNull(graph, URIs.Union); - hasChildShape = getResourceOrNull(graph, URIs.hasChildShape); - hasChildShape_Inverse = getResourceOrNull(graph, URIs.hasChildShape_Inverse); - hasPrimaryShape = getResourceOrNull(graph, URIs.hasPrimaryShape); - hasPrimaryShape_Inverse = getResourceOrNull(graph, URIs.hasPrimaryShape_Inverse); - hasSecondaryShape = getResourceOrNull(graph, URIs.hasSecondaryShape); - hasSecondaryShape_Inverse = getResourceOrNull(graph, URIs.hasSecondaryShape_Inverse); - } - - public static CSG getInstance(ReadGraph graph) { - Session session = graph.getSession(); - CSG ret = session.peekService(CSG.class); - if(ret == null) { - QueryControl qc = graph.getService(QueryControl.class); - ret = new CSG(qc.getIndependentGraph(graph)); - session.registerService(CSG.class, ret); - } - return ret; - } - - public static CSG getInstance(RequestProcessor session) throws DatabaseException { - CSG ret = session.peekService(CSG.class); - if(ret == null) { - ret = session.syncRequest(new Read() { - public CSG perform(ReadGraph graph) throws DatabaseException { - QueryControl qc = graph.getService(QueryControl.class); - return new CSG(qc.getIndependentGraph(graph)); - } - }); - session.registerService(CSG.class, ret); - } - return ret; - } - + + public final Resource Barrel; + public final Resource BooleanOperation; + public final Resource Box; + public final Resource CSGBrowseContext; + public final Resource CSGBrowseContext_ActiveLabelDecorationRule; + public final Resource CSGBrowseContext_RunLabelRule; + public final Resource CSGBrowseContext_ShapeTabContribution; + public final Resource Cone; + public final Resource Cylinder; + public final Resource Difference; + public final Resource EllipticCylinder; + public final Resource HasBottomRadius; + public final Resource HasBottomRadius_Inverse; + public final Resource HasCorners; + public final Resource HasCorners_Inverse; + public final Resource HasHeight; + public final Resource HasHeight_Inverse; + public final Resource HasMajorRadius; + public final Resource HasMajorRadius_Inverse; + public final Resource HasMinorRadius; + public final Resource HasMinorRadius_Inverse; + public final Resource HasRadius; + public final Resource HasRadius_Inverse; + public final Resource HasSizingProperty; + public final Resource HasSizingProperty_Inverse; + public final Resource HasTopRadius; + public final Resource HasTopRadius_Inverse; + public final Resource HasXAxisMaximumSize; + public final Resource HasXAxisMaximumSize_Inverse; + public final Resource HasXAxisMinimumSize; + public final Resource HasXAxisMinimumSize_Inverse; + public final Resource HasXAxisSize; + public final Resource HasXAxisSize_Inverse; + public final Resource HasYAxisSize; + public final Resource HasYAxisSize_Inverse; + public final Resource HasZAxisMaximumSize; + public final Resource HasZAxisMaximumSize_Inverse; + public final Resource HasZAxisMinimumSize; + public final Resource HasZAxisMinimumSize_Inverse; + public final Resource HasZAxisSize; + public final Resource HasZAxisSize_Inverse; + public final Resource Images; + public final Resource Images_Difference; + public final Resource Images_Intersection; + public final Resource Images_Ruby; + public final Resource Images_Union; + public final Resource Intersection; + public final Resource Model; + public final Resource Primitive; + public final Resource RectangularSolid; + public final Resource RegularPrism; + public final Resource Shape; + public final Resource Sphere; + public final Resource Torus; + public final Resource Union; + public final Resource hasChildShape; + public final Resource hasChildShape_Inverse; + public final Resource hasPrimaryShape; + public final Resource hasPrimaryShape_Inverse; + public final Resource hasSecondaryShape; + public final Resource hasSecondaryShape_Inverse; + + public static class URIs { + public static final String Barrel = "http://www.simantics.org/CSG-0.1/Barrel"; + public static final String BooleanOperation = "http://www.simantics.org/CSG-0.1/BooleanOperation"; + public static final String Box = "http://www.simantics.org/CSG-0.1/Box"; + public static final String CSGBrowseContext = "http://www.simantics.org/CSG-0.1/CSGBrowseContext"; + public static final String CSGBrowseContext_ActiveLabelDecorationRule = "http://www.simantics.org/CSG-0.1/CSGBrowseContext/ActiveLabelDecorationRule"; + public static final String CSGBrowseContext_RunLabelRule = "http://www.simantics.org/CSG-0.1/CSGBrowseContext/RunLabelRule"; + public static final String CSGBrowseContext_ShapeTabContribution = "http://www.simantics.org/CSG-0.1/CSGBrowseContext/ShapeTabContribution"; + public static final String Cone = "http://www.simantics.org/CSG-0.1/Cone"; + public static final String Cylinder = "http://www.simantics.org/CSG-0.1/Cylinder"; + public static final String Difference = "http://www.simantics.org/CSG-0.1/Difference"; + public static final String EllipticCylinder = "http://www.simantics.org/CSG-0.1/EllipticCylinder"; + public static final String HasBottomRadius = "http://www.simantics.org/CSG-0.1/HasBottomRadius"; + public static final String HasBottomRadius_Inverse = "http://www.simantics.org/CSG-0.1/HasBottomRadius/Inverse"; + public static final String HasCorners = "http://www.simantics.org/CSG-0.1/HasCorners"; + public static final String HasCorners_Inverse = "http://www.simantics.org/CSG-0.1/HasCorners/Inverse"; + public static final String HasHeight = "http://www.simantics.org/CSG-0.1/HasHeight"; + public static final String HasHeight_Inverse = "http://www.simantics.org/CSG-0.1/HasHeight/Inverse"; + public static final String HasMajorRadius = "http://www.simantics.org/CSG-0.1/HasMajorRadius"; + public static final String HasMajorRadius_Inverse = "http://www.simantics.org/CSG-0.1/HasMajorRadius/Inverse"; + public static final String HasMinorRadius = "http://www.simantics.org/CSG-0.1/HasMinorRadius"; + public static final String HasMinorRadius_Inverse = "http://www.simantics.org/CSG-0.1/HasMinorRadius/Inverse"; + public static final String HasRadius = "http://www.simantics.org/CSG-0.1/HasRadius"; + public static final String HasRadius_Inverse = "http://www.simantics.org/CSG-0.1/HasRadius/Inverse"; + public static final String HasSizingProperty = "http://www.simantics.org/CSG-0.1/HasSizingProperty"; + public static final String HasSizingProperty_Inverse = "http://www.simantics.org/CSG-0.1/HasSizingProperty/Inverse"; + public static final String HasTopRadius = "http://www.simantics.org/CSG-0.1/HasTopRadius"; + public static final String HasTopRadius_Inverse = "http://www.simantics.org/CSG-0.1/HasTopRadius/Inverse"; + public static final String HasXAxisMaximumSize = "http://www.simantics.org/CSG-0.1/HasXAxisMaximumSize"; + public static final String HasXAxisMaximumSize_Inverse = "http://www.simantics.org/CSG-0.1/HasXAxisMaximumSize/Inverse"; + public static final String HasXAxisMinimumSize = "http://www.simantics.org/CSG-0.1/HasXAxisMinimumSize"; + public static final String HasXAxisMinimumSize_Inverse = "http://www.simantics.org/CSG-0.1/HasXAxisMinimumSize/Inverse"; + public static final String HasXAxisSize = "http://www.simantics.org/CSG-0.1/HasXAxisSize"; + public static final String HasXAxisSize_Inverse = "http://www.simantics.org/CSG-0.1/HasXAxisSize/Inverse"; + public static final String HasYAxisSize = "http://www.simantics.org/CSG-0.1/HasYAxisSize"; + public static final String HasYAxisSize_Inverse = "http://www.simantics.org/CSG-0.1/HasYAxisSize/Inverse"; + public static final String HasZAxisMaximumSize = "http://www.simantics.org/CSG-0.1/HasZAxisMaximumSize"; + public static final String HasZAxisMaximumSize_Inverse = "http://www.simantics.org/CSG-0.1/HasZAxisMaximumSize/Inverse"; + public static final String HasZAxisMinimumSize = "http://www.simantics.org/CSG-0.1/HasZAxisMinimumSize"; + public static final String HasZAxisMinimumSize_Inverse = "http://www.simantics.org/CSG-0.1/HasZAxisMinimumSize/Inverse"; + public static final String HasZAxisSize = "http://www.simantics.org/CSG-0.1/HasZAxisSize"; + public static final String HasZAxisSize_Inverse = "http://www.simantics.org/CSG-0.1/HasZAxisSize/Inverse"; + public static final String Images = "http://www.simantics.org/CSG-0.1/Images"; + public static final String Images_Difference = "http://www.simantics.org/CSG-0.1/Images/Difference"; + public static final String Images_Intersection = "http://www.simantics.org/CSG-0.1/Images/Intersection"; + public static final String Images_Ruby = "http://www.simantics.org/CSG-0.1/Images/Ruby"; + public static final String Images_Union = "http://www.simantics.org/CSG-0.1/Images/Union"; + public static final String Intersection = "http://www.simantics.org/CSG-0.1/Intersection"; + public static final String Model = "http://www.simantics.org/CSG-0.1/Model"; + public static final String Primitive = "http://www.simantics.org/CSG-0.1/Primitive"; + public static final String RectangularSolid = "http://www.simantics.org/CSG-0.1/RectangularSolid"; + public static final String RegularPrism = "http://www.simantics.org/CSG-0.1/RegularPrism"; + public static final String Shape = "http://www.simantics.org/CSG-0.1/Shape"; + public static final String Sphere = "http://www.simantics.org/CSG-0.1/Sphere"; + public static final String Torus = "http://www.simantics.org/CSG-0.1/Torus"; + public static final String Union = "http://www.simantics.org/CSG-0.1/Union"; + public static final String hasChildShape = "http://www.simantics.org/CSG-0.1/hasChildShape"; + public static final String hasChildShape_Inverse = "http://www.simantics.org/CSG-0.1/hasChildShape/Inverse"; + public static final String hasPrimaryShape = "http://www.simantics.org/CSG-0.1/hasPrimaryShape"; + public static final String hasPrimaryShape_Inverse = "http://www.simantics.org/CSG-0.1/hasPrimaryShape/Inverse"; + public static final String hasSecondaryShape = "http://www.simantics.org/CSG-0.1/hasSecondaryShape"; + public static final String hasSecondaryShape_Inverse = "http://www.simantics.org/CSG-0.1/hasSecondaryShape/Inverse"; + } + + public static Resource getResourceOrNull(ReadGraph graph, String uri) { + try { + return graph.getResource(uri); + } catch(DatabaseException e) { + System.err.println(e.getMessage()); + return null; + } + } + + public CSG(ReadGraph graph) { + Barrel = getResourceOrNull(graph, URIs.Barrel); + BooleanOperation = getResourceOrNull(graph, URIs.BooleanOperation); + Box = getResourceOrNull(graph, URIs.Box); + CSGBrowseContext = getResourceOrNull(graph, URIs.CSGBrowseContext); + CSGBrowseContext_ActiveLabelDecorationRule = getResourceOrNull(graph, URIs.CSGBrowseContext_ActiveLabelDecorationRule); + CSGBrowseContext_RunLabelRule = getResourceOrNull(graph, URIs.CSGBrowseContext_RunLabelRule); + CSGBrowseContext_ShapeTabContribution = getResourceOrNull(graph, URIs.CSGBrowseContext_ShapeTabContribution); + Cone = getResourceOrNull(graph, URIs.Cone); + Cylinder = getResourceOrNull(graph, URIs.Cylinder); + Difference = getResourceOrNull(graph, URIs.Difference); + EllipticCylinder = getResourceOrNull(graph, URIs.EllipticCylinder); + HasBottomRadius = getResourceOrNull(graph, URIs.HasBottomRadius); + HasBottomRadius_Inverse = getResourceOrNull(graph, URIs.HasBottomRadius_Inverse); + HasCorners = getResourceOrNull(graph, URIs.HasCorners); + HasCorners_Inverse = getResourceOrNull(graph, URIs.HasCorners_Inverse); + HasHeight = getResourceOrNull(graph, URIs.HasHeight); + HasHeight_Inverse = getResourceOrNull(graph, URIs.HasHeight_Inverse); + HasMajorRadius = getResourceOrNull(graph, URIs.HasMajorRadius); + HasMajorRadius_Inverse = getResourceOrNull(graph, URIs.HasMajorRadius_Inverse); + HasMinorRadius = getResourceOrNull(graph, URIs.HasMinorRadius); + HasMinorRadius_Inverse = getResourceOrNull(graph, URIs.HasMinorRadius_Inverse); + HasRadius = getResourceOrNull(graph, URIs.HasRadius); + HasRadius_Inverse = getResourceOrNull(graph, URIs.HasRadius_Inverse); + HasSizingProperty = getResourceOrNull(graph, URIs.HasSizingProperty); + HasSizingProperty_Inverse = getResourceOrNull(graph, URIs.HasSizingProperty_Inverse); + HasTopRadius = getResourceOrNull(graph, URIs.HasTopRadius); + HasTopRadius_Inverse = getResourceOrNull(graph, URIs.HasTopRadius_Inverse); + HasXAxisMaximumSize = getResourceOrNull(graph, URIs.HasXAxisMaximumSize); + HasXAxisMaximumSize_Inverse = getResourceOrNull(graph, URIs.HasXAxisMaximumSize_Inverse); + HasXAxisMinimumSize = getResourceOrNull(graph, URIs.HasXAxisMinimumSize); + HasXAxisMinimumSize_Inverse = getResourceOrNull(graph, URIs.HasXAxisMinimumSize_Inverse); + HasXAxisSize = getResourceOrNull(graph, URIs.HasXAxisSize); + HasXAxisSize_Inverse = getResourceOrNull(graph, URIs.HasXAxisSize_Inverse); + HasYAxisSize = getResourceOrNull(graph, URIs.HasYAxisSize); + HasYAxisSize_Inverse = getResourceOrNull(graph, URIs.HasYAxisSize_Inverse); + HasZAxisMaximumSize = getResourceOrNull(graph, URIs.HasZAxisMaximumSize); + HasZAxisMaximumSize_Inverse = getResourceOrNull(graph, URIs.HasZAxisMaximumSize_Inverse); + HasZAxisMinimumSize = getResourceOrNull(graph, URIs.HasZAxisMinimumSize); + HasZAxisMinimumSize_Inverse = getResourceOrNull(graph, URIs.HasZAxisMinimumSize_Inverse); + HasZAxisSize = getResourceOrNull(graph, URIs.HasZAxisSize); + HasZAxisSize_Inverse = getResourceOrNull(graph, URIs.HasZAxisSize_Inverse); + Images = getResourceOrNull(graph, URIs.Images); + Images_Difference = getResourceOrNull(graph, URIs.Images_Difference); + Images_Intersection = getResourceOrNull(graph, URIs.Images_Intersection); + Images_Ruby = getResourceOrNull(graph, URIs.Images_Ruby); + Images_Union = getResourceOrNull(graph, URIs.Images_Union); + Intersection = getResourceOrNull(graph, URIs.Intersection); + Model = getResourceOrNull(graph, URIs.Model); + Primitive = getResourceOrNull(graph, URIs.Primitive); + RectangularSolid = getResourceOrNull(graph, URIs.RectangularSolid); + RegularPrism = getResourceOrNull(graph, URIs.RegularPrism); + Shape = getResourceOrNull(graph, URIs.Shape); + Sphere = getResourceOrNull(graph, URIs.Sphere); + Torus = getResourceOrNull(graph, URIs.Torus); + Union = getResourceOrNull(graph, URIs.Union); + hasChildShape = getResourceOrNull(graph, URIs.hasChildShape); + hasChildShape_Inverse = getResourceOrNull(graph, URIs.hasChildShape_Inverse); + hasPrimaryShape = getResourceOrNull(graph, URIs.hasPrimaryShape); + hasPrimaryShape_Inverse = getResourceOrNull(graph, URIs.hasPrimaryShape_Inverse); + hasSecondaryShape = getResourceOrNull(graph, URIs.hasSecondaryShape); + hasSecondaryShape_Inverse = getResourceOrNull(graph, URIs.hasSecondaryShape_Inverse); + } + + public static CSG getInstance(ReadGraph graph) { + Session session = graph.getSession(); + CSG ret = session.peekService(CSG.class); + if(ret == null) { + QueryControl qc = graph.getService(QueryControl.class); + ret = new CSG(qc.getIndependentGraph(graph)); + session.registerService(CSG.class, ret); + } + return ret; + } + + public static CSG getInstance(RequestProcessor session) throws DatabaseException { + CSG ret = session.peekService(CSG.class); + if(ret == null) { + ret = session.syncRequest(new Read() { + public CSG perform(ReadGraph graph) throws DatabaseException { + QueryControl qc = graph.getService(QueryControl.class); + return new CSG(qc.getIndependentGraph(graph)); + } + }); + session.registerService(CSG.class, ret); + } + return ret; + } + } diff --git a/org.simantics.g3d.csg/src/org/simantics/g3d/csg/editor/CSGEditor2.java b/org.simantics.g3d.csg/src/org/simantics/g3d/csg/editor/CSGEditor2.java index bed44873..91b51419 100644 --- a/org.simantics.g3d.csg/src/org/simantics/g3d/csg/editor/CSGEditor2.java +++ b/org.simantics.g3d.csg/src/org/simantics/g3d/csg/editor/CSGEditor2.java @@ -283,12 +283,12 @@ public class CSGEditor2 extends ResourceEditorPart { ren1.SetBackground(0.9,0.9,0.9); ren1.SetGradientBackground(true); - // vtkActor grid = vtkShape.createGridActor(8,1.0,1|2|4); - vtkActor grid = vtkShape.createGridActor(8,1.0, 2 ); - grid.SetPickable(0); - ren1.AddActor(grid); - panel.addDeletable(grid); - + // vtkActor grid = vtkShape.createGridActor(8,1.0,1|2|4); + vtkActor grid = vtkShape.createGridActor(8,1.0, 2 ); + grid.SetPickable(0); + ren1.AddActor(grid); + panel.addDeletable(grid); + } @@ -296,24 +296,24 @@ public class CSGEditor2 extends ResourceEditorPart { protected Menu contextMenu; protected void hookContextMenu() { - MenuManager menuMgr = new MenuManager("#PopupMenu"); - menuMgr.setRemoveAllWhenShown(true); - menuMgr.addMenuListener(new IMenuListener() { - public void menuAboutToShow(IMenuManager manager) { - final IMenuManager m = manager; - List selected = selectionProvider.getSelectedNodes(); - if (selected.size() == 0) { - m.add(new AddPrimitiveAction2(rootNode, BarrelNode.class)); - m.add(new AddPrimitiveAction2(rootNode, BoxNode.class)); - m.add(new AddPrimitiveAction2(rootNode, ConeNode.class)); - m.add(new AddPrimitiveAction2(rootNode, CylinderNode.class)); - m.add(new AddPrimitiveAction2(rootNode, EllipticCylinderNode.class)); - m.add(new AddPrimitiveAction2(rootNode, RectangularSolidNode.class)); - m.add(new AddPrimitiveAction2(rootNode, RegularPrismNode.class)); - m.add(new AddPrimitiveAction2(rootNode, SphereNode.class)); - m.add(new AddPrimitiveAction2(rootNode, TorusNode.class)); - } else if (selected.size() == 1) { - m.add(translateAction); + MenuManager menuMgr = new MenuManager("#PopupMenu"); + menuMgr.setRemoveAllWhenShown(true); + menuMgr.addMenuListener(new IMenuListener() { + public void menuAboutToShow(IMenuManager manager) { + final IMenuManager m = manager; + List selected = selectionProvider.getSelectedNodes(); + if (selected.size() == 0) { + m.add(new AddPrimitiveAction2(rootNode, BarrelNode.class)); + m.add(new AddPrimitiveAction2(rootNode, BoxNode.class)); + m.add(new AddPrimitiveAction2(rootNode, ConeNode.class)); + m.add(new AddPrimitiveAction2(rootNode, CylinderNode.class)); + m.add(new AddPrimitiveAction2(rootNode, EllipticCylinderNode.class)); + m.add(new AddPrimitiveAction2(rootNode, RectangularSolidNode.class)); + m.add(new AddPrimitiveAction2(rootNode, RegularPrismNode.class)); + m.add(new AddPrimitiveAction2(rootNode, SphereNode.class)); + m.add(new AddPrimitiveAction2(rootNode, TorusNode.class)); + } else if (selected.size() == 1) { + m.add(translateAction); m.add(rotateAction); m.add(removeAction); ICSGnode node = (ICSGnode)selected.get(0); @@ -323,16 +323,16 @@ public class CSGEditor2 extends ResourceEditorPart { if (node instanceof CSGparentNode) { m.add(new SplitBooleanOpAction2(rootNode,(CSGparentNode)node)); } - } else if (selected.size() == 2) { - if (selected.get(0).getParent().equals(rootNode) && selected.get(1).getParent().equals(rootNode)) { - Collection nodes = new ArrayList(); - for (IG3DNode n : selected) - nodes.add((ICSGnode)n); - m.add(new AddBooleanOpAction2(rootNode, DifferenceNode.class, nodes)); - m.add(new AddBooleanOpAction2(rootNode, IntersectionNode.class, nodes)); - m.add(new AddBooleanOpAction2(rootNode, UnionNode.class, nodes)); - } - } + } else if (selected.size() == 2) { + if (selected.get(0).getParent().equals(rootNode) && selected.get(1).getParent().equals(rootNode)) { + Collection nodes = new ArrayList(); + for (IG3DNode n : selected) + nodes.add((ICSGnode)n); + m.add(new AddBooleanOpAction2(rootNode, DifferenceNode.class, nodes)); + m.add(new AddBooleanOpAction2(rootNode, IntersectionNode.class, nodes)); + m.add(new AddBooleanOpAction2(rootNode, UnionNode.class, nodes)); + } + } // try { // SimanticsUI.getSession().syncRequest(new ReadRequest() { // @@ -389,12 +389,12 @@ public class CSGEditor2 extends ResourceEditorPart { // // TODO Auto-generated catch block // e.printStackTrace(); // } - - } - }); + + } + }); - contextMenu = menuMgr.createContextMenu(parent); - } + contextMenu = menuMgr.createContextMenu(parent); + } private IContentOutlinePage createOutline() { if (rootNode == null || selectionProvider == null) diff --git a/org.simantics.g3d.csg/src/org/simantics/g3d/csg/editor/CSGNodeMap.java b/org.simantics.g3d.csg/src/org/simantics/g3d/csg/editor/CSGNodeMap.java index b4eaa148..c2712b8c 100644 --- a/org.simantics.g3d.csg/src/org/simantics/g3d/csg/editor/CSGNodeMap.java +++ b/org.simantics.g3d.csg/src/org/simantics/g3d/csg/editor/CSGNodeMap.java @@ -90,10 +90,10 @@ public class CSGNodeMap extends AbstractVTKNodeMap { for (vtkProp3D act : node.getActors()) { nodeToActor.add(node, act); - actorToNode.put(act, node); + actorToNode.put(act, node); } - view.unlock(); + view.unlock(); } diff --git a/org.simantics.g3d.csg/src/org/simantics/g3d/csg/wizard/CSGBRepExportWizard.java b/org.simantics.g3d.csg/src/org/simantics/g3d/csg/wizard/CSGBRepExportWizard.java index 06ceb3b9..dbcbf761 100644 --- a/org.simantics.g3d.csg/src/org/simantics/g3d/csg/wizard/CSGBRepExportWizard.java +++ b/org.simantics.g3d.csg/src/org/simantics/g3d/csg/wizard/CSGBRepExportWizard.java @@ -25,7 +25,7 @@ public class CSGBRepExportWizard extends ModelExportWizard { public static final String RECENT_CSG_EXPORT_LOCATIONS = "RECENT_CSG_EXPORT_LOCATIONS"; public static final String CSG_EXPORT_OVERWRITE = "CSG_EXPORT_OVERWRITE"; - + public CSGBRepExportWizard() { setWindowTitle("Export CSG Model to Brep"); setNeedsProgressMonitor(true); diff --git a/org.simantics.g3d.csg/src/org/simantics/g3d/csg/wizard/CSGBrepModelExporter.java b/org.simantics.g3d.csg/src/org/simantics/g3d/csg/wizard/CSGBrepModelExporter.java index 4ac0b728..a0e742ec 100644 --- a/org.simantics.g3d.csg/src/org/simantics/g3d/csg/wizard/CSGBrepModelExporter.java +++ b/org.simantics.g3d.csg/src/org/simantics/g3d/csg/wizard/CSGBrepModelExporter.java @@ -43,19 +43,19 @@ public class CSGBrepModelExporter implements IRunnableWithProgress { @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { - SubMonitor progress = SubMonitor.convert(monitor, 50); - SubMonitor mon = progress.newChild(50, SubMonitor.SUPPRESS_NONE); - try { - exportModel(mon); - } catch (IOException e) { - mon.setCanceled(true); - throw new InvocationTargetException(e); - } catch (DatabaseException e) { - mon.setCanceled(true); - throw new InvocationTargetException(e); - } finally { - monitor.done(); - } + SubMonitor progress = SubMonitor.convert(monitor, 50); + SubMonitor mon = progress.newChild(50, SubMonitor.SUPPRESS_NONE); + try { + exportModel(mon); + } catch (IOException e) { + mon.setCanceled(true); + throw new InvocationTargetException(e); + } catch (DatabaseException e) { + mon.setCanceled(true); + throw new InvocationTargetException(e); + } finally { + monitor.done(); + } } diff --git a/org.simantics.g3d.csg/src/org/simantics/g3d/csg/wizard/CSGExportModel.java b/org.simantics.g3d.csg/src/org/simantics/g3d/csg/wizard/CSGExportModel.java index c1a66a6c..833a333f 100644 --- a/org.simantics.g3d.csg/src/org/simantics/g3d/csg/wizard/CSGExportModel.java +++ b/org.simantics.g3d.csg/src/org/simantics/g3d/csg/wizard/CSGExportModel.java @@ -17,16 +17,16 @@ import org.simantics.g3d.wizard.IExportModel; public class CSGExportModel extends IExportModel{ - - - public CSGExportModel(Deque recentLocations) { - super(); - setRecentLocations(recentLocations); - } - - @Override - public boolean usesFile() { - return true; - } + + + public CSGExportModel(Deque recentLocations) { + super(); + setRecentLocations(recentLocations); + } + + @Override + public boolean usesFile() { + return true; + } } diff --git a/org.simantics.g3d.csg/src/org/simantics/g3d/csg/wizard/CSGExportPage.java b/org.simantics.g3d.csg/src/org/simantics/g3d/csg/wizard/CSGExportPage.java index 8a3237dc..5e9dc85c 100644 --- a/org.simantics.g3d.csg/src/org/simantics/g3d/csg/wizard/CSGExportPage.java +++ b/org.simantics.g3d.csg/src/org/simantics/g3d/csg/wizard/CSGExportPage.java @@ -25,7 +25,7 @@ import org.simantics.layer0.Layer0; public class CSGExportPage extends ModelExportWizardPage { - + public CSGExportPage(CSGExportModel model) { super("Export CSG Model","Define Export Location",null,model); } @@ -45,18 +45,14 @@ public class CSGExportPage extends ModelExportWizardPage { protected List getSupportedModels(ReadGraph graph, Resource project) throws DatabaseException { List models = new ArrayList(); Layer0 L0 = Layer0.getInstance(graph); - CSG csg = CSG.getInstance(graph); - - for (Resource r : graph.getObjects(project, L0.ConsistsOf)) { - if (graph.isInstanceOf(r, csg.Model)) { - models.add(new NamedResource((String)graph.getRelatedValue(r, L0.HasName), r)); - } - } - return models; + CSG csg = CSG.getInstance(graph); + + for (Resource r : graph.getObjects(project, L0.ConsistsOf)) { + if (graph.isInstanceOf(r, csg.Model)) { + models.add(new NamedResource((String)graph.getRelatedValue(r, L0.HasName), r)); + } + } + return models; } - - - - } diff --git a/org.simantics.g3d.ontology/src/org/simantics/g3d/ontology/G3D.java b/org.simantics.g3d.ontology/src/org/simantics/g3d/ontology/G3D.java index f58a9f6d..1569ad9f 100644 --- a/org.simantics.g3d.ontology/src/org/simantics/g3d/ontology/G3D.java +++ b/org.simantics.g3d.ontology/src/org/simantics/g3d/ontology/G3D.java @@ -9,134 +9,134 @@ import org.simantics.db.exception.DatabaseException; import org.simantics.db.service.QueryControl; public class G3D { - - public final Resource BaseNode; - public final Resource Node; - public final Resource Orientation; - public final Resource Position; - public final Resource RootNode; - public final Resource Tuple3D; - public final Resource Tuple4D; - public final Resource children; - public final Resource geometryDefinition; - public final Resource geometryDefinitionOf; - public final Resource hasNodeProperty; - public final Resource hasNodeProperty_Inverse; - public final Resource hasNonTransformation; - public final Resource hasNonTransformation_Inverse; - public final Resource hasOrientation; - public final Resource hasOrientation_Inverse; - public final Resource hasPosition; - public final Resource hasPosition_Inverse; - public final Resource hasTransformation; - public final Resource hasTransformation_Inverse; - public final Resource hasWorldOrientation; - public final Resource hasWorldOrientation_Inverse; - public final Resource hasWorldPosition; - public final Resource hasWorldPosition_Inverse; - public final Resource nodes; - public final Resource parent; - public final Resource parentNode; - public final Resource publishes; - public final Resource publishes_Inverse; - - public static class URIs { - public static final String BaseNode = "http://www.simantics.org/G3D-0.1/BaseNode"; - public static final String Node = "http://www.simantics.org/G3D-0.1/Node"; - public static final String Orientation = "http://www.simantics.org/G3D-0.1/Orientation"; - public static final String Position = "http://www.simantics.org/G3D-0.1/Position"; - public static final String RootNode = "http://www.simantics.org/G3D-0.1/RootNode"; - public static final String Tuple3D = "http://www.simantics.org/G3D-0.1/Tuple3D"; - public static final String Tuple4D = "http://www.simantics.org/G3D-0.1/Tuple4D"; - public static final String children = "http://www.simantics.org/G3D-0.1/children"; - public static final String geometryDefinition = "http://www.simantics.org/G3D-0.1/geometryDefinition"; - public static final String geometryDefinitionOf = "http://www.simantics.org/G3D-0.1/geometryDefinitionOf"; - public static final String hasNodeProperty = "http://www.simantics.org/G3D-0.1/hasNodeProperty"; - public static final String hasNodeProperty_Inverse = "http://www.simantics.org/G3D-0.1/hasNodeProperty/Inverse"; - public static final String hasNonTransformation = "http://www.simantics.org/G3D-0.1/hasNonTransformation"; - public static final String hasNonTransformation_Inverse = "http://www.simantics.org/G3D-0.1/hasNonTransformation/Inverse"; - public static final String hasOrientation = "http://www.simantics.org/G3D-0.1/hasOrientation"; - public static final String hasOrientation_Inverse = "http://www.simantics.org/G3D-0.1/hasOrientation/Inverse"; - public static final String hasPosition = "http://www.simantics.org/G3D-0.1/hasPosition"; - public static final String hasPosition_Inverse = "http://www.simantics.org/G3D-0.1/hasPosition/Inverse"; - public static final String hasTransformation = "http://www.simantics.org/G3D-0.1/hasTransformation"; - public static final String hasTransformation_Inverse = "http://www.simantics.org/G3D-0.1/hasTransformation/Inverse"; - public static final String hasWorldOrientation = "http://www.simantics.org/G3D-0.1/hasWorldOrientation"; - public static final String hasWorldOrientation_Inverse = "http://www.simantics.org/G3D-0.1/hasWorldOrientation/Inverse"; - public static final String hasWorldPosition = "http://www.simantics.org/G3D-0.1/hasWorldPosition"; - public static final String hasWorldPosition_Inverse = "http://www.simantics.org/G3D-0.1/hasWorldPosition/Inverse"; - public static final String nodes = "http://www.simantics.org/G3D-0.1/nodes"; - public static final String parent = "http://www.simantics.org/G3D-0.1/parent"; - public static final String parentNode = "http://www.simantics.org/G3D-0.1/parentNode"; - public static final String publishes = "http://www.simantics.org/G3D-0.1/publishes"; - public static final String publishes_Inverse = "http://www.simantics.org/G3D-0.1/publishes/Inverse"; - } - - public static Resource getResourceOrNull(ReadGraph graph, String uri) { - try { - return graph.getResource(uri); - } catch(DatabaseException e) { - System.err.println(e.getMessage()); - return null; - } - } - - public G3D(ReadGraph graph) { - BaseNode = getResourceOrNull(graph, URIs.BaseNode); - Node = getResourceOrNull(graph, URIs.Node); - Orientation = getResourceOrNull(graph, URIs.Orientation); - Position = getResourceOrNull(graph, URIs.Position); - RootNode = getResourceOrNull(graph, URIs.RootNode); - Tuple3D = getResourceOrNull(graph, URIs.Tuple3D); - Tuple4D = getResourceOrNull(graph, URIs.Tuple4D); - children = getResourceOrNull(graph, URIs.children); - geometryDefinition = getResourceOrNull(graph, URIs.geometryDefinition); - geometryDefinitionOf = getResourceOrNull(graph, URIs.geometryDefinitionOf); - hasNodeProperty = getResourceOrNull(graph, URIs.hasNodeProperty); - hasNodeProperty_Inverse = getResourceOrNull(graph, URIs.hasNodeProperty_Inverse); - hasNonTransformation = getResourceOrNull(graph, URIs.hasNonTransformation); - hasNonTransformation_Inverse = getResourceOrNull(graph, URIs.hasNonTransformation_Inverse); - hasOrientation = getResourceOrNull(graph, URIs.hasOrientation); - hasOrientation_Inverse = getResourceOrNull(graph, URIs.hasOrientation_Inverse); - hasPosition = getResourceOrNull(graph, URIs.hasPosition); - hasPosition_Inverse = getResourceOrNull(graph, URIs.hasPosition_Inverse); - hasTransformation = getResourceOrNull(graph, URIs.hasTransformation); - hasTransformation_Inverse = getResourceOrNull(graph, URIs.hasTransformation_Inverse); - hasWorldOrientation = getResourceOrNull(graph, URIs.hasWorldOrientation); - hasWorldOrientation_Inverse = getResourceOrNull(graph, URIs.hasWorldOrientation_Inverse); - hasWorldPosition = getResourceOrNull(graph, URIs.hasWorldPosition); - hasWorldPosition_Inverse = getResourceOrNull(graph, URIs.hasWorldPosition_Inverse); - nodes = getResourceOrNull(graph, URIs.nodes); - parent = getResourceOrNull(graph, URIs.parent); - parentNode = getResourceOrNull(graph, URIs.parentNode); - publishes = getResourceOrNull(graph, URIs.publishes); - publishes_Inverse = getResourceOrNull(graph, URIs.publishes_Inverse); - } - - public static G3D getInstance(ReadGraph graph) { - Session session = graph.getSession(); - G3D ret = session.peekService(G3D.class); - if(ret == null) { - QueryControl qc = graph.getService(QueryControl.class); - ret = new G3D(qc.getIndependentGraph(graph)); - session.registerService(G3D.class, ret); - } - return ret; - } - - public static G3D getInstance(RequestProcessor session) throws DatabaseException { - G3D ret = session.peekService(G3D.class); - if(ret == null) { - ret = session.syncRequest(new Read() { - public G3D perform(ReadGraph graph) throws DatabaseException { - QueryControl qc = graph.getService(QueryControl.class); - return new G3D(qc.getIndependentGraph(graph)); - } - }); - session.registerService(G3D.class, ret); - } - return ret; - } - + + public final Resource BaseNode; + public final Resource Node; + public final Resource Orientation; + public final Resource Position; + public final Resource RootNode; + public final Resource Tuple3D; + public final Resource Tuple4D; + public final Resource children; + public final Resource geometryDefinition; + public final Resource geometryDefinitionOf; + public final Resource hasNodeProperty; + public final Resource hasNodeProperty_Inverse; + public final Resource hasNonTransformation; + public final Resource hasNonTransformation_Inverse; + public final Resource hasOrientation; + public final Resource hasOrientation_Inverse; + public final Resource hasPosition; + public final Resource hasPosition_Inverse; + public final Resource hasTransformation; + public final Resource hasTransformation_Inverse; + public final Resource hasWorldOrientation; + public final Resource hasWorldOrientation_Inverse; + public final Resource hasWorldPosition; + public final Resource hasWorldPosition_Inverse; + public final Resource nodes; + public final Resource parent; + public final Resource parentNode; + public final Resource publishes; + public final Resource publishes_Inverse; + + public static class URIs { + public static final String BaseNode = "http://www.simantics.org/G3D-0.1/BaseNode"; + public static final String Node = "http://www.simantics.org/G3D-0.1/Node"; + public static final String Orientation = "http://www.simantics.org/G3D-0.1/Orientation"; + public static final String Position = "http://www.simantics.org/G3D-0.1/Position"; + public static final String RootNode = "http://www.simantics.org/G3D-0.1/RootNode"; + public static final String Tuple3D = "http://www.simantics.org/G3D-0.1/Tuple3D"; + public static final String Tuple4D = "http://www.simantics.org/G3D-0.1/Tuple4D"; + public static final String children = "http://www.simantics.org/G3D-0.1/children"; + public static final String geometryDefinition = "http://www.simantics.org/G3D-0.1/geometryDefinition"; + public static final String geometryDefinitionOf = "http://www.simantics.org/G3D-0.1/geometryDefinitionOf"; + public static final String hasNodeProperty = "http://www.simantics.org/G3D-0.1/hasNodeProperty"; + public static final String hasNodeProperty_Inverse = "http://www.simantics.org/G3D-0.1/hasNodeProperty/Inverse"; + public static final String hasNonTransformation = "http://www.simantics.org/G3D-0.1/hasNonTransformation"; + public static final String hasNonTransformation_Inverse = "http://www.simantics.org/G3D-0.1/hasNonTransformation/Inverse"; + public static final String hasOrientation = "http://www.simantics.org/G3D-0.1/hasOrientation"; + public static final String hasOrientation_Inverse = "http://www.simantics.org/G3D-0.1/hasOrientation/Inverse"; + public static final String hasPosition = "http://www.simantics.org/G3D-0.1/hasPosition"; + public static final String hasPosition_Inverse = "http://www.simantics.org/G3D-0.1/hasPosition/Inverse"; + public static final String hasTransformation = "http://www.simantics.org/G3D-0.1/hasTransformation"; + public static final String hasTransformation_Inverse = "http://www.simantics.org/G3D-0.1/hasTransformation/Inverse"; + public static final String hasWorldOrientation = "http://www.simantics.org/G3D-0.1/hasWorldOrientation"; + public static final String hasWorldOrientation_Inverse = "http://www.simantics.org/G3D-0.1/hasWorldOrientation/Inverse"; + public static final String hasWorldPosition = "http://www.simantics.org/G3D-0.1/hasWorldPosition"; + public static final String hasWorldPosition_Inverse = "http://www.simantics.org/G3D-0.1/hasWorldPosition/Inverse"; + public static final String nodes = "http://www.simantics.org/G3D-0.1/nodes"; + public static final String parent = "http://www.simantics.org/G3D-0.1/parent"; + public static final String parentNode = "http://www.simantics.org/G3D-0.1/parentNode"; + public static final String publishes = "http://www.simantics.org/G3D-0.1/publishes"; + public static final String publishes_Inverse = "http://www.simantics.org/G3D-0.1/publishes/Inverse"; + } + + public static Resource getResourceOrNull(ReadGraph graph, String uri) { + try { + return graph.getResource(uri); + } catch(DatabaseException e) { + System.err.println(e.getMessage()); + return null; + } + } + + public G3D(ReadGraph graph) { + BaseNode = getResourceOrNull(graph, URIs.BaseNode); + Node = getResourceOrNull(graph, URIs.Node); + Orientation = getResourceOrNull(graph, URIs.Orientation); + Position = getResourceOrNull(graph, URIs.Position); + RootNode = getResourceOrNull(graph, URIs.RootNode); + Tuple3D = getResourceOrNull(graph, URIs.Tuple3D); + Tuple4D = getResourceOrNull(graph, URIs.Tuple4D); + children = getResourceOrNull(graph, URIs.children); + geometryDefinition = getResourceOrNull(graph, URIs.geometryDefinition); + geometryDefinitionOf = getResourceOrNull(graph, URIs.geometryDefinitionOf); + hasNodeProperty = getResourceOrNull(graph, URIs.hasNodeProperty); + hasNodeProperty_Inverse = getResourceOrNull(graph, URIs.hasNodeProperty_Inverse); + hasNonTransformation = getResourceOrNull(graph, URIs.hasNonTransformation); + hasNonTransformation_Inverse = getResourceOrNull(graph, URIs.hasNonTransformation_Inverse); + hasOrientation = getResourceOrNull(graph, URIs.hasOrientation); + hasOrientation_Inverse = getResourceOrNull(graph, URIs.hasOrientation_Inverse); + hasPosition = getResourceOrNull(graph, URIs.hasPosition); + hasPosition_Inverse = getResourceOrNull(graph, URIs.hasPosition_Inverse); + hasTransformation = getResourceOrNull(graph, URIs.hasTransformation); + hasTransformation_Inverse = getResourceOrNull(graph, URIs.hasTransformation_Inverse); + hasWorldOrientation = getResourceOrNull(graph, URIs.hasWorldOrientation); + hasWorldOrientation_Inverse = getResourceOrNull(graph, URIs.hasWorldOrientation_Inverse); + hasWorldPosition = getResourceOrNull(graph, URIs.hasWorldPosition); + hasWorldPosition_Inverse = getResourceOrNull(graph, URIs.hasWorldPosition_Inverse); + nodes = getResourceOrNull(graph, URIs.nodes); + parent = getResourceOrNull(graph, URIs.parent); + parentNode = getResourceOrNull(graph, URIs.parentNode); + publishes = getResourceOrNull(graph, URIs.publishes); + publishes_Inverse = getResourceOrNull(graph, URIs.publishes_Inverse); + } + + public static G3D getInstance(ReadGraph graph) { + Session session = graph.getSession(); + G3D ret = session.peekService(G3D.class); + if(ret == null) { + QueryControl qc = graph.getService(QueryControl.class); + ret = new G3D(qc.getIndependentGraph(graph)); + session.registerService(G3D.class, ret); + } + return ret; + } + + public static G3D getInstance(RequestProcessor session) throws DatabaseException { + G3D ret = session.peekService(G3D.class); + if(ret == null) { + ret = session.syncRequest(new Read() { + public G3D perform(ReadGraph graph) throws DatabaseException { + QueryControl qc = graph.getService(QueryControl.class); + return new G3D(qc.getIndependentGraph(graph)); + } + }); + session.registerService(G3D.class, ret); + } + return ret; + } + } diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/awt/InteractiveVtkPanel.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/awt/InteractiveVtkPanel.java index df91a5d4..09e88ae6 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/awt/InteractiveVtkPanel.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/awt/InteractiveVtkPanel.java @@ -42,11 +42,11 @@ import vtk.vtkScenePicker; public class InteractiveVtkPanel extends vtkPanel implements VtkView { protected vtkGenericRenderWindowInteractor iren; - + public vtkGenericRenderWindowInteractor getRenderWindowInteractor() { - return this.iren; - } + return this.iren; + } private static final long serialVersionUID = 2815073937537950615L; @@ -54,13 +54,13 @@ public class InteractiveVtkPanel extends vtkPanel implements VtkView { super(); iren = new vtkGenericRenderWindowInteractor(); iren.SetRenderWindow(rw); - iren.TimerEventResetsTimerOff(); - iren.SetSize(200, 200); - iren.ConfigureEvent(); - vtkInteractorStyleTrackballCamera style = new vtkInteractorStyleTrackballCamera(); - iren.SetInteractorStyle(style); - addDeletable(style); - addDeletable(iren); + iren.TimerEventResetsTimerOff(); + iren.SetSize(200, 200); + iren.ConfigureEvent(); + vtkInteractorStyleTrackballCamera style = new vtkInteractorStyleTrackballCamera(); + iren.SetInteractorStyle(style); + addDeletable(style); + addDeletable(iren); } @Override @@ -119,14 +119,14 @@ public class InteractiveVtkPanel extends vtkPanel implements VtkView { } public void setSize(int x, int y) { - if (windowset == 1) { - Lock(); - rw.SetSize(x, y); - iren.SetSize(x, y); - iren.ConfigureEvent(); - UnLock(); - } - } + if (windowset == 1) { + Lock(); + rw.SetSize(x, y); + iren.SetSize(x, y); + iren.ConfigureEvent(); + UnLock(); + } + } private vtkScenePicker scenePicker; diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/awt/RotateAction.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/awt/RotateAction.java index 4f62533b..aaadc0ed 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/awt/RotateAction.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/awt/RotateAction.java @@ -44,9 +44,9 @@ import vtk.vtkProp; public class RotateAction extends vtkAwtAction{ public static final int X = 0; - public static final int Y = 1; - public static final int Z = 2; - public static final int P = 3; + public static final int Y = 1; + public static final int Z = 2; + public static final int P = 3; private VTKNodeMap nodeMap; //private TranslateGizmo gizmo = new TranslateGizmo(); @@ -62,8 +62,8 @@ public class RotateAction extends vtkAwtAction{ int stepMethod = 1; Order order = Order.YXZ; - private int steps; - private double angles[]; + private int steps; + private double angles[]; int index = P; boolean valid = false; @@ -110,10 +110,10 @@ public class RotateAction extends vtkAwtAction{ steps = 36; - angles = new double[steps+1]; - for (int i = 0; i < angles.length; i++) { - angles[i] = - Math.PI + (Math.PI * i * 2.0 / steps); - } + angles = new double[steps+1]; + for (int i = 0; i < angles.length; i++) { + angles[i] = - Math.PI + (Math.PI * i * 2.0 / steps); + } } public void attach() { @@ -251,31 +251,31 @@ public class RotateAction extends vtkAwtAction{ if (panel.GetRenderer().GetActiveCamera().GetParallelProjection() == 0) { double distance = p.length(); p.negate(); - double fov = panel.GetRenderer().GetActiveCamera().GetViewAngle(); - float s = (float) (Math.sin(fov) * distance * 0.1); + double fov = panel.GetRenderer().GetActiveCamera().GetViewAngle(); + float s = (float) (Math.sin(fov) * distance * 0.1); - Vector3d scale = new Vector3d(1., 1., 1.); - + Vector3d scale = new Vector3d(1., 1., 1.); + // if (p.x > 0.f) // scale.x = -1.; // if (p.y > 0.f) // scale.y = -1.; // if (p.z > 0.f) // scale.z = -1.; - scale.scale(s); - gizmo.setScale(scale); + scale.scale(s); + gizmo.setScale(scale); } else { Vector3d scale = new Vector3d(1.f, 1.f, 1.f); - double s = panel.GetRenderer().GetActiveCamera().GetParallelScale() / 5.; + double s = panel.GetRenderer().GetActiveCamera().GetParallelScale() / 5.; // if (p.x > 0.f) // scale.x = -1.; // if (p.y > 0.f) // scale.y = -1.; // if (p.z > 0.f) // scale.z = -1.; - scale.scale(s); - gizmo.setScale(scale); + scale.scale(s); + gizmo.setScale(scale); } panel.Render(); @@ -303,9 +303,9 @@ public class RotateAction extends vtkAwtAction{ valid = true; if ((e.getModifiers() & MouseEvent.CTRL_MASK) > 0) { useStep = true; - } else { - useStep = false; - } + } else { + useStep = false; + } worldOrientation = node.getWorldOrientation(); doChanges(true, e.getX(), e.getY()); @@ -338,9 +338,9 @@ public class RotateAction extends vtkAwtAction{ if ((e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) > 0 && valid) { if ((e.getModifiers() & MouseEvent.CTRL_MASK) > 0) { useStep = true; - } else { - useStep = false; - } + } else { + useStep = false; + } doChanges(false, e.getX(), e.getY()); //nodeMap.modified(node); @@ -351,187 +351,187 @@ public class RotateAction extends vtkAwtAction{ } } - Vector3d axis = null; + Vector3d axis = null; @Override public void keyTyped(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_LEFT) { - inputType = InputType.KEY; - axis = new Vector3d(0.0,1.0,0.0); - } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { - inputType = InputType.KEY; - axis = new Vector3d(0.0,-1.0,0.0); - } else if (e.getKeyCode() ==KeyEvent.VK_UP) { - inputType = InputType.KEY; - axis = new Vector3d(1.0,0.0,0.0); - } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { - inputType = InputType.KEY; - axis = new Vector3d(-1.0,0.0,0.0); - } + if (e.getKeyCode() == KeyEvent.VK_LEFT) { + inputType = InputType.KEY; + axis = new Vector3d(0.0,1.0,0.0); + } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { + inputType = InputType.KEY; + axis = new Vector3d(0.0,-1.0,0.0); + } else if (e.getKeyCode() ==KeyEvent.VK_UP) { + inputType = InputType.KEY; + axis = new Vector3d(1.0,0.0,0.0); + } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { + inputType = InputType.KEY; + axis = new Vector3d(-1.0,0.0,0.0); + } } - public void doChanges(boolean pressed, int x, int y) { - Ray ray = vtkUtil.createMouseRay(panel.GetRenderer(),x, y); - Vector3d p = node.getWorldPosition(); - - if (pressed) { - Vector3d axis = getRotationAxis(); - if (axis != null) { - if (!worldCoord) { - MathTools.rotate(parentWorldOrientation, axis, axis); - } + public void doChanges(boolean pressed, int x, int y) { + Ray ray = vtkUtil.createMouseRay(panel.GetRenderer(),x, y); + Vector3d p = node.getWorldPosition(); + + if (pressed) { + Vector3d axis = getRotationAxis(); + if (axis != null) { + if (!worldCoord) { + MathTools.rotate(parentWorldOrientation, axis, axis); + } - - double s[] = new double[2]; - Vector3d i2 = new Vector3d(); - - boolean intersect = MathTools.intersectStraightPlane(ray.pos, ray.dir, p, axis, i2, s); - double dot = Math.abs(ray.dir.dot(axis)); - if (intersect && dot > 0.4) - inputType = InputType.INTERSECT; - else - inputType = InputType.NONINTERSECT; - - - if (inputType == InputType.INTERSECT) { - // picking ray and plane defined by gizmo's center point and - // rotation axis can intersect - // vector from center point to intersection point - i2.sub(p); - // creating vectors i and j that are lying on the plane and - // are perpendicular - // vectors are used to calculate polar coordinate for - // intersection point - j.set(i2); - i.cross(j, axis); - System.out.println("I,J " + i + " " + j); - double angleI = i2.angle(i); - double angleJ = i2.angle(j); - prevAngle = Math.atan2(Math.cos(angleJ), Math.cos(angleI)); - } else { - // picking ray and plane defined by gizmo's center point and - // rotation axis are parallel, - // so we'll use cross product of rotation axis and picking - // ray to detect amount of rotation - i.cross(ray.dir, axis); - MathTools.intersectStraightStraight(ray.pos, ray.dir, p, i, new Vector3d(), new Vector3d(), s); - prevS = s[1]; - } - } - - - } + + double s[] = new double[2]; + Vector3d i2 = new Vector3d(); + + boolean intersect = MathTools.intersectStraightPlane(ray.pos, ray.dir, p, axis, i2, s); + double dot = Math.abs(ray.dir.dot(axis)); + if (intersect && dot > 0.4) + inputType = InputType.INTERSECT; + else + inputType = InputType.NONINTERSECT; + + + if (inputType == InputType.INTERSECT) { + // picking ray and plane defined by gizmo's center point and + // rotation axis can intersect + // vector from center point to intersection point + i2.sub(p); + // creating vectors i and j that are lying on the plane and + // are perpendicular + // vectors are used to calculate polar coordinate for + // intersection point + j.set(i2); + i.cross(j, axis); + System.out.println("I,J " + i + " " + j); + double angleI = i2.angle(i); + double angleJ = i2.angle(j); + prevAngle = Math.atan2(Math.cos(angleJ), Math.cos(angleI)); + } else { + // picking ray and plane defined by gizmo's center point and + // rotation axis are parallel, + // so we'll use cross product of rotation axis and picking + // ray to detect amount of rotation + i.cross(ray.dir, axis); + MathTools.intersectStraightStraight(ray.pos, ray.dir, p, i, new Vector3d(), new Vector3d(), s); + prevS = s[1]; + } + } + + + } - if (inputType != InputType.KEY) - axis = getRotationAxis(); - if (axis == null) { - return; - } - Vector3d taxis = null; - if (!worldCoord) { - taxis = new Vector3d(axis); - MathTools.rotate(parentWorldOrientation, axis, axis); - } - System.out.println(inputType); - if (inputType == InputType.INTERSECT) { + if (inputType != InputType.KEY) + axis = getRotationAxis(); + if (axis == null) { + return; + } + Vector3d taxis = null; + if (!worldCoord) { + taxis = new Vector3d(axis); + MathTools.rotate(parentWorldOrientation, axis, axis); + } + System.out.println(inputType); + if (inputType == InputType.INTERSECT) { - double s[] = new double[2]; - Vector3d i2 = new Vector3d(); - MathTools.intersectStraightPlane(ray.pos, ray.dir, p, axis, i2, s); - i2.sub(p); - double angleI = i2.angle(i); - double angleJ = i2.angle(j); - double angle = Math.atan2(Math.cos(angleJ), Math.cos(angleI)); - System.out.println("Angle " + angle + " i " + angleI + " j " + angleJ + " prev " + prevAngle); - if(!worldCoord) - axis = taxis; - if (useStep) { + double s[] = new double[2]; + Vector3d i2 = new Vector3d(); + MathTools.intersectStraightPlane(ray.pos, ray.dir, p, axis, i2, s); + i2.sub(p); + double angleI = i2.angle(i); + double angleJ = i2.angle(j); + double angle = Math.atan2(Math.cos(angleJ), Math.cos(angleI)); + System.out.println("Angle " + angle + " i " + angleI + " j " + angleJ + " prev " + prevAngle); + if(!worldCoord) + axis = taxis; + if (useStep) { - //setOrientation(MathTools.getQuat(rotation)); - AxisAngle4d rot = new AxisAngle4d(axis,angle-prevAngle); - Quat4d qrot = new Quat4d(); - MathTools.getQuat(rot, qrot); - //prevAngle = angle; - qrot.mulInverse(worldOrientation); - - - if (stepMethod == 0) { - rot.set(qrot); - rot.angle = roundAngle(rot.angle); - //qrot.set(rot); - MathTools.getQuat(rot,qrot); - setOrientation(qrot); - } else if (stepMethod == 1){ - - //Vector3d euler = MathTools.getEuler(qrot); - Vector3d euler = EulerTools.getEulerFromQuat(order, qrot); - euler.x = roundAngle(euler.x); - euler.y = roundAngle(euler.y); - euler.z = roundAngle(euler.z); - //Quat4d q = MathTools.getQuat(euler); - Quat4d q = EulerTools.getQuatFromEuler(order, euler); - setOrientation(q); - System.out.println(" (" + MathTools.radToDeg(euler.x) + " " + MathTools.radToDeg(euler.y) + " " + MathTools.radToDeg(euler.z) + ") " + qrot + " "+ q); - } else { - setOrientation(qrot); - } - - } else { - if (worldCoord) { - //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getWorldOrientation(), new AxisAngle4d(axis,angle-prevAngle)); - AxisAngle4d aa = MathTools.getAxisAngle(node.getWorldOrientation()); - AxisAngle4d rot = new AxisAngle4d(axis,angle-prevAngle); - MathTools.multiplyOrientation(aa, rot); - setWorldOrientation(MathTools.getQuat(rot)); - } else { - AxisAngle4d aa = MathTools.getAxisAngle(node.getOrientation()); - AxisAngle4d rot = new AxisAngle4d(axis,angle-prevAngle); - MathTools.multiplyOrientation(aa, rot); - setOrientation(MathTools.getQuat(rot)); - //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getLocalOrientation(), new AxisAngle4d(axis,angle-prevAngle)); - } - prevAngle = angle; - } - - } else if (inputType == InputType.NONINTERSECT){ + //setOrientation(MathTools.getQuat(rotation)); + AxisAngle4d rot = new AxisAngle4d(axis,angle-prevAngle); + Quat4d qrot = new Quat4d(); + MathTools.getQuat(rot, qrot); + //prevAngle = angle; + qrot.mulInverse(worldOrientation); + + + if (stepMethod == 0) { + rot.set(qrot); + rot.angle = roundAngle(rot.angle); + //qrot.set(rot); + MathTools.getQuat(rot,qrot); + setOrientation(qrot); + } else if (stepMethod == 1){ + + //Vector3d euler = MathTools.getEuler(qrot); + Vector3d euler = EulerTools.getEulerFromQuat(order, qrot); + euler.x = roundAngle(euler.x); + euler.y = roundAngle(euler.y); + euler.z = roundAngle(euler.z); + //Quat4d q = MathTools.getQuat(euler); + Quat4d q = EulerTools.getQuatFromEuler(order, euler); + setOrientation(q); + System.out.println(" (" + MathTools.radToDeg(euler.x) + " " + MathTools.radToDeg(euler.y) + " " + MathTools.radToDeg(euler.z) + ") " + qrot + " "+ q); + } else { + setOrientation(qrot); + } + + } else { + if (worldCoord) { + //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getWorldOrientation(), new AxisAngle4d(axis,angle-prevAngle)); + AxisAngle4d aa = MathTools.getAxisAngle(node.getWorldOrientation()); + AxisAngle4d rot = new AxisAngle4d(axis,angle-prevAngle); + MathTools.multiplyOrientation(aa, rot); + setWorldOrientation(MathTools.getQuat(rot)); + } else { + AxisAngle4d aa = MathTools.getAxisAngle(node.getOrientation()); + AxisAngle4d rot = new AxisAngle4d(axis,angle-prevAngle); + MathTools.multiplyOrientation(aa, rot); + setOrientation(MathTools.getQuat(rot)); + //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getLocalOrientation(), new AxisAngle4d(axis,angle-prevAngle)); + } + prevAngle = angle; + } + + } else if (inputType == InputType.NONINTERSECT){ - double s[] = new double[2]; - MathTools.intersectStraightStraight(ray.pos, ray.dir, p, i, new Vector3d(), new Vector3d(), s); - if(!worldCoord) - axis = taxis; - if (useStep) { - //setOrientation(MathTools.getQuat(rotation)); - AxisAngle4d rot = new AxisAngle4d(axis,s[1] - prevS); - - Quat4d qrot = new Quat4d(); - //qrot.set(rot); - MathTools.getQuat(rot, qrot); - //prevAngle = angle; - qrot.mulInverse(worldOrientation); - - - if (stepMethod == 0) { - rot.set(qrot); - rot.angle = roundAngle(rot.angle); - //qrot.set(rot); - MathTools.getQuat(rot,qrot); - setOrientation(qrot); - } else if (stepMethod == 1){ - - //Vector3d euler = MathTools.getEuler(qrot); - Vector3d euler = EulerTools.getEulerFromQuat(order, qrot); - euler.x = roundAngle(euler.x); - euler.y = roundAngle(euler.y); - euler.z = roundAngle(euler.z); - //Quat4d q = MathTools.getQuat(euler); - Quat4d q = EulerTools.getQuatFromEuler(order, euler); - setOrientation(q); - System.out.println(" (" + MathTools.radToDeg(euler.x) + " " + MathTools.radToDeg(euler.y) + " " + MathTools.radToDeg(euler.z) + ") " + qrot + " "+ q); - } else { - setOrientation(qrot); - } - prevS = s[1]; - + double s[] = new double[2]; + MathTools.intersectStraightStraight(ray.pos, ray.dir, p, i, new Vector3d(), new Vector3d(), s); + if(!worldCoord) + axis = taxis; + if (useStep) { + //setOrientation(MathTools.getQuat(rotation)); + AxisAngle4d rot = new AxisAngle4d(axis,s[1] - prevS); + + Quat4d qrot = new Quat4d(); + //qrot.set(rot); + MathTools.getQuat(rot, qrot); + //prevAngle = angle; + qrot.mulInverse(worldOrientation); + + + if (stepMethod == 0) { + rot.set(qrot); + rot.angle = roundAngle(rot.angle); + //qrot.set(rot); + MathTools.getQuat(rot,qrot); + setOrientation(qrot); + } else if (stepMethod == 1){ + + //Vector3d euler = MathTools.getEuler(qrot); + Vector3d euler = EulerTools.getEulerFromQuat(order, qrot); + euler.x = roundAngle(euler.x); + euler.y = roundAngle(euler.y); + euler.z = roundAngle(euler.z); + //Quat4d q = MathTools.getQuat(euler); + Quat4d q = EulerTools.getQuatFromEuler(order, euler); + setOrientation(q); + System.out.println(" (" + MathTools.radToDeg(euler.x) + " " + MathTools.radToDeg(euler.y) + " " + MathTools.radToDeg(euler.z) + ") " + qrot + " "+ q); + } else { + setOrientation(qrot); + } + prevS = s[1]; + // G3DTools.setOrientation(mo.getG3DNode(graph).getLocalOrientation(), rotations.get(mo)); // G3DTools.multiplyOrientation(mo.getG3DNode(graph).getWorldOrientation(), new AxisAngle4d(axis,s[1] - prevS)); // AxisAngle4d aa = G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation()); @@ -546,55 +546,55 @@ public class RotateAction extends vtkAwtAction{ // Vector3d e = MathTools.getEuler(G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation())); // e.scale(180.0/Math.PI); // text += G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation()) + " " + e + " "; - - - } else { - if (worldCoord) { - AxisAngle4d aa = MathTools.getAxisAngle(node.getWorldOrientation()); - AxisAngle4d rot = new AxisAngle4d(axis,s[1] - prevS); - MathTools.multiplyOrientation(aa, rot); - setWorldOrientation(MathTools.getQuat(rot)); - //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getWorldOrientation(), new AxisAngle4d(axis,s[1] - prevS)); - } else { - AxisAngle4d aa = MathTools.getAxisAngle(node.getOrientation()); - AxisAngle4d rot = new AxisAngle4d(axis,s[1] - prevS); - MathTools.multiplyOrientation(aa, rot); - setOrientation(MathTools.getQuat(rot)); - //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getLocalOrientation(), new AxisAngle4d(axis,s[1] - prevS)); - } - //text += G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation()) + " " + MathTools.getEuler(G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation())) + " "; - prevS = s[1]; - - } - - } else { - if (worldCoord) { - AxisAngle4d aa = MathTools.getAxisAngle(node.getWorldOrientation()); - AxisAngle4d rot = new AxisAngle4d(axis,Math.PI * 0.5); - MathTools.multiplyOrientation(aa, rot); - setWorldOrientation(MathTools.getQuat(rot)); - //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getWorldOrientation(), new AxisAngle4d(axis,Math.PI * 0.5)); - } else { - AxisAngle4d aa = MathTools.getAxisAngle(node.getOrientation()); - AxisAngle4d rot = new AxisAngle4d(axis,Math.PI * 0.5); - MathTools.multiplyOrientation(aa, rot); - setOrientation(MathTools.getQuat(rot)); - //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getLocalOrientation(), new AxisAngle4d(axis,Math.PI * 0.5)); - } - // text += G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation()) + " " + MathTools.getEuler(G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation())) + " "; - - } - //setInfoText(text); - - } - - protected void setOrientation(Quat4d q) { - node.setOrientation(q); - } - - protected void setWorldOrientation(Quat4d q) { - node.setWorldOrientation(q); - } + + + } else { + if (worldCoord) { + AxisAngle4d aa = MathTools.getAxisAngle(node.getWorldOrientation()); + AxisAngle4d rot = new AxisAngle4d(axis,s[1] - prevS); + MathTools.multiplyOrientation(aa, rot); + setWorldOrientation(MathTools.getQuat(rot)); + //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getWorldOrientation(), new AxisAngle4d(axis,s[1] - prevS)); + } else { + AxisAngle4d aa = MathTools.getAxisAngle(node.getOrientation()); + AxisAngle4d rot = new AxisAngle4d(axis,s[1] - prevS); + MathTools.multiplyOrientation(aa, rot); + setOrientation(MathTools.getQuat(rot)); + //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getLocalOrientation(), new AxisAngle4d(axis,s[1] - prevS)); + } + //text += G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation()) + " " + MathTools.getEuler(G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation())) + " "; + prevS = s[1]; + + } + + } else { + if (worldCoord) { + AxisAngle4d aa = MathTools.getAxisAngle(node.getWorldOrientation()); + AxisAngle4d rot = new AxisAngle4d(axis,Math.PI * 0.5); + MathTools.multiplyOrientation(aa, rot); + setWorldOrientation(MathTools.getQuat(rot)); + //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getWorldOrientation(), new AxisAngle4d(axis,Math.PI * 0.5)); + } else { + AxisAngle4d aa = MathTools.getAxisAngle(node.getOrientation()); + AxisAngle4d rot = new AxisAngle4d(axis,Math.PI * 0.5); + MathTools.multiplyOrientation(aa, rot); + setOrientation(MathTools.getQuat(rot)); + //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getLocalOrientation(), new AxisAngle4d(axis,Math.PI * 0.5)); + } + // text += G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation()) + " " + MathTools.getEuler(G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation())) + " "; + + } + //setInfoText(text); + + } + + protected void setOrientation(Quat4d q) { + node.setOrientation(q); + } + + protected void setWorldOrientation(Quat4d q) { + node.setWorldOrientation(q); + } @Override public void mouseMoved(MouseEvent e) { @@ -619,39 +619,39 @@ public class RotateAction extends vtkAwtAction{ } } - private double prevS = 0.0; - - private Vector3d i = new Vector3d(); - private Vector3d j = new Vector3d(); - private double prevAngle = 0; + private double prevS = 0.0; + + private Vector3d i = new Vector3d(); + private Vector3d j = new Vector3d(); + private double prevAngle = 0; - enum InputType{INTERSECT,NONINTERSECT,KEY,NONE}; - InputType inputType; - private boolean useStep = false; - - - - private double roundAngle(double angle) { - while (angle < - Math.PI) - angle += Math.PI*2.0; - while (angle > Math.PI) - angle -= Math.PI*2.0; - - - int index = 0; - while (angle > angles[index]) - index++; - if (index == 0) { - angle = angles[0]; - } else { - double d = angle - angles[index - 1]; - double d2 = angles[index] - angle; - if (d < d2) - angle = angles[index - 1]; - else - angle = angles[index]; - } - return angle; - } + enum InputType{INTERSECT,NONINTERSECT,KEY,NONE}; + InputType inputType; + private boolean useStep = false; + + + + private double roundAngle(double angle) { + while (angle < - Math.PI) + angle += Math.PI*2.0; + while (angle > Math.PI) + angle -= Math.PI*2.0; + + + int index = 0; + while (angle > angles[index]) + index++; + if (index == 0) { + angle = angles[0]; + } else { + double d = angle - angles[index - 1]; + double d2 = angles[index] - angle; + if (d < d2) + angle = angles[index - 1]; + else + angle = angles[index]; + } + return angle; + } } diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/awt/TranslateAction.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/awt/TranslateAction.java index 1b07afa8..bb59c563 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/awt/TranslateAction.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/awt/TranslateAction.java @@ -37,12 +37,12 @@ import vtk.vtkProp; public class TranslateAction extends vtkAwtAction{ public static final int X = 0; - public static final int Y = 1; - public static final int Z = 2; - public static final int XY = 3; - public static final int XZ = 4; - public static final int YZ = 5; - public static final int P = 6; + public static final int Y = 1; + public static final int Z = 2; + public static final int XY = 3; + public static final int XZ = 4; + public static final int YZ = 5; + public static final int P = 6; private VTKNodeMap nodeMap; //private TranslateGizmo gizmo = new TranslateGizmo(); @@ -235,31 +235,31 @@ public class TranslateAction extends vtkAwtAction{ if (panel.GetRenderer().GetActiveCamera().GetParallelProjection() == 0) { double distance = p.length(); p.negate(); - double fov = panel.GetRenderer().GetActiveCamera().GetViewAngle(); - float s = (float) (Math.sin(fov) * distance * 0.1); + double fov = panel.GetRenderer().GetActiveCamera().GetViewAngle(); + float s = (float) (Math.sin(fov) * distance * 0.1); - Vector3d scale = new Vector3d(1., 1., 1.); - + Vector3d scale = new Vector3d(1., 1., 1.); + // if (p.x > 0.f) // scale.x = -1.; // if (p.y > 0.f) // scale.y = -1.; // if (p.z > 0.f) // scale.z = -1.; - scale.scale(s); - gizmo.setScale(scale); + scale.scale(s); + gizmo.setScale(scale); } else { Vector3d scale = new Vector3d(1.f, 1.f, 1.f); - double s = panel.GetRenderer().GetActiveCamera().GetParallelScale() / 5.; + double s = panel.GetRenderer().GetActiveCamera().GetParallelScale() / 5.; // if (p.x > 0.f) // scale.x = -1.; // if (p.y > 0.f) // scale.y = -1.; // if (p.z > 0.f) // scale.z = -1.; - scale.scale(s); - gizmo.setScale(scale); + scale.scale(s); + gizmo.setScale(scale); } //panel.Render(); @@ -346,31 +346,31 @@ public class TranslateAction extends vtkAwtAction{ node.setWorldPosition(pos); } - private double istep = 10.0; - private int decimals = 2; - + private double istep = 10.0; + private int decimals = 2; + protected Vector3d constaints(Vector3d p, boolean step) { if(!step) return p; switch (index) { case X: - p.x = Math.round(istep * p.x) / istep; - BigDecimal bx = new BigDecimal(p.x); - bx.setScale(decimals, BigDecimal.ROUND_HALF_UP); - p.x = bx.doubleValue(); + p.x = Math.round(istep * p.x) / istep; + BigDecimal bx = new BigDecimal(p.x); + bx.setScale(decimals, BigDecimal.ROUND_HALF_UP); + p.x = bx.doubleValue(); break; case Y: - p.y = Math.round(istep * p.y) / istep; - BigDecimal by = new BigDecimal(p.y); - by.setScale(decimals, BigDecimal.ROUND_HALF_UP); - p.y = by.doubleValue(); + p.y = Math.round(istep * p.y) / istep; + BigDecimal by = new BigDecimal(p.y); + by.setScale(decimals, BigDecimal.ROUND_HALF_UP); + p.y = by.doubleValue(); break; - + case Z: - p.z = Math.round(istep * p.z) / istep; - BigDecimal bz = new BigDecimal(p.z); - bz.setScale(decimals, BigDecimal.ROUND_HALF_UP); - p.z = bz.doubleValue(); + p.z = Math.round(istep * p.z) / istep; + BigDecimal bz = new BigDecimal(p.z); + bz.setScale(decimals, BigDecimal.ROUND_HALF_UP); + p.z = bz.doubleValue(); break; } return p; @@ -401,85 +401,85 @@ public class TranslateAction extends vtkAwtAction{ } normal.normalize(); double s[] = new double[1]; - Vector3d r = new Vector3d(); - if (MathTools.intersectStraightPlane(ray.pos, ray.dir, p, normal, r)) { - r.sub(p); - translate.x = r.x; - translate.y = r.y; - translate.z = r.z; - } - break; + Vector3d r = new Vector3d(); + if (MathTools.intersectStraightPlane(ray.pos, ray.dir, p, normal, r)) { + r.sub(p); + translate.x = r.x; + translate.y = r.y; + translate.z = r.z; + } + break; - case X : - dir = new Vector3d(1.0,0.0,0.0); - if(!worldCoord) - MathTools.rotate(q, dir, dir); - Vector3d i1 = new Vector3d(); - Vector3d i2 = new Vector3d(); - s = new double[2]; - MathTools.intersectStraightStraight( p, dir,ray.pos, ray.dir, i2, i1,s); - translate.x = s[0]; - - break; - case Y : - dir = new Vector3d(0.0,1.0,0.0); - if(!worldCoord) - MathTools.rotate(q, dir, dir); - i1 = new Vector3d(); - i2 = new Vector3d(); - s = new double[2]; - MathTools.intersectStraightStraight( p, dir,ray.pos, ray.dir, i2, i1,s); - translate.y = s[0]; - break; - case Z : - dir = new Vector3d(0.0,0.0,1.0); - if(!worldCoord) - MathTools.rotate(q, dir, dir); - i1 = new Vector3d(); - i2 = new Vector3d(); - s = new double[2]; - MathTools.intersectStraightStraight( p, dir,ray.pos, ray.dir, i2, i1,s); - translate.z = s[0]; - break; - case XY : - normal = new Vector3d(0.0,0.0,1.0); - if(!worldCoord) - MathTools.rotate(q, normal, normal); - r = new Vector3d(); - if (MathTools.intersectStraightPlane(ray.pos, ray.dir, p, normal, r)) { - r.sub(p); - translate.x = r.x; - translate.y = r.y; - } - break; - case XZ : - normal = new Vector3d(0.0,1.0,0.0); - if(!worldCoord) - MathTools.rotate(q, normal, normal); - r = new Vector3d(); - if (MathTools.intersectStraightPlane(ray.pos, ray.dir, p, normal, r)) { - r.sub(p); - translate.x = r.x; - translate.z = r.z; - } - break; - case YZ : - normal = new Vector3d(1.0,0.0,0.0); - if(!worldCoord) - MathTools.rotate(q, normal, normal); - r = new Vector3d(); - if (MathTools.intersectStraightPlane(ray.pos, ray.dir, p, normal, r)) { - r.sub(p); - translate.y = r.y; - translate.z = r.z; - } - break; - default : - - return null; - } - translate.sub(offset); - return translate; + case X : + dir = new Vector3d(1.0,0.0,0.0); + if(!worldCoord) + MathTools.rotate(q, dir, dir); + Vector3d i1 = new Vector3d(); + Vector3d i2 = new Vector3d(); + s = new double[2]; + MathTools.intersectStraightStraight( p, dir,ray.pos, ray.dir, i2, i1,s); + translate.x = s[0]; + + break; + case Y : + dir = new Vector3d(0.0,1.0,0.0); + if(!worldCoord) + MathTools.rotate(q, dir, dir); + i1 = new Vector3d(); + i2 = new Vector3d(); + s = new double[2]; + MathTools.intersectStraightStraight( p, dir,ray.pos, ray.dir, i2, i1,s); + translate.y = s[0]; + break; + case Z : + dir = new Vector3d(0.0,0.0,1.0); + if(!worldCoord) + MathTools.rotate(q, dir, dir); + i1 = new Vector3d(); + i2 = new Vector3d(); + s = new double[2]; + MathTools.intersectStraightStraight( p, dir,ray.pos, ray.dir, i2, i1,s); + translate.z = s[0]; + break; + case XY : + normal = new Vector3d(0.0,0.0,1.0); + if(!worldCoord) + MathTools.rotate(q, normal, normal); + r = new Vector3d(); + if (MathTools.intersectStraightPlane(ray.pos, ray.dir, p, normal, r)) { + r.sub(p); + translate.x = r.x; + translate.y = r.y; + } + break; + case XZ : + normal = new Vector3d(0.0,1.0,0.0); + if(!worldCoord) + MathTools.rotate(q, normal, normal); + r = new Vector3d(); + if (MathTools.intersectStraightPlane(ray.pos, ray.dir, p, normal, r)) { + r.sub(p); + translate.x = r.x; + translate.z = r.z; + } + break; + case YZ : + normal = new Vector3d(1.0,0.0,0.0); + if(!worldCoord) + MathTools.rotate(q, normal, normal); + r = new Vector3d(); + if (MathTools.intersectStraightPlane(ray.pos, ray.dir, p, normal, r)) { + r.sub(p); + translate.y = r.y; + translate.z = r.z; + } + break; + default : + + return null; + } + translate.sub(offset); + return translate; } } diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/awt/vtkCameraAndSelectorAction.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/awt/vtkCameraAndSelectorAction.java index f1e6f324..d1d4ac0c 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/awt/vtkCameraAndSelectorAction.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/awt/vtkCameraAndSelectorAction.java @@ -59,148 +59,148 @@ public class vtkCameraAndSelectorAction extends vtkAwtAction implements ISelecti } public void InteractionModeRotate() - { - this.InteractionMode = 1; - } - - public void InteractionModeTranslate() - { - this.InteractionMode = 2; - } - - public void InteractionModeZoom() - { - this.InteractionMode = 3; - } - + { + this.InteractionMode = 1; + } + + public void InteractionModeTranslate() + { + this.InteractionMode = 2; + } + + public void InteractionModeZoom() + { + this.InteractionMode = 3; + } + public void resetCameraClippingRange() { - Lock(); - ren.ResetCameraClippingRange(); - UnLock(); - } + Lock(); + ren.ResetCameraClippingRange(); + UnLock(); + } - public void resetCamera() { - Lock(); - ren.ResetCamera(); - UnLock(); - } - - public void mousePressed(MouseEvent e) - { - - if (ren.VisibleActorCount() == 0) return; - rw.SetDesiredUpdateRate(activeRate); - lastX = e.getX(); - lastY = e.getY(); - if ((e.getModifiers()==InputEvent.BUTTON2_MASK) || - (e.getModifiers()==(InputEvent.BUTTON1_MASK | InputEvent.SHIFT_MASK))) - { - InteractionModeTranslate(); - } - else if (e.getModifiers()==InputEvent.BUTTON3_MASK) - { - InteractionModeZoom(); - } - else - { - InteractionModeRotate(); - } - } - - public void mouseReleased(MouseEvent e) - { - rw.SetDesiredUpdateRate(passiveRate); - } - + public void resetCamera() { + Lock(); + ren.ResetCamera(); + UnLock(); + } + + public void mousePressed(MouseEvent e) + { + + if (ren.VisibleActorCount() == 0) return; + rw.SetDesiredUpdateRate(activeRate); + lastX = e.getX(); + lastY = e.getY(); + if ((e.getModifiers()==InputEvent.BUTTON2_MASK) || + (e.getModifiers()==(InputEvent.BUTTON1_MASK | InputEvent.SHIFT_MASK))) + { + InteractionModeTranslate(); + } + else if (e.getModifiers()==InputEvent.BUTTON3_MASK) + { + InteractionModeZoom(); + } + else + { + InteractionModeRotate(); + } + } + + public void mouseReleased(MouseEvent e) + { + rw.SetDesiredUpdateRate(passiveRate); + } + - - public void mouseDragged(MouseEvent e) - { - if (ren.VisibleActorCount() == 0) return; - int x = e.getX(); - int y = e.getY(); - // rotate - if (this.InteractionMode == 1) - { - cam.Azimuth(lastX - x); - cam.Elevation(y - lastY); - if (doNotRotate) - cam.SetRoll(0); - cam.OrthogonalizeViewUp(); - resetCameraClippingRange(); - panel.UpdateLight(); - } - // translate - if (this.InteractionMode == 2) - { - double FPoint[]; - double PPoint[]; - double APoint[] = new double[3]; - double RPoint[]; - double focalDepth; - - // get the current focal point and position - FPoint = cam.GetFocalPoint(); - PPoint = cam.GetPosition(); - - // calculate the focal depth since we'll be using it a lot - ren.SetWorldPoint(FPoint[0],FPoint[1],FPoint[2],1.0); - ren.WorldToDisplay(); - focalDepth = ren.GetDisplayPoint()[2]; - - APoint[0] = rw.GetSize()[0]/2.0 + (x - lastX); - APoint[1] = rw.GetSize()[1]/2.0 - (y - lastY); - APoint[2] = focalDepth; - ren.SetDisplayPoint(APoint); - ren.DisplayToWorld(); - RPoint = ren.GetWorldPoint(); - if (RPoint[3] != 0.0) - { - RPoint[0] = RPoint[0]/RPoint[3]; - RPoint[1] = RPoint[1]/RPoint[3]; - RPoint[2] = RPoint[2]/RPoint[3]; - } - - /* - * Compute a translation vector, moving everything 1/2 - * the distance to the cursor. (Arbitrary scale factor) - */ - cam.SetFocalPoint( - (FPoint[0]-RPoint[0])/2.0 + FPoint[0], - (FPoint[1]-RPoint[1])/2.0 + FPoint[1], - (FPoint[2]-RPoint[2])/2.0 + FPoint[2]); - cam.SetPosition( - (FPoint[0]-RPoint[0])/2.0 + PPoint[0], - (FPoint[1]-RPoint[1])/2.0 + PPoint[1], - (FPoint[2]-RPoint[2])/2.0 + PPoint[2]); - resetCameraClippingRange(); - } - // zoom - if (this.InteractionMode == 3) - { - double zoomFactor; - //double clippingRange[]; - - zoomFactor = Math.pow(1.02,(y - lastY)); - if (cam.GetParallelProjection() == 1) - { - cam.SetParallelScale(cam.GetParallelScale()/zoomFactor); - } - else - { - cam.Dolly(zoomFactor); - resetCameraClippingRange(); - } - } - lastX = x; - lastY = y; - panel.Render(); - } + + public void mouseDragged(MouseEvent e) + { + if (ren.VisibleActorCount() == 0) return; + int x = e.getX(); + int y = e.getY(); + // rotate + if (this.InteractionMode == 1) + { + cam.Azimuth(lastX - x); + cam.Elevation(y - lastY); + if (doNotRotate) + cam.SetRoll(0); + cam.OrthogonalizeViewUp(); + resetCameraClippingRange(); + panel.UpdateLight(); + } + // translate + if (this.InteractionMode == 2) + { + double FPoint[]; + double PPoint[]; + double APoint[] = new double[3]; + double RPoint[]; + double focalDepth; + + // get the current focal point and position + FPoint = cam.GetFocalPoint(); + PPoint = cam.GetPosition(); + + // calculate the focal depth since we'll be using it a lot + ren.SetWorldPoint(FPoint[0],FPoint[1],FPoint[2],1.0); + ren.WorldToDisplay(); + focalDepth = ren.GetDisplayPoint()[2]; + + APoint[0] = rw.GetSize()[0]/2.0 + (x - lastX); + APoint[1] = rw.GetSize()[1]/2.0 - (y - lastY); + APoint[2] = focalDepth; + ren.SetDisplayPoint(APoint); + ren.DisplayToWorld(); + RPoint = ren.GetWorldPoint(); + if (RPoint[3] != 0.0) + { + RPoint[0] = RPoint[0]/RPoint[3]; + RPoint[1] = RPoint[1]/RPoint[3]; + RPoint[2] = RPoint[2]/RPoint[3]; + } + + /* + * Compute a translation vector, moving everything 1/2 + * the distance to the cursor. (Arbitrary scale factor) + */ + cam.SetFocalPoint( + (FPoint[0]-RPoint[0])/2.0 + FPoint[0], + (FPoint[1]-RPoint[1])/2.0 + FPoint[1], + (FPoint[2]-RPoint[2])/2.0 + FPoint[2]); + cam.SetPosition( + (FPoint[0]-RPoint[0])/2.0 + PPoint[0], + (FPoint[1]-RPoint[1])/2.0 + PPoint[1], + (FPoint[2]-RPoint[2])/2.0 + PPoint[2]); + resetCameraClippingRange(); + } + // zoom + if (this.InteractionMode == 3) + { + double zoomFactor; + //double clippingRange[]; + + zoomFactor = Math.pow(1.02,(y - lastY)); + if (cam.GetParallelProjection() == 1) + { + cam.SetParallelScale(cam.GetParallelScale()/zoomFactor); + } + else + { + cam.Dolly(zoomFactor); + resetCameraClippingRange(); + } + } + lastX = x; + lastY = y; + panel.Render(); + } - + private List selectActors = new ArrayList(); private List hoverActor = new ArrayList(); - + @Override public void mouseClicked(MouseEvent e) { if (!panel.isFocusOwner()) @@ -271,8 +271,8 @@ public class vtkCameraAndSelectorAction extends vtkAwtAction implements ISelecti @Override public void mouseMoved(MouseEvent e) { lastX = e.getX(); - lastY = e.getY(); - + lastY = e.getY(); + if (!panel.isFocusOwner()) return; List prevHover = new ArrayList(); @@ -298,7 +298,7 @@ public class vtkCameraAndSelectorAction extends vtkAwtAction implements ISelecti } private List selectionListeners = new ArrayList(); - + @Override public void addSelectionChangedListener(ISelectionChangedListener listener) { selectionListeners.add(listener); @@ -346,7 +346,7 @@ public class vtkCameraAndSelectorAction extends vtkAwtAction implements ISelecti private List hoverListeners = new ArrayList(); - + public void addHoverChangedListener(ISelectionChangedListener listener) { hoverListeners.add(listener); @@ -384,10 +384,10 @@ public class vtkCameraAndSelectorAction extends vtkAwtAction implements ISelecti Lock(); cam.SetFocalPoint(x, y, z); if (doNotRotate) - cam.SetRoll(0); - cam.OrthogonalizeViewUp(); - resetCameraClippingRange(); - panel.UpdateLight(); + cam.SetRoll(0); + cam.OrthogonalizeViewUp(); + resetCameraClippingRange(); + panel.UpdateLight(); UnLock(); } diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/common/AbstractVTKNodeMap.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/common/AbstractVTKNodeMap.java index b5a7dfe6..674a71f2 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/common/AbstractVTKNodeMap.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/common/AbstractVTKNodeMap.java @@ -48,448 +48,448 @@ import vtk.vtkProp; public abstract class AbstractVTKNodeMap implements VTKNodeMap, IMappingListener, RenderListener, NodeListener, UndoRedoSupport.ChangeListener{ - private static final boolean DEBUG = false; - - protected Session session; - protected IMapping mapping; - protected VtkView view; - - protected MapList nodeToActor = new MapList(); - protected Map actorToNode = new HashMap(); + private static final boolean DEBUG = false; + + protected Session session; + protected IMapping mapping; + protected VtkView view; + + protected MapList nodeToActor = new MapList(); + protected Map actorToNode = new HashMap(); - protected ParentNode rootNode; - - protected UndoRedoSupport undoRedoSupport; - protected int undoOpCount = 0; - protected int redoOpCount = 0; - protected boolean runUndo = false; - protected boolean runRedo = false; - public AbstractVTKNodeMap(Session session, IMapping mapping, VtkView view, ParentNode rootNode) { - this.session = session; - this.mapping = mapping; - this.view = view; - this.rootNode = rootNode; - view.addListener(this); - mapping.addMappingListener(this); - rootNode.addListener(this); - - undoRedoSupport = session.getService(UndoRedoSupport.class); - undoRedoSupport.subscribe(this); - try { - UndoContext undoContext = undoRedoSupport.getUndoContext(session); - undoOpCount = undoContext.getAll().size(); - redoOpCount = undoContext.getRedoList().size(); - } catch(DatabaseException e) { - e.printStackTrace(); - } - } - - - - protected abstract void addActor(E node); - protected abstract void removeActor(E node); - protected abstract void updateActor(E node,Set ids); - - public void repaint() { - view.refresh(); - } - - public void populate() { - for (E node : rootNode.getNodes()) { - receiveAdd(node, node.getParentRel(),true); - } - repaint(); - } - - @Override - public E getNode(vtkProp prop) { - return actorToNode.get(prop); - } - - @SuppressWarnings("unchecked") - @Override - public Collection getRenderObjects(INode node) { - return nodeToActor.getValues((E)node); - } - - @SuppressWarnings("unchecked") - @Override - public ParentNode getRootNode() { - return (ParentNode)rootNode; - } - - - - @Override - public boolean isChangeTracking() { - return changeTracking; - } - - @Override - public void setChangeTracking(boolean enabled) { - changeTracking = enabled; - } - - private boolean changeTracking = true; - - protected Object syncMutex = new Object(); - + protected ParentNode rootNode; + + protected UndoRedoSupport undoRedoSupport; + protected int undoOpCount = 0; + protected int redoOpCount = 0; + protected boolean runUndo = false; + protected boolean runRedo = false; + public AbstractVTKNodeMap(Session session, IMapping mapping, VtkView view, ParentNode rootNode) { + this.session = session; + this.mapping = mapping; + this.view = view; + this.rootNode = rootNode; + view.addListener(this); + mapping.addMappingListener(this); + rootNode.addListener(this); + + undoRedoSupport = session.getService(UndoRedoSupport.class); + undoRedoSupport.subscribe(this); + try { + UndoContext undoContext = undoRedoSupport.getUndoContext(session); + undoOpCount = undoContext.getAll().size(); + redoOpCount = undoContext.getRedoList().size(); + } catch(DatabaseException e) { + e.printStackTrace(); + } + } + + + + protected abstract void addActor(E node); + protected abstract void removeActor(E node); + protected abstract void updateActor(E node,Set ids); + + public void repaint() { + view.refresh(); + } + + public void populate() { + for (E node : rootNode.getNodes()) { + receiveAdd(node, node.getParentRel(),true); + } + repaint(); + } + + @Override + public E getNode(vtkProp prop) { + return actorToNode.get(prop); + } + + @SuppressWarnings("unchecked") + @Override + public Collection getRenderObjects(INode node) { + return nodeToActor.getValues((E)node); + } + + @SuppressWarnings("unchecked") + @Override + public ParentNode getRootNode() { + return (ParentNode)rootNode; + } + + + + @Override + public boolean isChangeTracking() { + return changeTracking; + } + + @Override + public void setChangeTracking(boolean enabled) { + changeTracking = enabled; + } + + private boolean changeTracking = true; + + protected Object syncMutex = new Object(); + - private List> added = new ArrayList>(); - private List> removed = new ArrayList>(); - private MapSet updated = new MapSet.Hash(); + private List> added = new ArrayList>(); + private List> removed = new ArrayList>(); + private MapSet updated = new MapSet.Hash(); - private boolean rangeModified = false; - - @Override - public void onChanged() { - try { - UndoContext undoContext = undoRedoSupport.getUndoContext(session); - int ucount = undoContext.getAll().size(); - int rcount = undoContext.getRedoList().size(); - if (DEBUG) System.out.println("Previous U:" + undoOpCount +" R:" + redoOpCount +" Current U:"+ucount+" R:"+rcount); - if (ucount < undoOpCount) { - runUndo = true; - } else { - runUndo = false; - } - if (!runUndo && rcount > 0) - runRedo = true; - else - runRedo = false; - undoOpCount = ucount; - redoOpCount = rcount; - - if (DEBUG) System.out.println("Undo " + runUndo + " Redo " + runRedo); - } catch (DatabaseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - - } - - @SuppressWarnings("unchecked") - @Override - public void updateRenderObjectsFor(E node) { - List toDelete = new ArrayList(); - view.lock(); - for (vtkProp prop : nodeToActor.getValues((E)node)) { - if (prop.GetVTKId() != 0) { - view.getRenderer().RemoveActor(prop); - //prop.Delete(); - toDelete.add(prop); - } - actorToNode.remove(prop); - } - view.unlock(); - nodeToActor.remove((E)node); - Collection coll = getActors((E)node); - if (coll != null) { - for (vtkProp prop : coll) { - nodeToActor.add((E)node,prop); - actorToNode.put(prop, (E)node); - toDelete.remove(prop); - } - } - for (vtkProp p : toDelete) - p.Delete(); - } - - protected abstract Collection getActors(E node); - - @SuppressWarnings("unchecked") - private void receiveAdd(E node, String id, boolean db) { - if (DEBUG) System.out.println("receiveAdd " + debugString(node) + " " + id + " " + db); - synchronized (syncMutex) { - for (Pair n : added) { - if (n.first.equals(node)) - return; - } - if (changeTracking) { - mapping.rangeModified((E)node.getParent()); - } - added.add(new Pair(node, id)); - rangeModified = true; - } - view.refresh(); - } - - @SuppressWarnings("unchecked") - private void receiveRemove(E node, String id, boolean db) { - if (DEBUG) System.out.println("receiveRemove " + debugString(node) + " " + id + " " + db); - synchronized (syncMutex) { - for (Pair n : removed) { - if (n.first.equals(node)) - return; - } - if (changeTracking && !db) - mapping.rangeModified((E)node.getParent()); - removed.add(new Pair(node, id)); - rangeModified = true; - } - repaint(); - } - - @SuppressWarnings("unchecked") - private void receiveUpdate(E node, String id, boolean db) { - if (DEBUG) System.out.println("receiveUpdate " + debugString(node) + " " + id + " " + db); - synchronized (syncMutex) { + private boolean rangeModified = false; + + @Override + public void onChanged() { + try { + UndoContext undoContext = undoRedoSupport.getUndoContext(session); + int ucount = undoContext.getAll().size(); + int rcount = undoContext.getRedoList().size(); + if (DEBUG) System.out.println("Previous U:" + undoOpCount +" R:" + redoOpCount +" Current U:"+ucount+" R:"+rcount); + if (ucount < undoOpCount) { + runUndo = true; + } else { + runUndo = false; + } + if (!runUndo && rcount > 0) + runRedo = true; + else + runRedo = false; + undoOpCount = ucount; + redoOpCount = rcount; + + if (DEBUG) System.out.println("Undo " + runUndo + " Redo " + runRedo); + } catch (DatabaseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + } + + @SuppressWarnings("unchecked") + @Override + public void updateRenderObjectsFor(E node) { + List toDelete = new ArrayList(); + view.lock(); + for (vtkProp prop : nodeToActor.getValues((E)node)) { + if (prop.GetVTKId() != 0) { + view.getRenderer().RemoveActor(prop); + //prop.Delete(); + toDelete.add(prop); + } + actorToNode.remove(prop); + } + view.unlock(); + nodeToActor.remove((E)node); + Collection coll = getActors((E)node); + if (coll != null) { + for (vtkProp prop : coll) { + nodeToActor.add((E)node,prop); + actorToNode.put(prop, (E)node); + toDelete.remove(prop); + } + } + for (vtkProp p : toDelete) + p.Delete(); + } + + protected abstract Collection getActors(E node); + + @SuppressWarnings("unchecked") + private void receiveAdd(E node, String id, boolean db) { + if (DEBUG) System.out.println("receiveAdd " + debugString(node) + " " + id + " " + db); + synchronized (syncMutex) { + for (Pair n : added) { + if (n.first.equals(node)) + return; + } + if (changeTracking) { + mapping.rangeModified((E)node.getParent()); + } + added.add(new Pair(node, id)); + rangeModified = true; + } + view.refresh(); + } + + @SuppressWarnings("unchecked") + private void receiveRemove(E node, String id, boolean db) { + if (DEBUG) System.out.println("receiveRemove " + debugString(node) + " " + id + " " + db); + synchronized (syncMutex) { + for (Pair n : removed) { + if (n.first.equals(node)) + return; + } + if (changeTracking && !db) + mapping.rangeModified((E)node.getParent()); + removed.add(new Pair(node, id)); + rangeModified = true; + } + repaint(); + } + + @SuppressWarnings("unchecked") + private void receiveUpdate(E node, String id, boolean db) { + if (DEBUG) System.out.println("receiveUpdate " + debugString(node) + " " + id + " " + db); + synchronized (syncMutex) { // for (Pair n : updated) { // if (n.first.equals(node)) // return; // } - if (changeTracking && !db) - mapping.rangeModified(node); - //updated.add(new Pair(node, id)); - updated.add(node, id); - rangeModified = true; - } - repaint(); - } - - private boolean graphUpdates = false; - private Set graphModified = new HashSet(); - - private boolean requestCommit = false; - private String commitMessage = null; - - @Override - public void commit(String message) { - requestCommit = true; - commitMessage = message; - } - - protected void doCommit() { - session.asyncRequest(new WriteRequest() { - - @Override - public void perform(WriteGraph graph) throws DatabaseException { - if (DEBUG) System.out.println("Commit " + commitMessage); - if (commitMessage != null) { - Layer0Utils.addCommentMetadata(graph, commitMessage); - graph.markUndoPoint(); - commitMessage = null; - } - commit(graph); - } - - }, new Callback() { - - @Override - public void run(DatabaseException parameter) { - if (parameter != null) - ExceptionUtils.logAndShowError("Cannot commit editor changes", parameter); - } - }); - } - - protected void commit(WriteGraph graph) throws DatabaseException { - synchronized(syncMutex) { - if (DEBUG) System.out.println("Commit"); - graphUpdates = true; - mapping.updateDomain(graph); - graphUpdates = false; - clearDeletes(); - if (DEBUG) System.out.println("Commit done"); - } - } - - - - @Override - public void domainModified() { - if (graphUpdates) - return; - if (DEBUG)System.out.println("domainModified"); - session.asyncRequest(new ReadRequest() { - - @SuppressWarnings("unchecked") - @Override - public void run(ReadGraph graph) throws DatabaseException { - update(graph); - } - }); - - } - - protected void reset(ReadGraph graph) throws MappingException { - if (DEBUG) System.out.println("Reset"); - synchronized (syncMutex) { - graphUpdates = true; - mapping.getRangeModified().clear(); - for (Object o : mapping.getDomain()) - mapping.domainModified(o); - mapping.updateRange(graph); - graphModified.clear(); - graphUpdates = false; - } - } - - private boolean useFullSyncWithUndo = false; - - protected void update(ReadGraph graph) throws DatabaseException { - if (DEBUG) System.out.println("Graph update start"); - if (runUndo && useFullSyncWithUndo) { - reset(graph); - } else { - synchronized (syncMutex) { - graphUpdates = true; - for (Object domainObject : mapping.getDomainModified()) { - E rangeObject = mapping.get(domainObject); - if (rangeObject != null) - graphModified.add(rangeObject); - } - mapping.updateRange(graph); - graphModified.clear(); - syncDeletes(); - clearDeletes(); - graphUpdates = false; - } - } - - if (mapping.isRangeModified() && !runUndo && !runRedo) - commit((String)null); - if (DEBUG) System.out.println("Graph update done"); - } - - @Override - public void rangeModified() { - //System.out.println("rangeModified"); + if (changeTracking && !db) + mapping.rangeModified(node); + //updated.add(new Pair(node, id)); + updated.add(node, id); + rangeModified = true; + } + repaint(); + } + + private boolean graphUpdates = false; + private Set graphModified = new HashSet(); + + private boolean requestCommit = false; + private String commitMessage = null; + + @Override + public void commit(String message) { + requestCommit = true; + commitMessage = message; + } + + protected void doCommit() { + session.asyncRequest(new WriteRequest() { + + @Override + public void perform(WriteGraph graph) throws DatabaseException { + if (DEBUG) System.out.println("Commit " + commitMessage); + if (commitMessage != null) { + Layer0Utils.addCommentMetadata(graph, commitMessage); + graph.markUndoPoint(); + commitMessage = null; + } + commit(graph); + } + + }, new Callback() { + + @Override + public void run(DatabaseException parameter) { + if (parameter != null) + ExceptionUtils.logAndShowError("Cannot commit editor changes", parameter); + } + }); + } + + protected void commit(WriteGraph graph) throws DatabaseException { + synchronized(syncMutex) { + if (DEBUG) System.out.println("Commit"); + graphUpdates = true; + mapping.updateDomain(graph); + graphUpdates = false; + clearDeletes(); + if (DEBUG) System.out.println("Commit done"); + } + } + + + + @Override + public void domainModified() { + if (graphUpdates) + return; + if (DEBUG)System.out.println("domainModified"); + session.asyncRequest(new ReadRequest() { + + @SuppressWarnings("unchecked") + @Override + public void run(ReadGraph graph) throws DatabaseException { + update(graph); + } + }); + + } + + protected void reset(ReadGraph graph) throws MappingException { + if (DEBUG) System.out.println("Reset"); + synchronized (syncMutex) { + graphUpdates = true; + mapping.getRangeModified().clear(); + for (Object o : mapping.getDomain()) + mapping.domainModified(o); + mapping.updateRange(graph); + graphModified.clear(); + graphUpdates = false; + } + } + + private boolean useFullSyncWithUndo = false; + + protected void update(ReadGraph graph) throws DatabaseException { + if (DEBUG) System.out.println("Graph update start"); + if (runUndo && useFullSyncWithUndo) { + reset(graph); + } else { + synchronized (syncMutex) { + graphUpdates = true; + for (Object domainObject : mapping.getDomainModified()) { + E rangeObject = mapping.get(domainObject); + if (rangeObject != null) + graphModified.add(rangeObject); + } + mapping.updateRange(graph); + graphModified.clear(); + syncDeletes(); + clearDeletes(); + graphUpdates = false; + } + } + + if (mapping.isRangeModified() && !runUndo && !runRedo) + commit((String)null); + if (DEBUG) System.out.println("Graph update done"); + } + + @Override + public void rangeModified() { + //System.out.println("rangeModified"); - } - - @Override - public void postRender() { - // Commit changes if - // 1. Commit has been requested - // 2. There are no pending changes that should be processed in preRender() - if (requestCommit && !rangeModified) { // FIXME : not thread safe. - requestCommit = false; - doCommit(); - } - } - - // Reusable containers for data synchronisation - List> rem = new ArrayList>(); // Removed objects - List> add = new ArrayList>(); // Added objects - MapSet mod = new MapSet.Hash(); // Modified objects - Set propagation = new HashSet(); // Objects with propagated changes - Stack stack = new Stack(); // Stack for handling propagation - Set delete = Collections.synchronizedSet(new HashSet()); // Objects to be completely deleted - Set deleteUC = new HashSet(); - - @Override - public synchronized void preRender() { - updateCycle(); - } - - - /** - * When objects are removed (either from Java or Graph), after remove processing the Java objects remain in mapping cache. - * This causes problems with Undo and Redo, whcih the end up re-using the removed objects from mapping cache. - * - * This code here synchronizes removed and added objects to collect deletable objects. (a deletable object is one which is removed but not added). - * - */ - protected void syncDeletes() { - deleteUC.clear(); - for (Pair n : removed) { - deleteUC.add(n.first); - } - for (Pair n : added) { - deleteUC.remove(n.first); - } - if (DEBUG && deleteUC.size() > 0) { - System.out.println("Delete sync"); - for (E n : delete) { - System.out.println(debugString(n)); - } - } - delete.addAll(deleteUC); - deleteUC.clear(); - } - - /** - * Clears deletable objects from mapping cache. - */ - protected void clearDeletes() { - if (DEBUG && delete.size() > 0) System.out.println("Delete"); - for (E n : delete) { - if (DEBUG) System.out.println(debugString(n)); - mapping.getRange().remove(n); - } - delete.clear(); - } - - protected String debugString(E n) { - return n + "@" + Integer.toHexString(n.hashCode()); - } - - @SuppressWarnings("unchecked") - protected void updateCycle() { - rem.clear(); - add.clear(); - mod.clear(); - propagation.clear(); - - - synchronized (syncMutex) { - rem.addAll(removed); - add.addAll(added); - for (E e : updated.getKeys()) { - for (String s : updated.getValues(e)) { - mod.add(e, s); - } - } - syncDeletes(); - removed.clear(); - added.clear(); - updated.clear(); - } - - for (Pair n : rem) { - stopListening(n.first); - removeActor(n.first); - } - - for (Pair n : add) { - addActor(n.first); - listen(n.first); - } - - for (E e : mod.getKeys()) { - Set ids = mod.getValues(e); - if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) { - if (!propagation.contains(e)) - propagation.add(e); - } - } + } + + @Override + public void postRender() { + // Commit changes if + // 1. Commit has been requested + // 2. There are no pending changes that should be processed in preRender() + if (requestCommit && !rangeModified) { // FIXME : not thread safe. + requestCommit = false; + doCommit(); + } + } + + // Reusable containers for data synchronisation + List> rem = new ArrayList>(); // Removed objects + List> add = new ArrayList>(); // Added objects + MapSet mod = new MapSet.Hash(); // Modified objects + Set propagation = new HashSet(); // Objects with propagated changes + Stack stack = new Stack(); // Stack for handling propagation + Set delete = Collections.synchronizedSet(new HashSet()); // Objects to be completely deleted + Set deleteUC = new HashSet(); + + @Override + public synchronized void preRender() { + updateCycle(); + } + + + /** + * When objects are removed (either from Java or Graph), after remove processing the Java objects remain in mapping cache. + * This causes problems with Undo and Redo, whcih the end up re-using the removed objects from mapping cache. + * + * This code here synchronizes removed and added objects to collect deletable objects. (a deletable object is one which is removed but not added). + * + */ + protected void syncDeletes() { + deleteUC.clear(); + for (Pair n : removed) { + deleteUC.add(n.first); + } + for (Pair n : added) { + deleteUC.remove(n.first); + } + if (DEBUG && deleteUC.size() > 0) { + System.out.println("Delete sync"); + for (E n : delete) { + System.out.println(debugString(n)); + } + } + delete.addAll(deleteUC); + deleteUC.clear(); + } - if (propagation.size() > 0) { - stack.clear(); - stack.addAll(propagation); - propagation.clear(); - while (!stack.isEmpty()) { - E node = stack.pop(); - if (propagation.contains(node)) - continue; - propagation.add(node); - for (NodeListener l : node.getListeners()) { - if (l == this) { - //changeTracking = false; - //l.propertyChanged(node, G3D.URIs.hasPosition); - //changeTracking = true; - } else { - l.propertyChanged(node, G3D.URIs.hasWorldPosition); - } - } - if (node instanceof ParentNode) { - stack.addAll(((ParentNode)node).getNodes()); - } - } - } - + /** + * Clears deletable objects from mapping cache. + */ + protected void clearDeletes() { + if (DEBUG && delete.size() > 0) System.out.println("Delete"); + for (E n : delete) { + if (DEBUG) System.out.println(debugString(n)); + mapping.getRange().remove(n); + } + delete.clear(); + } + + protected String debugString(E n) { + return n + "@" + Integer.toHexString(n.hashCode()); + } + + @SuppressWarnings("unchecked") + protected void updateCycle() { + rem.clear(); + add.clear(); + mod.clear(); + propagation.clear(); + + + synchronized (syncMutex) { + rem.addAll(removed); + add.addAll(added); + for (E e : updated.getKeys()) { + for (String s : updated.getValues(e)) { + mod.add(e, s); + } + } + syncDeletes(); + removed.clear(); + added.clear(); + updated.clear(); + } + + for (Pair n : rem) { + stopListening(n.first); + removeActor(n.first); + } + + for (Pair n : add) { + addActor(n.first); + listen(n.first); + } + + for (E e : mod.getKeys()) { + Set ids = mod.getValues(e); + if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) { + if (!propagation.contains(e)) + propagation.add(e); + } + } + + if (propagation.size() > 0) { + stack.clear(); + stack.addAll(propagation); + propagation.clear(); + while (!stack.isEmpty()) { + E node = stack.pop(); + if (propagation.contains(node)) + continue; + propagation.add(node); + for (NodeListener l : node.getListeners()) { + if (l == this) { + //changeTracking = false; + //l.propertyChanged(node, G3D.URIs.hasPosition); + //changeTracking = true; + } else { + l.propertyChanged(node, G3D.URIs.hasWorldPosition); + } + } + if (node instanceof ParentNode) { + stack.addAll(((ParentNode)node).getNodes()); + } + } + } + // synchronized (syncMutex) { // rem.addAll(removed); // add.addAll(added); @@ -503,130 +503,130 @@ public abstract class AbstractVTKNodeMap implements VTKNodeMap< // added.clear(); // updated.clear(); // } - - for (E e : mod.getKeys()) { - Set ids = mod.getValues(e); - updateActor(e,ids); - } - - - for (Pair n : rem) { - for (NodeListener l : nodeListeners) - l.nodeRemoved(null, n.first, n.second); - } - for (Pair n : add) { - for (NodeListener l : nodeListeners) - l.nodeAdded(n.first.getParent(), n.first, n.second); - } + + for (E e : mod.getKeys()) { + Set ids = mod.getValues(e); + updateActor(e,ids); + } + + + for (Pair n : rem) { + for (NodeListener l : nodeListeners) + l.nodeRemoved(null, n.first, n.second); + } + for (Pair n : add) { + for (NodeListener l : nodeListeners) + l.nodeAdded(n.first.getParent(), n.first, n.second); + } // for (Pair n : mod) { // for (NodeListener l : nodeListeners) // l.propertyChanged(n.first, n.second); // } - for (E e : mod.getKeys()) { - for (NodeListener l : nodeListeners) - for (String s : mod.getValues(e)) - l.propertyChanged(e, s); - } - - synchronized (syncMutex) { - if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0) - rangeModified = false; - } - } - - @SuppressWarnings("unchecked") - private void listen(INode node) { - node.addListener(this); - if (node instanceof ParentNode) { - ParentNode parentNode = (ParentNode)node; - for (INode n : parentNode.getNodes()) - listen(n); - } - } - - private void stopListening(INode node) { - node.removeListener(this); - if (node instanceof ParentNode) { - @SuppressWarnings("unchecked") - ParentNode parentNode = (ParentNode)node; - for (INode n : parentNode.getNodes()) - stopListening(n); - } - } - - @SuppressWarnings("unchecked") - @Override - public void propertyChanged(INode node, String id) { - //receiveUpdate((E)node, id, graphUpdates); - receiveUpdate((E)node, id, graphModified.contains(node)); - - } - - @SuppressWarnings("unchecked") - @Override - public void nodeAdded(ParentNode node, INode child, - String rel) { - if (DEBUG) System.out.println("Node added " + child + " parent " + node); - //receiveAdd((E)child, rel ,graphUpdates); - receiveAdd((E)child, rel ,graphModified.contains(node)); - - } - - @SuppressWarnings("unchecked") - @Override - public void nodeRemoved(ParentNode node, INode child, - String rel) { - if (DEBUG) System.out.println("Node removed " + child + " parent " + node); - //receiveRemove((E)child, rel, graphUpdates); - receiveRemove((E)child, rel, graphModified.contains(node)); - - //FIXME : sometimes removed structural models cause ObjMap to add their children again. - // removing the listener here prevents corruption of visual model, but better fix is needed. - stopListening(child); - } - - @Override - public void delete() { - if (undoRedoSupport != null) - undoRedoSupport.cancel(this); - - changeTracking = false; - view.removeListener(this); - mapping.removeMappingListener(this); + for (E e : mod.getKeys()) { + for (NodeListener l : nodeListeners) + for (String s : mod.getValues(e)) + l.propertyChanged(e, s); + } + + synchronized (syncMutex) { + if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0) + rangeModified = false; + } + } + + @SuppressWarnings("unchecked") + private void listen(INode node) { + node.addListener(this); + if (node instanceof ParentNode) { + ParentNode parentNode = (ParentNode)node; + for (INode n : parentNode.getNodes()) + listen(n); + } + } + + private void stopListening(INode node) { + node.removeListener(this); + if (node instanceof ParentNode) { + @SuppressWarnings("unchecked") + ParentNode parentNode = (ParentNode)node; + for (INode n : parentNode.getNodes()) + stopListening(n); + } + } + + @SuppressWarnings("unchecked") + @Override + public void propertyChanged(INode node, String id) { + //receiveUpdate((E)node, id, graphUpdates); + receiveUpdate((E)node, id, graphModified.contains(node)); + + } + + @SuppressWarnings("unchecked") + @Override + public void nodeAdded(ParentNode node, INode child, + String rel) { + if (DEBUG) System.out.println("Node added " + child + " parent " + node); + //receiveAdd((E)child, rel ,graphUpdates); + receiveAdd((E)child, rel ,graphModified.contains(node)); + + } + + @SuppressWarnings("unchecked") + @Override + public void nodeRemoved(ParentNode node, INode child, + String rel) { + if (DEBUG) System.out.println("Node removed " + child + " parent " + node); + //receiveRemove((E)child, rel, graphUpdates); + receiveRemove((E)child, rel, graphModified.contains(node)); + + //FIXME : sometimes removed structural models cause ObjMap to add their children again. + // removing the listener here prevents corruption of visual model, but better fix is needed. + stopListening(child); + } + + @Override + public void delete() { + if (undoRedoSupport != null) + undoRedoSupport.cancel(this); + + changeTracking = false; + view.removeListener(this); + mapping.removeMappingListener(this); - List nodes = new ArrayList(nodeToActor.getKeySize()); - nodes.addAll(nodeToActor.getKeys()); - for (E node : nodes) { - node.removeListener(this); - removeActor(node); - node.cleanup(); - } - for (vtkProp prop : actorToNode.keySet()) { - if (prop.GetVTKId() != 0) - prop.Delete(); - } - actorToNode.clear(); - nodeToActor.clear(); - - } - - - private List nodeListeners = new ArrayList(); - @Override - public void addListener(NodeListener listener) { - nodeListeners.add(listener); - - } - - @Override - public void removeListener(NodeListener listener) { - nodeListeners.remove(listener); - - } - - public IMapping getMapping() { - return mapping; - } - - + List nodes = new ArrayList(nodeToActor.getKeySize()); + nodes.addAll(nodeToActor.getKeys()); + for (E node : nodes) { + node.removeListener(this); + removeActor(node); + node.cleanup(); + } + for (vtkProp prop : actorToNode.keySet()) { + if (prop.GetVTKId() != 0) + prop.Delete(); + } + actorToNode.clear(); + nodeToActor.clear(); + + } + + + private List nodeListeners = new ArrayList(); + @Override + public void addListener(NodeListener listener) { + nodeListeners.add(listener); + + } + + @Override + public void removeListener(NodeListener listener) { + nodeListeners.remove(listener); + + } + + public IMapping getMapping() { + return mapping; + } + + } diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/gizmo/TranslateGizmo.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/gizmo/TranslateGizmo.java index 49abd1f2..02e496e7 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/gizmo/TranslateGizmo.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/gizmo/TranslateGizmo.java @@ -35,18 +35,18 @@ public class TranslateGizmo extends vtkGizmo { float size = 2.f; - float sizeD2 = 1.f; - float offset = 0.2f; - - double[] colorX = new double[]{0.5,0.0,0.0}; - double[] colorY = new double[]{0.0,0.5,0.0}; - double[] colorZ = new double[]{0.0,0.0,0.5}; - - double[] colorXY = add(colorX, colorY); - double[] colorXZ = add(colorX, colorZ); - double[] colorYZ = add(colorY, colorZ); - double[] colorP = add(colorX,colorY,colorZ); - + float sizeD2 = 1.f; + float offset = 0.2f; + + double[] colorX = new double[]{0.5,0.0,0.0}; + double[] colorY = new double[]{0.0,0.5,0.0}; + double[] colorZ = new double[]{0.0,0.0,0.5}; + + double[] colorXY = add(colorX, colorY); + double[] colorXZ = add(colorX, colorZ); + double[] colorYZ = add(colorY, colorZ); + double[] colorP = add(colorX,colorY,colorZ); + vtkActor actorX = new vtkActor(); vtkActor actorY = new vtkActor(); vtkActor actorZ = new vtkActor(); diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/gizmo/vtkGizmo.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/gizmo/vtkGizmo.java index dacbc008..47ee62b4 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/gizmo/vtkGizmo.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/gizmo/vtkGizmo.java @@ -89,35 +89,35 @@ public abstract class vtkGizmo implements Gizmo { return false; } - public void setPosition(Tuple3d position) { - this.position = position; - for (vtkProp p : gizmo) { - ((vtkProp3D)p).SetPosition(position.x, position.y, position.z); - } - } - - public void setRotation(AxisAngle4d q) { - this.orientation = q; - for (vtkProp p : gizmo) { - ((vtkProp3D)p).SetOrientation(0,0,0); - ((vtkProp3D)p).RotateWXYZ(MathTools.radToDeg(q.angle), q.x, q.y, q.z); - } - } - - - public void setScale(Tuple3d s) { - this.scale = s; - for (vtkProp p : gizmo) { - ((vtkProp3D)p).SetScale(s.x, s.y, s.z); - } - } - - public void setScale(double s) { - this.scale = new Vector3d(s,s,s); - for (vtkProp p : gizmo) { - ((vtkProp3D)p).SetScale(s, s, s); - } - } + public void setPosition(Tuple3d position) { + this.position = position; + for (vtkProp p : gizmo) { + ((vtkProp3D)p).SetPosition(position.x, position.y, position.z); + } + } + + public void setRotation(AxisAngle4d q) { + this.orientation = q; + for (vtkProp p : gizmo) { + ((vtkProp3D)p).SetOrientation(0,0,0); + ((vtkProp3D)p).RotateWXYZ(MathTools.radToDeg(q.angle), q.x, q.y, q.z); + } + } + + + public void setScale(Tuple3d s) { + this.scale = s; + for (vtkProp p : gizmo) { + ((vtkProp3D)p).SetScale(s.x, s.y, s.z); + } + } + + public void setScale(double s) { + this.scale = new Vector3d(s,s,s); + for (vtkProp p : gizmo) { + ((vtkProp3D)p).SetScale(s, s, s); + } + } public abstract Collection getGizmo(); diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/handlers/CameraPositionHandler.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/handlers/CameraPositionHandler.java index c3e0e54a..1f88e118 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/handlers/CameraPositionHandler.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/handlers/CameraPositionHandler.java @@ -31,17 +31,17 @@ public class CameraPositionHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { - - final IWorkbenchPart ap = HandlerUtil.getActiveEditor(event); - final VtkView panel = (VtkView)ap.getAdapter(VtkView.class); - - String param = event.getParameter("org.simantics.g3d.viewDirection"); - String vals[] = param.split(","); - final Vector3d direction = new Vector3d(Double.parseDouble(vals[0]),Double.parseDouble(vals[1]),Double.parseDouble(vals[2])); - - - ThreadUtils.asyncExec(panel.getThreadQueue(), new Runnable() { - + + final IWorkbenchPart ap = HandlerUtil.getActiveEditor(event); + final VtkView panel = (VtkView)ap.getAdapter(VtkView.class); + + String param = event.getParameter("org.simantics.g3d.viewDirection"); + String vals[] = param.split(","); + final Vector3d direction = new Vector3d(Double.parseDouble(vals[0]),Double.parseDouble(vals[1]),Double.parseDouble(vals[2])); + + + ThreadUtils.asyncExec(panel.getThreadQueue(), new Runnable() { + @Override public void run() { @@ -51,7 +51,7 @@ public class CameraPositionHandler extends AbstractHandler { Vector3d dir = new Vector3d(pos); dir.sub(focal); double distance = dir.length(); - + dir.set(direction); dir.scale(distance); dir.add(focal); @@ -60,17 +60,17 @@ public class CameraPositionHandler extends AbstractHandler { panel.getRenderer().GetActiveCamera().SetViewUp(0, 1, 0); else panel.getRenderer().GetActiveCamera().SetViewUp(1, 0, 0); - + panel.getRenderer().ResetCameraClippingRange(); - + //panel.UpdateLight(); panel.refresh(); } - }); - - return null; - + }); + + return null; + } - + } diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/handlers/ParallelPerspectiveHandler.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/handlers/ParallelPerspectiveHandler.java index 855a0d14..70eb3a63 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/handlers/ParallelPerspectiveHandler.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/handlers/ParallelPerspectiveHandler.java @@ -33,15 +33,15 @@ public class ParallelPerspectiveHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { - Command command = event.getCommand(); - boolean oldValue = HandlerUtil.toggleCommandState(command); - final boolean activate = !oldValue; - - final IWorkbenchPart ap = HandlerUtil.getActiveEditor(event); - final VtkView panel = (VtkView)ap.getAdapter(VtkView.class); - - ThreadUtils.asyncExec(AWTThread.getThreadAccess(), new Runnable() { - + Command command = event.getCommand(); + boolean oldValue = HandlerUtil.toggleCommandState(command); + final boolean activate = !oldValue; + + final IWorkbenchPart ap = HandlerUtil.getActiveEditor(event); + final VtkView panel = (VtkView)ap.getAdapter(VtkView.class); + + ThreadUtils.asyncExec(AWTThread.getThreadAccess(), new Runnable() { + @Override public void run() { if (activate){ @@ -54,8 +54,8 @@ public class ParallelPerspectiveHandler extends AbstractHandler { dir.scale(100); dir.add(focal); panel.getRenderer().GetActiveCamera().SetPosition(dir.x, dir.y, dir.z); - - + + panel.getRenderer().GetActiveCamera().SetParallelProjection(1); panel.getRenderer().ResetCameraClippingRange(); } else { @@ -65,16 +65,16 @@ public class ParallelPerspectiveHandler extends AbstractHandler { panel.getRenderer().GetActiveCamera().SetPosition(pos.x, pos.y, pos.z); } panel.getRenderer().ResetCameraClippingRange(); - + } -// panel.UpdateLight(); + // panel.UpdateLight(); panel.refresh(); } - }); - - return null; - + }); + + return null; + } diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/preferences/VTKPreferencePage.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/preferences/VTKPreferencePage.java index 7bc568d7..f7e47855 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/preferences/VTKPreferencePage.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/preferences/VTKPreferencePage.java @@ -52,8 +52,8 @@ public class VTKPreferencePage "When to close VTK", 1, new String[][] { { "On &Editor Close", CloseMethod.ON_CLOSE.toString() }, - { "On &Last Editor Close", CloseMethod.ON_LAST_CLOSE.toString() }, - { "&Closing Disabled", CloseMethod.NO_CLOSE.toString() } + { "On &Last Editor Close", CloseMethod.ON_LAST_CLOSE.toString() }, + { "&Closing Disabled", CloseMethod.NO_CLOSE.toString() } }, getFieldEditorParent())); } diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/shape/MeshActor.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/shape/MeshActor.java index c52e021e..43aaadb1 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/shape/MeshActor.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/shape/MeshActor.java @@ -35,53 +35,53 @@ public class MeshActor extends vtkActor { polyData.Allocate(mesh.getIndices().size()/3, mesh.getIndices().size()/3); vtkTriangle triangle = new vtkTriangle(); - vtkIdList list = triangle.GetPointIds(); - for (int i = 0; i < mesh.getIndices().size(); i+=3) { - list.SetId(0, mesh.getIndices().get(i)); - list.SetId(1, mesh.getIndices().get(i+1)); - list.SetId(2, mesh.getIndices().get(i+2)); - polyData.InsertNextCell(triangle.GetCellType(), list); - } - list.Delete(); - triangle.Delete(); - - - vtkPoints points = new vtkPoints(); - for (int i = 0; i < mesh.getVertices().size(); i++) { - Tuple3d p = mesh.getVertices().get(i); - points.InsertPoint(i, p.x, p.y, p.z); - } - - polyData.SetPoints(points); - points.Delete(); - - if (mesh.getNormals() != null) { - vtkFloatArray normals = new vtkFloatArray(); - normals.SetNumberOfComponents(3); - normals.SetNumberOfTuples(mesh.getNormals().size()); - for (int i = 0; i < mesh.getNormals().size(); i++) { - Tuple3d p = mesh.getNormals().get(i); - normals.InsertTuple3(i, p.x, p.y, p.z); - } - vtkPointData pointData = polyData.GetPointData(); - pointData.SetNormals(normals); - normals.Delete(); - pointData.Delete(); - } - if (mesh.getColors() != null) { - vtkUnsignedCharArray colors = new vtkUnsignedCharArray(); - colors.SetName("Colors"); - colors.SetNumberOfComponents(3); - colors.SetNumberOfTuples(mesh.getColors().size()); - for (int i = 0; i < mesh.getColors().size(); i++) { - Color4d c = mesh.getColors().get(i); - colors.InsertTuple3(i, 255.0* c.x, 255.0 * c.y, 255.0 * c.z); - } - polyData.GetPointData().AddArray(colors); - colors.Delete(); - - } - return polyData; + vtkIdList list = triangle.GetPointIds(); + for (int i = 0; i < mesh.getIndices().size(); i+=3) { + list.SetId(0, mesh.getIndices().get(i)); + list.SetId(1, mesh.getIndices().get(i+1)); + list.SetId(2, mesh.getIndices().get(i+2)); + polyData.InsertNextCell(triangle.GetCellType(), list); + } + list.Delete(); + triangle.Delete(); + + + vtkPoints points = new vtkPoints(); + for (int i = 0; i < mesh.getVertices().size(); i++) { + Tuple3d p = mesh.getVertices().get(i); + points.InsertPoint(i, p.x, p.y, p.z); + } + + polyData.SetPoints(points); + points.Delete(); + + if (mesh.getNormals() != null) { + vtkFloatArray normals = new vtkFloatArray(); + normals.SetNumberOfComponents(3); + normals.SetNumberOfTuples(mesh.getNormals().size()); + for (int i = 0; i < mesh.getNormals().size(); i++) { + Tuple3d p = mesh.getNormals().get(i); + normals.InsertTuple3(i, p.x, p.y, p.z); + } + vtkPointData pointData = polyData.GetPointData(); + pointData.SetNormals(normals); + normals.Delete(); + pointData.Delete(); + } + if (mesh.getColors() != null) { + vtkUnsignedCharArray colors = new vtkUnsignedCharArray(); + colors.SetName("Colors"); + colors.SetNumberOfComponents(3); + colors.SetNumberOfTuples(mesh.getColors().size()); + for (int i = 0; i < mesh.getColors().size(); i++) { + Color4d c = mesh.getColors().get(i); + colors.InsertTuple3(i, 255.0* c.x, 255.0 * c.y, 255.0 * c.z); + } + polyData.GetPointData().AddArray(colors); + colors.Delete(); + + } + return polyData; } public void setMesh(Mesh mesh) { @@ -89,29 +89,29 @@ public class MeshActor extends vtkActor { vtkPolyDataMapper mapper = new vtkPolyDataMapper(); vtkPolyData polyData = createPolyData(mesh); - - if (mesh.getNormals() == null) { - vtkPolyDataNormals normals = new vtkPolyDataNormals(); - normals.SetInputData(polyData); - normals.ComputePointNormalsOn(); - mapper.SetInputConnection(normals.GetOutputPort()); - normals.GetOutputPort().Delete(); - normals.Delete(); - } else { - mapper.SetInputData(polyData); - } - - if (mesh.getColors() != null) { - mapper.ScalarVisibilityOn(); - mapper.SetScalarModeToUsePointFieldData(); - mapper.SelectColorArray("Colors"); - } - - SetMapper(mapper); - mapper.Delete(); - polyData.GetPointData().Delete(); - polyData.Delete(); - + + if (mesh.getNormals() == null) { + vtkPolyDataNormals normals = new vtkPolyDataNormals(); + normals.SetInputData(polyData); + normals.ComputePointNormalsOn(); + mapper.SetInputConnection(normals.GetOutputPort()); + normals.GetOutputPort().Delete(); + normals.Delete(); + } else { + mapper.SetInputData(polyData); + } + + if (mesh.getColors() != null) { + mapper.ScalarVisibilityOn(); + mapper.SetScalarModeToUsePointFieldData(); + mapper.SelectColorArray("Colors"); + } + + SetMapper(mapper); + mapper.Delete(); + polyData.GetPointData().Delete(); + polyData.Delete(); + } @Override diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/shape/vtkShape.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/shape/vtkShape.java index c992547f..8157dfe3 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/shape/vtkShape.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/shape/vtkShape.java @@ -148,14 +148,14 @@ public class vtkShape { linePoints.Delete(); aLine.GetPointIds().Delete(); - aLine.Delete(); - aLineGrid.Delete(); - aLineMapper.Delete(); - - aLineActor.GetProperty().SetColor(0, 0, 0); - aLineActor.GetProperty().Delete(); - - return aLineActor; + aLine.Delete(); + aLineGrid.Delete(); + aLineMapper.Delete(); + + aLineActor.GetProperty().SetColor(0, 0, 0); + aLineActor.GetProperty().Delete(); + + return aLineActor; } /** @@ -182,14 +182,14 @@ public class vtkShape { vtkActor aLineActor = new vtkActor(); aLineActor.SetMapper(aLineMapper); //aLineActor.GetProperty().SetDiffuseColor(.2, 1, 1); - - linePoints.Delete(); - aLine.GetPointIds().Delete(); - aLine.Delete(); - aLineGrid.Delete(); - aLineMapper.Delete(); - - return aLineActor; + + linePoints.Delete(); + aLine.GetPointIds().Delete(); + aLine.Delete(); + aLineGrid.Delete(); + aLineMapper.Delete(); + + return aLineActor; } } diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/swt/InteractiveVtkComposite.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/swt/InteractiveVtkComposite.java index b20bcac7..b8f9ff0c 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/swt/InteractiveVtkComposite.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/swt/InteractiveVtkComposite.java @@ -280,26 +280,26 @@ public class InteractiveVtkComposite extends vtkSwtComponent implements VtkView{ return processPick(picker, apath); } else if (pickType == 5) { vtkActor2DCollection coll = ren.GetActors2D(); - coll.InitTraversal(); - vtkActor2D a; - - List picked = new ArrayList(); - while ((a = coll.GetNextItem()) != null) { - double pos[] = a.GetPosition(); - // TODO : width and height do not seem to affect the perceived size of Actor2D. - // actual size should be fetched from mapper. - double w = a.GetWidth(); - double h = a.GetHeight(); - int minx = (int)(pos[0]-w*0.5); - int miny = (int)(pos[1]-h*0.5); - int maxx = (int)(pos[0]+w*0.5); - int maxy = (int)(pos[1]+h*0.5); - if (minx <= ax && maxx >= ax && - miny <= ay && maxy >= ay) { - picked.add(a); - } - } - return picked.toArray(new vtkProp[picked.size()]); + coll.InitTraversal(); + vtkActor2D a; + + List picked = new ArrayList(); + while ((a = coll.GetNextItem()) != null) { + double pos[] = a.GetPosition(); + // TODO : width and height do not seem to affect the perceived size of Actor2D. + // actual size should be fetched from mapper. + double w = a.GetWidth(); + double h = a.GetHeight(); + int minx = (int)(pos[0]-w*0.5); + int miny = (int)(pos[1]-h*0.5); + int maxx = (int)(pos[0]+w*0.5); + int maxy = (int)(pos[1]+h*0.5); + if (minx <= ax && maxx >= ax && + miny <= ay && maxy >= ay) { + picked.add(a); + } + } + return picked.toArray(new vtkProp[picked.size()]); } return null; diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/swt/RotateAction.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/swt/RotateAction.java index c45316e8..bd581ac2 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/swt/RotateAction.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/swt/RotateAction.java @@ -47,9 +47,9 @@ import vtk.vtkProp; public class RotateAction extends vtkSwtAction{ public static final int X = 0; - public static final int Y = 1; - public static final int Z = 2; - public static final int P = 3; + public static final int Y = 1; + public static final int Z = 2; + public static final int P = 3; private VTKNodeMap nodeMap; //private TranslateGizmo gizmo = new TranslateGizmo(); @@ -65,8 +65,8 @@ public class RotateAction extends vtkSwtAction{ int stepMethod = 1; Order order = Order.YXZ; - private int steps; - private double angles[]; + private int steps; + private double angles[]; int index = P; boolean valid = false; @@ -113,13 +113,13 @@ public class RotateAction extends vtkSwtAction{ steps = 36; - angles = new double[steps+1]; - for (int i = 0; i < angles.length; i++) { - angles[i] = - Math.PI + (Math.PI * i * 2.0 / steps); - } - - activeCursor = Display.getCurrent().getSystemCursor(SWT.CURSOR_HAND); - dragCursor = Display.getCurrent().getSystemCursor(SWT.CURSOR_CROSS); + angles = new double[steps+1]; + for (int i = 0; i < angles.length; i++) { + angles[i] = - Math.PI + (Math.PI * i * 2.0 / steps); + } + + activeCursor = Display.getCurrent().getSystemCursor(SWT.CURSOR_HAND); + dragCursor = Display.getCurrent().getSystemCursor(SWT.CURSOR_CROSS); } public void attach() { @@ -251,31 +251,31 @@ public class RotateAction extends vtkSwtAction{ if (panel.getRenderer().GetActiveCamera().GetParallelProjection() == 0) { double distance = p.length(); p.negate(); - double fov = panel.getRenderer().GetActiveCamera().GetViewAngle(); - float s = (float) (Math.sin(fov) * distance * 0.1); + double fov = panel.getRenderer().GetActiveCamera().GetViewAngle(); + float s = (float) (Math.sin(fov) * distance * 0.1); - Vector3d scale = new Vector3d(1., 1., 1.); - + Vector3d scale = new Vector3d(1., 1., 1.); + // if (p.x > 0.f) // scale.x = -1.; // if (p.y > 0.f) // scale.y = -1.; // if (p.z > 0.f) // scale.z = -1.; - scale.scale(s); - gizmo.setScale(scale); + scale.scale(s); + gizmo.setScale(scale); } else { Vector3d scale = new Vector3d(1.f, 1.f, 1.f); - double s = panel.getRenderer().GetActiveCamera().GetParallelScale() / 5.; + double s = panel.getRenderer().GetActiveCamera().GetParallelScale() / 5.; // if (p.x > 0.f) // scale.x = -1.; // if (p.y > 0.f) // scale.y = -1.; // if (p.z > 0.f) // scale.z = -1.; - scale.scale(s); - gizmo.setScale(scale); + scale.scale(s); + gizmo.setScale(scale); } panel.refresh(); @@ -303,9 +303,9 @@ public class RotateAction extends vtkSwtAction{ valid = true; if ((e.getModifiers() & MouseEvent.CTRL_MASK) > 0) { useStep = true; - } else { - useStep = false; - } + } else { + useStep = false; + } worldOrientation = node.getWorldOrientation(); doChanges(true, e.getX(), e.getY()); @@ -340,9 +340,9 @@ public class RotateAction extends vtkSwtAction{ if ((e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) > 0 && valid) { if ((e.getModifiers() & MouseEvent.CTRL_MASK) > 0) { useStep = true; - } else { - useStep = false; - } + } else { + useStep = false; + } doChanges(false, e.getX(), e.getY()); //nodeMap.modified(node); @@ -354,188 +354,188 @@ public class RotateAction extends vtkSwtAction{ return true; } - Vector3d axis = null; + Vector3d axis = null; @Override public boolean keyTyped(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_LEFT) { - inputType = InputType.KEY; - axis = new Vector3d(0.0,1.0,0.0); - } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { - inputType = InputType.KEY; - axis = new Vector3d(0.0,-1.0,0.0); - } else if (e.getKeyCode() ==KeyEvent.VK_UP) { - inputType = InputType.KEY; - axis = new Vector3d(1.0,0.0,0.0); - } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { - inputType = InputType.KEY; - axis = new Vector3d(-1.0,0.0,0.0); - } - return true; + if (e.getKeyCode() == KeyEvent.VK_LEFT) { + inputType = InputType.KEY; + axis = new Vector3d(0.0,1.0,0.0); + } else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { + inputType = InputType.KEY; + axis = new Vector3d(0.0,-1.0,0.0); + } else if (e.getKeyCode() ==KeyEvent.VK_UP) { + inputType = InputType.KEY; + axis = new Vector3d(1.0,0.0,0.0); + } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { + inputType = InputType.KEY; + axis = new Vector3d(-1.0,0.0,0.0); + } + return true; } - public void doChanges(boolean pressed, int x, int y) { - Ray ray = vtkUtil.createMouseRay(panel.getRenderer(),x, y); - Vector3d p = node.getWorldPosition(); - - if (pressed) { - Vector3d axis = getRotationAxis(); - if (axis != null) { - if (!worldCoord) { - MathTools.rotate(parentWorldOrientation, axis, axis); - } + public void doChanges(boolean pressed, int x, int y) { + Ray ray = vtkUtil.createMouseRay(panel.getRenderer(),x, y); + Vector3d p = node.getWorldPosition(); + + if (pressed) { + Vector3d axis = getRotationAxis(); + if (axis != null) { + if (!worldCoord) { + MathTools.rotate(parentWorldOrientation, axis, axis); + } - - double s[] = new double[2]; - Vector3d i2 = new Vector3d(); - - boolean intersect = MathTools.intersectStraightPlane(ray.pos, ray.dir, p, axis, i2, s); - double dot = Math.abs(ray.dir.dot(axis)); - if (intersect && dot > 0.4) - inputType = InputType.INTERSECT; - else - inputType = InputType.NONINTERSECT; - - - if (inputType == InputType.INTERSECT) { - // picking ray and plane defined by gizmo's center point and - // rotation axis can intersect - // vector from center point to intersection point - i2.sub(p); - // creating vectors i and j that are lying on the plane and - // are perpendicular - // vectors are used to calculate polar coordinate for - // intersection point - j.set(i2); - i.cross(j, axis); - System.out.println("I,J " + i + " " + j); - double angleI = i2.angle(i); - double angleJ = i2.angle(j); - prevAngle = Math.atan2(Math.cos(angleJ), Math.cos(angleI)); - } else { - // picking ray and plane defined by gizmo's center point and - // rotation axis are parallel, - // so we'll use cross product of rotation axis and picking - // ray to detect amount of rotation - i.cross(ray.dir, axis); - MathTools.intersectStraightStraight(ray.pos, ray.dir, p, i, new Vector3d(), new Vector3d(), s); - prevS = s[1]; - } - } - - - } + + double s[] = new double[2]; + Vector3d i2 = new Vector3d(); + + boolean intersect = MathTools.intersectStraightPlane(ray.pos, ray.dir, p, axis, i2, s); + double dot = Math.abs(ray.dir.dot(axis)); + if (intersect && dot > 0.4) + inputType = InputType.INTERSECT; + else + inputType = InputType.NONINTERSECT; + + + if (inputType == InputType.INTERSECT) { + // picking ray and plane defined by gizmo's center point and + // rotation axis can intersect + // vector from center point to intersection point + i2.sub(p); + // creating vectors i and j that are lying on the plane and + // are perpendicular + // vectors are used to calculate polar coordinate for + // intersection point + j.set(i2); + i.cross(j, axis); + System.out.println("I,J " + i + " " + j); + double angleI = i2.angle(i); + double angleJ = i2.angle(j); + prevAngle = Math.atan2(Math.cos(angleJ), Math.cos(angleI)); + } else { + // picking ray and plane defined by gizmo's center point and + // rotation axis are parallel, + // so we'll use cross product of rotation axis and picking + // ray to detect amount of rotation + i.cross(ray.dir, axis); + MathTools.intersectStraightStraight(ray.pos, ray.dir, p, i, new Vector3d(), new Vector3d(), s); + prevS = s[1]; + } + } + + + } - if (inputType != InputType.KEY) - axis = getRotationAxis(); - if (axis == null) { - return; - } - Vector3d taxis = null; - if (!worldCoord) { - taxis = new Vector3d(axis); - MathTools.rotate(parentWorldOrientation, axis, axis); - } - System.out.println(inputType); - if (inputType == InputType.INTERSECT) { + if (inputType != InputType.KEY) + axis = getRotationAxis(); + if (axis == null) { + return; + } + Vector3d taxis = null; + if (!worldCoord) { + taxis = new Vector3d(axis); + MathTools.rotate(parentWorldOrientation, axis, axis); + } + System.out.println(inputType); + if (inputType == InputType.INTERSECT) { - double s[] = new double[2]; - Vector3d i2 = new Vector3d(); - MathTools.intersectStraightPlane(ray.pos, ray.dir, p, axis, i2, s); - i2.sub(p); - double angleI = i2.angle(i); - double angleJ = i2.angle(j); - double angle = Math.atan2(Math.cos(angleJ), Math.cos(angleI)); - System.out.println("Angle " + angle + " i " + angleI + " j " + angleJ + " prev " + prevAngle); - if(!worldCoord) - axis = taxis; - if (useStep) { + double s[] = new double[2]; + Vector3d i2 = new Vector3d(); + MathTools.intersectStraightPlane(ray.pos, ray.dir, p, axis, i2, s); + i2.sub(p); + double angleI = i2.angle(i); + double angleJ = i2.angle(j); + double angle = Math.atan2(Math.cos(angleJ), Math.cos(angleI)); + System.out.println("Angle " + angle + " i " + angleI + " j " + angleJ + " prev " + prevAngle); + if(!worldCoord) + axis = taxis; + if (useStep) { - //setOrientation(MathTools.getQuat(rotation)); - AxisAngle4d rot = new AxisAngle4d(axis,angle-prevAngle); - Quat4d qrot = new Quat4d(); - MathTools.getQuat(rot, qrot); - //prevAngle = angle; - qrot.mulInverse(worldOrientation); - - - if (stepMethod == 0) { - rot.set(qrot); - rot.angle = roundAngle(rot.angle); - //qrot.set(rot); - MathTools.getQuat(rot,qrot); - setOrientation(qrot); - } else if (stepMethod == 1){ - - //Vector3d euler = MathTools.getEuler(qrot); - Vector3d euler = EulerTools.getEulerFromQuat(order, qrot); - euler.x = roundAngle(euler.x); - euler.y = roundAngle(euler.y); - euler.z = roundAngle(euler.z); - //Quat4d q = MathTools.getQuat(euler); - Quat4d q = EulerTools.getQuatFromEuler(order, euler); - setOrientation(q); - System.out.println(" (" + MathTools.radToDeg(euler.x) + " " + MathTools.radToDeg(euler.y) + " " + MathTools.radToDeg(euler.z) + ") " + qrot + " "+ q); - } else { - setOrientation(qrot); - } - - } else { - if (worldCoord) { - //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getWorldOrientation(), new AxisAngle4d(axis,angle-prevAngle)); - AxisAngle4d aa = MathTools.getAxisAngle(node.getWorldOrientation()); - AxisAngle4d rot = new AxisAngle4d(axis,angle-prevAngle); - MathTools.multiplyOrientation(aa, rot); - setWorldOrientation(MathTools.getQuat(rot)); - } else { - AxisAngle4d aa = MathTools.getAxisAngle(node.getOrientation()); - AxisAngle4d rot = new AxisAngle4d(axis,angle-prevAngle); - MathTools.multiplyOrientation(aa, rot); - setOrientation(MathTools.getQuat(rot)); - //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getLocalOrientation(), new AxisAngle4d(axis,angle-prevAngle)); - } - prevAngle = angle; - } - - } else if (inputType == InputType.NONINTERSECT){ + //setOrientation(MathTools.getQuat(rotation)); + AxisAngle4d rot = new AxisAngle4d(axis,angle-prevAngle); + Quat4d qrot = new Quat4d(); + MathTools.getQuat(rot, qrot); + //prevAngle = angle; + qrot.mulInverse(worldOrientation); + + + if (stepMethod == 0) { + rot.set(qrot); + rot.angle = roundAngle(rot.angle); + //qrot.set(rot); + MathTools.getQuat(rot,qrot); + setOrientation(qrot); + } else if (stepMethod == 1){ + + //Vector3d euler = MathTools.getEuler(qrot); + Vector3d euler = EulerTools.getEulerFromQuat(order, qrot); + euler.x = roundAngle(euler.x); + euler.y = roundAngle(euler.y); + euler.z = roundAngle(euler.z); + //Quat4d q = MathTools.getQuat(euler); + Quat4d q = EulerTools.getQuatFromEuler(order, euler); + setOrientation(q); + System.out.println(" (" + MathTools.radToDeg(euler.x) + " " + MathTools.radToDeg(euler.y) + " " + MathTools.radToDeg(euler.z) + ") " + qrot + " "+ q); + } else { + setOrientation(qrot); + } + + } else { + if (worldCoord) { + //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getWorldOrientation(), new AxisAngle4d(axis,angle-prevAngle)); + AxisAngle4d aa = MathTools.getAxisAngle(node.getWorldOrientation()); + AxisAngle4d rot = new AxisAngle4d(axis,angle-prevAngle); + MathTools.multiplyOrientation(aa, rot); + setWorldOrientation(MathTools.getQuat(rot)); + } else { + AxisAngle4d aa = MathTools.getAxisAngle(node.getOrientation()); + AxisAngle4d rot = new AxisAngle4d(axis,angle-prevAngle); + MathTools.multiplyOrientation(aa, rot); + setOrientation(MathTools.getQuat(rot)); + //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getLocalOrientation(), new AxisAngle4d(axis,angle-prevAngle)); + } + prevAngle = angle; + } + + } else if (inputType == InputType.NONINTERSECT){ - double s[] = new double[2]; - MathTools.intersectStraightStraight(ray.pos, ray.dir, p, i, new Vector3d(), new Vector3d(), s); - if(!worldCoord) - axis = taxis; - if (useStep) { - //setOrientation(MathTools.getQuat(rotation)); - AxisAngle4d rot = new AxisAngle4d(axis,s[1] - prevS); - - Quat4d qrot = new Quat4d(); - //qrot.set(rot); - MathTools.getQuat(rot, qrot); - //prevAngle = angle; - qrot.mulInverse(worldOrientation); - - - if (stepMethod == 0) { - rot.set(qrot); - rot.angle = roundAngle(rot.angle); - //qrot.set(rot); - MathTools.getQuat(rot,qrot); - setOrientation(qrot); - } else if (stepMethod == 1){ - - //Vector3d euler = MathTools.getEuler(qrot); - Vector3d euler = EulerTools.getEulerFromQuat(order, qrot); - euler.x = roundAngle(euler.x); - euler.y = roundAngle(euler.y); - euler.z = roundAngle(euler.z); - //Quat4d q = MathTools.getQuat(euler); - Quat4d q = EulerTools.getQuatFromEuler(order, euler); - setOrientation(q); - System.out.println(" (" + MathTools.radToDeg(euler.x) + " " + MathTools.radToDeg(euler.y) + " " + MathTools.radToDeg(euler.z) + ") " + qrot + " "+ q); - } else { - setOrientation(qrot); - } - prevS = s[1]; - + double s[] = new double[2]; + MathTools.intersectStraightStraight(ray.pos, ray.dir, p, i, new Vector3d(), new Vector3d(), s); + if(!worldCoord) + axis = taxis; + if (useStep) { + //setOrientation(MathTools.getQuat(rotation)); + AxisAngle4d rot = new AxisAngle4d(axis,s[1] - prevS); + + Quat4d qrot = new Quat4d(); + //qrot.set(rot); + MathTools.getQuat(rot, qrot); + //prevAngle = angle; + qrot.mulInverse(worldOrientation); + + + if (stepMethod == 0) { + rot.set(qrot); + rot.angle = roundAngle(rot.angle); + //qrot.set(rot); + MathTools.getQuat(rot,qrot); + setOrientation(qrot); + } else if (stepMethod == 1){ + + //Vector3d euler = MathTools.getEuler(qrot); + Vector3d euler = EulerTools.getEulerFromQuat(order, qrot); + euler.x = roundAngle(euler.x); + euler.y = roundAngle(euler.y); + euler.z = roundAngle(euler.z); + //Quat4d q = MathTools.getQuat(euler); + Quat4d q = EulerTools.getQuatFromEuler(order, euler); + setOrientation(q); + System.out.println(" (" + MathTools.radToDeg(euler.x) + " " + MathTools.radToDeg(euler.y) + " " + MathTools.radToDeg(euler.z) + ") " + qrot + " "+ q); + } else { + setOrientation(qrot); + } + prevS = s[1]; + // G3DTools.setOrientation(mo.getG3DNode(graph).getLocalOrientation(), rotations.get(mo)); // G3DTools.multiplyOrientation(mo.getG3DNode(graph).getWorldOrientation(), new AxisAngle4d(axis,s[1] - prevS)); // AxisAngle4d aa = G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation()); @@ -550,55 +550,55 @@ public class RotateAction extends vtkSwtAction{ // Vector3d e = MathTools.getEuler(G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation())); // e.scale(180.0/Math.PI); // text += G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation()) + " " + e + " "; - - - } else { - if (worldCoord) { - AxisAngle4d aa = MathTools.getAxisAngle(node.getWorldOrientation()); - AxisAngle4d rot = new AxisAngle4d(axis,s[1] - prevS); - MathTools.multiplyOrientation(aa, rot); - setWorldOrientation(MathTools.getQuat(rot)); - //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getWorldOrientation(), new AxisAngle4d(axis,s[1] - prevS)); - } else { - AxisAngle4d aa = MathTools.getAxisAngle(node.getOrientation()); - AxisAngle4d rot = new AxisAngle4d(axis,s[1] - prevS); - MathTools.multiplyOrientation(aa, rot); - setOrientation(MathTools.getQuat(rot)); - //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getLocalOrientation(), new AxisAngle4d(axis,s[1] - prevS)); - } - //text += G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation()) + " " + MathTools.getEuler(G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation())) + " "; - prevS = s[1]; - - } - - } else { - if (worldCoord) { - AxisAngle4d aa = MathTools.getAxisAngle(node.getWorldOrientation()); - AxisAngle4d rot = new AxisAngle4d(axis,Math.PI * 0.5); - MathTools.multiplyOrientation(aa, rot); - setWorldOrientation(MathTools.getQuat(rot)); - //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getWorldOrientation(), new AxisAngle4d(axis,Math.PI * 0.5)); - } else { - AxisAngle4d aa = MathTools.getAxisAngle(node.getOrientation()); - AxisAngle4d rot = new AxisAngle4d(axis,Math.PI * 0.5); - MathTools.multiplyOrientation(aa, rot); - setOrientation(MathTools.getQuat(rot)); - //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getLocalOrientation(), new AxisAngle4d(axis,Math.PI * 0.5)); - } - // text += G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation()) + " " + MathTools.getEuler(G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation())) + " "; - - } - //setInfoText(text); - - } - - protected void setOrientation(Quat4d q) { - node.setOrientation(q); - } - - protected void setWorldOrientation(Quat4d q) { - node.setWorldOrientation(q); - } + + + } else { + if (worldCoord) { + AxisAngle4d aa = MathTools.getAxisAngle(node.getWorldOrientation()); + AxisAngle4d rot = new AxisAngle4d(axis,s[1] - prevS); + MathTools.multiplyOrientation(aa, rot); + setWorldOrientation(MathTools.getQuat(rot)); + //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getWorldOrientation(), new AxisAngle4d(axis,s[1] - prevS)); + } else { + AxisAngle4d aa = MathTools.getAxisAngle(node.getOrientation()); + AxisAngle4d rot = new AxisAngle4d(axis,s[1] - prevS); + MathTools.multiplyOrientation(aa, rot); + setOrientation(MathTools.getQuat(rot)); + //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getLocalOrientation(), new AxisAngle4d(axis,s[1] - prevS)); + } + //text += G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation()) + " " + MathTools.getEuler(G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation())) + " "; + prevS = s[1]; + + } + + } else { + if (worldCoord) { + AxisAngle4d aa = MathTools.getAxisAngle(node.getWorldOrientation()); + AxisAngle4d rot = new AxisAngle4d(axis,Math.PI * 0.5); + MathTools.multiplyOrientation(aa, rot); + setWorldOrientation(MathTools.getQuat(rot)); + //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getWorldOrientation(), new AxisAngle4d(axis,Math.PI * 0.5)); + } else { + AxisAngle4d aa = MathTools.getAxisAngle(node.getOrientation()); + AxisAngle4d rot = new AxisAngle4d(axis,Math.PI * 0.5); + MathTools.multiplyOrientation(aa, rot); + setOrientation(MathTools.getQuat(rot)); + //G3DTools.multiplyOrientation(mo.getG3DNode(graph).getLocalOrientation(), new AxisAngle4d(axis,Math.PI * 0.5)); + } + // text += G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation()) + " " + MathTools.getEuler(G3DTools.getOrientation(mo.getG3DNode(graph).getLocalOrientation())) + " "; + + } + //setInfoText(text); + + } + + protected void setOrientation(Quat4d q) { + node.setOrientation(q); + } + + protected void setWorldOrientation(Quat4d q) { + node.setWorldOrientation(q); + } @Override public boolean mouseMoved(MouseEvent e) { @@ -623,39 +623,39 @@ public class RotateAction extends vtkSwtAction{ } } - private double prevS = 0.0; - - private Vector3d i = new Vector3d(); - private Vector3d j = new Vector3d(); - private double prevAngle = 0; + private double prevS = 0.0; + + private Vector3d i = new Vector3d(); + private Vector3d j = new Vector3d(); + private double prevAngle = 0; - enum InputType{INTERSECT,NONINTERSECT,KEY,NONE}; - InputType inputType; - private boolean useStep = false; - - - - private double roundAngle(double angle) { - while (angle < - Math.PI) - angle += Math.PI*2.0; - while (angle > Math.PI) - angle -= Math.PI*2.0; - - - int index = 0; - while (angle > angles[index]) - index++; - if (index == 0) { - angle = angles[0]; - } else { - double d = angle - angles[index - 1]; - double d2 = angles[index] - angle; - if (d < d2) - angle = angles[index - 1]; - else - angle = angles[index]; - } - return angle; - } + enum InputType{INTERSECT,NONINTERSECT,KEY,NONE}; + InputType inputType; + private boolean useStep = false; + + + + private double roundAngle(double angle) { + while (angle < - Math.PI) + angle += Math.PI*2.0; + while (angle > Math.PI) + angle -= Math.PI*2.0; + + + int index = 0; + while (angle > angles[index]) + index++; + if (index == 0) { + angle = angles[0]; + } else { + double d = angle - angles[index - 1]; + double d2 = angles[index] - angle; + if (d < d2) + angle = angles[index - 1]; + else + angle = angles[index]; + } + return angle; + } } diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/swt/TranslateAction.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/swt/TranslateAction.java index 83c434bb..47a3ea3b 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/swt/TranslateAction.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/swt/TranslateAction.java @@ -40,12 +40,12 @@ import vtk.vtkProp; public class TranslateAction extends vtkSwtAction{ public static final int X = 0; - public static final int Y = 1; - public static final int Z = 2; - public static final int XY = 3; - public static final int XZ = 4; - public static final int YZ = 5; - public static final int P = 6; + public static final int Y = 1; + public static final int Z = 2; + public static final int XY = 3; + public static final int XZ = 4; + public static final int YZ = 5; + public static final int P = 6; private VTKNodeMap nodeMap; //private TranslateGizmo gizmo = new TranslateGizmo(); @@ -77,7 +77,7 @@ public class TranslateAction extends vtkSwtAction{ this.nodeMap = nodeMap; activeCursor = Display.getCurrent().getSystemCursor(SWT.CURSOR_HAND); - dragCursor = Display.getCurrent().getSystemCursor(SWT.CURSOR_SIZEALL); + dragCursor = Display.getCurrent().getSystemCursor(SWT.CURSOR_SIZEALL); } public void attach() { @@ -226,31 +226,31 @@ public class TranslateAction extends vtkSwtAction{ if (panel.getRenderer().GetActiveCamera().GetParallelProjection() == 0) { double distance = p.length(); p.negate(); - double fov = panel.getRenderer().GetActiveCamera().GetViewAngle(); - float s = (float) (Math.sin(fov) * distance * 0.1); + double fov = panel.getRenderer().GetActiveCamera().GetViewAngle(); + float s = (float) (Math.sin(fov) * distance * 0.1); - Vector3d scale = new Vector3d(1., 1., 1.); - + Vector3d scale = new Vector3d(1., 1., 1.); + // if (p.x > 0.f) // scale.x = -1.; // if (p.y > 0.f) // scale.y = -1.; // if (p.z > 0.f) // scale.z = -1.; - scale.scale(s); - gizmo.setScale(scale); + scale.scale(s); + gizmo.setScale(scale); } else { Vector3d scale = new Vector3d(1.f, 1.f, 1.f); - double s = panel.getRenderer().GetActiveCamera().GetParallelScale() / 5.; + double s = panel.getRenderer().GetActiveCamera().GetParallelScale() / 5.; // if (p.x > 0.f) // scale.x = -1.; // if (p.y > 0.f) // scale.y = -1.; // if (p.z > 0.f) // scale.z = -1.; - scale.scale(s); - gizmo.setScale(scale); + scale.scale(s); + gizmo.setScale(scale); } //panel.Render(); @@ -333,9 +333,9 @@ public class TranslateAction extends vtkSwtAction{ } @Override - public boolean mouseWheelMoved(MouseWheelEvent e) { - return getDefaultAction().mouseWheelMoved(e); - } + public boolean mouseWheelMoved(MouseWheelEvent e) { + return getDefaultAction().mouseWheelMoved(e); + } protected void setPos(Vector3d pos) { node.setPosition(pos); @@ -345,31 +345,31 @@ public class TranslateAction extends vtkSwtAction{ node.setWorldPosition(pos); } - private double istep = 10.0; - private int decimals = 2; + private double istep = 10.0; + private int decimals = 2; protected Vector3d constaints(Vector3d p, boolean step) { if(!step) return p; switch (index) { case X: - p.x = Math.round(istep * p.x) / istep; - BigDecimal bx = new BigDecimal(p.x); - bx.setScale(decimals, BigDecimal.ROUND_HALF_UP); - p.x = bx.doubleValue(); + p.x = Math.round(istep * p.x) / istep; + BigDecimal bx = new BigDecimal(p.x); + bx.setScale(decimals, BigDecimal.ROUND_HALF_UP); + p.x = bx.doubleValue(); break; case Y: - p.y = Math.round(istep * p.y) / istep; - BigDecimal by = new BigDecimal(p.y); - by.setScale(decimals, BigDecimal.ROUND_HALF_UP); - p.y = by.doubleValue(); + p.y = Math.round(istep * p.y) / istep; + BigDecimal by = new BigDecimal(p.y); + by.setScale(decimals, BigDecimal.ROUND_HALF_UP); + p.y = by.doubleValue(); break; - + case Z: - p.z = Math.round(istep * p.z) / istep; - BigDecimal bz = new BigDecimal(p.z); - bz.setScale(decimals, BigDecimal.ROUND_HALF_UP); - p.z = bz.doubleValue(); + p.z = Math.round(istep * p.z) / istep; + BigDecimal bz = new BigDecimal(p.z); + bz.setScale(decimals, BigDecimal.ROUND_HALF_UP); + p.z = bz.doubleValue(); break; } return p; @@ -401,85 +401,85 @@ public class TranslateAction extends vtkSwtAction{ } normal.normalize(); double s[] = new double[1]; - Vector3d r = new Vector3d(); - if (MathTools.intersectStraightPlane(ray.pos, ray.dir, p, normal, r)) { - r.sub(p); - translate.x = r.x; - translate.y = r.y; - translate.z = r.z; - } - break; + Vector3d r = new Vector3d(); + if (MathTools.intersectStraightPlane(ray.pos, ray.dir, p, normal, r)) { + r.sub(p); + translate.x = r.x; + translate.y = r.y; + translate.z = r.z; + } + break; - case X : - dir = new Vector3d(1.0,0.0,0.0); - if(!worldCoord) - MathTools.rotate(q, dir, dir); - Vector3d i1 = new Vector3d(); - Vector3d i2 = new Vector3d(); - s = new double[2]; - MathTools.intersectStraightStraight( p, dir,ray.pos, ray.dir, i2, i1,s); - translate.x = s[0]; - - break; - case Y : - dir = new Vector3d(0.0,1.0,0.0); - if(!worldCoord) - MathTools.rotate(q, dir, dir); - i1 = new Vector3d(); - i2 = new Vector3d(); - s = new double[2]; - MathTools.intersectStraightStraight( p, dir,ray.pos, ray.dir, i2, i1,s); - translate.y = s[0]; - break; - case Z : - dir = new Vector3d(0.0,0.0,1.0); - if(!worldCoord) - MathTools.rotate(q, dir, dir); - i1 = new Vector3d(); - i2 = new Vector3d(); - s = new double[2]; - MathTools.intersectStraightStraight( p, dir,ray.pos, ray.dir, i2, i1,s); - translate.z = s[0]; - break; - case XY : - normal = new Vector3d(0.0,0.0,1.0); - if(!worldCoord) - MathTools.rotate(q, normal, normal); - r = new Vector3d(); - if (MathTools.intersectStraightPlane(ray.pos, ray.dir, p, normal, r)) { - r.sub(p); - translate.x = r.x; - translate.y = r.y; - } - break; - case XZ : - normal = new Vector3d(0.0,1.0,0.0); - if(!worldCoord) - MathTools.rotate(q, normal, normal); - r = new Vector3d(); - if (MathTools.intersectStraightPlane(ray.pos, ray.dir, p, normal, r)) { - r.sub(p); - translate.x = r.x; - translate.z = r.z; - } - break; - case YZ : - normal = new Vector3d(1.0,0.0,0.0); - if(!worldCoord) - MathTools.rotate(q, normal, normal); - r = new Vector3d(); - if (MathTools.intersectStraightPlane(ray.pos, ray.dir, p, normal, r)) { - r.sub(p); - translate.y = r.y; - translate.z = r.z; - } - break; - default : - - return null; - } - translate.sub(offset); - return translate; + case X : + dir = new Vector3d(1.0,0.0,0.0); + if(!worldCoord) + MathTools.rotate(q, dir, dir); + Vector3d i1 = new Vector3d(); + Vector3d i2 = new Vector3d(); + s = new double[2]; + MathTools.intersectStraightStraight( p, dir,ray.pos, ray.dir, i2, i1,s); + translate.x = s[0]; + + break; + case Y : + dir = new Vector3d(0.0,1.0,0.0); + if(!worldCoord) + MathTools.rotate(q, dir, dir); + i1 = new Vector3d(); + i2 = new Vector3d(); + s = new double[2]; + MathTools.intersectStraightStraight( p, dir,ray.pos, ray.dir, i2, i1,s); + translate.y = s[0]; + break; + case Z : + dir = new Vector3d(0.0,0.0,1.0); + if(!worldCoord) + MathTools.rotate(q, dir, dir); + i1 = new Vector3d(); + i2 = new Vector3d(); + s = new double[2]; + MathTools.intersectStraightStraight( p, dir,ray.pos, ray.dir, i2, i1,s); + translate.z = s[0]; + break; + case XY : + normal = new Vector3d(0.0,0.0,1.0); + if(!worldCoord) + MathTools.rotate(q, normal, normal); + r = new Vector3d(); + if (MathTools.intersectStraightPlane(ray.pos, ray.dir, p, normal, r)) { + r.sub(p); + translate.x = r.x; + translate.y = r.y; + } + break; + case XZ : + normal = new Vector3d(0.0,1.0,0.0); + if(!worldCoord) + MathTools.rotate(q, normal, normal); + r = new Vector3d(); + if (MathTools.intersectStraightPlane(ray.pos, ray.dir, p, normal, r)) { + r.sub(p); + translate.x = r.x; + translate.z = r.z; + } + break; + case YZ : + normal = new Vector3d(1.0,0.0,0.0); + if(!worldCoord) + MathTools.rotate(q, normal, normal); + r = new Vector3d(); + if (MathTools.intersectStraightPlane(ray.pos, ray.dir, p, normal, r)) { + r.sub(p); + translate.y = r.y; + translate.z = r.z; + } + break; + default : + + return null; + } + translate.sub(offset); + return translate; } } diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/swt/vtkCameraAndSelectorAction.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/swt/vtkCameraAndSelectorAction.java index 96f51c69..56255631 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/swt/vtkCameraAndSelectorAction.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/swt/vtkCameraAndSelectorAction.java @@ -33,356 +33,356 @@ import vtk.vtkRenderer; public class vtkCameraAndSelectorAction extends vtkSwtAction implements ISelectionProvider { - protected vtkRenderer ren; - protected int lastX; - protected int lastY; - protected vtkRenderWindow rw; - protected vtkCamera cam; - protected int InteractionMode = 1; - - protected double activeRate = 5.0; - protected double passiveRate = 0.01; - protected boolean doNotRotate = true; - - public vtkCameraAndSelectorAction(InteractiveVtkComposite panel) { - super(panel); - this.ren = panel.getRenderer(); - this.rw = panel.getRenderWindow(); - this.cam = ren.GetActiveCamera(); - } - - public void Lock() { - panel.lock(); - } - - public void UnLock() { - panel.unlock(); - } - - public void InteractionModeRotate() { - this.InteractionMode = 1; - } - - public void InteractionModeTranslate() { - this.InteractionMode = 2; - } - - public void InteractionModeZoom() { - this.InteractionMode = 3; - } - - public void resetCameraClippingRange() { - Lock(); - ren.ResetCameraClippingRange(); - UnLock(); - } - - public void resetCamera() { - Lock(); - ren.ResetCamera(); - UnLock(); - } - - public boolean mousePressed(MouseEvent e) { - - if (ren.VisibleActorCount() == 0) - return false; - rw.SetDesiredUpdateRate(activeRate); - lastX = e.getX(); - lastY = e.getY(); - if ((e.getModifiers() == InputEvent.BUTTON2_MASK) - || (e.getModifiers() == (InputEvent.BUTTON1_MASK | InputEvent.SHIFT_MASK))) { - InteractionModeTranslate(); - } else if (e.getModifiers() == InputEvent.BUTTON3_MASK) { - InteractionModeZoom(); - } else { - InteractionModeRotate(); - } - return true; - } - - public boolean mouseReleased(MouseEvent e) { - rw.SetDesiredUpdateRate(passiveRate); - return true; - } - - public boolean mouseDragged(MouseEvent e) { - if (ren.VisibleActorCount() == 0) - return false; - int x = e.getX(); - int y = e.getY(); - // rotate - if (this.InteractionMode == 1) { - cam.Azimuth(lastX - x); - cam.Elevation(y - lastY); - if (doNotRotate) - cam.SetRoll(0); - cam.OrthogonalizeViewUp(); - resetCameraClippingRange(); - // panel.UpdateLight(); - } - // translate - if (this.InteractionMode == 2) { - double FPoint[]; - double PPoint[]; - double APoint[] = new double[3]; - double RPoint[]; - double focalDepth; - - // get the current focal point and position - FPoint = cam.GetFocalPoint(); - PPoint = cam.GetPosition(); - - // calculate the focal depth since we'll be using it a lot - ren.SetWorldPoint(FPoint[0], FPoint[1], FPoint[2], 1.0); - ren.WorldToDisplay(); - focalDepth = ren.GetDisplayPoint()[2]; - - APoint[0] = rw.GetSize()[0] / 2.0 + (x - lastX); - APoint[1] = rw.GetSize()[1] / 2.0 - (y - lastY); - APoint[2] = focalDepth; - ren.SetDisplayPoint(APoint); - ren.DisplayToWorld(); - RPoint = ren.GetWorldPoint(); - if (RPoint[3] != 0.0) { - RPoint[0] = RPoint[0] / RPoint[3]; - RPoint[1] = RPoint[1] / RPoint[3]; - RPoint[2] = RPoint[2] / RPoint[3]; - } - - /* - * Compute a translation vector, moving everything 1/2 the distance to the - * cursor. (Arbitrary scale factor) - */ - cam.SetFocalPoint((FPoint[0] - RPoint[0]) / 2.0 + FPoint[0], (FPoint[1] - RPoint[1]) / 2.0 + FPoint[1], - (FPoint[2] - RPoint[2]) / 2.0 + FPoint[2]); - cam.SetPosition((FPoint[0] - RPoint[0]) / 2.0 + PPoint[0], (FPoint[1] - RPoint[1]) / 2.0 + PPoint[1], - (FPoint[2] - RPoint[2]) / 2.0 + PPoint[2]); - resetCameraClippingRange(); - } - // zoom - if (this.InteractionMode == 3) { - double zoomFactor; - // double clippingRange[]; - - zoomFactor = Math.pow(1.02, (y - lastY)); - if (cam.GetParallelProjection() == 1) { - cam.SetParallelScale(cam.GetParallelScale() / zoomFactor); - } else { - cam.Dolly(zoomFactor); - resetCameraClippingRange(); - } - } - lastX = x; - lastY = y; - panel.refresh(); - return true; - } - - @Override - public boolean mouseWheelMoved(MouseWheelEvent e) { - double zoomFactor; - // double clippingRange[]; - zoomFactor = Math.pow(1.02, (e.getWheelRotation())); - if (cam.GetParallelProjection() == 1) { - cam.SetParallelScale(cam.GetParallelScale() / zoomFactor); - } else { - cam.Dolly(zoomFactor); - resetCameraClippingRange(); - } - panel.refresh(); - return true; - } - - private List selectActors = new ArrayList(); - private List hoverActor = new ArrayList(); - - @Override - public boolean mouseClicked(MouseEvent e) { - if (!panel.getComponent().isFocusControl()) - return false; - if (e.getButton() != MouseEvent.BUTTON1) - return false; - vtkProp spick[] = panel.pick(e.getX(), e.getY()); - if (spick != null && spick.length > 0) { - for (vtkProp selectActor : spick) { - if (!e.isControlDown()) { - selectActors.clear(); - selectActors.add(selectActor); - } else { - if (selectActors.contains(selectActor)) - selectActors.remove(selectActor); - else - selectActors.add(selectActor); - } - } - fireSelectionChanged(); - } else if (!e.isControlDown()) { - selectActors.clear(); - fireSelectionChanged(); - } - return true; - // if (e.getClickCount() > 1) - // updatePickRay(e.getX(), e.getY()); - - } - - // private void updatePickRay(double x , double y) { - // Ray ray = vtkUtil.createMouseRay(panel.GetRenderer(), x, y); - // - // - // System.out.println(ray.pos + " " + ray.dir); - // vtkPoints linePoints = new vtkPoints(); - // linePoints.InsertPoint(0,ray.pos.x, ray.pos.y, ray.pos.z); - // linePoints.InsertPoint(1, ray.pos.x + ray.dir.x, ray.pos.y + ray.dir.y, - // ray.pos.z + ray.dir.z); - // vtkLine aLine = new vtkLine(); - // aLine.GetPointIds().SetId(0, 0); - // aLine.GetPointIds().SetId(1, 1); - // vtkUnstructuredGrid aLineGrid = new vtkUnstructuredGrid(); - // aLineGrid.Allocate(1, 1); - // aLineGrid.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds()); - // aLineGrid.SetPoints(linePoints); - // vtkDataSetMapper aLineMapper = new vtkDataSetMapper(); - // aLineMapper.SetInput(aLineGrid); - // vtkActor aLineActor = new vtkActor(); - // aLineActor.SetMapper(aLineMapper); - // aLineActor.GetProperty().SetDiffuseColor(.2, 1, 1); - // - // if (rayActor != null) { - // panel.GetRenderer().RemoveActor(rayActor); - // rayActor.Delete(); - // } - // rayActor = aLineActor; - // panel.GetRenderer().AddActor(rayActor); - // - // linePoints.Delete(); - // aLine.Delete(); - // aLineGrid.Delete(); - // aLineMapper.Delete(); - // panel.repaint(); - // } - // - // private vtkActor rayActor; - - @Override - public boolean mouseMoved(MouseEvent e) { - lastX = e.getX(); - lastY = e.getY(); - - if (!panel.getComponent().isFocusControl()) - return false; - List prevHover = new ArrayList(); - prevHover.addAll(hoverActor); - hoverActor.clear(); - vtkProp pick[] = panel.pick(e.getX(), e.getY()); - if (pick != null) { - for (vtkProp p : pick) - hoverActor.add(p); - } - - if (!prevHover.containsAll(hoverActor) || !hoverActor.containsAll(prevHover)) { - fireHoverChanged(); - } - return true; - } - - public List getSelectActor() { - return selectActors; - } - - public List getHoverActor() { - return hoverActor; - } - - private List selectionListeners = new ArrayList(); - - @Override - public void addSelectionChangedListener(ISelectionChangedListener listener) { - selectionListeners.add(listener); - } - - @Override - public ISelection getSelection() { - return new StructuredSelection(selectActors); - } - - @Override - public void removeSelectionChangedListener(ISelectionChangedListener listener) { - selectionListeners.remove(listener); - } - - @Override - public void setSelection(ISelection selection) { - setSelection(selection, false); - - } - - public void setSelection(ISelection selection, boolean fire) { - Collection selectedProps = AdaptationUtils.adaptToCollection(selection, vtkProp.class); - - selectActors.clear(); - selectActors.addAll(selectedProps); - if (fire) - fireSelectionChanged(); - } - - private void fireSelectionChanged() { - Display.getDefault().asyncExec(new Runnable() { - @Override - public void run() { - - SelectionChangedEvent evt = new SelectionChangedEvent(vtkCameraAndSelectorAction.this, - new StructuredSelection(selectActors)); - for (ISelectionChangedListener l : selectionListeners) { - l.selectionChanged(evt); - } - - } - }); - } - - private List hoverListeners = new ArrayList(); - - public void addHoverChangedListener(ISelectionChangedListener listener) { - hoverListeners.add(listener); - } - - public ISelection getHoverSelection() { - return new StructuredSelection(hoverActor); - } - - public void removeHoverChangedListener(ISelectionChangedListener listener) { - hoverListeners.remove(listener); - } - - private void fireHoverChanged() { - Display.getDefault().asyncExec(new Runnable() { - @Override - public void run() { - StructuredSelection sel = null; - if (hoverActor == null) - sel = new StructuredSelection(); - else - sel = new StructuredSelection(hoverActor); - SelectionChangedEvent evt = new SelectionChangedEvent(vtkCameraAndSelectorAction.this, sel); - for (ISelectionChangedListener l : hoverListeners) { - l.selectionChanged(evt); - } - - } - }); - } - - public void focus(double x, double y, double z) { - Lock(); - cam.SetFocalPoint(x, y, z); - if (doNotRotate) - cam.SetRoll(0); - cam.OrthogonalizeViewUp(); - resetCameraClippingRange(); - // panel.UpdateLight(); - UnLock(); - } + protected vtkRenderer ren; + protected int lastX; + protected int lastY; + protected vtkRenderWindow rw; + protected vtkCamera cam; + protected int InteractionMode = 1; + + protected double activeRate = 5.0; + protected double passiveRate = 0.01; + protected boolean doNotRotate = true; + + public vtkCameraAndSelectorAction(InteractiveVtkComposite panel) { + super(panel); + this.ren = panel.getRenderer(); + this.rw = panel.getRenderWindow(); + this.cam = ren.GetActiveCamera(); + } + + public void Lock() { + panel.lock(); + } + + public void UnLock() { + panel.unlock(); + } + + public void InteractionModeRotate() { + this.InteractionMode = 1; + } + + public void InteractionModeTranslate() { + this.InteractionMode = 2; + } + + public void InteractionModeZoom() { + this.InteractionMode = 3; + } + + public void resetCameraClippingRange() { + Lock(); + ren.ResetCameraClippingRange(); + UnLock(); + } + + public void resetCamera() { + Lock(); + ren.ResetCamera(); + UnLock(); + } + + public boolean mousePressed(MouseEvent e) { + + if (ren.VisibleActorCount() == 0) + return false; + rw.SetDesiredUpdateRate(activeRate); + lastX = e.getX(); + lastY = e.getY(); + if ((e.getModifiers() == InputEvent.BUTTON2_MASK) + || (e.getModifiers() == (InputEvent.BUTTON1_MASK | InputEvent.SHIFT_MASK))) { + InteractionModeTranslate(); + } else if (e.getModifiers() == InputEvent.BUTTON3_MASK) { + InteractionModeZoom(); + } else { + InteractionModeRotate(); + } + return true; + } + + public boolean mouseReleased(MouseEvent e) { + rw.SetDesiredUpdateRate(passiveRate); + return true; + } + + public boolean mouseDragged(MouseEvent e) { + if (ren.VisibleActorCount() == 0) + return false; + int x = e.getX(); + int y = e.getY(); + // rotate + if (this.InteractionMode == 1) { + cam.Azimuth(lastX - x); + cam.Elevation(y - lastY); + if (doNotRotate) + cam.SetRoll(0); + cam.OrthogonalizeViewUp(); + resetCameraClippingRange(); + // panel.UpdateLight(); + } + // translate + if (this.InteractionMode == 2) { + double FPoint[]; + double PPoint[]; + double APoint[] = new double[3]; + double RPoint[]; + double focalDepth; + + // get the current focal point and position + FPoint = cam.GetFocalPoint(); + PPoint = cam.GetPosition(); + + // calculate the focal depth since we'll be using it a lot + ren.SetWorldPoint(FPoint[0], FPoint[1], FPoint[2], 1.0); + ren.WorldToDisplay(); + focalDepth = ren.GetDisplayPoint()[2]; + + APoint[0] = rw.GetSize()[0] / 2.0 + (x - lastX); + APoint[1] = rw.GetSize()[1] / 2.0 - (y - lastY); + APoint[2] = focalDepth; + ren.SetDisplayPoint(APoint); + ren.DisplayToWorld(); + RPoint = ren.GetWorldPoint(); + if (RPoint[3] != 0.0) { + RPoint[0] = RPoint[0] / RPoint[3]; + RPoint[1] = RPoint[1] / RPoint[3]; + RPoint[2] = RPoint[2] / RPoint[3]; + } + + /* + * Compute a translation vector, moving everything 1/2 the distance to the + * cursor. (Arbitrary scale factor) + */ + cam.SetFocalPoint((FPoint[0] - RPoint[0]) / 2.0 + FPoint[0], (FPoint[1] - RPoint[1]) / 2.0 + FPoint[1], + (FPoint[2] - RPoint[2]) / 2.0 + FPoint[2]); + cam.SetPosition((FPoint[0] - RPoint[0]) / 2.0 + PPoint[0], (FPoint[1] - RPoint[1]) / 2.0 + PPoint[1], + (FPoint[2] - RPoint[2]) / 2.0 + PPoint[2]); + resetCameraClippingRange(); + } + // zoom + if (this.InteractionMode == 3) { + double zoomFactor; + // double clippingRange[]; + + zoomFactor = Math.pow(1.02, (y - lastY)); + if (cam.GetParallelProjection() == 1) { + cam.SetParallelScale(cam.GetParallelScale() / zoomFactor); + } else { + cam.Dolly(zoomFactor); + resetCameraClippingRange(); + } + } + lastX = x; + lastY = y; + panel.refresh(); + return true; + } + + @Override + public boolean mouseWheelMoved(MouseWheelEvent e) { + double zoomFactor; + // double clippingRange[]; + zoomFactor = Math.pow(1.02, (e.getWheelRotation())); + if (cam.GetParallelProjection() == 1) { + cam.SetParallelScale(cam.GetParallelScale() / zoomFactor); + } else { + cam.Dolly(zoomFactor); + resetCameraClippingRange(); + } + panel.refresh(); + return true; + } + + private List selectActors = new ArrayList(); + private List hoverActor = new ArrayList(); + + @Override + public boolean mouseClicked(MouseEvent e) { + if (!panel.getComponent().isFocusControl()) + return false; + if (e.getButton() != MouseEvent.BUTTON1) + return false; + vtkProp spick[] = panel.pick(e.getX(), e.getY()); + if (spick != null && spick.length > 0) { + for (vtkProp selectActor : spick) { + if (!e.isControlDown()) { + selectActors.clear(); + selectActors.add(selectActor); + } else { + if (selectActors.contains(selectActor)) + selectActors.remove(selectActor); + else + selectActors.add(selectActor); + } + } + fireSelectionChanged(); + } else if (!e.isControlDown()) { + selectActors.clear(); + fireSelectionChanged(); + } + return true; + // if (e.getClickCount() > 1) + // updatePickRay(e.getX(), e.getY()); + + } + + // private void updatePickRay(double x , double y) { + // Ray ray = vtkUtil.createMouseRay(panel.GetRenderer(), x, y); + // + // + // System.out.println(ray.pos + " " + ray.dir); + // vtkPoints linePoints = new vtkPoints(); + // linePoints.InsertPoint(0,ray.pos.x, ray.pos.y, ray.pos.z); + // linePoints.InsertPoint(1, ray.pos.x + ray.dir.x, ray.pos.y + ray.dir.y, + // ray.pos.z + ray.dir.z); + // vtkLine aLine = new vtkLine(); + // aLine.GetPointIds().SetId(0, 0); + // aLine.GetPointIds().SetId(1, 1); + // vtkUnstructuredGrid aLineGrid = new vtkUnstructuredGrid(); + // aLineGrid.Allocate(1, 1); + // aLineGrid.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds()); + // aLineGrid.SetPoints(linePoints); + // vtkDataSetMapper aLineMapper = new vtkDataSetMapper(); + // aLineMapper.SetInput(aLineGrid); + // vtkActor aLineActor = new vtkActor(); + // aLineActor.SetMapper(aLineMapper); + // aLineActor.GetProperty().SetDiffuseColor(.2, 1, 1); + // + // if (rayActor != null) { + // panel.GetRenderer().RemoveActor(rayActor); + // rayActor.Delete(); + // } + // rayActor = aLineActor; + // panel.GetRenderer().AddActor(rayActor); + // + // linePoints.Delete(); + // aLine.Delete(); + // aLineGrid.Delete(); + // aLineMapper.Delete(); + // panel.repaint(); + // } + // + // private vtkActor rayActor; + + @Override + public boolean mouseMoved(MouseEvent e) { + lastX = e.getX(); + lastY = e.getY(); + + if (!panel.getComponent().isFocusControl()) + return false; + List prevHover = new ArrayList(); + prevHover.addAll(hoverActor); + hoverActor.clear(); + vtkProp pick[] = panel.pick(e.getX(), e.getY()); + if (pick != null) { + for (vtkProp p : pick) + hoverActor.add(p); + } + + if (!prevHover.containsAll(hoverActor) || !hoverActor.containsAll(prevHover)) { + fireHoverChanged(); + } + return true; + } + + public List getSelectActor() { + return selectActors; + } + + public List getHoverActor() { + return hoverActor; + } + + private List selectionListeners = new ArrayList(); + + @Override + public void addSelectionChangedListener(ISelectionChangedListener listener) { + selectionListeners.add(listener); + } + + @Override + public ISelection getSelection() { + return new StructuredSelection(selectActors); + } + + @Override + public void removeSelectionChangedListener(ISelectionChangedListener listener) { + selectionListeners.remove(listener); + } + + @Override + public void setSelection(ISelection selection) { + setSelection(selection, false); + + } + + public void setSelection(ISelection selection, boolean fire) { + Collection selectedProps = AdaptationUtils.adaptToCollection(selection, vtkProp.class); + + selectActors.clear(); + selectActors.addAll(selectedProps); + if (fire) + fireSelectionChanged(); + } + + private void fireSelectionChanged() { + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + + SelectionChangedEvent evt = new SelectionChangedEvent(vtkCameraAndSelectorAction.this, + new StructuredSelection(selectActors)); + for (ISelectionChangedListener l : selectionListeners) { + l.selectionChanged(evt); + } + + } + }); + } + + private List hoverListeners = new ArrayList(); + + public void addHoverChangedListener(ISelectionChangedListener listener) { + hoverListeners.add(listener); + } + + public ISelection getHoverSelection() { + return new StructuredSelection(hoverActor); + } + + public void removeHoverChangedListener(ISelectionChangedListener listener) { + hoverListeners.remove(listener); + } + + private void fireHoverChanged() { + Display.getDefault().asyncExec(new Runnable() { + @Override + public void run() { + StructuredSelection sel = null; + if (hoverActor == null) + sel = new StructuredSelection(); + else + sel = new StructuredSelection(hoverActor); + SelectionChangedEvent evt = new SelectionChangedEvent(vtkCameraAndSelectorAction.this, sel); + for (ISelectionChangedListener l : hoverListeners) { + l.selectionChanged(evt); + } + + } + }); + } + + public void focus(double x, double y, double z) { + Lock(); + cam.SetFocalPoint(x, y, z); + if (doNotRotate) + cam.SetRoll(0); + cam.OrthogonalizeViewUp(); + resetCameraClippingRange(); + // panel.UpdateLight(); + UnLock(); + } } diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/utils/AxesDisplay.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/utils/AxesDisplay.java index 13ffac08..4bbaaccd 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/utils/AxesDisplay.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/utils/AxesDisplay.java @@ -16,33 +16,33 @@ public class AxesDisplay { public void show() { vtkAxesActor axes = new vtkAxesActor(); - axes.GetXAxisCaptionActor2D().GetCaptionTextProperty().SetColor(0,0,0); - axes.GetYAxisCaptionActor2D().GetCaptionTextProperty().SetColor(0,0,0); - axes.GetZAxisCaptionActor2D().GetCaptionTextProperty().SetColor(0,0,0); - axes.GetXAxisCaptionActor2D().GetCaptionTextProperty().SetShadow(0); - axes.GetYAxisCaptionActor2D().GetCaptionTextProperty().SetShadow(0); - axes.GetZAxisCaptionActor2D().GetCaptionTextProperty().SetShadow(0); - axes.GetXAxisCaptionActor2D().GetCaptionTextProperty().ItalicOff(); - axes.GetYAxisCaptionActor2D().GetCaptionTextProperty().ItalicOff(); - axes.GetZAxisCaptionActor2D().GetCaptionTextProperty().ItalicOff(); - axes.GetXAxisCaptionActor2D().GetCaptionTextProperty().Delete(); - axes.GetYAxisCaptionActor2D().GetCaptionTextProperty().Delete(); - axes.GetZAxisCaptionActor2D().GetCaptionTextProperty().Delete(); - axes.GetXAxisCaptionActor2D().Delete(); - axes.GetYAxisCaptionActor2D().Delete(); - axes.GetZAxisCaptionActor2D().Delete(); - vtkOrientationMarkerWidget widget = new vtkOrientationMarkerWidget(); - widget.SetOutlineColor(0.9300, 0.5700, 0.1300 ); - widget.SetOrientationMarker(axes); - widget.SetInteractor(panel.getRenderWindowInteractor()); - //widget.SetViewport(0.8, 0.0, 1.0, 0.2); // bottom right - //widget.SetViewport(0.0, 0.0, 0.4, 0.4); - widget.SetViewport(0.0, 0.0, 0.2, 0.2); // bottom left - widget.SetEnabled(1); - widget.InteractiveOff(); - - panel.addDeletable(widget); - panel.addDeletable(axes); + axes.GetXAxisCaptionActor2D().GetCaptionTextProperty().SetColor(0,0,0); + axes.GetYAxisCaptionActor2D().GetCaptionTextProperty().SetColor(0,0,0); + axes.GetZAxisCaptionActor2D().GetCaptionTextProperty().SetColor(0,0,0); + axes.GetXAxisCaptionActor2D().GetCaptionTextProperty().SetShadow(0); + axes.GetYAxisCaptionActor2D().GetCaptionTextProperty().SetShadow(0); + axes.GetZAxisCaptionActor2D().GetCaptionTextProperty().SetShadow(0); + axes.GetXAxisCaptionActor2D().GetCaptionTextProperty().ItalicOff(); + axes.GetYAxisCaptionActor2D().GetCaptionTextProperty().ItalicOff(); + axes.GetZAxisCaptionActor2D().GetCaptionTextProperty().ItalicOff(); + axes.GetXAxisCaptionActor2D().GetCaptionTextProperty().Delete(); + axes.GetYAxisCaptionActor2D().GetCaptionTextProperty().Delete(); + axes.GetZAxisCaptionActor2D().GetCaptionTextProperty().Delete(); + axes.GetXAxisCaptionActor2D().Delete(); + axes.GetYAxisCaptionActor2D().Delete(); + axes.GetZAxisCaptionActor2D().Delete(); + vtkOrientationMarkerWidget widget = new vtkOrientationMarkerWidget(); + widget.SetOutlineColor(0.9300, 0.5700, 0.1300 ); + widget.SetOrientationMarker(axes); + widget.SetInteractor(panel.getRenderWindowInteractor()); + //widget.SetViewport(0.8, 0.0, 1.0, 0.2); // bottom right + //widget.SetViewport(0.0, 0.0, 0.4, 0.4); + widget.SetViewport(0.0, 0.0, 0.2, 0.2); // bottom left + widget.SetEnabled(1); + widget.InteractiveOff(); + + panel.addDeletable(widget); + panel.addDeletable(axes); } } diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/utils/vtkEffect.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/utils/vtkEffect.java index d4cd7103..09a93e34 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/utils/vtkEffect.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/utils/vtkEffect.java @@ -87,7 +87,7 @@ public class vtkEffect { double center_contour[] = new double[3]; double trans_x=0., trans_y=0., trans_z=0., ratio_x=0., ratio_y=0.; contour.GetBounds(bounds_contour); - + ratio_x = (bounds_data[1]-bounds_data[0])/(bounds_contour[1]-bounds_contour[0]); ratio_y = (bounds_data[3]-bounds_data[2])/(bounds_contour[3]-bounds_contour[2]); @@ -119,7 +119,7 @@ public class vtkEffect { vtkPolyDataMapper mapper = new vtkPolyDataMapper(); mapper.SetInputData(contour); - + vtkActor actor =new vtkActor(); actor.SetMapper(mapper); actor.GetProperty().SetLineWidth(2.); @@ -274,7 +274,7 @@ public class vtkEffect { vtkPolyDataMapper mapper = new vtkPolyDataMapper(); mapper.SetInputData(contour); - + vtkActor actor =new vtkActor(); actor.SetMapper(mapper); actor.GetProperty().SetLineWidth(2.); diff --git a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/utils/vtkUtil.java b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/utils/vtkUtil.java index 71710def..6cba6831 100644 --- a/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/utils/vtkUtil.java +++ b/org.simantics.g3d.vtk/src/org/simantics/g3d/vtk/utils/vtkUtil.java @@ -41,21 +41,21 @@ public class vtkUtil { public static Point3d getWorldCoordinates(vtkRenderer ren1, Point2d screenPosition, double zPos) { - ren1.SetDisplayPoint(screenPosition.x, ren1.GetSize()[1]-screenPosition.y, zPos); - ren1.DisplayToWorld(); - double world[] = ren1.GetWorldPoint(); + ren1.SetDisplayPoint(screenPosition.x, ren1.GetSize()[1]-screenPosition.y, zPos); + ren1.DisplayToWorld(); + double world[] = ren1.GetWorldPoint(); return new Point3d(world); - + } public static Point2d getScreenCoordinates(vtkRenderer ren1, Tuple3d worldPos) { - ren1.SetWorldPoint(worldPos.x, worldPos.y, worldPos.z, 0.0); - ren1.WorldToDisplay(); - double screen[] = ren1.GetDisplayPoint(); - - return new Point2d(screen); - + ren1.SetWorldPoint(worldPos.x, worldPos.y, worldPos.z, 0.0); + ren1.WorldToDisplay(); + double screen[] = ren1.GetDisplayPoint(); + + return new Point2d(screen); + } public static Matrix4d getMatrix(vtkMatrix4x4 ptm) { diff --git a/org.simantics.g3d/src/org/simantics/g3d/gizmo/Gizmo.java b/org.simantics.g3d/src/org/simantics/g3d/gizmo/Gizmo.java index 9b9b0727..053e29a5 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/gizmo/Gizmo.java +++ b/org.simantics.g3d/src/org/simantics/g3d/gizmo/Gizmo.java @@ -23,6 +23,6 @@ public interface Gizmo { public void attach(T2 renderingPart); public void deattach(); - public void setPosition(Tuple3d position); - public void setRotation(AxisAngle4d q); + public void setPosition(Tuple3d position); + public void setRotation(AxisAngle4d q); } diff --git a/org.simantics.g3d/src/org/simantics/g3d/math/MathTools.java b/org.simantics.g3d/src/org/simantics/g3d/math/MathTools.java index 08a1e7b0..0fbd110f 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/math/MathTools.java +++ b/org.simantics.g3d/src/org/simantics/g3d/math/MathTools.java @@ -32,11 +32,11 @@ import org.simantics.g3d.math.EulerTools.Order; * */ public class MathTools { - - public static double NEAR_ZERO = 0.000000001; - public static double NEAR_HALF = 0.499999999; - - public static final Vector3d Z_AXIS = new Vector3d(0.0,0.0,1.0); + + public static double NEAR_ZERO = 0.000000001; + public static double NEAR_HALF = 0.499999999; + + public static final Vector3d Z_AXIS = new Vector3d(0.0,0.0,1.0); public static final Vector3d Y_AXIS = new Vector3d(0.0,1.0,0.0); public static final Vector3d X_AXIS = new Vector3d(1.0,0.0,0.0); public static final Vector3d ORIGIN = new Vector3d(0.0,0.0,0.0); @@ -96,264 +96,264 @@ public class MathTools { public static boolean isValid(Tuple3d t) { return !(Double.isInfinite(t.x) || Double.isNaN(t.x) || - Double.isInfinite(t.y) || Double.isNaN(t.y) || - Double.isInfinite(t.z) || Double.isNaN(t.z)); - } - - public static Vector3d closestPointOnEdge(Vector3d point, Vector3d edgePoint1, Vector3d edgePoint2) { - point.sub(edgePoint1); - Vector3d v = new Vector3d(edgePoint2); - v.sub(edgePoint1); - double t = v.dot(point); - t /= v.lengthSquared(); - if (t <= 0.0f) - return edgePoint1; - if (t >= 1.0f) - return edgePoint2; - v.scale(t); - v.add(edgePoint1); - return v; - } - - public static Vector3d closestPointOnStraight(Tuple3d point, Tuple3d straightPoint, Vector3d straightDir) { - Vector3d v = new Vector3d(point); - v.sub(straightPoint); - double t = straightDir.dot(v); - t /= straightDir.lengthSquared(); - v.set(straightDir); - v.scale(t); - v.add(straightPoint); - return v; - } - - public static Vector3d closestPointOnStraight(Tuple3d point, Tuple3d straightPoint, Vector3d straightDir, double u[]) { - Vector3d v = new Vector3d(point); - v.sub(straightPoint); - u[0] = straightDir.dot(v); - u[0] /= straightDir.lengthSquared(); - v.set(straightDir); - v.scale(u[0]); - v.add(straightPoint); - return v; - } - - public static double distanceFromPlane(Vector3d point, Vector3d planeNormal, Tuple3d planePoint) { - point.sub(planePoint); - - return planeNormal.dot(point); - } - - public static double distanceFromPlane(Vector3d point, Vector3d planeNormal, float d) { - return (planeNormal.dot(point) + d); - } - - public static boolean intersectStraightPlane(Tuple3d linePoint, Vector3d lineDir, Tuple3d planePoint, Vector3d planeNormal, Tuple3d intersectPoint) { - intersectPoint.set(planePoint); - intersectPoint.sub(linePoint); - double u = planeNormal.dot(new Vector3d(intersectPoint)); - double v = planeNormal.dot(lineDir); - if (Math.abs(v) < NEAR_ZERO) - return false; - u /= v; - intersectPoint.set(lineDir); - intersectPoint.scale(u); - intersectPoint.add(linePoint); - return true; - } - - public static boolean intersectStraightPlane(Tuple3d linePoint, Vector3d lineDir, Tuple3d planePoint, Vector3d planeNormal, Vector3d intersectPoint, double[] u) { - intersectPoint.set(planePoint); - intersectPoint.sub(linePoint); - u[0] = planeNormal.dot(intersectPoint); - double v = planeNormal.dot(lineDir); - if (Math.abs(v) < NEAR_ZERO) - return false; - u[0] /= v; - intersectPoint.set(lineDir); - intersectPoint.scale(u[0]); - intersectPoint.add(linePoint); - return true; - } - - public static boolean intersectLineLine(Tuple3d l1_start,Tuple3d l1_end,Tuple3d l2_start,Tuple3d l2_end,Tuple3d l1_pos, Tuple3d l2_pos) { - Vector3d p13 = new Vector3d(); - Vector3d p43 = new Vector3d(); - Vector3d p21 = new Vector3d(); - double d1343,d4321,d1321,d4343,d2121; - double numer,denom; - p13.sub(l1_start, l2_start); - p43.sub(l2_end,l2_start); - if (Math.abs(p43.x) < NEAR_ZERO && Math.abs(p43.y) < NEAR_ZERO && Math.abs(p43.z) < NEAR_ZERO) - return false; - p21.sub(l1_end,l1_start); - if (Math.abs(p21.x) < NEAR_ZERO && Math.abs(p21.y) < NEAR_ZERO && Math.abs(p21.z) < NEAR_ZERO) - return false; - - d1343 = p13.dot(p43); - d4321 = p43.dot(p21); - d1321 = p13.dot(p21); - d4343 = p43.lengthSquared(); - d2121 = p21.lengthSquared(); - - denom = d2121 * d4343 - d4321 * d4321; - if (Math.abs(denom) < NEAR_ZERO) - return false; - numer = d1343 * d4321 - d1321 * d4343; - - double mua = numer / denom; - double mub = (d1343 + d4321 * mua) / d4343; - - l1_pos.x = l1_start.x + mua * p21.x; - l1_pos.y = l1_start.y + mua * p21.y; - l1_pos.z = l1_start.z + mua * p21.z; - l2_pos.x = l2_start.x + mub * p43.x; - l2_pos.y = l2_start.y + mub * p43.y; - l2_pos.z = l2_start.z + mub * p43.z; - - return true; - } - - public static boolean intersectStraightStraight(Tuple3d p1,Vector3d p21,Tuple3d p3,Vector3d p43,Tuple3d pa,Tuple3d pb) { - Vector3d p13 = new Vector3d(); - - double d1343,d4321,d1321,d4343,d2121; - double numer,denom; - - p13.sub(p1, p3); - if (Math.abs(p43.x) < NEAR_ZERO && Math.abs(p43.y) < NEAR_ZERO && Math.abs(p43.z) < NEAR_ZERO) - return false; - if (Math.abs(p21.x) < NEAR_ZERO && Math.abs(p21.y) < NEAR_ZERO && Math.abs(p21.z) < NEAR_ZERO) - return false; - - d1343 = p13.dot(p43); - d4321 = p43.dot(p21); - d1321 = p13.dot(p21); - d4343 = p43.lengthSquared(); - d2121 = p21.lengthSquared(); - - denom = d2121 * d4343 - d4321 * d4321; - if (Math.abs(denom) < NEAR_ZERO) - return false; - numer = d1343 * d4321 - d1321 * d4343; - - double mua = numer / denom; - double mub = (d1343 + d4321 * mua) / d4343; - - pa.x = p1.x + mua * p21.x; - pa.y = p1.y + mua * p21.y; - pa.z = p1.z + mua * p21.z; - pb.x = p3.x + mub * p43.x; - pb.y = p3.y + mub * p43.y; - pb.z = p3.z + mub * p43.z; - - return true; - } - - /** - * Calculate the line segment PaPb that is the shortest route between - * two lines P1P2 and P3P4. Calculate also the values of mua and mub where - * Pa = P1 + mua (P2 - P1) - * Pb = P3 + mub (P4 - P3) - * @param p1 - * @param p21 - * @param p3 - * @param p43 - * @param pa - * @param pb - * @param mu - * @return - */ - public static boolean intersectStraightStraight(Tuple3d p1,Vector3d p21,Tuple3d p3,Vector3d p43,Tuple3d pa,Tuple3d pb, double mu[]) { - Vector3d p13 = new Vector3d(); - - double d1343,d4321,d1321,d4343,d2121; - double numer,denom; - double EPS = 0.001; - p13.sub(p1, p3); - if (Math.abs(p43.x) < EPS && Math.abs(p43.y) < EPS && Math.abs(p43.z) < EPS) - return false; - if (Math.abs(p21.x) < EPS && Math.abs(p21.y) < EPS && Math.abs(p21.z) < EPS) - return false; - - d1343 = p13.dot(p43); - d4321 = p43.dot(p21); - d1321 = p13.dot(p21); - d4343 = p43.lengthSquared(); - d2121 = p21.lengthSquared(); - - denom = d2121 * d4343 - d4321 * d4321; - if (Math.abs(denom) < EPS) - return false; - numer = d1343 * d4321 - d1321 * d4343; - - mu[0] = numer / denom; - mu[1] = (d1343 + d4321 * mu[0]) / d4343; - - pa.x = p1.x + mu[0] * p21.x; - pa.y = p1.y + mu[0] * p21.y; - pa.z = p1.z + mu[0] * p21.z; - pb.x = p3.x + mu[1] * p43.x; - pb.y = p3.y + mu[1] * p43.y; - pb.z = p3.z + mu[1] * p43.z; - - return true; - } - - - - public static void rotate(Quat4d q, Tuple3d in, Tuple3d out) { - // p' = q * p * q' - double tw = - q.x*in.x - q.y*in.y - q.z*in.z; - double tx = q.w*in.x + q.y*in.z - q.z*in.y; - double ty = q.w*in.y - q.x*in.z + q.z*in.x; - double tz = q.w*in.z + q.x*in.y - q.y*in.x ; - - //temp * q' -> x = -x, y = -y z = -z - //out.w = tw*q.w + tx*q.x + ty*q.y + tz*q.z; - out.x = -tw*q.x + tx*q.w - ty*q.z + tz*q.y; - out.y = -tw*q.y + tx*q.z + ty*q.w - tz*q.x; - out.z = -tw*q.z - tx*q.y + ty*q.x + tz*q.w; - } - - public static void getMatrix(Quat4d quat, Matrix3d m) { - m.m00 = 1.0f - 2.0 * (quat.y * quat.y + quat.z * quat.z); - m.m01 = 2.0 * (quat.x * quat.y + quat.w * quat.z); - m.m02 = 2.0 * (quat.x * quat.z - quat.w * quat.y); - m.m10 = 2.0 * (quat.x * quat.y - quat.w * quat.z); - m.m11 = 1.0 - 2.0f * (quat.x * quat.x + quat.z * quat.z); - m.m12 = 2.0 * (quat.y * quat.z + quat.w * quat.x); - m.m20 = 2.0 * (quat.x * quat.z + quat.w * quat.y); - m.m21 = 2.0 * (quat.y * quat.z - quat.w * quat.x); - m.m22 = 1.0 - 2.0f * (quat.x * quat.x + quat.y * quat.y); - - } - - public static void getMatrix(Quat4d quat, Matrix4d m) { - m.setZero(); - m.m00 = 1.0f - 2.0 * (quat.y * quat.y + quat.z * quat.z); - m.m01 = 2.0 * (quat.x * quat.y + quat.w * quat.z); - m.m02 = 2.0 * (quat.x * quat.z - quat.w * quat.y); - m.m10 = 2.0 * (quat.x * quat.y - quat.w * quat.z); - m.m11 = 1.0 - 2.0f * (quat.x * quat.x + quat.z * quat.z); - m.m12 = 2.0 * (quat.y * quat.z + quat.w * quat.x); - m.m20 = 2.0 * (quat.x * quat.z + quat.w * quat.y); - m.m21 = 2.0 * (quat.y * quat.z - quat.w * quat.x); - m.m22 = 1.0 - 2.0f * (quat.x * quat.x + quat.y * quat.y); - m.m33 = 1.0; - } - - private static double q[] = new double[3]; - private static int nxt[] = { 1, 2, 0 }; - /** - * Converts Matrix to Quaternion - * - * Note: non-thread safe. - * - * @param mat - * @param quat - */ - public static void getQuat(Matrix3d mat, Quat4d quat) { - double tr = mat.m00 + mat.m11 + mat.m22; + Double.isInfinite(t.y) || Double.isNaN(t.y) || + Double.isInfinite(t.z) || Double.isNaN(t.z)); + } + + public static Vector3d closestPointOnEdge(Vector3d point, Vector3d edgePoint1, Vector3d edgePoint2) { + point.sub(edgePoint1); + Vector3d v = new Vector3d(edgePoint2); + v.sub(edgePoint1); + double t = v.dot(point); + t /= v.lengthSquared(); + if (t <= 0.0f) + return edgePoint1; + if (t >= 1.0f) + return edgePoint2; + v.scale(t); + v.add(edgePoint1); + return v; + } + + public static Vector3d closestPointOnStraight(Tuple3d point, Tuple3d straightPoint, Vector3d straightDir) { + Vector3d v = new Vector3d(point); + v.sub(straightPoint); + double t = straightDir.dot(v); + t /= straightDir.lengthSquared(); + v.set(straightDir); + v.scale(t); + v.add(straightPoint); + return v; + } + + public static Vector3d closestPointOnStraight(Tuple3d point, Tuple3d straightPoint, Vector3d straightDir, double u[]) { + Vector3d v = new Vector3d(point); + v.sub(straightPoint); + u[0] = straightDir.dot(v); + u[0] /= straightDir.lengthSquared(); + v.set(straightDir); + v.scale(u[0]); + v.add(straightPoint); + return v; + } + + public static double distanceFromPlane(Vector3d point, Vector3d planeNormal, Tuple3d planePoint) { + point.sub(planePoint); + + return planeNormal.dot(point); + } + + public static double distanceFromPlane(Vector3d point, Vector3d planeNormal, float d) { + return (planeNormal.dot(point) + d); + } + + public static boolean intersectStraightPlane(Tuple3d linePoint, Vector3d lineDir, Tuple3d planePoint, Vector3d planeNormal, Tuple3d intersectPoint) { + intersectPoint.set(planePoint); + intersectPoint.sub(linePoint); + double u = planeNormal.dot(new Vector3d(intersectPoint)); + double v = planeNormal.dot(lineDir); + if (Math.abs(v) < NEAR_ZERO) + return false; + u /= v; + intersectPoint.set(lineDir); + intersectPoint.scale(u); + intersectPoint.add(linePoint); + return true; + } + + public static boolean intersectStraightPlane(Tuple3d linePoint, Vector3d lineDir, Tuple3d planePoint, Vector3d planeNormal, Vector3d intersectPoint, double[] u) { + intersectPoint.set(planePoint); + intersectPoint.sub(linePoint); + u[0] = planeNormal.dot(intersectPoint); + double v = planeNormal.dot(lineDir); + if (Math.abs(v) < NEAR_ZERO) + return false; + u[0] /= v; + intersectPoint.set(lineDir); + intersectPoint.scale(u[0]); + intersectPoint.add(linePoint); + return true; + } + + public static boolean intersectLineLine(Tuple3d l1_start,Tuple3d l1_end,Tuple3d l2_start,Tuple3d l2_end,Tuple3d l1_pos, Tuple3d l2_pos) { + Vector3d p13 = new Vector3d(); + Vector3d p43 = new Vector3d(); + Vector3d p21 = new Vector3d(); + double d1343,d4321,d1321,d4343,d2121; + double numer,denom; + p13.sub(l1_start, l2_start); + p43.sub(l2_end,l2_start); + if (Math.abs(p43.x) < NEAR_ZERO && Math.abs(p43.y) < NEAR_ZERO && Math.abs(p43.z) < NEAR_ZERO) + return false; + p21.sub(l1_end,l1_start); + if (Math.abs(p21.x) < NEAR_ZERO && Math.abs(p21.y) < NEAR_ZERO && Math.abs(p21.z) < NEAR_ZERO) + return false; + + d1343 = p13.dot(p43); + d4321 = p43.dot(p21); + d1321 = p13.dot(p21); + d4343 = p43.lengthSquared(); + d2121 = p21.lengthSquared(); + + denom = d2121 * d4343 - d4321 * d4321; + if (Math.abs(denom) < NEAR_ZERO) + return false; + numer = d1343 * d4321 - d1321 * d4343; + + double mua = numer / denom; + double mub = (d1343 + d4321 * mua) / d4343; + + l1_pos.x = l1_start.x + mua * p21.x; + l1_pos.y = l1_start.y + mua * p21.y; + l1_pos.z = l1_start.z + mua * p21.z; + l2_pos.x = l2_start.x + mub * p43.x; + l2_pos.y = l2_start.y + mub * p43.y; + l2_pos.z = l2_start.z + mub * p43.z; + + return true; + } + + public static boolean intersectStraightStraight(Tuple3d p1,Vector3d p21,Tuple3d p3,Vector3d p43,Tuple3d pa,Tuple3d pb) { + Vector3d p13 = new Vector3d(); + + double d1343,d4321,d1321,d4343,d2121; + double numer,denom; + + p13.sub(p1, p3); + if (Math.abs(p43.x) < NEAR_ZERO && Math.abs(p43.y) < NEAR_ZERO && Math.abs(p43.z) < NEAR_ZERO) + return false; + if (Math.abs(p21.x) < NEAR_ZERO && Math.abs(p21.y) < NEAR_ZERO && Math.abs(p21.z) < NEAR_ZERO) + return false; + + d1343 = p13.dot(p43); + d4321 = p43.dot(p21); + d1321 = p13.dot(p21); + d4343 = p43.lengthSquared(); + d2121 = p21.lengthSquared(); + + denom = d2121 * d4343 - d4321 * d4321; + if (Math.abs(denom) < NEAR_ZERO) + return false; + numer = d1343 * d4321 - d1321 * d4343; + + double mua = numer / denom; + double mub = (d1343 + d4321 * mua) / d4343; + + pa.x = p1.x + mua * p21.x; + pa.y = p1.y + mua * p21.y; + pa.z = p1.z + mua * p21.z; + pb.x = p3.x + mub * p43.x; + pb.y = p3.y + mub * p43.y; + pb.z = p3.z + mub * p43.z; + + return true; + } + + /** + * Calculate the line segment PaPb that is the shortest route between + * two lines P1P2 and P3P4. Calculate also the values of mua and mub where + * Pa = P1 + mua (P2 - P1) + * Pb = P3 + mub (P4 - P3) + * @param p1 + * @param p21 + * @param p3 + * @param p43 + * @param pa + * @param pb + * @param mu + * @return + */ + public static boolean intersectStraightStraight(Tuple3d p1,Vector3d p21,Tuple3d p3,Vector3d p43,Tuple3d pa,Tuple3d pb, double mu[]) { + Vector3d p13 = new Vector3d(); + + double d1343,d4321,d1321,d4343,d2121; + double numer,denom; + double EPS = 0.001; + p13.sub(p1, p3); + if (Math.abs(p43.x) < EPS && Math.abs(p43.y) < EPS && Math.abs(p43.z) < EPS) + return false; + if (Math.abs(p21.x) < EPS && Math.abs(p21.y) < EPS && Math.abs(p21.z) < EPS) + return false; + + d1343 = p13.dot(p43); + d4321 = p43.dot(p21); + d1321 = p13.dot(p21); + d4343 = p43.lengthSquared(); + d2121 = p21.lengthSquared(); + + denom = d2121 * d4343 - d4321 * d4321; + if (Math.abs(denom) < EPS) + return false; + numer = d1343 * d4321 - d1321 * d4343; + + mu[0] = numer / denom; + mu[1] = (d1343 + d4321 * mu[0]) / d4343; + + pa.x = p1.x + mu[0] * p21.x; + pa.y = p1.y + mu[0] * p21.y; + pa.z = p1.z + mu[0] * p21.z; + pb.x = p3.x + mu[1] * p43.x; + pb.y = p3.y + mu[1] * p43.y; + pb.z = p3.z + mu[1] * p43.z; + + return true; + } + + + + public static void rotate(Quat4d q, Tuple3d in, Tuple3d out) { + // p' = q * p * q' + double tw = - q.x*in.x - q.y*in.y - q.z*in.z; + double tx = q.w*in.x + q.y*in.z - q.z*in.y; + double ty = q.w*in.y - q.x*in.z + q.z*in.x; + double tz = q.w*in.z + q.x*in.y - q.y*in.x ; + + //temp * q' -> x = -x, y = -y z = -z + //out.w = tw*q.w + tx*q.x + ty*q.y + tz*q.z; + out.x = -tw*q.x + tx*q.w - ty*q.z + tz*q.y; + out.y = -tw*q.y + tx*q.z + ty*q.w - tz*q.x; + out.z = -tw*q.z - tx*q.y + ty*q.x + tz*q.w; + } + + public static void getMatrix(Quat4d quat, Matrix3d m) { + m.m00 = 1.0f - 2.0 * (quat.y * quat.y + quat.z * quat.z); + m.m01 = 2.0 * (quat.x * quat.y + quat.w * quat.z); + m.m02 = 2.0 * (quat.x * quat.z - quat.w * quat.y); + m.m10 = 2.0 * (quat.x * quat.y - quat.w * quat.z); + m.m11 = 1.0 - 2.0f * (quat.x * quat.x + quat.z * quat.z); + m.m12 = 2.0 * (quat.y * quat.z + quat.w * quat.x); + m.m20 = 2.0 * (quat.x * quat.z + quat.w * quat.y); + m.m21 = 2.0 * (quat.y * quat.z - quat.w * quat.x); + m.m22 = 1.0 - 2.0f * (quat.x * quat.x + quat.y * quat.y); + + } + + public static void getMatrix(Quat4d quat, Matrix4d m) { + m.setZero(); + m.m00 = 1.0f - 2.0 * (quat.y * quat.y + quat.z * quat.z); + m.m01 = 2.0 * (quat.x * quat.y + quat.w * quat.z); + m.m02 = 2.0 * (quat.x * quat.z - quat.w * quat.y); + m.m10 = 2.0 * (quat.x * quat.y - quat.w * quat.z); + m.m11 = 1.0 - 2.0f * (quat.x * quat.x + quat.z * quat.z); + m.m12 = 2.0 * (quat.y * quat.z + quat.w * quat.x); + m.m20 = 2.0 * (quat.x * quat.z + quat.w * quat.y); + m.m21 = 2.0 * (quat.y * quat.z - quat.w * quat.x); + m.m22 = 1.0 - 2.0f * (quat.x * quat.x + quat.y * quat.y); + m.m33 = 1.0; + } + + private static double q[] = new double[3]; + private static int nxt[] = { 1, 2, 0 }; + /** + * Converts Matrix to Quaternion + * + * Note: non-thread safe. + * + * @param mat + * @param quat + */ + public static void getQuat(Matrix3d mat, Quat4d quat) { + double tr = mat.m00 + mat.m11 + mat.m22; if (tr > 0.0) { double s = Math.sqrt(tr + 1.0); quat.w = 0.5 * s; @@ -388,50 +388,50 @@ public class MathTools { quat.z = q[2]; } } - - public static Quat4d getQuat(Matrix3d mat) { - Quat4d q = new Quat4d(); - getQuat(mat, q); - return q; - } - - public static AxisAngle4d getFromPseudoEuler(Vector3d euler) { - AxisAngle4d aa = new AxisAngle4d(); - aa.angle = euler.length(); - Vector3d normal = new Vector3d(euler); - if (aa.angle > NEAR_ZERO) { - normal.normalize(); - aa.x = normal.x; - aa.y = normal.y; - aa.z = normal.z; - } else { - aa.x = 1.0; - aa.y = 0.0; - aa.z = 0.0; - } - - return aa; - } - - public static Vector3d getPseudoEuler(AxisAngle4d aa) { - Vector3d euler = new Vector3d(aa.x,aa.y,aa.z); - euler.scale(aa.angle); - return euler; - } - - - public static void getQuat(Vector3d euler, Quat4d quat) { - Quat4d q = EulerTools.getQuatFromEuler(Order.YXZ, euler.y,euler.x,euler.z); - quat.set(q); + + public static Quat4d getQuat(Matrix3d mat) { + Quat4d q = new Quat4d(); + getQuat(mat, q); + return q; + } + + public static AxisAngle4d getFromPseudoEuler(Vector3d euler) { + AxisAngle4d aa = new AxisAngle4d(); + aa.angle = euler.length(); + Vector3d normal = new Vector3d(euler); + if (aa.angle > NEAR_ZERO) { + normal.normalize(); + aa.x = normal.x; + aa.y = normal.y; + aa.z = normal.z; + } else { + aa.x = 1.0; + aa.y = 0.0; + aa.z = 0.0; + } + + return aa; + } + + public static Vector3d getPseudoEuler(AxisAngle4d aa) { + Vector3d euler = new Vector3d(aa.x,aa.y,aa.z); + euler.scale(aa.angle); + return euler; + } + + + public static void getQuat(Vector3d euler, Quat4d quat) { + Quat4d q = EulerTools.getQuatFromEuler(Order.YXZ, euler.y,euler.x,euler.z); + quat.set(q); // http://en.wikipedia.org/wiki/Rotation_formalisms_in_three_dimensions#Conversion_formulae_between_formalisms // Using the x-convention, the 3-1-3 Euler angles phi, theta and psi (around the Z, X and again the Z-axis) // quat.x = -Math.cos((euler.x - euler.z)*0.5)*Math.sin(euler.y*0.5); // quat.y = -Math.sin((euler.x - euler.z)*0.5)*Math.sin(euler.y*0.5); // quat.z = -Math.sin((euler.x + euler.z)*0.5)*Math.cos(euler.y*0.5); // quat.w = Math.sin((euler.x + euler.z)*0.5)*Math.cos(euler.y*0.5); - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/index.htm - // Y, Z, X order + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/index.htm + // Y, Z, X order // double c1 = Math.cos(euler.y*0.5); // double s1 = Math.sin(euler.y*0.5); // double c2 = Math.cos(euler.z*0.5); @@ -458,24 +458,24 @@ public class MathTools { // quat.x = (c2 * s3 + c1 * s3 + s1 * s2 * c3) / w4 ; // quat.y = (s1 * c2 + s1 * c3 + c1 * s2 * s3) / w4 ; // quat.z = (-s1 * s3 + c1 * s2 * c3 +s2) / w4 ; - } - - - - - public static void getEuler(Quat4d quat,Vector3d euler) { - Vector3d e = EulerTools.getEulerFromQuat(Order.YXZ, quat); - euler.x = e.y; - euler.y = e.x; - euler.z = e.z; - - // http://en.wikipedia.org/wiki/Rotation_formalisms_in_three_dimensions#Conversion_formulae_between_formalisms + } + + + + + public static void getEuler(Quat4d quat,Vector3d euler) { + Vector3d e = EulerTools.getEulerFromQuat(Order.YXZ, quat); + euler.x = e.y; + euler.y = e.x; + euler.z = e.z; + + // http://en.wikipedia.org/wiki/Rotation_formalisms_in_three_dimensions#Conversion_formulae_between_formalisms // euler.x = Math.atan2(quat.x * quat.z + quat.y* quat.w, quat.y*quat.z - quat.x * quat.w); // euler.y = Math.acos(-square(quat.x) - square(quat.y) + square(quat.z) + square(quat.w)); // euler.z = -Math.atan2(quat.x * quat.z - quat.y* quat.w, quat.y*quat.z + quat.x * quat.w); - - // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/index.htm - // Y, Z, X order + + // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/index.htm + // Y, Z, X order // double test = quat.x * quat.y + quat.z * quat.w; // if (test > NEAR_HALF) { // euler.y = 2.0 * Math.atan2(quat.x,quat.w); @@ -515,27 +515,27 @@ public class MathTools { // euler.y = Math.atan2(2*quat.y*quat.w-2*quat.x*quat.z , sqx - sqy - sqz + sqw); // euler.z = Math.asin(2*test/unit); // euler.x = Math.atan2(2*quat.x*quat.w-2*quat.y*quat.z , -sqx + sqy - sqz + sqw); - } - - public static Quat4d getQuat(Vector3d euler) { - Quat4d q = new Quat4d(); - getQuat(euler,q); - return q; - } - - - public static Vector3d getEuler(Quat4d quat) { - Vector3d v = new Vector3d(); - getEuler(quat, v); - return v; - } - - public static Quat4d getQuat(AxisAngle4d aa) { - Quat4d q = new Quat4d(); - getQuat(aa, q); - return q; - } - + } + + public static Quat4d getQuat(Vector3d euler) { + Quat4d q = new Quat4d(); + getQuat(euler,q); + return q; + } + + + public static Vector3d getEuler(Quat4d quat) { + Vector3d v = new Vector3d(); + getEuler(quat, v); + return v; + } + + public static Quat4d getQuat(AxisAngle4d aa) { + Quat4d q = new Quat4d(); + getQuat(aa, q); + return q; + } + public static AxisAngle4d getAxisAngle(Quat4d q) { AxisAngle4d aa = new AxisAngle4d(); double mag = q.x * q.x + q.y * q.y + q.z * q.z; @@ -557,33 +557,33 @@ public class MathTools { // aa.set(q); return aa; } - - public static Quat4d getIdentityQuat() { - return new Quat4d(0, 0, 0, 1); - } - - public static void getQuat(AxisAngle4d aa, Quat4d q) { - double mag,amag; + + public static Quat4d getIdentityQuat() { + return new Quat4d(0, 0, 0, 1); + } + + public static void getQuat(AxisAngle4d aa, Quat4d q) { + double mag,amag; // Quat = cos(theta/2) + sin(theta/2)(roation_axis) amag = Math.sqrt( aa.x*aa.x + aa.y*aa.y + aa.z*aa.z); if( amag < NEAR_ZERO ) { - q.w = 1.0; - q.x = 0.0; - q.y = 0.0; - q.z = 0.0; + q.w = 1.0; + q.x = 0.0; + q.y = 0.0; + q.z = 0.0; } else { - amag = 1.0/amag; - double a2 = aa.angle * 0.5; - mag = Math.sin(a2); - q.w = Math.cos(a2); - q.x = aa.x*amag*mag; - q.y = aa.y*amag*mag; - q.z = aa.z*amag*mag; + amag = 1.0/amag; + double a2 = aa.angle * 0.5; + mag = Math.sin(a2); + q.w = Math.cos(a2); + q.x = aa.x*amag*mag; + q.y = aa.y*amag*mag; + q.z = aa.z*amag*mag; } - } - - + } + + /* * Cohen-Sutherland */ @@ -658,46 +658,46 @@ public class MathTools { } - public static void multiplyOrientation(AxisAngle4d aa, AxisAngle4d rot) { + public static void multiplyOrientation(AxisAngle4d aa, AxisAngle4d rot) { Quat4d q1 = new Quat4d(); getQuat(aa, q1); Quat4d q2 = new Quat4d(); getQuat(rot, q2); q2.mul(q1); rot.set(q2); - } - - public static double radToDeg(double rad) { - return (rad / Math.PI) * 180.0; - } - - public static double degToRad(double deg) { - return (deg / 180.0) * Math.PI; - } - - public static double clamp(double min, double max,double v) { - if (v < min) - return min; - if (v > max) - return max; - return v; - } - - public static AxisAngle4d createRotation(Vector3d original, Vector3d rotated) { + } + + public static double radToDeg(double rad) { + return (rad / Math.PI) * 180.0; + } + + public static double degToRad(double deg) { + return (deg / 180.0) * Math.PI; + } + + public static double clamp(double min, double max,double v) { + if (v < min) + return min; + if (v > max) + return max; + return v; + } + + public static AxisAngle4d createRotation(Vector3d original, Vector3d rotated) { AxisAngle4d result = new AxisAngle4d(); if (createRotation(original, rotated, result)) return result; return null; - } - - - public static void setIdentity(Quat4d q) { + } + + + public static void setIdentity(Quat4d q) { q.w = 1.0; q.x = 0.0; q.y = 0.0; q.z = 0.0; - } - + } + public static void setIdentity(AxisAngle4d aa) { aa.angle = 0.0; aa.x = 0.0; @@ -743,9 +743,9 @@ public class MathTools { mat.m33 = v[15]; } - - public static boolean createRotation(Vector3d original, Vector3d rotated, AxisAngle4d result) { - + + public static boolean createRotation(Vector3d original, Vector3d rotated, AxisAngle4d result) { + if (rotated.lengthSquared() > 0.01) rotated.normalize(); else @@ -770,10 +770,10 @@ public class MathTools { result.set(axis,angle); } return true; - } - - public static boolean createRotation(Vector3d original, Vector3d rotated, Quat4d result) { - + } + + public static boolean createRotation(Vector3d original, Vector3d rotated, Quat4d result) { + if (rotated.lengthSquared() > 0.01) rotated.normalize(); else @@ -799,159 +799,159 @@ public class MathTools { getQuat(axis, angle, result); } return true; - } - - public static void getQuat(Vector3d axis, double angle, Quat4d q) - { + } + + public static void getQuat(Vector3d axis, double angle, Quat4d q) + { double mag,amag; // Quat = cos(theta/2) + sin(theta/2)(roation_axis) amag = Math.sqrt( axis.x*axis.x + axis.y*axis.y + axis.z*axis.z); if( amag < EPS ) { - q.w = 1.0; - q.x = 0.0; - q.y = 0.0; - q.z = 0.0; + q.w = 1.0; + q.x = 0.0; + q.y = 0.0; + q.z = 0.0; } else { - amag = 1.0/amag; - double a2 = angle*0.5; - mag = Math.sin(a2); - q.w = Math.cos(a2); - q.x = axis.x*amag*mag; - q.y = axis.y*amag*mag; - q.z = axis.z*amag*mag; + amag = 1.0/amag; + double a2 = angle*0.5; + mag = Math.sin(a2); + q.w = Math.cos(a2); + q.x = axis.x*amag*mag; + q.y = axis.y*amag*mag; + q.z = axis.z*amag*mag; + } + + } + + /** + * Linear interpolation of quaternions. Result IS set to q1. + * @param q1 + * @param q2 + * @param alpha + */ + public static void lip(Quat4d q1, Quat4d q2, double alpha) { + double s1 = 1.0 - alpha; + double s2 = alpha; + q1.scale(s1); + mad(q1,q2,s2); + q1.normalize(); + } + + public static double dot(Quat4d q1, Quat4d q2) { + return q1.x * q2.x + q1.y * q2.y + q1.z * q2.z + q1.w * q2.w; + } + + public static void mad(Tuple3d q1, Tuple3d q2, double s2) { + q1.x += q2.x * s2; + q1.y += q2.y * s2; + q1.z += q2.z * s2; + } + + public static void mad(Quat4d q1, Quat4d q2, double s2) { + q1.x += q2.x * s2; + q1.y += q2.y * s2; + q1.z += q2.z * s2; + q1.w += q2.w * s2; + } + + /** + * Slerp + * + * Sets results to q1. Modifies q2. + * + * @param q1 + * @param q2 + * @param alpha + */ + public static void sip(Quat4d q1, Quat4d q2, double alpha) { + double cosom = dot(q1,q2); + if (cosom < 0.0) { + cosom = -cosom; + q2.negate(); } + + if (cosom > 0.9999) { + q2.sub(q1); + q2.scale(alpha); + q1.add(q2); + q1.normalize(); + return; + } + double theta_0 = Math.acos(cosom); + double theta = theta_0 * alpha; + Quat4d t = new Quat4d(q1); + t.scale(-cosom); + t.add(q2); + t.normalize(); + t.scale(Math.sin(theta)); + q1.scale(Math.cos(theta)); + q1.add(t); + } - } - - /** - * Linear interpolation of quaternions. Result IS set to q1. - * @param q1 - * @param q2 - * @param alpha - */ - public static void lip(Quat4d q1, Quat4d q2, double alpha) { - double s1 = 1.0 - alpha; - double s2 = alpha; - q1.scale(s1); - mad(q1,q2,s2); - q1.normalize(); - } - - public static double dot(Quat4d q1, Quat4d q2) { - return q1.x * q2.x + q1.y * q2.y + q1.z * q2.z + q1.w * q2.w; - } - - public static void mad(Tuple3d q1, Tuple3d q2, double s2) { - q1.x += q2.x * s2; - q1.y += q2.y * s2; - q1.z += q2.z * s2; - } - - public static void mad(Quat4d q1, Quat4d q2, double s2) { - q1.x += q2.x * s2; - q1.y += q2.y * s2; - q1.z += q2.z * s2; - q1.w += q2.w * s2; - } - - /** - * Slerp - * - * Sets results to q1. Modifies q2. - * - * @param q1 - * @param q2 - * @param alpha - */ - public static void sip(Quat4d q1, Quat4d q2, double alpha) { - double cosom = dot(q1,q2); - if (cosom < 0.0) { - cosom = -cosom; - q2.negate(); - } - - if (cosom > 0.9999) { - q2.sub(q1); - q2.scale(alpha); - q1.add(q2); - q1.normalize(); - return; - } - double theta_0 = Math.acos(cosom); - double theta = theta_0 * alpha; - Quat4d t = new Quat4d(q1); - t.scale(-cosom); - t.add(q2); - t.normalize(); - t.scale(Math.sin(theta)); - q1.scale(Math.cos(theta)); - q1.add(t); - } - - - public static void rotate(double angle, Tuple2d v1, Tuple2d v2) { - // TODO : verify implementation - double sin = Math.sin(angle); - if (sin == 1.0) { - v2.x = v1.y; - v2.y = -v1.x; - } else if (sin == -1.0) { - v2.x = -v1.y; - v2.y = v1.x; - } else { - double cos = Math.cos(angle); - if (cos == -1.0) { - v2.x = -v1.x; - v2.y = -v1.y; - } else if (cos != 1.0) { - v2.x= v1.x * cos + v1.y * -sin; - v2.y= v1.x* sin + v1.y *cos; - } - } - } - - public static Tuple3d getPosRot(double m3x2[]) { - Vector3d t = new Vector3d(); - t.x = m3x2[4]; - t.y = m3x2[5]; - - - Vector2d v2 = new Vector2d(1,0); - Vector2d v = new Vector2d(); - // use rotation of (1,0) to calculate the rotation component - v.x = m3x2[0]; - v.y = m3x2[2]; - double a1 = v2.angle(v); - if (v.y < 0) { - t.z = a1; - } else { - t.z = Math.PI*2.0 - a1; - } - return t; - } - - public static Matrix4d glFrustum(double l, double r, double b, double t, double n, double f) { - Matrix4d mat = new Matrix4d(); - mat.m00 = 2.0 * n / (r - l); - mat.m11 = 2.0 * n / (t - b); - mat.m02 = (r+l) / (r-l); - mat.m12 = (t+b) / (t-b); - mat.m22 = -(f+n) / (f-n); - mat.m23 = -(2.0 *f * n) / (f-n); - mat.m32 = -1.0; - return mat; - } - - public static Matrix4d glOrtho(double l, double r, double b, double t, double n, double f) { - Matrix4d mat = new Matrix4d(); - mat.m00 = 2.0 / (r - l); - mat.m11 = 2.0 / (t - b); - mat.m22 = -2.0 / (f-n); - mat.m33 = 1.0; - mat.m03 = -(r+l)/(r-l); - mat.m13 = -(t+b)/(t-b); - mat.m23 = -(f+n)/(f-n); - return mat; - } + + public static void rotate(double angle, Tuple2d v1, Tuple2d v2) { + // TODO : verify implementation + double sin = Math.sin(angle); + if (sin == 1.0) { + v2.x = v1.y; + v2.y = -v1.x; + } else if (sin == -1.0) { + v2.x = -v1.y; + v2.y = v1.x; + } else { + double cos = Math.cos(angle); + if (cos == -1.0) { + v2.x = -v1.x; + v2.y = -v1.y; + } else if (cos != 1.0) { + v2.x= v1.x * cos + v1.y * -sin; + v2.y= v1.x* sin + v1.y *cos; + } + } + } + + public static Tuple3d getPosRot(double m3x2[]) { + Vector3d t = new Vector3d(); + t.x = m3x2[4]; + t.y = m3x2[5]; + + + Vector2d v2 = new Vector2d(1,0); + Vector2d v = new Vector2d(); + // use rotation of (1,0) to calculate the rotation component + v.x = m3x2[0]; + v.y = m3x2[2]; + double a1 = v2.angle(v); + if (v.y < 0) { + t.z = a1; + } else { + t.z = Math.PI*2.0 - a1; + } + return t; + } + + public static Matrix4d glFrustum(double l, double r, double b, double t, double n, double f) { + Matrix4d mat = new Matrix4d(); + mat.m00 = 2.0 * n / (r - l); + mat.m11 = 2.0 * n / (t - b); + mat.m02 = (r+l) / (r-l); + mat.m12 = (t+b) / (t-b); + mat.m22 = -(f+n) / (f-n); + mat.m23 = -(2.0 *f * n) / (f-n); + mat.m32 = -1.0; + return mat; + } + + public static Matrix4d glOrtho(double l, double r, double b, double t, double n, double f) { + Matrix4d mat = new Matrix4d(); + mat.m00 = 2.0 / (r - l); + mat.m11 = 2.0 / (t - b); + mat.m22 = -2.0 / (f-n); + mat.m33 = 1.0; + mat.m03 = -(r+l)/(r-l); + mat.m13 = -(t+b)/(t-b); + mat.m23 = -(f+n)/(f-n); + return mat; + } } diff --git a/org.simantics.g3d/src/org/simantics/g3d/property/AnnotatedPropertyTabContributorFactory.java b/org.simantics.g3d/src/org/simantics/g3d/property/AnnotatedPropertyTabContributorFactory.java index a3fca78b..e216e5e7 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/property/AnnotatedPropertyTabContributorFactory.java +++ b/org.simantics.g3d/src/org/simantics/g3d/property/AnnotatedPropertyTabContributorFactory.java @@ -131,85 +131,85 @@ public class AnnotatedPropertyTabContributorFactory implements PropertyTabContri private static void collectItems(Class clazz, Map items) throws InstantiationException, IllegalAccessException { - Class superclass = clazz.getSuperclass(); - if(superclass != null) - collectItems(superclass, items); - - for (Method m : clazz.getDeclaredMethods()) { - m.setAccessible(true); - for (Annotation annotation : m.getAnnotations()) { - if (annotation.annotationType().equals(GetPropertyValue.class)) { - GetPropertyValue get = (GetPropertyValue)annotation; - PropertyItem item = (PropertyItem)items.get(get.value()); - if (item == null) { - item = new PropertyItem(get.value()); - items.put(item.id, item); - } + Class superclass = clazz.getSuperclass(); + if(superclass != null) + collectItems(superclass, items); + + for (Method m : clazz.getDeclaredMethods()) { + m.setAccessible(true); + for (Annotation annotation : m.getAnnotations()) { + if (annotation.annotationType().equals(GetPropertyValue.class)) { + GetPropertyValue get = (GetPropertyValue)annotation; + PropertyItem item = (PropertyItem)items.get(get.value()); + if (item == null) { + item = new PropertyItem(get.value()); + items.put(item.id, item); + } - item.getter = m; - item.manipulatorClass = get.manipulator().newInstance().get(m,null); + item.getter = m; + item.manipulatorClass = get.manipulator().newInstance().get(m,null); - item.tabId = get.tabId(); + item.tabId = get.tabId(); - item.name = get.name(); - - - } else if (annotation.annotationType().equals(SetPropertyValue.class)) { - SetPropertyValue set = (SetPropertyValue)annotation; - PropertyItem item = (PropertyItem)items.get(set.value()); - if (item == null) { - item = new PropertyItem(set.value()); - items.put(item.id, item); - } - - item.setter = m; - } else if (annotation.annotationType().equals(CompoundGetPropertyValue.class)) { - CompoundGetPropertyValue get = (CompoundGetPropertyValue)annotation; - CompoundPropertyItem item = (CompoundPropertyItem)items.get(get.value()); - if (item == null) { - item = new CompoundPropertyItem(get.value()); - items.put(item.id, item); - } + item.name = get.name(); + + + } else if (annotation.annotationType().equals(SetPropertyValue.class)) { + SetPropertyValue set = (SetPropertyValue)annotation; + PropertyItem item = (PropertyItem)items.get(set.value()); + if (item == null) { + item = new PropertyItem(set.value()); + items.put(item.id, item); + } + + item.setter = m; + } else if (annotation.annotationType().equals(CompoundGetPropertyValue.class)) { + CompoundGetPropertyValue get = (CompoundGetPropertyValue)annotation; + CompoundPropertyItem item = (CompoundPropertyItem)items.get(get.value()); + if (item == null) { + item = new CompoundPropertyItem(get.value()); + items.put(item.id, item); + } - item.getter = m; - item.manipulatorFactory = get.manipulator().newInstance(); + item.getter = m; + item.manipulatorFactory = get.manipulator().newInstance(); - item.tabId = get.tabId(); + item.tabId = get.tabId(); - item.name = get.name(); - } else if (annotation.annotationType().equals(CompoundSetPropertyValue.class)) { - CompoundSetPropertyValue set = (CompoundSetPropertyValue)annotation; - CompoundPropertyItem item = (CompoundPropertyItem)items.get(set.value()); - if (item == null) { - item = new CompoundPropertyItem(set.value()); - items.put(item.id, item); - } - - item.setter = m; - } - } - } + item.name = get.name(); + } else if (annotation.annotationType().equals(CompoundSetPropertyValue.class)) { + CompoundSetPropertyValue set = (CompoundSetPropertyValue)annotation; + CompoundPropertyItem item = (CompoundPropertyItem)items.get(set.value()); + if (item == null) { + item = new CompoundPropertyItem(set.value()); + items.put(item.id, item); + } + + item.setter = m; + } + } + } } private static void collectBlacklist(Class clazz, List blacklist) throws InstantiationException, IllegalAccessException { - Class superclass = clazz.getSuperclass(); - if(superclass != null) - collectBlacklist(superclass, blacklist); - - PropertyTabBlacklist ann = clazz.getAnnotation(PropertyTabBlacklist.class); - if (ann == null) - return; - String s = ann.value(); - if (s == null) - return; - if (s.length() == 0) - return; - for (String item : s.split(";")) { - blacklist.add(item); - } - + Class superclass = clazz.getSuperclass(); + if(superclass != null) + collectBlacklist(superclass, blacklist); + + PropertyTabBlacklist ann = clazz.getAnnotation(PropertyTabBlacklist.class); + if (ann == null) + return; + String s = ann.value(); + if (s == null) + return; + if (s.length() == 0) + return; + for (String item : s.split(";")) { + blacklist.add(item); + } + } diff --git a/org.simantics.g3d/src/org/simantics/g3d/scenegraph/base/INode.java b/org.simantics.g3d/src/org/simantics/g3d/scenegraph/base/INode.java index 390b3a20..5a0297af 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/scenegraph/base/INode.java +++ b/org.simantics.g3d/src/org/simantics/g3d/scenegraph/base/INode.java @@ -20,47 +20,47 @@ import java.util.List; public interface INode { /** - * - * @return unique node identifier - */ - // public Long getId(); + * + * @return unique node identifier + */ + // public Long getId(); - /** - * @return root node of the scene graph or null if this node is - * not part of a properly rooted scene graph hierarchy - */ - public ParentNode getRootNode(); + /** + * @return root node of the scene graph or null if this node is + * not part of a properly rooted scene graph hierarchy + */ + public ParentNode getRootNode(); - /** - * @return Parent node reference or null if not set - */ - public ParentNode getParent(); - - public String getParentRel(); - /** - * Set parent node. This method is for scene graph internal use only and - * should not be called outside the scene graph structure. This method - * simply sets the parent node parent field, and does not affect on parent - * node (i.e., should be called only from parent node). - */ - public void setParent(ParentNode parent, String name); + /** + * @return Parent node reference or null if not set + */ + public ParentNode getParent(); + + public String getParentRel(); + /** + * Set parent node. This method is for scene graph internal use only and + * should not be called outside the scene graph structure. This method + * simply sets the parent node parent field, and does not affect on parent + * node (i.e., should be called only from parent node). + */ + public void setParent(ParentNode parent, String name); - /** - * Perform cleanup for this node and for the child nodes. Any resources - * (including child nodes) related to this node are unusable after this - * operation. This method is for scene graph internal use only, thus should - * not be called outside the scene graph structure. - */ - public void cleanup(); - /** - * Remove this node and its children from the scene graph. - */ - public void remove(); - - public void deattach(); + /** + * Perform cleanup for this node and for the child nodes. Any resources + * (including child nodes) related to this node are unusable after this + * operation. This method is for scene graph internal use only, thus should + * not be called outside the scene graph structure. + */ + public void cleanup(); + /** + * Remove this node and its children from the scene graph. + */ + public void remove(); + + public void deattach(); - - public void addListener(NodeListener listener); + + public void addListener(NodeListener listener); public void removeListener(NodeListener listener); public List getListeners(); diff --git a/org.simantics.g3d/src/org/simantics/g3d/scenegraph/base/Node.java b/org.simantics.g3d/src/org/simantics/g3d/scenegraph/base/Node.java index ae1b300c..f7fe9ede 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/scenegraph/base/Node.java +++ b/org.simantics.g3d/src/org/simantics/g3d/scenegraph/base/Node.java @@ -22,57 +22,57 @@ public abstract class Node implements INode { protected Long id = IDCOUNTER++; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public ParentNode getParent() { - return parent; - } + public ParentNode getParent() { + return parent; + } - - @Override - public String getParentRel() { - return parentName; - } - - public void setParent(ParentNode parent, String name) { - this.parent = parent; - this.parentName = name; - } - - public ParentNode getRootNode() { - return parent != null ? parent.getRootNode() : null; - } - - public void remove() { - if (parent != null) { - parent.removeNode(parentName, this); - } - } - - public void deattach() { - if (parent != null) { - parent.deattachNode(parentName, this); - } - } - - public void init() { - } - - public void cleanup() { - if (parent != null) { - parent.removeNode(parentName, this); - } - } - - @Override + + @Override + public String getParentRel() { + return parentName; + } + + public void setParent(ParentNode parent, String name) { + this.parent = parent; + this.parentName = name; + } + + public ParentNode getRootNode() { + return parent != null ? parent.getRootNode() : null; + } + + public void remove() { + if (parent != null) { + parent.removeNode(parentName, this); + } + } + + public void deattach() { + if (parent != null) { + parent.deattachNode(parentName, this); + } + } + + public void init() { + } + + public void cleanup() { + if (parent != null) { + parent.removeNode(parentName, this); + } + } + + @Override public String toString() { return getClass().getSimpleName(); } - - protected List listeners = new ArrayList(); + + protected List listeners = new ArrayList(); @Override public void addListener(NodeListener listener) { @@ -95,5 +95,5 @@ public abstract class Node implements INode { listener.propertyChanged(this, id); } } - + } diff --git a/org.simantics.g3d/src/org/simantics/g3d/scenegraph/base/ParentNode.java b/org.simantics.g3d/src/org/simantics/g3d/scenegraph/base/ParentNode.java index 14618318..7da387d7 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/scenegraph/base/ParentNode.java +++ b/org.simantics.g3d/src/org/simantics/g3d/scenegraph/base/ParentNode.java @@ -42,7 +42,7 @@ public abstract class ParentNode extends Node { public synchronized final boolean removeNode(String relName, INode child) { if (children.remove(relName, (T) child)) { fireNodeRemoved(child, relName); - child.remove(); + child.remove(); child.setParent(null, null); return true; } @@ -70,7 +70,7 @@ public abstract class ParentNode extends Node { for (T child : nodes) { if (children.remove(relName, (T) child)) { fireNodeRemoved(child, relName); - child.remove(); + child.remove(); child.setParent(null, null); } diff --git a/org.simantics.g3d/src/org/simantics/g3d/scenegraph/structural/ComponentNode.java b/org.simantics.g3d/src/org/simantics/g3d/scenegraph/structural/ComponentNode.java index b701aca5..9cdc3bf4 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/scenegraph/structural/ComponentNode.java +++ b/org.simantics.g3d/src/org/simantics/g3d/scenegraph/structural/ComponentNode.java @@ -130,33 +130,33 @@ public abstract class ComponentNode connections = new MapList(); diff --git a/org.simantics.g3d/src/org/simantics/g3d/scenegraph/structural/G3DComponentNode.java b/org.simantics.g3d/src/org/simantics/g3d/scenegraph/structural/G3DComponentNode.java index 54eea059..0221bee2 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/scenegraph/structural/G3DComponentNode.java +++ b/org.simantics.g3d/src/org/simantics/g3d/scenegraph/structural/G3DComponentNode.java @@ -130,33 +130,33 @@ public abstract class G3DComponentNode connections = new MapList(); diff --git a/org.simantics.g3d/src/org/simantics/g3d/scenegraph/structural/StructuralParentNode.java b/org.simantics.g3d/src/org/simantics/g3d/scenegraph/structural/StructuralParentNode.java index 7d492ede..1ae00096 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/scenegraph/structural/StructuralParentNode.java +++ b/org.simantics.g3d/src/org/simantics/g3d/scenegraph/structural/StructuralParentNode.java @@ -80,7 +80,7 @@ public abstract class StructuralParentNode extends Pa ctx = object; } - private List publisher = new ArrayList(1); + private List publisher = new ArrayList(1); @Override public void addPublishedBy(IStructuralNode node) { diff --git a/org.simantics.g3d/src/org/simantics/g3d/scl/SCLUtil.java b/org.simantics.g3d/src/org/simantics/g3d/scl/SCLUtil.java index 99563462..940c244e 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/scl/SCLUtil.java +++ b/org.simantics.g3d/src/org/simantics/g3d/scl/SCLUtil.java @@ -15,65 +15,65 @@ import org.simantics.scl.compiler.types.Type; import org.simantics.scl.osgi.SCLOsgi; public class SCLUtil { - - static Map> typeMap = new HashMap>(); - // copied from org.simantics.scl.db.SCLFunctions - public static Class possibleFromDynamic(Type expectedType, String moduleName) { - - try { + + static Map> typeMap = new HashMap>(); + // copied from org.simantics.scl.db.SCLFunctions + public static Class possibleFromDynamic(Type expectedType, String moduleName) { + + try { - - Failable failable = SCLOsgi.MODULE_REPOSITORY.getModule(moduleName); - Module module = failable.getResult(); - - RuntimeEnvironment env = SCLOsgi.MODULE_REPOSITORY.createRuntimeEnvironment( - EnvironmentSpecification.of(moduleName, ""), module.getParentClassLoader()); + + Failable failable = SCLOsgi.MODULE_REPOSITORY.getModule(moduleName); + Module module = failable.getResult(); + + RuntimeEnvironment env = SCLOsgi.MODULE_REPOSITORY.createRuntimeEnvironment( + EnvironmentSpecification.of(moduleName, ""), module.getParentClassLoader()); - JavaTypeTranslator tr = new JavaTypeTranslator(env.getEnvironment()); - TypeDesc desc = tr.toTypeDesc(expectedType); - String className = desc.getFullName(); - Class clazz = env.getMutableClassLoader().loadClass(className); - return clazz; - } catch (ImportFailureException e) { - return null; - } catch (ClassNotFoundException e) { - return null; - } - } - - public static Class possibleClass(TCon type) { - Class clazz = typeMap.get(type); - if (clazz == null) { - clazz = possibleFromDynamic(type, type.module); - typeMap.put(type, clazz); - } - return clazz; - } - - public static boolean javaIsInstanceOf(org.simantics.scl.compiler.types.Type t, Object o) { - if (t instanceof TCon) { - Class clazz = possibleClass((TCon)t); - if (clazz == null) - return false; - if (!clazz.isAssignableFrom(o.getClass())) - return false; - - return true; - } - return false; - } - - public static Object javaSafeCoerce(org.simantics.scl.compiler.types.Type t, Object o) { - if (t instanceof TCon) { - Class clazz = possibleClass((TCon)t); - if (clazz == null) - return null; - if (!clazz.isAssignableFrom(o.getClass())) - return null; - - return o; - } - return null; - } + JavaTypeTranslator tr = new JavaTypeTranslator(env.getEnvironment()); + TypeDesc desc = tr.toTypeDesc(expectedType); + String className = desc.getFullName(); + Class clazz = env.getMutableClassLoader().loadClass(className); + return clazz; + } catch (ImportFailureException e) { + return null; + } catch (ClassNotFoundException e) { + return null; + } + } + + public static Class possibleClass(TCon type) { + Class clazz = typeMap.get(type); + if (clazz == null) { + clazz = possibleFromDynamic(type, type.module); + typeMap.put(type, clazz); + } + return clazz; + } + + public static boolean javaIsInstanceOf(org.simantics.scl.compiler.types.Type t, Object o) { + if (t instanceof TCon) { + Class clazz = possibleClass((TCon)t); + if (clazz == null) + return false; + if (!clazz.isAssignableFrom(o.getClass())) + return false; + + return true; + } + return false; + } + + public static Object javaSafeCoerce(org.simantics.scl.compiler.types.Type t, Object o) { + if (t instanceof TCon) { + Class clazz = possibleClass((TCon)t); + if (clazz == null) + return null; + if (!clazz.isAssignableFrom(o.getClass())) + return null; + + return o; + } + return null; + } } diff --git a/org.simantics.g3d/src/org/simantics/g3d/scl/ScriptNodeMap.java b/org.simantics.g3d/src/org/simantics/g3d/scl/ScriptNodeMap.java index 4af8e5a0..37b124e3 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/scl/ScriptNodeMap.java +++ b/org.simantics.g3d/src/org/simantics/g3d/scl/ScriptNodeMap.java @@ -42,190 +42,188 @@ import org.simantics.utils.datastructures.Pair; */ public abstract class ScriptNodeMap implements NodeMap, IMappingListener, NodeListener { - private static final boolean DEBUG = false; - - protected Session session; - protected IMapping mapping; - - protected ParentNode rootNode; - - protected Set nodes = new HashSet(); - - private boolean dirty = false; - - public ScriptNodeMap(Session session, IMapping mapping, ParentNode rootNode) { - this.session = session; - this.mapping = mapping; - this.rootNode = rootNode; - mapping.addMappingListener(this); - rootNode.addListener(this); - } - - - - protected abstract void addActor(E node); - protected abstract void removeActor(E node); - protected abstract void updateActor(E node,Set ids); - - public void repaint() { - dirty = true; - } - - public void populate() { - for (E node : rootNode.getNodes()) { - receiveAdd(node, node.getParentRel(),true); - } - repaint(); - } - - @Override - public E getNode(Object o) { - return null; - } - - @SuppressWarnings("unchecked") - @Override - public Collection getRenderObjects(INode node) { - return Collections.EMPTY_LIST; - } - - @SuppressWarnings("unchecked") - @Override - public ParentNode getRootNode() { - return (ParentNode)rootNode; - } - - - - @Override - public boolean isChangeTracking() { - return changeTracking; - } - - @Override - public void setChangeTracking(boolean enabled) { - changeTracking = enabled; - } - - private boolean changeTracking = true; - - protected Object syncMutex = new Object(); - + private static final boolean DEBUG = false; + + protected Session session; + protected IMapping mapping; + + protected ParentNode rootNode; + + protected Set nodes = new HashSet(); + + private boolean dirty = false; + + public ScriptNodeMap(Session session, IMapping mapping, ParentNode rootNode) { + this.session = session; + this.mapping = mapping; + this.rootNode = rootNode; + mapping.addMappingListener(this); + rootNode.addListener(this); + } + + + + protected abstract void addActor(E node); + protected abstract void removeActor(E node); + protected abstract void updateActor(E node,Set ids); + + public void repaint() { + dirty = true; + } + + public void populate() { + for (E node : rootNode.getNodes()) { + receiveAdd(node, node.getParentRel(),true); + } + repaint(); + } + + @Override + public E getNode(Object o) { + return null; + } + + @SuppressWarnings("unchecked") + @Override + public Collection getRenderObjects(INode node) { + return Collections.EMPTY_LIST; + } + + @SuppressWarnings("unchecked") + @Override + public ParentNode getRootNode() { + return (ParentNode)rootNode; + } + + + + @Override + public boolean isChangeTracking() { + return changeTracking; + } + + @Override + public void setChangeTracking(boolean enabled) { + changeTracking = enabled; + } + + private boolean changeTracking = true; + + protected Object syncMutex = new Object(); + - private List> added = new ArrayList>(); - private List> removed = new ArrayList>(); - private MapSet updated = new MapSet.Hash(); + private List> added = new ArrayList>(); + private List> removed = new ArrayList>(); + private MapSet updated = new MapSet.Hash(); - private boolean rangeModified = false; - - - - @SuppressWarnings("unchecked") - @Override - public void updateRenderObjectsFor(E node) { - nodes.add((E)node); + private boolean rangeModified = false; + + @SuppressWarnings("unchecked") + @Override + public void updateRenderObjectsFor(E node) { + nodes.add((E)node); - } - - @SuppressWarnings("unchecked") - private void receiveAdd(E node, String id, boolean db) { - if (DEBUG) System.out.println("receiveAdd " + debugString(node) + " " + id + " " + db); - synchronized (syncMutex) { - for (Pair n : added) { - if (n.first.equals(node)) - return; - } - if (changeTracking) { - mapping.rangeModified((E)node.getParent()); - } - added.add(new Pair(node, id)); - rangeModified = true; - } - repaint(); - } - - @SuppressWarnings("unchecked") - private void receiveRemove(E node, String id, boolean db) { - if (DEBUG) System.out.println("receiveRemove " + debugString(node) + " " + id + " " + db); - synchronized (syncMutex) { - for (Pair n : removed) { - if (n.first.equals(node)) - return; - } - if (changeTracking && !db) - mapping.rangeModified((E)node.getParent()); - removed.add(new Pair(node, id)); - rangeModified = true; - } - repaint(); - } - - @SuppressWarnings("unchecked") - private void receiveUpdate(E node, String id, boolean db) { - if (DEBUG) System.out.println("receiveUpdate " + debugString(node) + " " + id + " " + db); - synchronized (syncMutex) { + } + + @SuppressWarnings("unchecked") + private void receiveAdd(E node, String id, boolean db) { + if (DEBUG) System.out.println("receiveAdd " + debugString(node) + " " + id + " " + db); + synchronized (syncMutex) { + for (Pair n : added) { + if (n.first.equals(node)) + return; + } + if (changeTracking) { + mapping.rangeModified((E)node.getParent()); + } + added.add(new Pair(node, id)); + rangeModified = true; + } + repaint(); + } + + @SuppressWarnings("unchecked") + private void receiveRemove(E node, String id, boolean db) { + if (DEBUG) System.out.println("receiveRemove " + debugString(node) + " " + id + " " + db); + synchronized (syncMutex) { + for (Pair n : removed) { + if (n.first.equals(node)) + return; + } + if (changeTracking && !db) + mapping.rangeModified((E)node.getParent()); + removed.add(new Pair(node, id)); + rangeModified = true; + } + repaint(); + } + + @SuppressWarnings("unchecked") + private void receiveUpdate(E node, String id, boolean db) { + if (DEBUG) System.out.println("receiveUpdate " + debugString(node) + " " + id + " " + db); + synchronized (syncMutex) { // for (Pair n : updated) { // if (n.first.equals(node)) // return; // } - if (changeTracking && !db) - mapping.rangeModified(node); - //updated.add(new Pair(node, id)); - updated.add(node, id); - rangeModified = true; - } - repaint(); - } - - private boolean graphUpdates = false; - private Set graphModified = new HashSet(); - - private boolean requestCommit = false; - private String commitMessage = null; - - @Override - public void commit(String message) { - requestCommit = true; - commitMessage = message; - } - - protected void doCommit() throws DatabaseException { - session.syncRequest(new WriteRequest() { - - @Override - public void perform(WriteGraph graph) throws DatabaseException { - if (DEBUG) System.out.println("Commit " + commitMessage); - if (commitMessage != null) { - Layer0Utils.addCommentMetadata(graph, commitMessage); - graph.markUndoPoint(); - commitMessage = null; - } - commit(graph); - } - - }); - } - - protected void commit(WriteGraph graph) throws DatabaseException { - synchronized(syncMutex) { - if (DEBUG) System.out.println("Commit"); - graphUpdates = true; - mapping.updateDomain(graph); - graphUpdates = false; - clearDeletes(); - if (DEBUG) System.out.println("Commit done"); - } - } - - - - @Override - public void domainModified() { - if (graphUpdates) - return; - if (DEBUG)System.out.println("domainModified"); - // FIXME : this is called by IMapping id DB thread - dirty = true; + if (changeTracking && !db) + mapping.rangeModified(node); + //updated.add(new Pair(node, id)); + updated.add(node, id); + rangeModified = true; + } + repaint(); + } + + private boolean graphUpdates = false; + private Set graphModified = new HashSet(); + + private boolean requestCommit = false; + private String commitMessage = null; + + @Override + public void commit(String message) { + requestCommit = true; + commitMessage = message; + } + + protected void doCommit() throws DatabaseException { + session.syncRequest(new WriteRequest() { + + @Override + public void perform(WriteGraph graph) throws DatabaseException { + if (DEBUG) System.out.println("Commit " + commitMessage); + if (commitMessage != null) { + Layer0Utils.addCommentMetadata(graph, commitMessage); + graph.markUndoPoint(); + commitMessage = null; + } + commit(graph); + } + + }); + } + + protected void commit(WriteGraph graph) throws DatabaseException { + synchronized(syncMutex) { + if (DEBUG) System.out.println("Commit"); + graphUpdates = true; + mapping.updateDomain(graph); + graphUpdates = false; + clearDeletes(); + if (DEBUG) System.out.println("Commit done"); + } + } + + + + @Override + public void domainModified() { + if (graphUpdates) + return; + if (DEBUG)System.out.println("domainModified"); + // FIXME : this is called by IMapping id DB thread + dirty = true; // session.asyncRequest(new ReadRequest() { // // @SuppressWarnings("unchecked") @@ -234,191 +232,189 @@ public abstract class ScriptNodeMap implements NodeMap> rem = new ArrayList>(); // Removed objects - List> add = new ArrayList>(); // Added objects - MapSet mod = new MapSet.Hash(); // Modified objects - Set propagation = new HashSet(); // Objects with propagated changes - Stack stack = new Stack(); // Stack for handling propagation - Set delete = Collections.synchronizedSet(new HashSet()); // Objects to be completely deleted - Set deleteUC = new HashSet(); - - - - - /** - * When objects are removed (either from Java or Graph), after remove processing the Java objects remain in mapping cache. - * This causes problems with Undo and Redo, whcih the end up re-using the removed objects from mapping cache. - * - * This code here synchronizes removed and added objects to collect deletable objects. (a deletable object is one which is removed but not added). - * - */ - protected void syncDeletes() { - deleteUC.clear(); - for (Pair n : removed) { - deleteUC.add(n.first); - } - for (Pair n : added) { - deleteUC.remove(n.first); - } - if (DEBUG && deleteUC.size() > 0) { - System.out.println("Delete sync"); - for (E n : delete) { - System.out.println(debugString(n)); - } - } - delete.addAll(deleteUC); - deleteUC.clear(); - } - - /** - * Clears deletable objects from mapping cache. - */ - protected void clearDeletes() { - if (DEBUG && delete.size() > 0) System.out.println("Delete"); - for (E n : delete) { - if (DEBUG) System.out.println(debugString(n)); - mapping.getRange().remove(n); - } - delete.clear(); - } - - protected String debugString(E n) { - return n + "@" + Integer.toHexString(n.hashCode()); - } - - @SuppressWarnings("unchecked") - protected void updateCycle() { - rem.clear(); - add.clear(); - mod.clear(); - propagation.clear(); - - - synchronized (syncMutex) { - rem.addAll(removed); - add.addAll(added); - for (E e : updated.getKeys()) { - for (String s : updated.getValues(e)) { - mod.add(e, s); - } - } - syncDeletes(); - removed.clear(); - added.clear(); - updated.clear(); - } - - for (Pair n : rem) { - stopListening(n.first); - removeActor(n.first); - } - - for (Pair n : add) { - addActor(n.first); - listen(n.first); - } - - for (E e : mod.getKeys()) { - Set ids = mod.getValues(e); - if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) { - if (!propagation.contains(e)) - propagation.add(e); - } - } + + // Reusable containers for data synchronisation + List> rem = new ArrayList>(); // Removed objects + List> add = new ArrayList>(); // Added objects + MapSet mod = new MapSet.Hash(); // Modified objects + Set propagation = new HashSet(); // Objects with propagated changes + Stack stack = new Stack(); // Stack for handling propagation + Set delete = Collections.synchronizedSet(new HashSet()); // Objects to be completely deleted + Set deleteUC = new HashSet(); + + + + /** + * When objects are removed (either from Java or Graph), after remove processing the Java objects remain in mapping cache. + * This causes problems with Undo and Redo, whcih the end up re-using the removed objects from mapping cache. + * + * This code here synchronizes removed and added objects to collect deletable objects. (a deletable object is one which is removed but not added). + * + */ + protected void syncDeletes() { + deleteUC.clear(); + for (Pair n : removed) { + deleteUC.add(n.first); + } + for (Pair n : added) { + deleteUC.remove(n.first); + } + if (DEBUG && deleteUC.size() > 0) { + System.out.println("Delete sync"); + for (E n : delete) { + System.out.println(debugString(n)); + } + } + delete.addAll(deleteUC); + deleteUC.clear(); + } + + /** + * Clears deletable objects from mapping cache. + */ + protected void clearDeletes() { + if (DEBUG && delete.size() > 0) System.out.println("Delete"); + for (E n : delete) { + if (DEBUG) System.out.println(debugString(n)); + mapping.getRange().remove(n); + } + delete.clear(); + } + + protected String debugString(E n) { + return n + "@" + Integer.toHexString(n.hashCode()); + } + + @SuppressWarnings("unchecked") + protected void updateCycle() { + rem.clear(); + add.clear(); + mod.clear(); + propagation.clear(); + + + synchronized (syncMutex) { + rem.addAll(removed); + add.addAll(added); + for (E e : updated.getKeys()) { + for (String s : updated.getValues(e)) { + mod.add(e, s); + } + } + syncDeletes(); + removed.clear(); + added.clear(); + updated.clear(); + } + + for (Pair n : rem) { + stopListening(n.first); + removeActor(n.first); + } + + for (Pair n : add) { + addActor(n.first); + listen(n.first); + } + + for (E e : mod.getKeys()) { + Set ids = mod.getValues(e); + if (ids.contains(G3D.URIs.hasPosition) || ids.contains(G3D.URIs.hasOrientation)) { + if (!propagation.contains(e)) + propagation.add(e); + } + } - if (propagation.size() > 0) { - stack.clear(); - stack.addAll(propagation); - propagation.clear(); - while (!stack.isEmpty()) { - E node = stack.pop(); - if (propagation.contains(node)) - continue; - propagation.add(node); - for (NodeListener l : node.getListeners()) { - if (l == this) { - //changeTracking = false; - //l.propertyChanged(node, G3D.URIs.hasPosition); - //changeTracking = true; - } else { - l.propertyChanged(node, G3D.URIs.hasWorldPosition); - } - } - if (node instanceof ParentNode) { - stack.addAll(((ParentNode)node).getNodes()); - } - } - } - + if (propagation.size() > 0) { + stack.clear(); + stack.addAll(propagation); + propagation.clear(); + while (!stack.isEmpty()) { + E node = stack.pop(); + if (propagation.contains(node)) + continue; + propagation.add(node); + for (NodeListener l : node.getListeners()) { + if (l == this) { + //changeTracking = false; + //l.propertyChanged(node, G3D.URIs.hasPosition); + //changeTracking = true; + } else { + l.propertyChanged(node, G3D.URIs.hasWorldPosition); + } + } + if (node instanceof ParentNode) { + stack.addAll(((ParentNode)node).getNodes()); + } + } + } + // synchronized (syncMutex) { // rem.addAll(removed); // add.addAll(added); @@ -432,119 +428,119 @@ public abstract class ScriptNodeMap implements NodeMap ids = mod.getValues(e); - updateActor(e,ids); - } - - - for (Pair n : rem) { - for (NodeListener l : nodeListeners) - l.nodeRemoved(null, n.first, n.second); - } - for (Pair n : add) { - for (NodeListener l : nodeListeners) - l.nodeAdded(n.first.getParent(), n.first, n.second); - } + + for (E e : mod.getKeys()) { + Set ids = mod.getValues(e); + updateActor(e,ids); + } + + + for (Pair n : rem) { + for (NodeListener l : nodeListeners) + l.nodeRemoved(null, n.first, n.second); + } + for (Pair n : add) { + for (NodeListener l : nodeListeners) + l.nodeAdded(n.first.getParent(), n.first, n.second); + } // for (Pair n : mod) { // for (NodeListener l : nodeListeners) // l.propertyChanged(n.first, n.second); // } - for (E e : mod.getKeys()) { - for (NodeListener l : nodeListeners) - for (String s : mod.getValues(e)) - l.propertyChanged(e, s); - } - - synchronized (syncMutex) { - if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0) - rangeModified = false; - } - } - - @SuppressWarnings("unchecked") - private void listen(INode node) { - node.addListener(this); - if (node instanceof ParentNode) { - ParentNode parentNode = (ParentNode)node; - for (INode n : parentNode.getNodes()) - listen(n); - } - } - - private void stopListening(INode node) { - node.removeListener(this); - if (node instanceof ParentNode) { - @SuppressWarnings("unchecked") - ParentNode parentNode = (ParentNode)node; - for (INode n : parentNode.getNodes()) - stopListening(n); - } - } - - @SuppressWarnings("unchecked") - @Override - public void propertyChanged(INode node, String id) { - //receiveUpdate((E)node, id, graphUpdates); - receiveUpdate((E)node, id, graphModified.contains(node)); - - } - - @SuppressWarnings("unchecked") - @Override - public void nodeAdded(ParentNode node, INode child, - String rel) { - if (DEBUG) System.out.println("Node added " + child + " parent " + node); - //receiveAdd((E)child, rel ,graphUpdates); - receiveAdd((E)child, rel ,graphModified.contains(node)); - - } - - @SuppressWarnings("unchecked") - @Override - public void nodeRemoved(ParentNode node, INode child, - String rel) { - if (DEBUG) System.out.println("Node removed " + child + " parent " + node); - //receiveRemove((E)child, rel, graphUpdates); - receiveRemove((E)child, rel, graphModified.contains(node)); - - //FIXME : sometimes removed structural models cause ObjMap to add their children again. - // removing the listener here prevents corruption of visual model, but better fix is needed. - stopListening(child); - } - - @Override - public void delete() { - - changeTracking = false; - mapping.removeMappingListener(this); + for (E e : mod.getKeys()) { + for (NodeListener l : nodeListeners) + for (String s : mod.getValues(e)) + l.propertyChanged(e, s); + } + + synchronized (syncMutex) { + if (added.isEmpty() && removed.isEmpty() && updated.getKeys().size() == 0) + rangeModified = false; + } + } + + @SuppressWarnings("unchecked") + private void listen(INode node) { + node.addListener(this); + if (node instanceof ParentNode) { + ParentNode parentNode = (ParentNode)node; + for (INode n : parentNode.getNodes()) + listen(n); + } + } + + private void stopListening(INode node) { + node.removeListener(this); + if (node instanceof ParentNode) { + @SuppressWarnings("unchecked") + ParentNode parentNode = (ParentNode)node; + for (INode n : parentNode.getNodes()) + stopListening(n); + } + } + + @SuppressWarnings("unchecked") + @Override + public void propertyChanged(INode node, String id) { + //receiveUpdate((E)node, id, graphUpdates); + receiveUpdate((E)node, id, graphModified.contains(node)); + + } + + @SuppressWarnings("unchecked") + @Override + public void nodeAdded(ParentNode node, INode child, + String rel) { + if (DEBUG) System.out.println("Node added " + child + " parent " + node); + //receiveAdd((E)child, rel ,graphUpdates); + receiveAdd((E)child, rel ,graphModified.contains(node)); + + } + + @SuppressWarnings("unchecked") + @Override + public void nodeRemoved(ParentNode node, INode child, + String rel) { + if (DEBUG) System.out.println("Node removed " + child + " parent " + node); + //receiveRemove((E)child, rel, graphUpdates); + receiveRemove((E)child, rel, graphModified.contains(node)); + + //FIXME : sometimes removed structural models cause ObjMap to add their children again. + // removing the listener here prevents corruption of visual model, but better fix is needed. + stopListening(child); + } + + @Override + public void delete() { + + changeTracking = false; + mapping.removeMappingListener(this); - for (E node : nodes) { - node.removeListener(this); - removeActor(node); - node.cleanup(); - } - nodes.clear(); - } - - - private List nodeListeners = new ArrayList(); - @Override - public void addListener(NodeListener listener) { - nodeListeners.add(listener); - - } - - @Override - public void removeListener(NodeListener listener) { - nodeListeners.remove(listener); - - } - - public IMapping getMapping() { - return mapping; - } - - + for (E node : nodes) { + node.removeListener(this); + removeActor(node); + node.cleanup(); + } + nodes.clear(); + } + + + private List nodeListeners = new ArrayList(); + @Override + public void addListener(NodeListener listener) { + nodeListeners.add(listener); + + } + + @Override + public void removeListener(NodeListener listener) { + nodeListeners.remove(listener); + + } + + public IMapping getMapping() { + return mapping; + } + + } diff --git a/org.simantics.g3d/src/org/simantics/g3d/shape/ArcCylinder.java b/org.simantics.g3d/src/org/simantics/g3d/shape/ArcCylinder.java index 6e4a3d3b..6f82e33c 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/shape/ArcCylinder.java +++ b/org.simantics.g3d/src/org/simantics/g3d/shape/ArcCylinder.java @@ -178,9 +178,9 @@ public class ArcCylinder { int iv = c*resolution + s; /* - iv+1 ---- iv + resolution + 1 - | /| - |/ | + iv+1 ---- iv + resolution + 1 + | /| + |/ | iv ---- iv + resolution */ if (s < resolution - 1) { diff --git a/org.simantics.g3d/src/org/simantics/g3d/shape/Mesh.java b/org.simantics.g3d/src/org/simantics/g3d/shape/Mesh.java index a45cf812..22355f2c 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/shape/Mesh.java +++ b/org.simantics.g3d/src/org/simantics/g3d/shape/Mesh.java @@ -82,27 +82,27 @@ public class Mesh { for (int i = 0; i < vertices.size(); i++) { normals.add(new Vector3d()); } - Vector3d v1 = new Vector3d(); - Vector3d v2 = new Vector3d(); - Vector3d v3 = new Vector3d(); - Vector3d t1 = new Vector3d(); - Vector3d t2 = new Vector3d(); - Vector3d n = new Vector3d(); - for (int i = 0; i < indices.size(); i+=3) { - v1.set(vertices.get(i)); - v2.set(vertices.get(i+1)); - v3.set(vertices.get(i+2)); - t1.sub(v3,v1); - t2.sub(v2,v1); - n.cross(t2, t1); - normals.get(i).add(n); - normals.get(i+1).add(n); - normals.get(i+2).add(n); - } - for (int i = 0; i < normals.size(); i++) { - ((Vector3d)normals.get(i)).normalize(); - } - } + Vector3d v1 = new Vector3d(); + Vector3d v2 = new Vector3d(); + Vector3d v3 = new Vector3d(); + Vector3d t1 = new Vector3d(); + Vector3d t2 = new Vector3d(); + Vector3d n = new Vector3d(); + for (int i = 0; i < indices.size(); i+=3) { + v1.set(vertices.get(i)); + v2.set(vertices.get(i+1)); + v3.set(vertices.get(i+2)); + t1.sub(v3,v1); + t2.sub(v2,v1); + n.cross(t2, t1); + normals.get(i).add(n); + normals.get(i+1).add(n); + normals.get(i+2).add(n); + } + for (int i = 0; i < normals.size(); i++) { + ((Vector3d)normals.get(i)).normalize(); + } + } public void translate(Vector3d v) { for (int i = 0; i < vertices.size(); i++) { diff --git a/org.simantics.g3d/src/org/simantics/g3d/shape/Tube.java b/org.simantics.g3d/src/org/simantics/g3d/shape/Tube.java index 0300f068..dc7ff4e5 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/shape/Tube.java +++ b/org.simantics.g3d/src/org/simantics/g3d/shape/Tube.java @@ -194,9 +194,9 @@ public class Tube { int iv = c*resolution + s; /* - iv+1 ---- iv + resolution + 1 - | /| - |/ | + iv+1 ---- iv + resolution + 1 + | /| + |/ | iv ---- iv + resolution */ if (s < resolution - 1) { diff --git a/org.simantics.g3d/src/org/simantics/g3d/toolbar/ToolBarCommandRegistry.java b/org.simantics.g3d/src/org/simantics/g3d/toolbar/ToolBarCommandRegistry.java index 9a1775e4..97262a8d 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/toolbar/ToolBarCommandRegistry.java +++ b/org.simantics.g3d/src/org/simantics/g3d/toolbar/ToolBarCommandRegistry.java @@ -92,9 +92,9 @@ public class ToolBarCommandRegistry implements IExtensionChangeHandler { } @Override - public void addExtension(IExtensionTracker tracker, IExtension extension) { - loadExtensions(extension.getConfigurationElements()); - } + public void addExtension(IExtensionTracker tracker, IExtension extension) { + loadExtensions(extension.getConfigurationElements()); + } @Override public synchronized void removeExtension(IExtension extension, Object[] objects) { diff --git a/org.simantics.g3d/src/org/simantics/g3d/toolbar/ToolbarContributor.java b/org.simantics.g3d/src/org/simantics/g3d/toolbar/ToolbarContributor.java index d9cc9529..70fb9c6b 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/toolbar/ToolbarContributor.java +++ b/org.simantics.g3d/src/org/simantics/g3d/toolbar/ToolbarContributor.java @@ -75,15 +75,15 @@ public abstract class ToolbarContributor extends EditorActionBarContributor impl private IEditorPart activePart; private Set parts = new HashSet(); - IToolBarManager mgr; - - - ICommandService service; - IHandlerService handlerService; - List items = new ArrayList(); - MapList actions = new MapList(); - - CommandStateRegistry stateRegistry; + IToolBarManager mgr; + + + ICommandService service; + IHandlerService handlerService; + List items = new ArrayList(); + MapList actions = new MapList(); + + CommandStateRegistry stateRegistry; private Map menus = new HashMap(); @@ -97,15 +97,15 @@ public abstract class ToolbarContributor extends EditorActionBarContributor impl public void contributeToCoolBar(ICoolBarManager coolBarManager) { IContributionItem toolBar = coolBarManager.find(getToolbarId()); - if (toolBar instanceof ToolBarContributionItem) - mgr = ((ToolBarContributionItem) toolBar).getToolBarManager(); - if (mgr == null) - return; - - createCommands(); - - mgr.markDirty(); - + if (toolBar instanceof ToolBarContributionItem) + mgr = ((ToolBarContributionItem) toolBar).getToolBarManager(); + if (mgr == null) + return; + + createCommands(); + + mgr.markDirty(); + } private void createCommands() { @@ -205,29 +205,29 @@ public abstract class ToolbarContributor extends EditorActionBarContributor impl private void setContext(IEditorPart part) { this.activePart = part; - if (!parts.contains(activePart)) { - activePart.getSite().getPage().addPartListener(this); - } - if (part != null) { - for (String commandId : actions.getKeys()) { + if (!parts.contains(activePart)) { + activePart.getSite().getPage().addPartListener(this); + } + if (part != null) { + for (String commandId : actions.getKeys()) { for (CommandAction a : actions.getValues(commandId)) { a.setEnabled(true); } } - updateActionBars(part); - } else { + updateActionBars(part); + } else { for (String commandId : actions.getKeys()) { for (CommandAction a : actions.getValues(commandId)) { a.setEnabled(false); } } - } - } + } + } - private void updateActionBars(IEditorPart part) { - restoreActionStates(); - part.getEditorSite().getActionBars().updateActionBars(); - } + private void updateActionBars(IEditorPart part) { + restoreActionStates(); + part.getEditorSite().getActionBars().updateActionBars(); + } @Override public void dispose() { @@ -239,7 +239,7 @@ public abstract class ToolbarContributor extends EditorActionBarContributor impl mgr.markDirty(); mgr.update(true); if (activePart != null) { - activePart.getEditorSite().getActionBars().updateActionBars(); + activePart.getEditorSite().getActionBars().updateActionBars(); } for (String commandId : actions.getKeys()) { diff --git a/org.simantics.g3d/src/org/simantics/g3d/tools/AdaptationUtils.java b/org.simantics.g3d/src/org/simantics/g3d/tools/AdaptationUtils.java index d0b8731a..f6c7f275 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/tools/AdaptationUtils.java +++ b/org.simantics.g3d/src/org/simantics/g3d/tools/AdaptationUtils.java @@ -33,32 +33,32 @@ public class AdaptationUtils { * @return object of given class or null */ @SuppressWarnings("unchecked") - public static T adaptToSingle(Object o, Class clazz) { - if (o instanceof IStructuredSelection) { - IStructuredSelection iss = (IStructuredSelection) o; - if (iss.size() != 1) - return null; - Object element = iss.getFirstElement(); - return adaptToSingle(element, clazz); - } else if (o instanceof Collection) { - Collection c = (Collection) o; - if (c.size() != 1) - return null; - Object element = c.iterator().next(); - return adaptToSingle(element, clazz); - } else if (o instanceof IAdaptable) { - IAdaptable a = (IAdaptable) o; - return (T)a.getAdapter(clazz); - } else if (clazz.isInstance(o)) { - return (T)o; - } else if (o instanceof Container) { - Object obj = ((Container) o).get(); - if (obj == o) - return null; - return adaptToSingle(obj, clazz); - } - return null; - } + public static T adaptToSingle(Object o, Class clazz) { + if (o instanceof IStructuredSelection) { + IStructuredSelection iss = (IStructuredSelection) o; + if (iss.size() != 1) + return null; + Object element = iss.getFirstElement(); + return adaptToSingle(element, clazz); + } else if (o instanceof Collection) { + Collection c = (Collection) o; + if (c.size() != 1) + return null; + Object element = c.iterator().next(); + return adaptToSingle(element, clazz); + } else if (o instanceof IAdaptable) { + IAdaptable a = (IAdaptable) o; + return (T)a.getAdapter(clazz); + } else if (clazz.isInstance(o)) { + return (T)o; + } else if (o instanceof Container) { + Object obj = ((Container) o).get(); + if (obj == o) + return null; + return adaptToSingle(obj, clazz); + } + return null; + } /** * * @param o @@ -68,24 +68,24 @@ public class AdaptationUtils { @SuppressWarnings("unchecked") public static Collection adaptToCollection(Object o, Class clazz) { if (clazz.isInstance(o)) { - return Collections.singletonList((T)o); + return Collections.singletonList((T)o); } else if (o instanceof IStructuredSelection) { - IStructuredSelection iss = (IStructuredSelection) o; - return adaptToCollection(iss.toArray(), clazz); - } else if (o instanceof Collection) { - Collection c = (Collection) o; - return adaptToCollection(c.toArray(), clazz); - } else if (o instanceof IAdaptable) { - IAdaptable a = (IAdaptable) o; - return Collections.singletonList((T)a.getAdapter(clazz)); - } else if (o instanceof Container) { - Object obj = ((Container) o).get(); - if (obj == o) - return Collections.EMPTY_LIST; - return adaptToCollection(obj, clazz); - } - return Collections.EMPTY_LIST; - } + IStructuredSelection iss = (IStructuredSelection) o; + return adaptToCollection(iss.toArray(), clazz); + } else if (o instanceof Collection) { + Collection c = (Collection) o; + return adaptToCollection(c.toArray(), clazz); + } else if (o instanceof IAdaptable) { + IAdaptable a = (IAdaptable) o; + return Collections.singletonList((T)a.getAdapter(clazz)); + } else if (o instanceof Container) { + Object obj = ((Container) o).get(); + if (obj == o) + return Collections.EMPTY_LIST; + return adaptToCollection(obj, clazz); + } + return Collections.EMPTY_LIST; + } public static Collection adaptToCollection(Object arr[], Class clazz) { Collection result = new ArrayList(); diff --git a/org.simantics.g3d/src/org/simantics/g3d/tools/ConstraintDetector.java b/org.simantics.g3d/src/org/simantics/g3d/tools/ConstraintDetector.java index 6af54146..fe8a4b2d 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/tools/ConstraintDetector.java +++ b/org.simantics.g3d/src/org/simantics/g3d/tools/ConstraintDetector.java @@ -22,187 +22,187 @@ import org.simantics.g3d.scenegraph.IG3DNode; import org.simantics.g3d.shape.Color4d; public abstract class ConstraintDetector { - - private static final int X = 0; - private static final int Y = 1; - private static final int Z = 2; - - + + private static final int X = 0; + private static final int Y = 1; + private static final int Z = 2; + + // private ThreeDimensionalEditorBase editor; - //private G3DNode constraintReference = null; - private IG3DNode constraintReference = null; - private ArrayList constraintPoints = new ArrayList(); - private ArrayList constraintDirections = new ArrayList(); + //private G3DNode constraintReference = null; + private IG3DNode constraintReference = null; + private ArrayList constraintPoints = new ArrayList(); + private ArrayList constraintDirections = new ArrayList(); // private MaterialState ms; - - private Color4d xColor = new Color4d(1.f,0.f,0.f,1.f); - private Color4d yColor = new Color4d(0.f,1.f,0.f,1.f); - private Color4d zColor = new Color4d(0.f,0.f,1.f,1.f); - - + + private Color4d xColor = new Color4d(1.f,0.f,0.f,1.f); + private Color4d yColor = new Color4d(0.f,1.f,0.f,1.f); + private Color4d zColor = new Color4d(0.f,0.f,1.f,1.f); + + // public ConstraintDetector(ThreeDimensionalEditorBase editor) { // this.editor = editor; // ms = editor.getRenderingComponent().getDisplaySystem().getRenderer().createMaterialState(); // ms.setEmissive(new ColorRGBA(1.f,1.f,1.f,1.f)); // ms.setColorMaterial(MaterialState.CM_EMISSIVE); // } - + - public void clearConstraints() { - //System.out.println("ConstraintDetector.clearConstraints()"); - constraintPoints.clear(); - constraintDirections.clear(); - } - - private void updateConstraints() { - clearConstraints(); - if (constraintReference == null) - return; - Constraint c = (Constraint)constraintReference.getAdapter(Constraint.class); - if (c == null) - return; - constraintPoints.addAll(c.points); - constraintDirections.addAll(c.dirs); - } - - - public ArrayList getConstraintPoints() { - return constraintPoints; - } - - public ArrayList getConstraintDirections() { - return constraintDirections; - } + public void clearConstraints() { + //System.out.println("ConstraintDetector.clearConstraints()"); + constraintPoints.clear(); + constraintDirections.clear(); + } + + private void updateConstraints() { + clearConstraints(); + if (constraintReference == null) + return; + Constraint c = (Constraint)constraintReference.getAdapter(Constraint.class); + if (c == null) + return; + constraintPoints.addAll(c.points); + constraintDirections.addAll(c.dirs); + } + + + public ArrayList getConstraintPoints() { + return constraintPoints; + } + + public ArrayList getConstraintDirections() { + return constraintDirections; + } - public void updateConstraintReference(IG3DNode node) { - if (constraintReference != null && !constraintReference.equals(node)) { - constraintReference = node; - updateConstraints(); - } else if (node != null){ - constraintReference = node; - updateConstraints(); - } - - } - - public void addContraintPoint(Point3d p) { - //System.out.println("ConstraintDetector.addConstraintPoint() " + p); - constraintPoints.add(p); - } - - public void addContraintDirection(Vector3d v) { - //System.out.println("ConstraintDetector.addConstraintDirection() " + v); - constraintDirections.add(v); - } - - private double snapAngle = 0.1; - private String snapString = ""; + public void updateConstraintReference(IG3DNode node) { + if (constraintReference != null && !constraintReference.equals(node)) { + constraintReference = node; + updateConstraints(); + } else if (node != null){ + constraintReference = node; + updateConstraints(); + } + + } + + public void addContraintPoint(Point3d p) { + //System.out.println("ConstraintDetector.addConstraintPoint() " + p); + constraintPoints.add(p); + } + + public void addContraintDirection(Vector3d v) { + //System.out.println("ConstraintDetector.addConstraintDirection() " + v); + constraintDirections.add(v); + } + + private double snapAngle = 0.1; + private String snapString = ""; // private ArrayList constraintHighlights = new ArrayList(); - - public Point3d getSnappedPoint(Vector3d pickPoint, Vector3d pickDir, Vector3d requestedPoint) { - - - Vector3d snappedPoint = new Vector3d(); - Vector3d t = new Vector3d(); - Point3d currentPoint = null; - // TODO : snap to closest angle - for (Vector3d constraintDir : constraintDirections) { - - MathTools.intersectStraightStraight(pickPoint,pickDir, requestedPoint, constraintDir, t, snappedPoint); - t.sub(snappedPoint); - if (t.lengthSquared() < snapAngle) { - - snapString += "Angle snap "; - currentPoint = new Point3d(snappedPoint); - break; - } - } - if (currentPoint != null) { - Vector3d dir = new Vector3d(currentPoint); - dir.sub(requestedPoint); - Point3d p = getPointSnap(requestedPoint, dir); - if (p != null) - currentPoint = p; - } else { - List distances = new ArrayList(); - List snapPoints = new ArrayList(); - List snapStrings = new ArrayList(); - List snapColors = new ArrayList(); - for (Point3d constraintPoint : constraintPoints) { - distances.clear(); - snapPoints.clear(); - snapStrings.clear(); - MathTools.intersectStraightStraight(new Vector3d(constraintPoint), new Vector3d(1.0, 0.0, 0.0), - pickPoint, pickDir, snappedPoint, t); - t.sub(snappedPoint); - double distance = t.lengthSquared(); - if (distance < snapAngle) { - distances.add(distance); - snapPoints.add(new Point3d(snappedPoint)); - snapStrings.add("Point x-snap "); - snapColors.add(xColor); - } - MathTools.intersectStraightStraight(new Vector3d(constraintPoint), new Vector3d(0.0, 1.0, 0.0), - pickPoint, pickDir, snappedPoint, t); - t.sub(snappedPoint); - distance = t.lengthSquared(); - if (distance < snapAngle) { - distances.add(distance); - snapPoints.add(new Point3d(snappedPoint)); - snapStrings.add("Point y-snap "); - snapColors.add(yColor); - } - MathTools.intersectStraightStraight(new Vector3d(constraintPoint), new Vector3d(0.0, 0.0, 1.0), - pickPoint, pickDir, snappedPoint, t); - t.sub(snappedPoint); - distance = t.lengthSquared(); - if (distance < snapAngle) { - distances.add(distance); - snapPoints.add(new Point3d(snappedPoint)); - snapStrings.add("Point z-snap "); - snapColors.add(zColor); - - } - if (distances.size() > 0) { - if (distances.size() > 1) { - // more than one axes snape - Vector3d ref = MathTools.closestPointOnStraight(constraintPoint, new Point3d(pickPoint), pickDir); - ref.sub(constraintPoint); - distance = ref.lengthSquared(); - if (distance < snapAngle) { - // we are close enought to point, so we'll just snap there - currentPoint = new Point3d(constraintPoint); - snapString += "Point snap "; - } else { - // select the closest of axes snap to - int min = 0; - for (int i = 1; i < distances.size(); i++) { - if (distances.get(i) < distances.get(min)) - min = i; - } - currentPoint = snapPoints.get(min); - addConstrainLineHighlight(currentPoint, constraintPoint,snapColors.get(min)); - snapString += snapStrings.get(min); - } - } else { - // only one of the axes snaps - currentPoint = snapPoints.get(0); - addConstrainLineHighlight(currentPoint, constraintPoint,snapColors.get(0)); - snapString += snapStrings.get(0); - } - break; - } - } - } - return currentPoint; + + public Point3d getSnappedPoint(Vector3d pickPoint, Vector3d pickDir, Vector3d requestedPoint) { + + + Vector3d snappedPoint = new Vector3d(); + Vector3d t = new Vector3d(); + Point3d currentPoint = null; + // TODO : snap to closest angle + for (Vector3d constraintDir : constraintDirections) { + + MathTools.intersectStraightStraight(pickPoint,pickDir, requestedPoint, constraintDir, t, snappedPoint); + t.sub(snappedPoint); + if (t.lengthSquared() < snapAngle) { + + snapString += "Angle snap "; + currentPoint = new Point3d(snappedPoint); + break; + } + } + if (currentPoint != null) { + Vector3d dir = new Vector3d(currentPoint); + dir.sub(requestedPoint); + Point3d p = getPointSnap(requestedPoint, dir); + if (p != null) + currentPoint = p; + } else { + List distances = new ArrayList(); + List snapPoints = new ArrayList(); + List snapStrings = new ArrayList(); + List snapColors = new ArrayList(); + for (Point3d constraintPoint : constraintPoints) { + distances.clear(); + snapPoints.clear(); + snapStrings.clear(); + MathTools.intersectStraightStraight(new Vector3d(constraintPoint), new Vector3d(1.0, 0.0, 0.0), + pickPoint, pickDir, snappedPoint, t); + t.sub(snappedPoint); + double distance = t.lengthSquared(); + if (distance < snapAngle) { + distances.add(distance); + snapPoints.add(new Point3d(snappedPoint)); + snapStrings.add("Point x-snap "); + snapColors.add(xColor); + } + MathTools.intersectStraightStraight(new Vector3d(constraintPoint), new Vector3d(0.0, 1.0, 0.0), + pickPoint, pickDir, snappedPoint, t); + t.sub(snappedPoint); + distance = t.lengthSquared(); + if (distance < snapAngle) { + distances.add(distance); + snapPoints.add(new Point3d(snappedPoint)); + snapStrings.add("Point y-snap "); + snapColors.add(yColor); + } + MathTools.intersectStraightStraight(new Vector3d(constraintPoint), new Vector3d(0.0, 0.0, 1.0), + pickPoint, pickDir, snappedPoint, t); + t.sub(snappedPoint); + distance = t.lengthSquared(); + if (distance < snapAngle) { + distances.add(distance); + snapPoints.add(new Point3d(snappedPoint)); + snapStrings.add("Point z-snap "); + snapColors.add(zColor); + + } + if (distances.size() > 0) { + if (distances.size() > 1) { + // more than one axes snape + Vector3d ref = MathTools.closestPointOnStraight(constraintPoint, new Point3d(pickPoint), pickDir); + ref.sub(constraintPoint); + distance = ref.lengthSquared(); + if (distance < snapAngle) { + // we are close enought to point, so we'll just snap there + currentPoint = new Point3d(constraintPoint); + snapString += "Point snap "; + } else { + // select the closest of axes snap to + int min = 0; + for (int i = 1; i < distances.size(); i++) { + if (distances.get(i) < distances.get(min)) + min = i; + } + currentPoint = snapPoints.get(min); + addConstrainLineHighlight(currentPoint, constraintPoint,snapColors.get(min)); + snapString += snapStrings.get(min); + } + } else { + // only one of the axes snaps + currentPoint = snapPoints.get(0); + addConstrainLineHighlight(currentPoint, constraintPoint,snapColors.get(0)); + snapString += snapStrings.get(0); + } + break; + } + } + } + return currentPoint; - } - - public abstract void clearConstraintHighlights(); - protected abstract void addConstrainLineHighlight(Point3d p1, Point3d p2, Color4d color); - protected abstract void addConstrainPlaneHighlight(Point3d p1, Point3d p2, int axis); - + } + + public abstract void clearConstraintHighlights(); + protected abstract void addConstrainLineHighlight(Point3d p1, Point3d p2, Color4d color); + protected abstract void addConstrainPlaneHighlight(Point3d p1, Point3d p2, int axis); + // public void clearConstraintHighlights() { // snapString = ""; // @@ -267,152 +267,152 @@ public abstract class ConstraintDetector { // shape.setRenderState(ms); // constraintHighlights.add(shape); // } - - /** - * Snaps position to axis-aligned planes defined by constraint points - * Form of position is p+v, meaning that the position that is snapped is requestedPoint + requestedDir - * @param requestedPoint one part of the position to be snapped - * @param requestedDir second part of the position to be snapped and direction that the position is allowed to move - * @return - */ - public Point3d getPointSnap(Vector3d requestedPoint, Vector3d requestedDir) { - - Vector3d snappedPoint = new Vector3d(); - Point3d currentPoint = null; - double u[] = new double[1]; - List p1s = new ArrayList(); - List p2s = new ArrayList(); - List axes = new ArrayList(); - - for (Point3d constraintPoint : constraintPoints) { - boolean snap = false; - - if (MathTools.intersectStraightPlane(requestedPoint, requestedDir, new Vector3d(constraintPoint), getAxialVector(X), snappedPoint,u) && Math.abs(1.0 - u[0]) < snapAngle) { - currentPoint = new Point3d(snappedPoint); - //snapString += "Point/Plane x-snap "; - snap = true; - //addConstrainPlaneHighlight(constraintPoint, currentPoint,X); - p1s.add(constraintPoint); - p2s.add(currentPoint); - axes.add(X); - } - - if (MathTools.intersectStraightPlane(requestedPoint, requestedDir, new Vector3d(constraintPoint), getAxialVector(Y), snappedPoint,u) && Math.abs(1.0 - u[0]) < snapAngle) { - currentPoint = new Point3d(snappedPoint); - //snapString += "Point/Plane y-snap "; - snap = true; - //addConstrainPlaneHighlight(constraintPoint, currentPoint,Y); - p1s.add(constraintPoint); - p2s.add(currentPoint); - axes.add(Y); - } - - if (MathTools.intersectStraightPlane(requestedPoint, requestedDir, new Vector3d(constraintPoint), getAxialVector(Z), snappedPoint,u) && Math.abs(1.0 - u[0]) < snapAngle) { - currentPoint = new Point3d(snappedPoint); - //snapString += "Point/Plane z-snap "; - snap = true; - //addConstrainPlaneHighlight(constraintPoint, currentPoint,Z); - p1s.add(constraintPoint); - p2s.add(currentPoint); - axes.add(Z); - } - if (snap) - break; - } - if (p1s.size() == 0) - return null; - if (p1s.size() == 1) { - snapString += "Point/Plane "; - switch (axes.get(0)) { - case X: - snapString += "x"; - break; - case Y: - snapString += "y"; - break; - case Z: - snapString += "z"; - break; - } - snapString += "-snap "; - addConstrainPlaneHighlight(p1s.get(0), p2s.get(0),axes.get(0)); - return currentPoint; - } else if (p1s.size() == 3){ - // all axial planes are intersecting, snapping point must be the constraint point - // all constraint points are the same, so just pick the first in the list - snapString += "Point/Point "; - return p1s.get(0); - } else { - Vector3d dir = new Vector3d(); - dir.cross(getAxialVector(axes.get(0)), getAxialVector(axes.get(1))); - currentPoint = new Point3d(MathTools.closestPointOnStraight(currentPoint, p1s.get(0), dir)); - addConstrainLineHighlight(p1s.get(0), currentPoint, xColor); - snapString += "Point/Line "; - return currentPoint; - } - - } - - private Vector3d getAxialVector(int axis) { - switch (axis) { - case X: - return new Vector3d(1.0,0.0,0.0); - case Y: - return new Vector3d(0.0,1.0,0.0); - case Z: - return new Vector3d(0.0,0.0,1.0); - } - throw new RuntimeException("Unknown axis " + axis); - } - - /** - * Snaps the position to axis-aligned planes defined by constraint points - * @param requestedPoint point that is snapped - * @param requestedDir direction that point is allowed to move - * @return - */ - - public Point3d getPointSnap2(Vector3d requestedPoint, Vector3d requestedDir) { - - Vector3d snappedPoint = new Vector3d(); - Point3d currentPoint = null; - double u[] = new double[1]; - //System.out.println(requestedPoint + " " + requestedDir); - for (Point3d constraintPoint : constraintPoints) { - boolean snap = false; - //System.out.print(constraintPoint + " "); - if (MathTools.intersectStraightPlane(requestedPoint, requestedDir, new Vector3d(constraintPoint), new Vector3d(1.0,0.0,0.0), snappedPoint,u) && Math.abs(u[0]) < snapAngle) { - currentPoint = new Point3d(snappedPoint); - snapString += "Point/Plane x-snap "; - snap = true; - addConstrainPlaneHighlight(constraintPoint, currentPoint,X); - //System.out.print(" x " + u[0]); - } - - if (MathTools.intersectStraightPlane(requestedPoint, requestedDir, new Vector3d(constraintPoint), new Vector3d(0.0,1.0,0.0), snappedPoint,u) && Math.abs(u[0]) < snapAngle) { - currentPoint = new Point3d(snappedPoint); - snapString += "Point/Plane y-snap "; - snap = true; - addConstrainPlaneHighlight(constraintPoint, currentPoint,Y); - //System.out.print(" y " + u[0]); - } - - - if (MathTools.intersectStraightPlane(requestedPoint, requestedDir, new Vector3d(constraintPoint), new Vector3d(0.0,0.0,1.0), snappedPoint,u) && Math.abs(u[0]) < snapAngle) { - currentPoint = new Point3d(snappedPoint); - snapString += "Point/Plane z-snap "; - snap = true; - addConstrainPlaneHighlight(constraintPoint, currentPoint,Z); - //System.out.print(" z " + u[0]); - } - //System.out.println(); - if (snap) - break; - } - return currentPoint; - } - - public String getSnapString() { - return snapString; - } + + /** + * Snaps position to axis-aligned planes defined by constraint points + * Form of position is p+v, meaning that the position that is snapped is requestedPoint + requestedDir + * @param requestedPoint one part of the position to be snapped + * @param requestedDir second part of the position to be snapped and direction that the position is allowed to move + * @return + */ + public Point3d getPointSnap(Vector3d requestedPoint, Vector3d requestedDir) { + + Vector3d snappedPoint = new Vector3d(); + Point3d currentPoint = null; + double u[] = new double[1]; + List p1s = new ArrayList(); + List p2s = new ArrayList(); + List axes = new ArrayList(); + + for (Point3d constraintPoint : constraintPoints) { + boolean snap = false; + + if (MathTools.intersectStraightPlane(requestedPoint, requestedDir, new Vector3d(constraintPoint), getAxialVector(X), snappedPoint,u) && Math.abs(1.0 - u[0]) < snapAngle) { + currentPoint = new Point3d(snappedPoint); + //snapString += "Point/Plane x-snap "; + snap = true; + //addConstrainPlaneHighlight(constraintPoint, currentPoint,X); + p1s.add(constraintPoint); + p2s.add(currentPoint); + axes.add(X); + } + + if (MathTools.intersectStraightPlane(requestedPoint, requestedDir, new Vector3d(constraintPoint), getAxialVector(Y), snappedPoint,u) && Math.abs(1.0 - u[0]) < snapAngle) { + currentPoint = new Point3d(snappedPoint); + //snapString += "Point/Plane y-snap "; + snap = true; + //addConstrainPlaneHighlight(constraintPoint, currentPoint,Y); + p1s.add(constraintPoint); + p2s.add(currentPoint); + axes.add(Y); + } + + if (MathTools.intersectStraightPlane(requestedPoint, requestedDir, new Vector3d(constraintPoint), getAxialVector(Z), snappedPoint,u) && Math.abs(1.0 - u[0]) < snapAngle) { + currentPoint = new Point3d(snappedPoint); + //snapString += "Point/Plane z-snap "; + snap = true; + //addConstrainPlaneHighlight(constraintPoint, currentPoint,Z); + p1s.add(constraintPoint); + p2s.add(currentPoint); + axes.add(Z); + } + if (snap) + break; + } + if (p1s.size() == 0) + return null; + if (p1s.size() == 1) { + snapString += "Point/Plane "; + switch (axes.get(0)) { + case X: + snapString += "x"; + break; + case Y: + snapString += "y"; + break; + case Z: + snapString += "z"; + break; + } + snapString += "-snap "; + addConstrainPlaneHighlight(p1s.get(0), p2s.get(0),axes.get(0)); + return currentPoint; + } else if (p1s.size() == 3){ + // all axial planes are intersecting, snapping point must be the constraint point + // all constraint points are the same, so just pick the first in the list + snapString += "Point/Point "; + return p1s.get(0); + } else { + Vector3d dir = new Vector3d(); + dir.cross(getAxialVector(axes.get(0)), getAxialVector(axes.get(1))); + currentPoint = new Point3d(MathTools.closestPointOnStraight(currentPoint, p1s.get(0), dir)); + addConstrainLineHighlight(p1s.get(0), currentPoint, xColor); + snapString += "Point/Line "; + return currentPoint; + } + + } + + private Vector3d getAxialVector(int axis) { + switch (axis) { + case X: + return new Vector3d(1.0,0.0,0.0); + case Y: + return new Vector3d(0.0,1.0,0.0); + case Z: + return new Vector3d(0.0,0.0,1.0); + } + throw new RuntimeException("Unknown axis " + axis); + } + + /** + * Snaps the position to axis-aligned planes defined by constraint points + * @param requestedPoint point that is snapped + * @param requestedDir direction that point is allowed to move + * @return + */ + + public Point3d getPointSnap2(Vector3d requestedPoint, Vector3d requestedDir) { + + Vector3d snappedPoint = new Vector3d(); + Point3d currentPoint = null; + double u[] = new double[1]; + //System.out.println(requestedPoint + " " + requestedDir); + for (Point3d constraintPoint : constraintPoints) { + boolean snap = false; + //System.out.print(constraintPoint + " "); + if (MathTools.intersectStraightPlane(requestedPoint, requestedDir, new Vector3d(constraintPoint), new Vector3d(1.0,0.0,0.0), snappedPoint,u) && Math.abs(u[0]) < snapAngle) { + currentPoint = new Point3d(snappedPoint); + snapString += "Point/Plane x-snap "; + snap = true; + addConstrainPlaneHighlight(constraintPoint, currentPoint,X); + //System.out.print(" x " + u[0]); + } + + if (MathTools.intersectStraightPlane(requestedPoint, requestedDir, new Vector3d(constraintPoint), new Vector3d(0.0,1.0,0.0), snappedPoint,u) && Math.abs(u[0]) < snapAngle) { + currentPoint = new Point3d(snappedPoint); + snapString += "Point/Plane y-snap "; + snap = true; + addConstrainPlaneHighlight(constraintPoint, currentPoint,Y); + //System.out.print(" y " + u[0]); + } + + + if (MathTools.intersectStraightPlane(requestedPoint, requestedDir, new Vector3d(constraintPoint), new Vector3d(0.0,0.0,1.0), snappedPoint,u) && Math.abs(u[0]) < snapAngle) { + currentPoint = new Point3d(snappedPoint); + snapString += "Point/Plane z-snap "; + snap = true; + addConstrainPlaneHighlight(constraintPoint, currentPoint,Z); + //System.out.print(" z " + u[0]); + } + //System.out.println(); + if (snap) + break; + } + return currentPoint; + } + + public String getSnapString() { + return snapString; + } } \ No newline at end of file diff --git a/org.simantics.g3d/src/org/simantics/g3d/tools/NodeTools.java b/org.simantics.g3d/src/org/simantics/g3d/tools/NodeTools.java index 458c4717..be778dc3 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/tools/NodeTools.java +++ b/org.simantics.g3d/src/org/simantics/g3d/tools/NodeTools.java @@ -60,22 +60,22 @@ public class NodeTools { public static Vector3d getLocalPosition(IG3DNode node, Vector3d worldCoord) { - + IG3DNode parent = (IG3DNode)node.getParent(); - if (parent == null) {// this is a root node ( has no transformation) - return worldCoord; - } + if (parent == null) {// this is a root node ( has no transformation) + return worldCoord; + } - Vector3d local = getLocalPosition(parent,worldCoord); - local.sub(node.getPosition()); - - Quat4d q = new Quat4d(); - q.set(node.getOrientation()); - q.inverse(); - MathTools.rotate(q, local, local); - - return local; - } + Vector3d local = getLocalPosition(parent,worldCoord); + local.sub(node.getPosition()); + + Quat4d q = new Quat4d(); + q.set(node.getOrientation()); + q.inverse(); + MathTools.rotate(q, local, local); + + return local; + } public static Quat4d getLocalOrientation(IG3DNode node, Quat4d worldRot) { diff --git a/org.simantics.g3d/src/org/simantics/g3d/tools/PluginTools.java b/org.simantics.g3d/src/org/simantics/g3d/tools/PluginTools.java index cf48ca3b..296f1a11 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/tools/PluginTools.java +++ b/org.simantics.g3d/src/org/simantics/g3d/tools/PluginTools.java @@ -21,19 +21,19 @@ import org.osgi.framework.Bundle; public class PluginTools { - public static String getAbsolutePath(Bundle inBundle, String fullpath) { - IPath path = new Path(fullpath); - URL u = FileLocator.find(inBundle, path, null); - if (u != null) { - try { - u = FileLocator.resolve(u); - if ("file".equals(u.getProtocol())) { - return new File(u.getFile()).getAbsolutePath(); - } - } catch (Exception e) { - } - } - return null; - } + public static String getAbsolutePath(Bundle inBundle, String fullpath) { + IPath path = new Path(fullpath); + URL u = FileLocator.find(inBundle, path, null); + if (u != null) { + try { + u = FileLocator.resolve(u); + if ("file".equals(u.getProtocol())) { + return new File(u.getFile()).getAbsolutePath(); + } + } catch (Exception e) { + } + } + return null; + } } diff --git a/org.simantics.g3d/src/org/simantics/g3d/ui/SceneGraphDebugger.java b/org.simantics.g3d/src/org/simantics/g3d/ui/SceneGraphDebugger.java index 42bc3af6..60f106a1 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/ui/SceneGraphDebugger.java +++ b/org.simantics.g3d/src/org/simantics/g3d/ui/SceneGraphDebugger.java @@ -50,31 +50,31 @@ public class SceneGraphDebugger extends ViewPart { viewer = new TreeViewer(parent,SWT.SINGLE|SWT.FULL_SELECTION); TreeColumnLayout layout = new TreeColumnLayout(); - parent.setLayout(layout); - - viewer.setContentProvider(new ScenegraphOutlinePage.ScenegraphContentProvider()); - viewer.getTree().setHeaderVisible(true); - - TreeViewerColumn nameColumn = new TreeViewerColumn(viewer, SWT.LEFT); - nameColumn.setLabelProvider(new CellLabelProvider() { + parent.setLayout(layout); + + viewer.setContentProvider(new ScenegraphOutlinePage.ScenegraphContentProvider()); + viewer.getTree().setHeaderVisible(true); + + TreeViewerColumn nameColumn = new TreeViewerColumn(viewer, SWT.LEFT); + nameColumn.setLabelProvider(new CellLabelProvider() { @Override public void update(ViewerCell cell) { cell.setText(cell.getElement().toString()); } }); - - TreeViewerColumn typeColumn = new TreeViewerColumn(viewer, SWT.LEFT); - typeColumn.setLabelProvider(new CellLabelProvider() { + + TreeViewerColumn typeColumn = new TreeViewerColumn(viewer, SWT.LEFT); + typeColumn.setLabelProvider(new CellLabelProvider() { @Override public void update(ViewerCell cell) { cell.setText(cell.getElement().getClass().getSimpleName()); } }); - - TreeViewerColumn contextColumn = new TreeViewerColumn(viewer, SWT.LEFT); - contextColumn.setLabelProvider(new CellLabelProvider() { + + TreeViewerColumn contextColumn = new TreeViewerColumn(viewer, SWT.LEFT); + contextColumn.setLabelProvider(new CellLabelProvider() { @Override public void update(ViewerCell cell) { @@ -92,9 +92,9 @@ public class SceneGraphDebugger extends ViewPart { } }); - - TreeViewerColumn mappingColumn = new TreeViewerColumn(viewer, SWT.LEFT); - mappingColumn.setLabelProvider(new CellLabelProvider() { + + TreeViewerColumn mappingColumn = new TreeViewerColumn(viewer, SWT.LEFT); + mappingColumn.setLabelProvider(new CellLabelProvider() { @Override public void update(ViewerCell cell) { @@ -112,20 +112,20 @@ public class SceneGraphDebugger extends ViewPart { } }); - - nameColumn.getColumn().setText("Name"); - typeColumn.getColumn().setText("Type"); - contextColumn.getColumn().setText("Context"); - mappingColumn.getColumn().setText("Mapping"); - - layout.setColumnData(nameColumn.getColumn(), new ColumnWeightData(10, true)); - layout.setColumnData(typeColumn.getColumn(), new ColumnWeightData(10, true)); - layout.setColumnData(contextColumn.getColumn(), new ColumnWeightData(10, true)); - layout.setColumnData(mappingColumn.getColumn(), new ColumnWeightData(10, true)); - - IPartService partService = (IPartService) getSite().getService(IPartService.class); - partService.addPartListener(partListener); - + + nameColumn.getColumn().setText("Name"); + typeColumn.getColumn().setText("Type"); + contextColumn.getColumn().setText("Context"); + mappingColumn.getColumn().setText("Mapping"); + + layout.setColumnData(nameColumn.getColumn(), new ColumnWeightData(10, true)); + layout.setColumnData(typeColumn.getColumn(), new ColumnWeightData(10, true)); + layout.setColumnData(contextColumn.getColumn(), new ColumnWeightData(10, true)); + layout.setColumnData(mappingColumn.getColumn(), new ColumnWeightData(10, true)); + + IPartService partService = (IPartService) getSite().getService(IPartService.class); + partService.addPartListener(partListener); + } @Override @@ -134,95 +134,95 @@ public class SceneGraphDebugger extends ViewPart { } protected void refresh() { - IWorkbenchPart part = null; - try { - IWorkbenchWindow window = getSite().getWorkbenchWindow(); - if (window == null) - return; - IWorkbenchPage page = window.getActivePage(); - if (page == null) - return; - part = page.getActiveEditor(); - if (part == null) - return; - } finally { - if (part == null) { - setContentDescription("No scene graph nodes available."); - // TODO: Show info page instead of tree view. - } - } + IWorkbenchPart part = null; + try { + IWorkbenchWindow window = getSite().getWorkbenchWindow(); + if (window == null) + return; + IWorkbenchPage page = window.getActivePage(); + if (page == null) + return; + part = page.getActiveEditor(); + if (part == null) + return; + } finally { + if (part == null) { + setContentDescription("No scene graph nodes available."); + // TODO: Show info page instead of tree view. + } + } - refresh(part); - } + refresh(part); + } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({ "unchecked", "rawtypes" }) protected boolean refresh(IWorkbenchPart part) { - if (viewer.getTree().isDisposed()) { - IPartService partService = (IPartService) getSite().getService(IPartService.class); - partService.removePartListener(partListener); + if (viewer.getTree().isDisposed()) { + IPartService partService = (IPartService) getSite().getService(IPartService.class); + partService.removePartListener(partListener); return false; } - boolean foundInput = false; - try { - Object obj = null; - if (part != null) { - obj = part.getAdapter(INode.class); - } + boolean foundInput = false; + try { + Object obj = null; + if (part != null) { + obj = part.getAdapter(INode.class); + } - if (obj != null) { - mapping = (IMapping)part.getAdapter(IMapping.class); - if (!viewer.getTree().isDisposed()) - viewer.setInput(obj); - foundInput = true; - } - lastPart = part; - return foundInput; - } finally { - if (!foundInput) { - setContentDescription("No scene graph nodes available."); - // TODO: Show info page instead of tree view. - } - } - } + if (obj != null) { + mapping = (IMapping)part.getAdapter(IMapping.class); + if (!viewer.getTree().isDisposed()) + viewer.setInput(obj); + foundInput = true; + } + lastPart = part; + return foundInput; + } finally { + if (!foundInput) { + setContentDescription("No scene graph nodes available."); + // TODO: Show info page instead of tree view. + } + } + } - IPartListener2 partListener = new IPartListener2() { - @Override - public void partVisible(IWorkbenchPartReference partRef) { - } - @Override - public void partOpened(IWorkbenchPartReference partRef) { - } - @Override - public void partInputChanged(IWorkbenchPartReference partRef) { - } - @Override - public void partHidden(IWorkbenchPartReference partRef) { - } - @Override - public void partDeactivated(IWorkbenchPartReference partRef) { - } - @Override - public void partClosed(IWorkbenchPartReference partRef) { - if (linkToPart) { - IWorkbenchPart part = partRef.getPart(false); - if (part != null) - refresh(null); - } - } - @Override - public void partBroughtToTop(IWorkbenchPartReference partRef) { - } - @Override - public void partActivated(IWorkbenchPartReference partRef) { - if (linkToPart) { - IWorkbenchPart part = partRef.getPart(false); - if (part != null) { - if (part != lastPart) { - refresh(part); - } - } - } - } - }; + IPartListener2 partListener = new IPartListener2() { + @Override + public void partVisible(IWorkbenchPartReference partRef) { + } + @Override + public void partOpened(IWorkbenchPartReference partRef) { + } + @Override + public void partInputChanged(IWorkbenchPartReference partRef) { + } + @Override + public void partHidden(IWorkbenchPartReference partRef) { + } + @Override + public void partDeactivated(IWorkbenchPartReference partRef) { + } + @Override + public void partClosed(IWorkbenchPartReference partRef) { + if (linkToPart) { + IWorkbenchPart part = partRef.getPart(false); + if (part != null) + refresh(null); + } + } + @Override + public void partBroughtToTop(IWorkbenchPartReference partRef) { + } + @Override + public void partActivated(IWorkbenchPartReference partRef) { + if (linkToPart) { + IWorkbenchPart part = partRef.getPart(false); + if (part != null) { + if (part != lastPart) { + refresh(part); + } + } + } + } + }; } diff --git a/org.simantics.g3d/src/org/simantics/g3d/wizard/ModelExportWizard.java b/org.simantics.g3d/src/org/simantics/g3d/wizard/ModelExportWizard.java index 9eddcd44..b5e684da 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/wizard/ModelExportWizard.java +++ b/org.simantics.g3d/src/org/simantics/g3d/wizard/ModelExportWizard.java @@ -42,149 +42,149 @@ public abstract class ModelExportWizard extends Wizard i private static final int MAX_RECENT_EXPORT_PATHS = 10; Deque recentExportPaths; - boolean overwrite; - - T exportModel; - - protected abstract T createExportModel(Deque recentExportPaths); - - protected abstract ModelExportWizardPage createExportPage(T exportModel); - - protected abstract IPersistentPreferenceStore getPreferenceStore(); - - protected abstract IRunnableWithProgress createExportRunnable(T exportModel); - - protected abstract String getExportLocationId(); - protected abstract String getExportOverwriteId(); - - @Override + boolean overwrite; + + T exportModel; + + protected abstract T createExportModel(Deque recentExportPaths); + + protected abstract ModelExportWizardPage createExportPage(T exportModel); + + protected abstract IPersistentPreferenceStore getPreferenceStore(); + + protected abstract IRunnableWithProgress createExportRunnable(T exportModel); + + protected abstract String getExportLocationId(); + protected abstract String getExportOverwriteId(); + + @Override public void init(IWorkbench workbench, IStructuredSelection selection) { readPreferences(); - ISessionContext ctx = Simantics.getSessionContext(); - if (ctx == null) - return; - IProject project = ctx.getHint(ProjectKeys.KEY_PROJECT); - if (project == null) - return; - - exportModel = createExportModel(recentExportPaths); - exportModel.setSelection(selection.getFirstElement()); - exportModel.setOverwrite(overwrite); + ISessionContext ctx = Simantics.getSessionContext(); + if (ctx == null) + return; + IProject project = ctx.getHint(ProjectKeys.KEY_PROJECT); + if (project == null) + return; + + exportModel = createExportModel(recentExportPaths); + exportModel.setSelection(selection.getFirstElement()); + exportModel.setOverwrite(overwrite); } - - @Override + + @Override public void addPages() { super.addPages(); if (exportModel != null) { addPage(createExportPage(exportModel)); } } - - - + + + @Override public boolean performFinish() { - try { - recentExportPaths.addFirst(exportModel.getExportLocation().getAbsolutePath()); - removeDuplicates(recentExportPaths); - if (recentExportPaths.size() > MAX_RECENT_EXPORT_PATHS) - recentExportPaths.pollLast(); + try { + recentExportPaths.addFirst(exportModel.getExportLocation().getAbsolutePath()); + removeDuplicates(recentExportPaths); + if (recentExportPaths.size() > MAX_RECENT_EXPORT_PATHS) + recentExportPaths.pollLast(); - writePreferences(); - } catch (IOException e) { - ErrorLogger.defaultLogError("Failed to write preferences", e); - } - - if (exportModel.usesFile()) { + writePreferences(); + } catch (IOException e) { + ErrorLogger.defaultLogError("Failed to write preferences", e); + } + + if (exportModel.usesFile()) { - File outputFile = exportModel.getExportLocation(); - - if (outputFile.exists()) { - if (!outputFile.isFile()) { - MessageDialog.openError(getShell(), "File Problem", "Output target is not a file " + outputFile.getAbsolutePath()); - return false; - } - if (!exportModel.isOverwrite()) { - boolean ok = MessageDialog.openConfirm(getShell(), "Overwrite", "A file by the name " + outputFile.getAbsolutePath() + " contains files.\n\nDo you want to overwrite the files?"); - if (!ok) { - return false; - } - if (!outputFile.delete()) { - MessageDialog.openError(getShell(), "Delete Problem", "Could not overwrite previously existing file " + outputFile.getAbsolutePath()); - return false; - } - } - } - } else { - File outputFolder = exportModel.getExportLocation(); - - if (outputFolder.exists()) { - if (!outputFolder.isDirectory()) { - MessageDialog.openError(getShell(), "Folder Problem", "Output target is not a folder " + outputFolder.getAbsolutePath()); - return false; - } - String files[] = outputFolder.list(); - if (files.length > 0) { - if (!exportModel.isOverwrite()) { - boolean ok = MessageDialog.openConfirm(getShell(), "Overwrite", "A folder by the name " + outputFolder.getAbsolutePath() + " contains files.\n\nDo you want to overwrite the files?"); - if (!ok) { - return false; - } - } - } + File outputFile = exportModel.getExportLocation(); + + if (outputFile.exists()) { + if (!outputFile.isFile()) { + MessageDialog.openError(getShell(), "File Problem", "Output target is not a file " + outputFile.getAbsolutePath()); + return false; + } + if (!exportModel.isOverwrite()) { + boolean ok = MessageDialog.openConfirm(getShell(), "Overwrite", "A file by the name " + outputFile.getAbsolutePath() + " contains files.\n\nDo you want to overwrite the files?"); + if (!ok) { + return false; + } + if (!outputFile.delete()) { + MessageDialog.openError(getShell(), "Delete Problem", "Could not overwrite previously existing file " + outputFile.getAbsolutePath()); + return false; + } + } + } + } else { + File outputFolder = exportModel.getExportLocation(); + + if (outputFolder.exists()) { + if (!outputFolder.isDirectory()) { + MessageDialog.openError(getShell(), "Folder Problem", "Output target is not a folder " + outputFolder.getAbsolutePath()); + return false; + } + String files[] = outputFolder.list(); + if (files.length > 0) { + if (!exportModel.isOverwrite()) { + boolean ok = MessageDialog.openConfirm(getShell(), "Overwrite", "A folder by the name " + outputFolder.getAbsolutePath() + " contains files.\n\nDo you want to overwrite the files?"); + if (!ok) { + return false; + } + } + } - } else { - if (!outputFolder.mkdir()) { - MessageDialog.openError(getShell(), "Folder Problem", "Could not create new folder " + outputFolder); - return false; - } - } - } + } else { + if (!outputFolder.mkdir()) { + MessageDialog.openError(getShell(), "Folder Problem", "Could not create new folder " + outputFolder); + return false; + } + } + } - try { - getContainer().run(true, true,createExportRunnable(exportModel)); - } catch (InvocationTargetException e) { - Throwable t = e.getTargetException(); - WizardPage cp = (WizardPage) getContainer().getCurrentPage(); - if (t instanceof IOException) { - ErrorLogger.defaultLogError("An I/O problem occurred while exporting the model. See exception for details.", t); - cp.setErrorMessage("An I/O problem occurred while exporting the model.\n\nMessage: " + e.getMessage()); - } else { - ErrorLogger.defaultLogError("Unexpected exception while exporting the model. See exception for details.", t); - cp.setErrorMessage("Unexpected exception while exporting the model. See error log for details.\n\nMessage: " + e.getMessage()); - } - return false; - } catch (InterruptedException e) { - ExceptionUtils.logAndShowError(e); - return false; - } + try { + getContainer().run(true, true,createExportRunnable(exportModel)); + } catch (InvocationTargetException e) { + Throwable t = e.getTargetException(); + WizardPage cp = (WizardPage) getContainer().getCurrentPage(); + if (t instanceof IOException) { + ErrorLogger.defaultLogError("An I/O problem occurred while exporting the model. See exception for details.", t); + cp.setErrorMessage("An I/O problem occurred while exporting the model.\n\nMessage: " + e.getMessage()); + } else { + ErrorLogger.defaultLogError("Unexpected exception while exporting the model. See exception for details.", t); + cp.setErrorMessage("Unexpected exception while exporting the model. See error log for details.\n\nMessage: " + e.getMessage()); + } + return false; + } catch (InterruptedException e) { + ExceptionUtils.logAndShowError(e); + return false; + } - return true; + return true; } private boolean readPreferences() { - IPreferenceStore store = getPreferenceStore(); + IPreferenceStore store = getPreferenceStore(); - String recentPathsPref = store.getString(getExportLocationId()); - recentExportPaths = decodePaths(recentPathsPref); - overwrite = store.getBoolean(getExportOverwriteId()); + String recentPathsPref = store.getString(getExportLocationId()); + recentExportPaths = decodePaths(recentPathsPref); + overwrite = store.getBoolean(getExportOverwriteId()); - return true; - } + return true; + } private void writePreferences() throws IOException { - IPersistentPreferenceStore store = getPreferenceStore(); + IPersistentPreferenceStore store = getPreferenceStore(); - store.putValue(getExportLocationId(), encodePaths(recentExportPaths)); - store.setValue(getExportOverwriteId(), exportModel.isOverwrite()); + store.putValue(getExportLocationId(), encodePaths(recentExportPaths)); + store.setValue(getExportOverwriteId(), exportModel.isOverwrite()); - if (store.needsSaving()) - store.save(); - } + if (store.needsSaving()) + store.save(); + } private static final String TAG_PATH = "path"; private static final String ATTR_NAME = "name"; diff --git a/org.simantics.g3d/src/org/simantics/g3d/wizard/ModelExportWizardPage.java b/org.simantics.g3d/src/org/simantics/g3d/wizard/ModelExportWizardPage.java index 264f1070..0146ff34 100644 --- a/org.simantics.g3d/src/org/simantics/g3d/wizard/ModelExportWizardPage.java +++ b/org.simantics.g3d/src/org/simantics/g3d/wizard/ModelExportWizardPage.java @@ -100,99 +100,99 @@ public abstract class ModelExportWizardPage extends Wiza } if (exportToFile) { - new Label(container, SWT.NONE).setText("&Target file:"); - exportLocation = new CCombo(container, SWT.BORDER); - { - exportLocation.setText(""); - GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(exportLocation); - exportLocation.addModifyListener(new ModifyListener(){ - @Override - public void modifyText(ModifyEvent e) { - validatePage(); - } - }); - } - Button browseFileButton = new Button(container, SWT.PUSH); - { - browseFileButton.setText("Browse..."); - browseFileButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - browseFileButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - FileDialog dialog = new FileDialog(getShell(), SWT.SAVE); - dialog.setText("Choose Export Target File"); - dialog.setFilterExtensions(getFilterExtensions()); - dialog.setFilterNames(getFilterNames()); - String loc = exportLocation.getText(); - dialog.setFilterPath(loc); - String file = dialog.open(); - if (file == null) - return; - exportLocation.setText(file); - validatePage(); - } - }); - } + new Label(container, SWT.NONE).setText("&Target file:"); + exportLocation = new CCombo(container, SWT.BORDER); + { + exportLocation.setText(""); + GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(exportLocation); + exportLocation.addModifyListener(new ModifyListener(){ + @Override + public void modifyText(ModifyEvent e) { + validatePage(); + } + }); + } + Button browseFileButton = new Button(container, SWT.PUSH); + { + browseFileButton.setText("Browse..."); + browseFileButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + browseFileButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + FileDialog dialog = new FileDialog(getShell(), SWT.SAVE); + dialog.setText("Choose Export Target File"); + dialog.setFilterExtensions(getFilterExtensions()); + dialog.setFilterNames(getFilterNames()); + String loc = exportLocation.getText(); + dialog.setFilterPath(loc); + String file = dialog.open(); + if (file == null) + return; + exportLocation.setText(file); + validatePage(); + } + }); + } - + - + } else { - new Label(container, SWT.NONE).setText("&Target folder:"); - exportLocation = new CCombo(container, SWT.BORDER); - { - exportLocation.setText(""); - GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(exportLocation); - exportLocation.addModifyListener(new ModifyListener(){ - @Override - public void modifyText(ModifyEvent e) { - validatePage(); - } - }); - } - Button browseFileButton = new Button(container, SWT.PUSH); - { - browseFileButton.setText("Browse..."); - browseFileButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); - browseFileButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.SAVE); - dialog.setText("Choose Export Target Folder"); - String loc = exportLocation.getText(); - dialog.setFilterPath(loc); - String file = dialog.open(); - if (file == null) - return; - exportLocation.setText(file); - validatePage(); - } - }); - } + new Label(container, SWT.NONE).setText("&Target folder:"); + exportLocation = new CCombo(container, SWT.BORDER); + { + exportLocation.setText(""); + GridDataFactory.fillDefaults().grab(true, false).span(1, 1).applyTo(exportLocation); + exportLocation.addModifyListener(new ModifyListener(){ + @Override + public void modifyText(ModifyEvent e) { + validatePage(); + } + }); + } + Button browseFileButton = new Button(container, SWT.PUSH); + { + browseFileButton.setText("Browse..."); + browseFileButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false)); + browseFileButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.SAVE); + dialog.setText("Choose Export Target Folder"); + String loc = exportLocation.getText(); + dialog.setFilterPath(loc); + String file = dialog.open(); + if (file == null) + return; + exportLocation.setText(file); + validatePage(); + } + }); + } } - Label horizRule = new Label(container, SWT.BORDER); - GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 0).grab(true, false).span(3, 1).applyTo(horizRule); + Label horizRule = new Label(container, SWT.BORDER); + GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 0).grab(true, false).span(3, 1).applyTo(horizRule); - overwrite = new Button(container, SWT.CHECK); - overwrite.setText("&Overwrite existing files without warning"); - overwrite.setSelection(exportData.isOverwrite()); - GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(overwrite); - overwrite.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - validatePage(); - } - }); + overwrite = new Button(container, SWT.CHECK); + overwrite.setText("&Overwrite existing files without warning"); + overwrite.setSelection(exportData.isOverwrite()); + GridDataFactory.fillDefaults().grab(true, false).span(3, 1).applyTo(overwrite); + overwrite.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + validatePage(); + } + }); - try { - initializeData(); - } catch (DatabaseException e) { - e.printStackTrace(); - } + try { + initializeData(); + } catch (DatabaseException e) { + e.printStackTrace(); + } - setControl(container); - validatePage(); + setControl(container); + validatePage(); } @@ -200,42 +200,42 @@ public abstract class ModelExportWizardPage extends Wiza protected void initializeData() throws DatabaseException { - final Resource selection = ResourceAdaptionUtils.toSingleResource(exportData.getSelection()); + final Resource selection = ResourceAdaptionUtils.toSingleResource(exportData.getSelection()); - Simantics.getSessionContext().getSession().syncRequest( - new ReadRequest() { - @Override - public void run(ReadGraph graph) throws DatabaseException { - Layer0 L0 = Layer0.getInstance(graph); - models = getSupportedModels(graph, Simantics.getProject().get()); - } - }); + Simantics.getSessionContext().getSession().syncRequest( + new ReadRequest() { + @Override + public void run(ReadGraph graph) throws DatabaseException { + Layer0 L0 = Layer0.getInstance(graph); + models = getSupportedModels(graph, Simantics.getProject().get()); + } + }); - Collections.sort(models); + Collections.sort(models); - // Populate combo boxes - int i = 0; - boolean selected = false; - for (NamedResource s : models) { - model.add(s.getName()); - model.setData(String.valueOf(i), s); - if (s.getResource().equals(selection)) { - model.select(i); - selected = true; - } - ++i; - } - if (!selected && i > 0) - model.select(0); - - if (model.getSelectionIndex() >= 0) { - exportData.setModel((NamedResource)model.getData(Integer.toString(model.getSelectionIndex()))); - } - for (String path : exportData.getRecentLocations()) { - exportLocation.add(path); - } - if (exportLocation.getItemCount() > 0) - exportLocation.select(0); + // Populate combo boxes + int i = 0; + boolean selected = false; + for (NamedResource s : models) { + model.add(s.getName()); + model.setData(String.valueOf(i), s); + if (s.getResource().equals(selection)) { + model.select(i); + selected = true; + } + ++i; + } + if (!selected && i > 0) + model.select(0); + + if (model.getSelectionIndex() >= 0) { + exportData.setModel((NamedResource)model.getData(Integer.toString(model.getSelectionIndex()))); + } + for (String path : exportData.getRecentLocations()) { + exportLocation.add(path); + } + if (exportLocation.getItemCount() > 0) + exportLocation.select(0); } diff --git a/org.simantics.opencascade.vtk/src/org/simantics/opencascade/vtk/EdgePointsFilter.java b/org.simantics.opencascade.vtk/src/org/simantics/opencascade/vtk/EdgePointsFilter.java index abae2170..17b78c73 100644 --- a/org.simantics.opencascade.vtk/src/org/simantics/opencascade/vtk/EdgePointsFilter.java +++ b/org.simantics.opencascade.vtk/src/org/simantics/opencascade/vtk/EdgePointsFilter.java @@ -40,8 +40,8 @@ public class EdgePointsFilter extends vtkProgrammableFilter { vtkPolyData polyDataInput = GetPolyDataInput(); vtkPolyData polyDataOutput = GetPolyDataOutput(); vtkPoints inputPoints = polyDataInput.GetPoints(); - - outputPoints = new vtkPoints(); + + outputPoints = new vtkPoints(); MapList edgeIndices = new MapList(); for (int i = 0; i meshPoints, List meshTriangles) - { - - - - - - int nofTriangles = meshTriangles.size() / 3; - int nofNodes = meshPoints.size() /3; - - - if(nofTriangles < 1) { - System.out.println("No triangles for mesh on face"); - return null; - } - - if(nofNodes < 1) { - System.out.println("No nodes for mesh on face:"); - return null; - } - //System.out.println("v " + nofNodes + " t " +nofTriangles); - vtkPolyData partGrid = new vtkPolyData(); - partGrid.Allocate(nofTriangles, nofTriangles); - - vtkTriangle triangle = new vtkTriangle(); - vtkIdList list = triangle.GetPointIds(); - for(int i = 0; i < nofTriangles; i++) - { - int n0, n1, n2; - n0 = meshTriangles.get(3 * i); - n1 = meshTriangles.get(3 * i + 1); - n2 = meshTriangles.get(3 * i + 2); - - - list.SetId(0, n0); - list.SetId(1, n1); - list.SetId(2, n2); - partGrid.InsertNextCell(triangle.GetCellType(), list); - - } - list.Delete(); - triangle.Delete(); - - - - double d_p[] = new double[3]; - - - vtkPoints partPoints = new vtkPoints(); - - for(int i = 0; i < nofNodes; i++) { - - d_p[0] = meshPoints.get(3*i); - d_p[1] = meshPoints.get(3*i+1); - d_p[2] = meshPoints.get(3*i+2); - partPoints.InsertPoint(i, d_p); - } - - partGrid.SetPoints(partPoints); - partPoints.Delete(); - - return partGrid; - } - + { + + + + + + int nofTriangles = meshTriangles.size() / 3; + int nofNodes = meshPoints.size() /3; + + + if(nofTriangles < 1) { + System.out.println("No triangles for mesh on face"); + return null; + } + + if(nofNodes < 1) { + System.out.println("No nodes for mesh on face:"); + return null; + } + //System.out.println("v " + nofNodes + " t " +nofTriangles); + vtkPolyData partGrid = new vtkPolyData(); + partGrid.Allocate(nofTriangles, nofTriangles); + + vtkTriangle triangle = new vtkTriangle(); + vtkIdList list = triangle.GetPointIds(); + for(int i = 0; i < nofTriangles; i++) + { + int n0, n1, n2; + n0 = meshTriangles.get(3 * i); + n1 = meshTriangles.get(3 * i + 1); + n2 = meshTriangles.get(3 * i + 2); + + + list.SetId(0, n0); + list.SetId(1, n1); + list.SetId(2, n2); + partGrid.InsertNextCell(triangle.GetCellType(), list); + + } + list.Delete(); + triangle.Delete(); + + + + double d_p[] = new double[3]; + + + vtkPoints partPoints = new vtkPoints(); + + for(int i = 0; i < nofNodes; i++) { + + d_p[0] = meshPoints.get(3*i); + d_p[1] = meshPoints.get(3*i+1); + d_p[2] = meshPoints.get(3*i+2); + partPoints.InsertPoint(i, d_p); + } + + partGrid.SetPoints(partPoints); + partPoints.Delete(); + + return partGrid; + } + private static vtkPolyData createTestPartGrid () - { + { int size = 64; - - double[] nodes = new double[(size+1)*(size+1)*3]; - int[] triangles = new int[3 * size * size * 2]; - - double es = 1.0; - for (int i = 0; i <= size; i++) { - for (int j = 0; j <= size; j++) { - int index = j * size + i; - index *= 3; - double x = (double)i * es; - double y = (Math.sin((double)i/(double)size) + Math.sin((double)j/(double)size)) * es; - double z = (double)j * es; - nodes[index] = x; - nodes[index+1] = y; - nodes[index+2] = z; - } - } - - for (int i = 0; i < size; i++) { - for (int j = 0; j < size; j++) { - int index = j * size + i; - index *= 3; - index *= 2; - triangles[index ] = (j * (size+1) + i ); - triangles[index+1] = (j * (size+1) + i+1); - triangles[index+2] = ((j+1) * (size+1) + i ); - triangles[index+3] = ((j+1) * (size+1) + i ); - triangles[index+4] = ((j ) * (size+1) + i +1 ); - triangles[index+5] = ((j+1) * (size+1) + i +1 ); - } - } - - int nofTriangles = triangles.length / 3; - int nofNodes = nodes.length / 3; - - if(nofTriangles < 1) { - - return null; - } - - if(nofNodes < 1) { - - return null; - } - //System.out.println("v " + nofNodes + " t " +nofTriangles); - vtkPolyData partGrid = new vtkPolyData(); - partGrid.Allocate(nofTriangles, nofTriangles); - - vtkTriangle triangle = new vtkTriangle(); - vtkIdList list = triangle.GetPointIds(); - for(int i = 0; i < nofTriangles; i++) - { - int n0, n1, n2; - n0 = triangles[3 * i]; n1 = triangles[3 * i + 1]; n2 = triangles[3 * i + 2]; // triangles(i).Get(n0, n1, n2); - -// if(face.orientation() != TopAbs_Orientation.FORWARD) { -// int tmp = n2; n2 = n1; n1 = tmp; -// } - - list.SetId(0, n0); - list.SetId(1, n1); - list.SetId(2, n2); - partGrid.InsertNextCell(triangle.GetCellType(), list); - - } - list.Delete(); - triangle.Delete(); - - vtkPoints partPoints = new vtkPoints(); - for(int i = 0; i < nofNodes; i++) { - double xyz[] = new double[]{nodes[3 * i], nodes[3 * i + 1], nodes[3 * i + 2]}; - partPoints.InsertPoint(i, xyz); - } - - partGrid.SetPoints(partPoints); - - partPoints.Delete(); - - return partGrid; - } - + + double[] nodes = new double[(size+1)*(size+1)*3]; + int[] triangles = new int[3 * size * size * 2]; + + double es = 1.0; + for (int i = 0; i <= size; i++) { + for (int j = 0; j <= size; j++) { + int index = j * size + i; + index *= 3; + double x = (double)i * es; + double y = (Math.sin((double)i/(double)size) + Math.sin((double)j/(double)size)) * es; + double z = (double)j * es; + nodes[index] = x; + nodes[index+1] = y; + nodes[index+2] = z; + } + } + + for (int i = 0; i < size; i++) { + for (int j = 0; j < size; j++) { + int index = j * size + i; + index *= 3; + index *= 2; + triangles[index ] = (j * (size+1) + i ); + triangles[index+1] = (j * (size+1) + i+1); + triangles[index+2] = ((j+1) * (size+1) + i ); + triangles[index+3] = ((j+1) * (size+1) + i ); + triangles[index+4] = ((j ) * (size+1) + i +1 ); + triangles[index+5] = ((j+1) * (size+1) + i +1 ); + } + } + + int nofTriangles = triangles.length / 3; + int nofNodes = nodes.length / 3; + + if(nofTriangles < 1) { + + return null; + } + + if(nofNodes < 1) { + + return null; + } + //System.out.println("v " + nofNodes + " t " +nofTriangles); + vtkPolyData partGrid = new vtkPolyData(); + partGrid.Allocate(nofTriangles, nofTriangles); + + vtkTriangle triangle = new vtkTriangle(); + vtkIdList list = triangle.GetPointIds(); + for(int i = 0; i < nofTriangles; i++) + { + int n0, n1, n2; + n0 = triangles[3 * i]; n1 = triangles[3 * i + 1]; n2 = triangles[3 * i + 2]; // triangles(i).Get(n0, n1, n2); + + // if(face.orientation() != TopAbs_Orientation.FORWARD) { + // int tmp = n2; n2 = n1; n1 = tmp; + // } + + list.SetId(0, n0); + list.SetId(1, n1); + list.SetId(2, n2); + partGrid.InsertNextCell(triangle.GetCellType(), list); + + } + list.Delete(); + triangle.Delete(); + + vtkPoints partPoints = new vtkPoints(); + for(int i = 0; i < nofNodes; i++) { + double xyz[] = new double[]{nodes[3 * i], nodes[3 * i + 1], nodes[3 * i + 2]}; + partPoints.InsertPoint(i, xyz); + } + + partGrid.SetPoints(partPoints); + + partPoints.Delete(); + + return partGrid; + } + public static void test() { TopoDS_Shape shape = null; //shape = OccTriangulator.makeCylinder(new double[]{0,0,0}, new double[]{0,1,0}, 1, 1); @@ -617,22 +617,22 @@ public static void gridToAssembly(vtkAssembly assemblies, vtkPolyData partGrid) if (test == 0) { vtkAssembly ass = VTKOCCTool.vtkOCCShapeToAssembly(shape); vtkPropCollection col; - col = ass.GetParts(); - for (int i = 0; i < col.GetNumberOfItems(); i++) - { - vtkProp prop = (vtkProp) col.GetItemAsObject(i); - //System.out.println(prop.Print()); - prop.Delete(); - } - col.Delete(); - ass.Delete(); + col = ass.GetParts(); + for (int i = 0; i < col.GetNumberOfItems(); i++) + { + vtkProp prop = (vtkProp) col.GetItemAsObject(i); + //System.out.println(prop.Print()); + prop.Delete(); + } + col.Delete(); + ass.Delete(); } else if (test == 1) { //BRepTools.clean(shape); - - + + vtkAssembly ass = new vtkAssembly(); - + double vol = OCCTTool.getBoundingBoxDiagonal(shape); double d = 0.001 * vol; BRepMesh_IncrementalMesh mesh = new BRepMesh_IncrementalMesh(shape,d); @@ -640,31 +640,31 @@ public static void gridToAssembly(vtkAssembly assemblies, vtkPolyData partGrid) for (expFace.init(shape, TopAbs_ShapeEnum.FACE); expFace.more(); expFace.next()) { TopoDS_Face face = (TopoDS_Face) expFace.current(); { -// TopLoc_Location Location = new TopLoc_Location(); -// Poly_Triangulation triangulation = BRep_Tool.triangulation(face, Location); -// if (triangulation != null) { -// -// int[]triangles = triangulation.triangles(); -// double[]nodes = triangulation.nodes(); -// int nofTriangles = triangulation.nbTriangles(); -// int nofNodes = triangulation.nbNodes(); -// -// triangulation.delete(); -// -// GP_Trsf transformation = Location.transformation(); -// double d_mat[] = new double[16]; -// transformation.getValues(d_mat); -// Matrix4d mat = new Matrix4d(d_mat); -// for(int i = 0; i < nofNodes; i++) { -// //double xyz[] = new double[]{nodes[3 * i], nodes[3 * i + 1], nodes[3 * i + 2]}; -// Point3d p = new Point3d(nodes[3 * i], nodes[3 * i + 1], nodes[3 * i + 2]); -// //transformation.transforms(xyz); -// mat.transform(p); -// } -// transformation.delete(); -// } -// -// Location.delete(); + // TopLoc_Location Location = new TopLoc_Location(); + // Poly_Triangulation triangulation = BRep_Tool.triangulation(face, Location); + // if (triangulation != null) { + // + // int[]triangles = triangulation.triangles(); + // double[]nodes = triangulation.nodes(); + // int nofTriangles = triangulation.nbTriangles(); + // int nofNodes = triangulation.nbNodes(); + // + // triangulation.delete(); + // + // GP_Trsf transformation = Location.transformation(); + // double d_mat[] = new double[16]; + // transformation.getValues(d_mat); + // Matrix4d mat = new Matrix4d(d_mat); + // for(int i = 0; i < nofNodes; i++) { + // //double xyz[] = new double[]{nodes[3 * i], nodes[3 * i + 1], nodes[3 * i + 2]}; + // Point3d p = new Point3d(nodes[3 * i], nodes[3 * i + 1], nodes[3 * i + 2]); + // //transformation.transforms(xyz); + // mat.transform(p); + // } + // transformation.delete(); + // } + // + // Location.delete(); vtkPolyData data = VTKOCCTool.createPartGrid(face); VTKOCCTool.gridToAssembly(ass, data); //data.Delete(); @@ -673,31 +673,31 @@ public static void gridToAssembly(vtkAssembly assemblies, vtkPolyData partGrid) } expFace.delete(); mesh.delete(); - + vtkPropCollection col; - col = ass.GetParts(); - for (int i = 0; i < col.GetNumberOfItems(); i++) - { - vtkProp prop = (vtkProp) col.GetItemAsObject(i); - //System.out.println(prop.Print()); - prop.Delete(); - } - col.Delete(); - ass.Delete(); + col = ass.GetParts(); + for (int i = 0; i < col.GetNumberOfItems(); i++) + { + vtkProp prop = (vtkProp) col.GetItemAsObject(i); + //System.out.println(prop.Print()); + prop.Delete(); + } + col.Delete(); + ass.Delete(); } else if (test == 2) { double[] pointStruct = new double[]{0,0,0}, dirStruct = new double[]{0,1,0}; double radius = 1.0; double height = 1.0; - + double[] axe = new double[6]; - - System.arraycopy(pointStruct, 0, axe, 0, 3); - System.arraycopy(dirStruct, 0, axe, 3, 3); - org.jcae.opencascade.jni.BRepPrimAPI_MakeCylinder cyl = new org.jcae.opencascade.jni.BRepPrimAPI_MakeCylinder(axe, radius, height, 2 * Math.PI); - org.jcae.opencascade.jni.TopoDS_Shape tds = cyl.shape(); - cyl.delete(); - - double vol = OCCTTool.getBoundingBoxDiagonal(tds); + + System.arraycopy(pointStruct, 0, axe, 0, 3); + System.arraycopy(dirStruct, 0, axe, 3, 3); + org.jcae.opencascade.jni.BRepPrimAPI_MakeCylinder cyl = new org.jcae.opencascade.jni.BRepPrimAPI_MakeCylinder(axe, radius, height, 2 * Math.PI); + org.jcae.opencascade.jni.TopoDS_Shape tds = cyl.shape(); + cyl.delete(); + + double vol = OCCTTool.getBoundingBoxDiagonal(tds); double d = 0.001 * vol; BRepMesh_IncrementalMesh mesh = new BRepMesh_IncrementalMesh(tds,d); // TopExp_Explorer expFace = new TopExp_Explorer(); @@ -709,11 +709,11 @@ public static void gridToAssembly(vtkAssembly assemblies, vtkPolyData partGrid) // face.delete(); // } mesh.delete(); - - tds.delete(); + + tds.delete(); } //shape.delete(); - System.out.println(t); + System.out.println(t); } //shape.delete(); } diff --git a/org.simantics.opencascade.vtk/src/org/simantics/opencascade/vtk/vtkSolidObject.java b/org.simantics.opencascade.vtk/src/org/simantics/opencascade/vtk/vtkSolidObject.java index 797c9ae2..2dc2416f 100644 --- a/org.simantics.opencascade.vtk/src/org/simantics/opencascade/vtk/vtkSolidObject.java +++ b/org.simantics.opencascade.vtk/src/org/simantics/opencascade/vtk/vtkSolidObject.java @@ -41,38 +41,38 @@ import vtk.vtkRenderer; import vtk.vtkSphereSource; public class vtkSolidObject { - + public static double deflection = 0.001; - + public static double featureAngle = 30; public static boolean computeNormals = true; public static boolean cleanPart = false; public static boolean mergePoints = false; - + private VtkView panel; private TopoDS_Shape shape; - + private List actors = new ArrayList(2); - + private List solid = new ArrayList(1); private List edges = new ArrayList(1); private vtkActor silhouette = null; - + private boolean errors = false; - + public vtkSolidObject(VtkView panel,TopoDS_Shape shape) { this.shape = shape; this.panel = panel; } - + public void visualizeSolid(boolean showEdges, boolean showVertices) { visualizeSolid(true, showEdges, showVertices); } - + public void visualizeSolid(boolean showFaces, boolean showEdges, boolean showVertices) { visualizeSolid(showFaces, showEdges, showVertices, false); } - + public void visualizeSolid(boolean showFaces, boolean showEdges, boolean showVertices, boolean showSilhouette) { clearActorsVTK(); errors = false; @@ -104,7 +104,7 @@ public class vtkSolidObject { data.Delete(); showActorsVTK(); } - + public void visualizeFaces(boolean showEdges, boolean showVertices) { errors = false; clearActorsVTK(); @@ -114,9 +114,9 @@ public class vtkSolidObject { errors = true; continue; } - + solid.add(createActor(data)); - + if (showEdges) { vtkActor edgesActor = createEdgesActor(data); edges.add(edgesActor); @@ -128,34 +128,34 @@ public class vtkSolidObject { } actors.addAll(solid); actors.addAll(edges); - + showActorsVTK(); } - + public boolean hasErrors() { return errors; } - + public List getActors() { assert (Thread.currentThread() == panel.getThreadQueue().getThread()); return actors; } - + public List getSolid() { assert (Thread.currentThread() == panel.getThreadQueue().getThread()); return solid; } - + public List getEdges() { assert (Thread.currentThread() == panel.getThreadQueue().getThread()); return edges; } - + public vtkActor getSilhouette() { assert (Thread.currentThread() == panel.getThreadQueue().getThread()); return silhouette; } - + public void showActorsVTK() { assert (Thread.currentThread() == panel.getThreadQueue().getThread()); panel.lock(); @@ -165,17 +165,17 @@ public class vtkSolidObject { } panel.unlock(); } - + public void showActors() { ThreadUtils.asyncExec(panel.getThreadQueue(), new Runnable() { - + @Override public void run() { showActorsVTK(); } }); } - + public void clearActorsVTK() { assert (Thread.currentThread() == panel.getThreadQueue().getThread()); if (actors.size() == 0) @@ -195,10 +195,10 @@ public class vtkSolidObject { solid.clear(); edges.clear(); } - + private void clearActorsAWT(List actors) { assert (Thread.currentThread() == panel.getThreadQueue().getThread()); - + if (actors.size() == 0) return; vtkRenderer ren = panel.getRenderer(); @@ -213,7 +213,7 @@ public class vtkSolidObject { } panel.unlock(); } - + public void clearActors() { if (actors.size() == 0) return; @@ -223,14 +223,14 @@ public class vtkSolidObject { solid.clear(); edges.clear(); ThreadUtils.asyncExec(panel.getThreadQueue(), new Runnable() { - + @Override public void run() { clearActorsAWT(temp); } }); } - + public void dispose() { if (shape != null) { shape.delete(); @@ -238,7 +238,7 @@ public class vtkSolidObject { } clearActors(); } - + public void delete() { if (shape != null) { shape.delete(); @@ -246,21 +246,21 @@ public class vtkSolidObject { } clearActorsVTK(); } - + private static double TOLERANCE = 0.01; - + public static Pair createSolidMesh(TopoDS_Shape shape) { - + boolean success = true; - + double volume = OCCTTool.getBoundingBoxDiagonal(shape); if (volume < TOLERANCE) return null; - + BRepMesh_IncrementalMesh mesh = new BRepMesh_IncrementalMesh(shape,deflection*volume); - + TopExp_Explorer expFace = new TopExp_Explorer(); - + List meshPoints = new ArrayList(); List meshTriangles = new ArrayList(); for (expFace.init(shape, TopAbs_ShapeEnum.FACE); expFace.more(); expFace.next()) { @@ -271,234 +271,234 @@ public class vtkSolidObject { } if (meshPoints.size() == 0 || meshTriangles.size() == 0) return null; - + vtkPolyData data = VTKOCCTool.createPartGrid(meshPoints, meshTriangles); - + expFace.delete(); mesh.delete(); - + return new Pair(data, success); } - + public static Collection createFaceMeshes(TopoDS_Shape shape) { - + double volume = OCCTTool.getBoundingBoxDiagonal(shape); Collection faces = new ArrayList(); - + if (volume > TOLERANCE) { - + BRepMesh_IncrementalMesh mesh = new BRepMesh_IncrementalMesh(shape,deflection*volume); - + TopExp_Explorer expFace = new TopExp_Explorer(); - - + + for (expFace.init(shape, TopAbs_ShapeEnum.FACE); expFace.more(); expFace.next()) { TopoDS_Face face = (TopoDS_Face) expFace.current(); vtkPolyData data = VTKOCCTool.createPartGrid(face); face.delete(); faces.add(data); } - + expFace.delete(); mesh.delete(); } - + return faces; } - - - + + + public static vtkActor createActor(vtkPolyData partGrid) { - - - vtkDataSetMapper partMapper = new vtkDataSetMapper(); - - vtkCleanPolyData partCleaner = null; - if (cleanPart) - { - partCleaner = new vtkCleanPolyData(); - partCleaner.SetInputData(partGrid); - if(mergePoints) { - partCleaner.PointMergingOn(); - } else { - partCleaner.PointMergingOff(); - } - } - - if (computeNormals) - { - vtkPolyDataNormals partNormals = new vtkPolyDataNormals(); - - if (cleanPart) - { - vtkAlgorithmOutput out = partCleaner.GetOutputPort(); - partNormals.SetInputConnection(out); - out.Delete(); - } - else partNormals.SetInputData(partGrid); - - partNormals.SetFeatureAngle(featureAngle); // this do not have to be neccesarily called - vtkAlgorithmOutput out = partNormals.GetOutputPort(); - partMapper.SetInputConnection(out); - out.Delete(); - partNormals.Delete(); - } - else - { - if (cleanPart) { - vtkAlgorithmOutput out = partCleaner.GetOutputPort(); - partMapper.SetInputConnection(out); // metoda 2, ne tak pekne, viz http://www.codeguru.com/cpp/g-m/opengl/article.php/c2681 - out.Delete(); - } - else partMapper.SetInputData(partGrid); // metoda 1, ne tak pekne stinovani, viz: http://www.codeguru.com/cpp/g-m/opengl/article.php/c2681 - } - partMapper.ScalarVisibilityOn(); - - vtkActor partActor = new vtkActor(); - // partActor.SetPickable(1); - vtkProperty prop = partActor.GetProperty(); - prop.SetColor(1, 1, 0); - prop.Delete(); - partActor.SetMapper(partMapper); - - partMapper.Delete(); - - if (cleanPart) - partCleaner.Delete(); - - return partActor; + + + vtkDataSetMapper partMapper = new vtkDataSetMapper(); + + vtkCleanPolyData partCleaner = null; + if (cleanPart) + { + partCleaner = new vtkCleanPolyData(); + partCleaner.SetInputData(partGrid); + if(mergePoints) { + partCleaner.PointMergingOn(); + } else { + partCleaner.PointMergingOff(); + } + } + + if (computeNormals) + { + vtkPolyDataNormals partNormals = new vtkPolyDataNormals(); + + if (cleanPart) + { + vtkAlgorithmOutput out = partCleaner.GetOutputPort(); + partNormals.SetInputConnection(out); + out.Delete(); + } + else partNormals.SetInputData(partGrid); + + partNormals.SetFeatureAngle(featureAngle); // this do not have to be neccesarily called + vtkAlgorithmOutput out = partNormals.GetOutputPort(); + partMapper.SetInputConnection(out); + out.Delete(); + partNormals.Delete(); + } + else + { + if (cleanPart) { + vtkAlgorithmOutput out = partCleaner.GetOutputPort(); + partMapper.SetInputConnection(out); // metoda 2, ne tak pekne, viz http://www.codeguru.com/cpp/g-m/opengl/article.php/c2681 + out.Delete(); + } + else partMapper.SetInputData(partGrid); // metoda 1, ne tak pekne stinovani, viz: http://www.codeguru.com/cpp/g-m/opengl/article.php/c2681 + } + partMapper.ScalarVisibilityOn(); + + vtkActor partActor = new vtkActor(); + // partActor.SetPickable(1); + vtkProperty prop = partActor.GetProperty(); + prop.SetColor(1, 1, 0); + prop.Delete(); + partActor.SetMapper(partMapper); + + partMapper.Delete(); + + if (cleanPart) + partCleaner.Delete(); + + return partActor; } - + public static vtkActor createEdgesActor(vtkPolyData partGrid) { vtkCleanPolyData partCleaner = null; - + if (cleanPart) - { + { partCleaner = new vtkCleanPolyData(); - partCleaner.SetInputData(partGrid); - if(mergePoints) { - partCleaner.PointMergingOn(); - } else { - partCleaner.PointMergingOff(); - } - } - + partCleaner.SetInputData(partGrid); + if(mergePoints) { + partCleaner.PointMergingOn(); + } else { + partCleaner.PointMergingOff(); + } + } + vtkFeatureEdges partEdges = new vtkFeatureEdges(); - if (cleanPart) { - vtkAlgorithmOutput out = partCleaner.GetOutputPort(); - partEdges.SetInputConnection(out); - out.Delete(); - } - else partEdges.SetInputData(partGrid); - // partEdges.SetFeatureAngle(featureAngle); // this do not have to be neccesarily called - partEdges.FeatureEdgesOn(); - partEdges.BoundaryEdgesOn(); - partEdges.NonManifoldEdgesOn(); - partEdges.ManifoldEdgesOn(); - - vtkDataSetMapper partEdgesMapper = new vtkDataSetMapper(); - vtkAlgorithmOutput out = partEdges.GetOutputPort(); - partEdgesMapper.SetInputConnection(out); - out.Delete(); - partEdgesMapper.SetResolveCoincidentTopologyToPolygonOffset(); - partEdgesMapper.ScalarVisibilityOff(); - - vtkActor partEdgesActor = new vtkActor(); - - vtkProperty prop = partEdgesActor.GetProperty(); - prop.SetColor(0, 0, 0); - prop.SetLineWidth(2.0); - prop.Delete(); - partEdgesActor.SetMapper(partEdgesMapper); - - partEdgesMapper.Delete(); - partEdges.Delete(); - - if (cleanPart) - partCleaner.Delete(); - - return partEdgesActor; + if (cleanPart) { + vtkAlgorithmOutput out = partCleaner.GetOutputPort(); + partEdges.SetInputConnection(out); + out.Delete(); + } + else partEdges.SetInputData(partGrid); + // partEdges.SetFeatureAngle(featureAngle); // this do not have to be neccesarily called + partEdges.FeatureEdgesOn(); + partEdges.BoundaryEdgesOn(); + partEdges.NonManifoldEdgesOn(); + partEdges.ManifoldEdgesOn(); + + vtkDataSetMapper partEdgesMapper = new vtkDataSetMapper(); + vtkAlgorithmOutput out = partEdges.GetOutputPort(); + partEdgesMapper.SetInputConnection(out); + out.Delete(); + partEdgesMapper.SetResolveCoincidentTopologyToPolygonOffset(); + partEdgesMapper.ScalarVisibilityOff(); + + vtkActor partEdgesActor = new vtkActor(); + + vtkProperty prop = partEdgesActor.GetProperty(); + prop.SetColor(0, 0, 0); + prop.SetLineWidth(2.0); + prop.Delete(); + partEdgesActor.SetMapper(partEdgesMapper); + + partEdgesMapper.Delete(); + partEdges.Delete(); + + if (cleanPart) + partCleaner.Delete(); + + return partEdgesActor; } - + public static vtkActor createVerticesActor(vtkActor partEdgesActor) { vtkDataSetMapper partEdgesMapper = (vtkDataSetMapper) partEdgesActor.GetMapper(); vtkAlgorithmOutput out = partEdgesMapper.GetInputConnection(0, 0); vtkFeatureEdges partEdges = (vtkFeatureEdges)out.GetProducer(); - + vtkActor edgePointsActor = createVerticesActor(partEdges); - + partEdges.Delete(); //out.Delete(); partEdgesMapper.Delete(); return edgePointsActor; } - + public static vtkActor createVerticesActor(vtkFeatureEdges partEdges) { EdgePointsFilter edgePoints = new EdgePointsFilter(); - - - vtkAlgorithmOutput out = partEdges.GetOutputPort(); - edgePoints.SetInputConnection(out); - out.Delete(); - - vtkSphereSource sphereSource = new vtkSphereSource(); - vtkGlyph3D glyph3D = new vtkGlyph3D(); - out = sphereSource.GetOutputPort(); - glyph3D.SetSourceConnection(out); - out.Delete(); - - out = edgePoints.GetOutputPort(); - glyph3D.SetInputConnection(out); - out.Delete(); - - glyph3D.SetScaleFactor(0.03); - - glyph3D.Update(); - - vtkPolyDataMapper partEdgePointsMapper = new vtkPolyDataMapper(); - out = glyph3D.GetOutputPort(); - partEdgePointsMapper.SetInputConnection(out); - out.Delete(); - - vtkActor edgePointsActor = new vtkActor(); - - vtkProperty prop = edgePointsActor.GetProperty(); - prop.SetColor(0, 0, 1); - prop.Delete(); - edgePointsActor.SetMapper(partEdgePointsMapper); - - edgePointsActor.PickableOn(); - - - partEdgePointsMapper.Delete(); - edgePoints.Delete(); - sphereSource.Delete(); - - return edgePointsActor; + + + vtkAlgorithmOutput out = partEdges.GetOutputPort(); + edgePoints.SetInputConnection(out); + out.Delete(); + + vtkSphereSource sphereSource = new vtkSphereSource(); + vtkGlyph3D glyph3D = new vtkGlyph3D(); + out = sphereSource.GetOutputPort(); + glyph3D.SetSourceConnection(out); + out.Delete(); + + out = edgePoints.GetOutputPort(); + glyph3D.SetInputConnection(out); + out.Delete(); + + glyph3D.SetScaleFactor(0.03); + + glyph3D.Update(); + + vtkPolyDataMapper partEdgePointsMapper = new vtkPolyDataMapper(); + out = glyph3D.GetOutputPort(); + partEdgePointsMapper.SetInputConnection(out); + out.Delete(); + + vtkActor edgePointsActor = new vtkActor(); + + vtkProperty prop = edgePointsActor.GetProperty(); + prop.SetColor(0, 0, 1); + prop.Delete(); + edgePointsActor.SetMapper(partEdgePointsMapper); + + edgePointsActor.PickableOn(); + + + partEdgePointsMapper.Delete(); + edgePoints.Delete(); + sphereSource.Delete(); + + return edgePointsActor; } - + public static vtkActor createSilhouette(vtkRenderer ren, vtkPolyData data) { - - + + vtkPolyDataSilhouette silhouette = new vtkPolyDataSilhouette(); - + silhouette.SetInputData(data); silhouette.SetCamera(ren.GetActiveCamera()); silhouette.SetEnableFeatureAngle(0); vtkPolyDataMapper mapper = new vtkPolyDataMapper(); - + mapper.SetInputConnection(silhouette.GetOutputPort()); - + vtkActor actor = new vtkActor(); actor.SetMapper(mapper); - + actor.GetProperty().SetColor(0,0,1); actor.GetProperty().SetLineWidth(6); - + return actor; - - - + + + } } diff --git a/org.simantics.opencascade/src/org/simantics/opencascade/OCCTTool.java b/org.simantics.opencascade/src/org/simantics/opencascade/OCCTTool.java index 6eac6724..c8b65a9e 100644 --- a/org.simantics.opencascade/src/org/simantics/opencascade/OCCTTool.java +++ b/org.simantics.opencascade/src/org/simantics/opencascade/OCCTTool.java @@ -30,69 +30,69 @@ import org.jcae.opencascade.jni.TopoDS_Face; import org.jcae.opencascade.jni.TopoDS_Shape; public class OCCTTool { -public static double getBoundingBoxDiagonal(TopoDS_Shape shape) { - - double []min = new double[3]; - double []max = new double[3]; - double []mmm = new double[3]; - double []bb = new double[6]; - - // Compute bounding box: - //---------------------- - Bnd_Box boundingBox = new Bnd_Box(); - BRepBndLib.add(shape, boundingBox); - boundingBox.get(bb); - boundingBox.delete(); - - min[0] = bb[0]; min[1] = bb[1]; min[2] = bb[2]; - max[0] = bb[3]; max[1] = bb[4]; max[2] = bb[5]; - - //System.out.println("Bounding box: "+"[ "+min[0]+", "+min[1]+", " + min[2] + "] x "+"[ " +max[0] +", " +max[1] +", " +max[2] +"]"); - - // The length of the space diagonal of cuboid - for (int i = 0; i < 3; i++) mmm[i] = max[i] - min[i]; - double length = Math.sqrt(mmm[2]*mmm[2] + mmm[1]*mmm[1] + mmm[0]*mmm[0]); - - double t0 = mmm[0]*mmm[0]; - double t1 = mmm[1]*mmm[1]; - double t2 = mmm[2]*mmm[2]; - - double tol = 1.0e-6 * length; - - if((t0 < tol) || (t1 < tol) || (t2 < tol)) { - System.out.println("Shape seems to be 2D. Unable to proceed. Aborting."); - return 0; - } - return length; - } - - public static double getBoundingBoxVolume(TopoDS_Shape shape) { - - double []min = new double[3]; - double []max = new double[3]; - double []mmm = new double[3]; - double []bb = new double[6]; - - // Compute bounding box: - //---------------------- - Bnd_Box boundingBox = new Bnd_Box(); - BRepBndLib.add(shape, boundingBox); - boundingBox.get(bb); - boundingBox.delete(); - - min[0] = bb[0]; min[1] = bb[1]; min[2] = bb[2]; - max[0] = bb[3]; max[1] = bb[4]; max[2] = bb[5]; - - //System.out.println("Bounding box: "+"[ "+min[0]+", "+min[1]+", " + min[2] + "] x "+"[ " +max[0] +", " +max[1] +", " +max[2] +"]"); - - for (int i = 0; i < 3; i++) mmm[i] = max[i] - min[i]; - double vol = Math.sqrt(mmm[2]*mmm[1]*mmm[0]); - - return vol; - } - - private static GProp_GProps getGProp(TopoDS_Shape shape) { - GProp_GProps GSystem = null; + public static double getBoundingBoxDiagonal(TopoDS_Shape shape) { + + double []min = new double[3]; + double []max = new double[3]; + double []mmm = new double[3]; + double []bb = new double[6]; + + // Compute bounding box: + //---------------------- + Bnd_Box boundingBox = new Bnd_Box(); + BRepBndLib.add(shape, boundingBox); + boundingBox.get(bb); + boundingBox.delete(); + + min[0] = bb[0]; min[1] = bb[1]; min[2] = bb[2]; + max[0] = bb[3]; max[1] = bb[4]; max[2] = bb[5]; + + //System.out.println("Bounding box: "+"[ "+min[0]+", "+min[1]+", " + min[2] + "] x "+"[ " +max[0] +", " +max[1] +", " +max[2] +"]"); + + // The length of the space diagonal of cuboid + for (int i = 0; i < 3; i++) mmm[i] = max[i] - min[i]; + double length = Math.sqrt(mmm[2]*mmm[2] + mmm[1]*mmm[1] + mmm[0]*mmm[0]); + + double t0 = mmm[0]*mmm[0]; + double t1 = mmm[1]*mmm[1]; + double t2 = mmm[2]*mmm[2]; + + double tol = 1.0e-6 * length; + + if((t0 < tol) || (t1 < tol) || (t2 < tol)) { + System.out.println("Shape seems to be 2D. Unable to proceed. Aborting."); + return 0; + } + return length; + } + + public static double getBoundingBoxVolume(TopoDS_Shape shape) { + + double []min = new double[3]; + double []max = new double[3]; + double []mmm = new double[3]; + double []bb = new double[6]; + + // Compute bounding box: + //---------------------- + Bnd_Box boundingBox = new Bnd_Box(); + BRepBndLib.add(shape, boundingBox); + boundingBox.get(bb); + boundingBox.delete(); + + min[0] = bb[0]; min[1] = bb[1]; min[2] = bb[2]; + max[0] = bb[3]; max[1] = bb[4]; max[2] = bb[5]; + + //System.out.println("Bounding box: "+"[ "+min[0]+", "+min[1]+", " + min[2] + "] x "+"[ " +max[0] +", " +max[1] +", " +max[2] +"]"); + + for (int i = 0; i < 3; i++) mmm[i] = max[i] - min[i]; + double vol = Math.sqrt(mmm[2]*mmm[1]*mmm[0]); + + return vol; + } + + private static GProp_GProps getGProp(TopoDS_Shape shape) { + GProp_GProps GSystem = null; int type = 0; if (type == 0) { GSystem = new GProp_GProps(); @@ -105,113 +105,113 @@ public static double getBoundingBoxDiagonal(TopoDS_Shape shape) { BRepGProp.volumePropertiesGK(shape, GSystem, 0.001); } return GSystem; - } - + } + public static double getMass( TopoDS_Shape shape) { - + GProp_GProps GSystem = getGProp(shape); - - + + double mass = GSystem.mass(); //System.out.println("Mass " + mass); GSystem.delete(); return mass; } - + public static double[] getInertia(TopoDS_Shape shape) { GProp_GProps GSystem = getGProp(shape); - + double inertia[] = GSystem.matrixOfInertia(); GSystem.delete(); return inertia; } - + public static double[] getCentreOfMass(TopoDS_Shape shape) { GProp_GProps GSystem = getGProp(shape); - + double cm[] = GSystem.centreOfMass(); GSystem.delete(); return cm; } - + public static boolean appendToMesh (TopoDS_Face face, List meshPoints, List meshTriangles) - { - TopLoc_Location Location = new TopLoc_Location(); - - Poly_Triangulation triangulation = BRep_Tool.triangulation(face, Location); - - if(triangulation == null) { - Location.delete(); - System.out.println("Encountered empty triangulation after face"); - return false; - } - - boolean reverse = face.orientation()==TopAbs_Orientation.REVERSED; - - int lastPoint = meshPoints.size() / 3; - - int[]triangles = triangulation.triangles(); - double[]nodes = triangulation.nodes(); - - int nofTriangles = triangulation.nbTriangles(); - int nofNodes = triangulation.nbNodes(); - - - triangulation.delete(); - - if(nofTriangles < 1) { - System.out.println("No triangles for mesh on face"); - Location.delete(); - return false; - } - - if(nofNodes < 1) { - System.out.println("No nodes for mesh on face:"); - Location.delete(); - return false; - } - - for(int i = 0; i < nofTriangles; i++) - { - int n0, n1, n2; - if (!reverse) { - n0 = triangles[3 * i]; - n1 = triangles[3 * i + 1]; - n2 = triangles[3 * i + 2]; - } else { - n0 = triangles[3 * i + 2]; - n1 = triangles[3 * i + 1]; - n2 = triangles[3 * i]; - } - - meshTriangles.add(n0 + lastPoint); - meshTriangles.add(n1 + lastPoint); - meshTriangles.add(n2 + lastPoint); - } - - - GP_Trsf transformation = Location.transformation(); - Location.delete(); - - double d_mat[] = new double[16]; - - transformation.getValues(d_mat); - Matrix4d mat = new Matrix4d(d_mat); - - - for(int i = 0; i < nofNodes; i++) { - - Point3d p = new Point3d(nodes[3 * i], nodes[3 * i + 1], nodes[3 * i + 2]); - mat.transform(p); - - meshPoints.add(p.x); - meshPoints.add(p.y); - meshPoints.add(p.z); - - } - - transformation.delete(); - - return true; - } + { + TopLoc_Location Location = new TopLoc_Location(); + + Poly_Triangulation triangulation = BRep_Tool.triangulation(face, Location); + + if(triangulation == null) { + Location.delete(); + System.out.println("Encountered empty triangulation after face"); + return false; + } + + boolean reverse = face.orientation()==TopAbs_Orientation.REVERSED; + + int lastPoint = meshPoints.size() / 3; + + int[]triangles = triangulation.triangles(); + double[]nodes = triangulation.nodes(); + + int nofTriangles = triangulation.nbTriangles(); + int nofNodes = triangulation.nbNodes(); + + + triangulation.delete(); + + if(nofTriangles < 1) { + System.out.println("No triangles for mesh on face"); + Location.delete(); + return false; + } + + if(nofNodes < 1) { + System.out.println("No nodes for mesh on face:"); + Location.delete(); + return false; + } + + for(int i = 0; i < nofTriangles; i++) + { + int n0, n1, n2; + if (!reverse) { + n0 = triangles[3 * i]; + n1 = triangles[3 * i + 1]; + n2 = triangles[3 * i + 2]; + } else { + n0 = triangles[3 * i + 2]; + n1 = triangles[3 * i + 1]; + n2 = triangles[3 * i]; + } + + meshTriangles.add(n0 + lastPoint); + meshTriangles.add(n1 + lastPoint); + meshTriangles.add(n2 + lastPoint); + } + + + GP_Trsf transformation = Location.transformation(); + Location.delete(); + + double d_mat[] = new double[16]; + + transformation.getValues(d_mat); + Matrix4d mat = new Matrix4d(d_mat); + + + for(int i = 0; i < nofNodes; i++) { + + Point3d p = new Point3d(nodes[3 * i], nodes[3 * i + 1], nodes[3 * i + 2]); + mat.transform(p); + + meshPoints.add(p.x); + meshPoints.add(p.y); + meshPoints.add(p.z); + + } + + transformation.delete(); + + return true; + } } diff --git a/org.simantics.opencascade/src/org/simantics/opencascade/OccTriangulator.java b/org.simantics.opencascade/src/org/simantics/opencascade/OccTriangulator.java index aca1f438..1b1af5e8 100644 --- a/org.simantics.opencascade/src/org/simantics/opencascade/OccTriangulator.java +++ b/org.simantics.opencascade/src/org/simantics/opencascade/OccTriangulator.java @@ -34,238 +34,238 @@ import org.jcae.opencascade.jni.TopoDS_Wire; public class OccTriangulator { - - public static final double MIN_VALUE = 0.001; - - public OccTriangulator() { - - } - - - public static TopoDS_Shape getShapeFromFile(String filename) { - assert (filename != null); - String lowerFileName = filename.toLowerCase(); - if (lowerFileName.endsWith(".stp") || lowerFileName.endsWith(".step")) { - TopoDS_Shape shape = importSTEP(filename); - return shape; - } else if (lowerFileName.endsWith(".iges")) { - TopoDS_Shape shape = importIGES(filename); - return shape; - } else if (lowerFileName.endsWith(".brep")) { - TopoDS_Shape shape = importBREP(filename); - return shape; - } else { - throw new UnsupportedOperationException("Unsupported format " + filename); - } - } - - public static TopoDS_Shape importBREP(String filename) { - return importBREP(filename,1.0); // convert to meters. - } - public static TopoDS_Shape importBREP(String filename, double scale) { - org.jcae.opencascade.jni.BRep_Builder aBuilder = new org.jcae.opencascade.jni.BRep_Builder(); - org.jcae.opencascade.jni.TopoDS_Shape myShape = org.jcae.opencascade.jni.BRepTools.read(filename, aBuilder); - aBuilder.delete(); - if (Math.abs(scale-1.0) < 0.001) - return myShape; - TopoDS_Shape scaled = makeScale(myShape, scale); - myShape.delete(); - return scaled; - } - - public static TopoDS_Shape importIGES(String filename) { - org.jcae.opencascade.jni.IGESControl_Reader aReader = new org.jcae.opencascade.jni.IGESControl_Reader(); - aReader.setReadUnitM(); - aReader.readFile(filename.getBytes()); - aReader.clearShapes(); - aReader.transferRoots(); - TopoDS_Shape result = aReader.oneShape(); - aReader.delete(); - return result; - } - - public static TopoDS_Shape importSTEP(String filename) { - org.jcae.opencascade.jni.STEPControl_Reader aReader = new org.jcae.opencascade.jni.STEPControl_Reader(); - aReader.setReadUnitM(); - aReader.readFile(filename.getBytes()); - aReader.clearShapes(); - aReader.transferRoots(); - TopoDS_Shape result = aReader.oneShape(); - aReader.delete(); - return result; - } - - - - public static TopoDS_Shape makeTranslation(TopoDS_Shape aShape, double x, double y, double z) { - GP_Trsf theTransformation = new GP_Trsf(); - theTransformation.setTranslation(new double[] { x, y, z }); - BRepBuilderAPI_Transform bt = new BRepBuilderAPI_Transform(aShape, theTransformation, true); - - TopoDS_Shape shape = bt.shape(); - bt.delete(); - theTransformation.delete(); - return shape; - } - - public static TopoDS_Shape makeTorus(double[] pointStruct, double[] dirStruct, double r1, double r2) { - double[] axe = new double[6]; - System.arraycopy(pointStruct, 0, axe, 0, 3); - System.arraycopy(dirStruct, 0, axe, 3, 3); - BRepPrimAPI_MakeTorus torus = new BRepPrimAPI_MakeTorus(axe, r1, r2); - org.jcae.opencascade.jni.TopoDS_Shape tds = torus.shape(); - torus.delete(); - return tds; - } - - - public static TopoDS_Shape makeTorus(double[] pointStruct, double[] dirStruct, double[] dirStruct2, double r1, double r2) { - double[] axe = new double[9]; - System.arraycopy(pointStruct, 0, axe, 0, 3); - System.arraycopy(dirStruct, 0, axe, 3, 3); - System.arraycopy(dirStruct2, 0, axe, 6, 3); - BRepPrimAPI_MakeTorus torus = new BRepPrimAPI_MakeTorus(axe, r1, r2); - org.jcae.opencascade.jni.TopoDS_Shape tds = torus.shape(); - torus.delete(); - return tds; - } - - public static TopoDS_Shape makeTorus(double[] pointStruct, double[] dirStruct, double r1, double r2, double angle1, double angle2, double angle) { - double[] axe = new double[6]; - System.arraycopy(pointStruct, 0, axe, 0, 3); - System.arraycopy(dirStruct, 0, axe, 3, 3); - BRepPrimAPI_MakeTorus torus = new BRepPrimAPI_MakeTorus(axe, r1, r2,angle1,angle2,angle); - org.jcae.opencascade.jni.TopoDS_Shape tds = torus.shape(); - torus.delete(); - return tds; - } - - public static TopoDS_Shape makeTorus(double[] pointStruct, double[] dirStruct, double[] dirStruct2, double r1, double r2, double angle1, double angle2, double angle) { - double[] axe = new double[9]; - System.arraycopy(pointStruct, 0, axe, 0, 3); - System.arraycopy(dirStruct, 0, axe, 3, 3); - System.arraycopy(dirStruct2, 0, axe, 6, 3); - BRepPrimAPI_MakeTorus torus = new BRepPrimAPI_MakeTorus(axe, r1, r2,angle1,angle2,angle); - org.jcae.opencascade.jni.TopoDS_Shape tds = torus.shape(); - torus.delete(); - return tds; - } - - public static TopoDS_Shape makeSphere(double x, double y, double z, double radius) { - double[] c = new double[] { x, y, z }; - org.jcae.opencascade.jni.BRepPrimAPI_MakeSphere sphere = new org.jcae.opencascade.jni.BRepPrimAPI_MakeSphere(c, radius); - org.jcae.opencascade.jni.TopoDS_Shape tds = sphere.shape(); - sphere.delete(); - return tds; - } - - - public static TopoDS_Shape makeRotation(TopoDS_Shape aShape, double[] axisStruct, double angle) { - - GP_Trsf theTransformation = new GP_Trsf(); - theTransformation.setRotation(axisStruct, angle); - BRepBuilderAPI_Transform bt = new BRepBuilderAPI_Transform(aShape, theTransformation, true); - TopoDS_Shape shape = bt.shape(); - bt.delete(); - theTransformation.delete(); - return shape; - } - - public static TopoDS_Shape makeScale(TopoDS_Shape aShape, double s) { - - GP_Trsf theTransformation = new GP_Trsf(); - theTransformation.setValues(s, 0, 0, 0, - 0, s, 0, 0, - 0, 0, s, 0); - BRepBuilderAPI_Transform bt = new BRepBuilderAPI_Transform(aShape, theTransformation, true); - TopoDS_Shape shape = bt.shape(); - bt.delete(); - theTransformation.delete(); - return shape; - } - - - public static TopoDS_Shape makeCylinder(double[] pointStruct, double[] dirStruct, double radius, double height) { - double[] axe = new double[6]; - System.arraycopy(pointStruct, 0, axe, 0, 3); - System.arraycopy(dirStruct, 0, axe, 3, 3); - org.jcae.opencascade.jni.BRepPrimAPI_MakeCylinder cyl = new org.jcae.opencascade.jni.BRepPrimAPI_MakeCylinder(axe, radius, height, 2 * Math.PI); - org.jcae.opencascade.jni.TopoDS_Shape tds = cyl.shape(); - cyl.delete(); - return tds; - } - - public static TopoDS_Shape makeCopy(TopoDS_Shape topoDS_Shape) { - throw new UnsupportedOperationException(); - } - - public static TopoDS_Shape makeCone(double[] pointStruct, double[] dirStruct, double radius1, double radius2, double height) { - double[] axe = new double[6]; - System.arraycopy(pointStruct, 0, axe, 0, 3); - System.arraycopy(dirStruct, 0, axe, 3, 3); - org.jcae.opencascade.jni.BRepPrimAPI_MakeCone cone = new org.jcae.opencascade.jni.BRepPrimAPI_MakeCone(axe, radius1, radius2, height, 2 * Math.PI); - org.jcae.opencascade.jni.TopoDS_Shape tds = cone.shape(); - cone.delete(); - return tds; - } - - public static TopoDS_Shape makeCompound(TopoDS_Shape[] shapes) { - BRep_Builder builder = new BRep_Builder(); - org.jcae.opencascade.jni.TopoDS_Compound comp = new org.jcae.opencascade.jni.TopoDS_Compound(); - builder.makeCompound(comp); - for (int i = 0; i < shapes.length; i++) { - - builder.add(comp, shapes[i]); - } - builder.delete(); - return comp; - } - - - public static TopoDS_Shape makeBox(double x1, double y1, double z1, double x2, double y2, double z2) { - double[] p1 = new double[] { x1, y1, z1 }; - double[] p2 = new double[] { x2, y2, z2 }; - org.jcae.opencascade.jni.BRepPrimAPI_MakeBox box = new org.jcae.opencascade.jni.BRepPrimAPI_MakeBox(p1, p2); - org.jcae.opencascade.jni.TopoDS_Shape tds = box.shape(); - box.delete(); - return tds; - } - - public static TopoDS_Shape makeCut(TopoDS_Shape shape1, TopoDS_Shape shape2) { - org.jcae.opencascade.jni.BRepAlgoAPI_Cut cut = new org.jcae.opencascade.jni.BRepAlgoAPI_Cut(shape1, shape2); - org.jcae.opencascade.jni.TopoDS_Shape s = cut.shape(); - cut.delete(); - return s; - } - - public static TopoDS_Shape makeCommon(TopoDS_Shape shape1, TopoDS_Shape shape2) { - org.jcae.opencascade.jni.BRepAlgoAPI_Common common = new org.jcae.opencascade.jni.BRepAlgoAPI_Common(shape1, shape2); - org.jcae.opencascade.jni.TopoDS_Shape s = common.shape(); - common.delete(); - return s; - } - - public static TopoDS_Shape makeFuse(TopoDS_Shape shape1, TopoDS_Shape shape2) { - org.jcae.opencascade.jni.BRepAlgoAPI_Fuse fuse = new org.jcae.opencascade.jni.BRepAlgoAPI_Fuse(shape1, shape2); - org.jcae.opencascade.jni.TopoDS_Shape s = fuse.shape(); - fuse.delete(); - return s; - } - - - public static TopoDS_Shape makeWedge(double[] pointStruct, double[] dirStruct,double dx, double dy, double dz, double xmin, double zmin, double xmax, double zmax) { - double[] axe = new double[6]; - System.arraycopy(pointStruct, 0, axe, 0, 3); - System.arraycopy(dirStruct, 0, axe, 3, 3); - - org.jcae.opencascade.jni.BRepPrimAPI_MakeWedge wedge = new org.jcae.opencascade.jni.BRepPrimAPI_MakeWedge(axe, dx, dy, dz, xmin, zmin, xmax, zmax); - org.jcae.opencascade.jni.TopoDS_Shape s = wedge.shape(); - wedge.delete(); - return s; - } - - public static TopoDS_Shape makeEllipticCylinder(double h, double r1, double r2) { - GP_Elips ellipse; + + public static final double MIN_VALUE = 0.001; + + public OccTriangulator() { + + } + + + public static TopoDS_Shape getShapeFromFile(String filename) { + assert (filename != null); + String lowerFileName = filename.toLowerCase(); + if (lowerFileName.endsWith(".stp") || lowerFileName.endsWith(".step")) { + TopoDS_Shape shape = importSTEP(filename); + return shape; + } else if (lowerFileName.endsWith(".iges")) { + TopoDS_Shape shape = importIGES(filename); + return shape; + } else if (lowerFileName.endsWith(".brep")) { + TopoDS_Shape shape = importBREP(filename); + return shape; + } else { + throw new UnsupportedOperationException("Unsupported format " + filename); + } + } + + public static TopoDS_Shape importBREP(String filename) { + return importBREP(filename,1.0); // convert to meters. + } + public static TopoDS_Shape importBREP(String filename, double scale) { + org.jcae.opencascade.jni.BRep_Builder aBuilder = new org.jcae.opencascade.jni.BRep_Builder(); + org.jcae.opencascade.jni.TopoDS_Shape myShape = org.jcae.opencascade.jni.BRepTools.read(filename, aBuilder); + aBuilder.delete(); + if (Math.abs(scale-1.0) < 0.001) + return myShape; + TopoDS_Shape scaled = makeScale(myShape, scale); + myShape.delete(); + return scaled; + } + + public static TopoDS_Shape importIGES(String filename) { + org.jcae.opencascade.jni.IGESControl_Reader aReader = new org.jcae.opencascade.jni.IGESControl_Reader(); + aReader.setReadUnitM(); + aReader.readFile(filename.getBytes()); + aReader.clearShapes(); + aReader.transferRoots(); + TopoDS_Shape result = aReader.oneShape(); + aReader.delete(); + return result; + } + + public static TopoDS_Shape importSTEP(String filename) { + org.jcae.opencascade.jni.STEPControl_Reader aReader = new org.jcae.opencascade.jni.STEPControl_Reader(); + aReader.setReadUnitM(); + aReader.readFile(filename.getBytes()); + aReader.clearShapes(); + aReader.transferRoots(); + TopoDS_Shape result = aReader.oneShape(); + aReader.delete(); + return result; + } + + + + public static TopoDS_Shape makeTranslation(TopoDS_Shape aShape, double x, double y, double z) { + GP_Trsf theTransformation = new GP_Trsf(); + theTransformation.setTranslation(new double[] { x, y, z }); + BRepBuilderAPI_Transform bt = new BRepBuilderAPI_Transform(aShape, theTransformation, true); + + TopoDS_Shape shape = bt.shape(); + bt.delete(); + theTransformation.delete(); + return shape; + } + + public static TopoDS_Shape makeTorus(double[] pointStruct, double[] dirStruct, double r1, double r2) { + double[] axe = new double[6]; + System.arraycopy(pointStruct, 0, axe, 0, 3); + System.arraycopy(dirStruct, 0, axe, 3, 3); + BRepPrimAPI_MakeTorus torus = new BRepPrimAPI_MakeTorus(axe, r1, r2); + org.jcae.opencascade.jni.TopoDS_Shape tds = torus.shape(); + torus.delete(); + return tds; + } + + + public static TopoDS_Shape makeTorus(double[] pointStruct, double[] dirStruct, double[] dirStruct2, double r1, double r2) { + double[] axe = new double[9]; + System.arraycopy(pointStruct, 0, axe, 0, 3); + System.arraycopy(dirStruct, 0, axe, 3, 3); + System.arraycopy(dirStruct2, 0, axe, 6, 3); + BRepPrimAPI_MakeTorus torus = new BRepPrimAPI_MakeTorus(axe, r1, r2); + org.jcae.opencascade.jni.TopoDS_Shape tds = torus.shape(); + torus.delete(); + return tds; + } + + public static TopoDS_Shape makeTorus(double[] pointStruct, double[] dirStruct, double r1, double r2, double angle1, double angle2, double angle) { + double[] axe = new double[6]; + System.arraycopy(pointStruct, 0, axe, 0, 3); + System.arraycopy(dirStruct, 0, axe, 3, 3); + BRepPrimAPI_MakeTorus torus = new BRepPrimAPI_MakeTorus(axe, r1, r2,angle1,angle2,angle); + org.jcae.opencascade.jni.TopoDS_Shape tds = torus.shape(); + torus.delete(); + return tds; + } + + public static TopoDS_Shape makeTorus(double[] pointStruct, double[] dirStruct, double[] dirStruct2, double r1, double r2, double angle1, double angle2, double angle) { + double[] axe = new double[9]; + System.arraycopy(pointStruct, 0, axe, 0, 3); + System.arraycopy(dirStruct, 0, axe, 3, 3); + System.arraycopy(dirStruct2, 0, axe, 6, 3); + BRepPrimAPI_MakeTorus torus = new BRepPrimAPI_MakeTorus(axe, r1, r2,angle1,angle2,angle); + org.jcae.opencascade.jni.TopoDS_Shape tds = torus.shape(); + torus.delete(); + return tds; + } + + public static TopoDS_Shape makeSphere(double x, double y, double z, double radius) { + double[] c = new double[] { x, y, z }; + org.jcae.opencascade.jni.BRepPrimAPI_MakeSphere sphere = new org.jcae.opencascade.jni.BRepPrimAPI_MakeSphere(c, radius); + org.jcae.opencascade.jni.TopoDS_Shape tds = sphere.shape(); + sphere.delete(); + return tds; + } + + + public static TopoDS_Shape makeRotation(TopoDS_Shape aShape, double[] axisStruct, double angle) { + + GP_Trsf theTransformation = new GP_Trsf(); + theTransformation.setRotation(axisStruct, angle); + BRepBuilderAPI_Transform bt = new BRepBuilderAPI_Transform(aShape, theTransformation, true); + TopoDS_Shape shape = bt.shape(); + bt.delete(); + theTransformation.delete(); + return shape; + } + + public static TopoDS_Shape makeScale(TopoDS_Shape aShape, double s) { + + GP_Trsf theTransformation = new GP_Trsf(); + theTransformation.setValues(s, 0, 0, 0, + 0, s, 0, 0, + 0, 0, s, 0); + BRepBuilderAPI_Transform bt = new BRepBuilderAPI_Transform(aShape, theTransformation, true); + TopoDS_Shape shape = bt.shape(); + bt.delete(); + theTransformation.delete(); + return shape; + } + + + public static TopoDS_Shape makeCylinder(double[] pointStruct, double[] dirStruct, double radius, double height) { + double[] axe = new double[6]; + System.arraycopy(pointStruct, 0, axe, 0, 3); + System.arraycopy(dirStruct, 0, axe, 3, 3); + org.jcae.opencascade.jni.BRepPrimAPI_MakeCylinder cyl = new org.jcae.opencascade.jni.BRepPrimAPI_MakeCylinder(axe, radius, height, 2 * Math.PI); + org.jcae.opencascade.jni.TopoDS_Shape tds = cyl.shape(); + cyl.delete(); + return tds; + } + + public static TopoDS_Shape makeCopy(TopoDS_Shape topoDS_Shape) { + throw new UnsupportedOperationException(); + } + + public static TopoDS_Shape makeCone(double[] pointStruct, double[] dirStruct, double radius1, double radius2, double height) { + double[] axe = new double[6]; + System.arraycopy(pointStruct, 0, axe, 0, 3); + System.arraycopy(dirStruct, 0, axe, 3, 3); + org.jcae.opencascade.jni.BRepPrimAPI_MakeCone cone = new org.jcae.opencascade.jni.BRepPrimAPI_MakeCone(axe, radius1, radius2, height, 2 * Math.PI); + org.jcae.opencascade.jni.TopoDS_Shape tds = cone.shape(); + cone.delete(); + return tds; + } + + public static TopoDS_Shape makeCompound(TopoDS_Shape[] shapes) { + BRep_Builder builder = new BRep_Builder(); + org.jcae.opencascade.jni.TopoDS_Compound comp = new org.jcae.opencascade.jni.TopoDS_Compound(); + builder.makeCompound(comp); + for (int i = 0; i < shapes.length; i++) { + + builder.add(comp, shapes[i]); + } + builder.delete(); + return comp; + } + + + public static TopoDS_Shape makeBox(double x1, double y1, double z1, double x2, double y2, double z2) { + double[] p1 = new double[] { x1, y1, z1 }; + double[] p2 = new double[] { x2, y2, z2 }; + org.jcae.opencascade.jni.BRepPrimAPI_MakeBox box = new org.jcae.opencascade.jni.BRepPrimAPI_MakeBox(p1, p2); + org.jcae.opencascade.jni.TopoDS_Shape tds = box.shape(); + box.delete(); + return tds; + } + + public static TopoDS_Shape makeCut(TopoDS_Shape shape1, TopoDS_Shape shape2) { + org.jcae.opencascade.jni.BRepAlgoAPI_Cut cut = new org.jcae.opencascade.jni.BRepAlgoAPI_Cut(shape1, shape2); + org.jcae.opencascade.jni.TopoDS_Shape s = cut.shape(); + cut.delete(); + return s; + } + + public static TopoDS_Shape makeCommon(TopoDS_Shape shape1, TopoDS_Shape shape2) { + org.jcae.opencascade.jni.BRepAlgoAPI_Common common = new org.jcae.opencascade.jni.BRepAlgoAPI_Common(shape1, shape2); + org.jcae.opencascade.jni.TopoDS_Shape s = common.shape(); + common.delete(); + return s; + } + + public static TopoDS_Shape makeFuse(TopoDS_Shape shape1, TopoDS_Shape shape2) { + org.jcae.opencascade.jni.BRepAlgoAPI_Fuse fuse = new org.jcae.opencascade.jni.BRepAlgoAPI_Fuse(shape1, shape2); + org.jcae.opencascade.jni.TopoDS_Shape s = fuse.shape(); + fuse.delete(); + return s; + } + + + public static TopoDS_Shape makeWedge(double[] pointStruct, double[] dirStruct,double dx, double dy, double dz, double xmin, double zmin, double xmax, double zmax) { + double[] axe = new double[6]; + System.arraycopy(pointStruct, 0, axe, 0, 3); + System.arraycopy(dirStruct, 0, axe, 3, 3); + + org.jcae.opencascade.jni.BRepPrimAPI_MakeWedge wedge = new org.jcae.opencascade.jni.BRepPrimAPI_MakeWedge(axe, dx, dy, dz, xmin, zmin, xmax, zmax); + org.jcae.opencascade.jni.TopoDS_Shape s = wedge.shape(); + wedge.delete(); + return s; + } + + public static TopoDS_Shape makeEllipticCylinder(double h, double r1, double r2) { + GP_Elips ellipse; if (r1 < r2) { // FIXME : ellipse should be rotated, but current JNI won't allow it since Ax2 is not separate object ellipse = new GP_Elips(new double[]{0.0,-h*0.5,0.0,0.0,1.0,0.0},r2,r1); @@ -277,24 +277,24 @@ public class OccTriangulator { BRepBuilderAPI_MakeWire wire = new BRepBuilderAPI_MakeWire(ed); TopoDS_Wire w = (TopoDS_Wire) wire.shape(); BRepBuilderAPI_MakeFace face = new BRepBuilderAPI_MakeFace(w); - TopoDS_Face F = (TopoDS_Face) face.shape(); - BRepPrimAPI_MakePrism prism = new BRepPrimAPI_MakePrism(F, new double[] { 0.0, h, 0.0 }); - TopoDS_Shape shape = prism.shape(); - ellipse.delete(); - edge.delete(); - wire.delete(); - face.delete(); - ed.delete(); - w.delete(); - F.delete(); - prism.delete(); - return shape; - } - - public static TopoDS_Shape makeReqularPrism(double h, double r, int n) { - if (n < 3) - n = 3; - Vector2d vertices[] = new Vector2d[n]; + TopoDS_Face F = (TopoDS_Face) face.shape(); + BRepPrimAPI_MakePrism prism = new BRepPrimAPI_MakePrism(F, new double[] { 0.0, h, 0.0 }); + TopoDS_Shape shape = prism.shape(); + ellipse.delete(); + edge.delete(); + wire.delete(); + face.delete(); + ed.delete(); + w.delete(); + F.delete(); + prism.delete(); + return shape; + } + + public static TopoDS_Shape makeReqularPrism(double h, double r, int n) { + if (n < 3) + n = 3; + Vector2d vertices[] = new Vector2d[n]; for (int i = 0; i < n; i++) { vertices[i] = new Vector2d(Math.sin(Math.PI * 2.0 * i / n)*r,Math.cos(Math.PI * 2.0 * i / n)*r); } @@ -313,61 +313,61 @@ public class OccTriangulator { face.delete(); BRepPrimAPI_MakePrism prism = new BRepPrimAPI_MakePrism(F, new double[] { 0.0, h, 0.0 }); - TopoDS_Shape shape = prism.shape(); - prism.delete(); - - wire.delete(); - w.delete(); - F.delete(); - return shape; - } - - public static TopoDS_Shape makeFillet(TopoDS_Shape shape, double r) { - BRepFilletAPI_MakeFillet fillet = new BRepFilletAPI_MakeFillet(shape); - - TopExp_Explorer exp = new TopExp_Explorer(shape, TopAbs_ShapeEnum.EDGE); - while (exp.more()) { - TopoDS_Edge e = (TopoDS_Edge) exp.current(); - fillet.add(r, e); - e.delete(); - exp.next(); - } - TopoDS_Shape result = fillet.shape(); - exp.delete(); - shape.delete(); - fillet.delete(); - return result; - - } - - public static TopoDS_Shape makeChamfer(TopoDS_Shape shape, double d) { - BRepFilletAPI_MakeChamfer fillet = new BRepFilletAPI_MakeChamfer(shape); - - TopExp_Explorer exp = new TopExp_Explorer(shape, TopAbs_ShapeEnum.FACE); - while (exp.more()) { - TopoDS_Face f = (TopoDS_Face) exp.current(); - TopExp_Explorer exp2 = new TopExp_Explorer(f, TopAbs_ShapeEnum.EDGE); - while (exp2.more()) { - TopoDS_Edge e = (TopoDS_Edge) exp2.current(); - fillet.add(d, e, f); - exp2.next(); - e.delete(); - } - exp2.delete(); - f.delete(); - exp.next(); - } - TopoDS_Shape result = fillet.shape(); - exp.delete(); - shape.delete(); - fillet.delete(); - return result; - - } - - - public static void exportBREP(TopoDS_Shape shape, String filename) { - org.jcae.opencascade.jni.BRepTools.write(shape, filename); - } - + TopoDS_Shape shape = prism.shape(); + prism.delete(); + + wire.delete(); + w.delete(); + F.delete(); + return shape; + } + + public static TopoDS_Shape makeFillet(TopoDS_Shape shape, double r) { + BRepFilletAPI_MakeFillet fillet = new BRepFilletAPI_MakeFillet(shape); + + TopExp_Explorer exp = new TopExp_Explorer(shape, TopAbs_ShapeEnum.EDGE); + while (exp.more()) { + TopoDS_Edge e = (TopoDS_Edge) exp.current(); + fillet.add(r, e); + e.delete(); + exp.next(); + } + TopoDS_Shape result = fillet.shape(); + exp.delete(); + shape.delete(); + fillet.delete(); + return result; + + } + + public static TopoDS_Shape makeChamfer(TopoDS_Shape shape, double d) { + BRepFilletAPI_MakeChamfer fillet = new BRepFilletAPI_MakeChamfer(shape); + + TopExp_Explorer exp = new TopExp_Explorer(shape, TopAbs_ShapeEnum.FACE); + while (exp.more()) { + TopoDS_Face f = (TopoDS_Face) exp.current(); + TopExp_Explorer exp2 = new TopExp_Explorer(f, TopAbs_ShapeEnum.EDGE); + while (exp2.more()) { + TopoDS_Edge e = (TopoDS_Edge) exp2.current(); + fillet.add(d, e, f); + exp2.next(); + e.delete(); + } + exp2.delete(); + f.delete(); + exp.next(); + } + TopoDS_Shape result = fillet.shape(); + exp.delete(); + shape.delete(); + fillet.delete(); + return result; + + } + + + public static void exportBREP(TopoDS_Shape shape, String filename) { + org.jcae.opencascade.jni.BRepTools.write(shape, filename); + } + } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/actions/AddComponentAction.java b/org.simantics.plant3d/src/org/simantics/plant3d/actions/AddComponentAction.java index defee702..a39d84c8 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/actions/AddComponentAction.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/actions/AddComponentAction.java @@ -64,19 +64,19 @@ public class AddComponentAction extends vtkSwtAction { allowed.clear(); if (component instanceof Nozzle) { - if (component.getNext() == null && component.getPrevious() == null) { - allowed.add(PositionType.NEXT); - } + if (component.getNext() == null && component.getPrevious() == null) { + allowed.add(PositionType.NEXT); + } } else { - if (component.getNext() == null) { - allowed.add(PositionType.NEXT); - } - if (component.getPrevious() == null) { - allowed.add(PositionType.PREVIOUS); - } - if (component instanceof InlineComponent && !component.getControlPoint().isFixed()){ - allowed.add(PositionType.SPLIT); - } + if (component.getNext() == null) { + allowed.add(PositionType.NEXT); + } + if (component.getPrevious() == null) { + allowed.add(PositionType.PREVIOUS); + } + if (component instanceof InlineComponent && !component.getControlPoint().isFixed()){ + allowed.add(PositionType.SPLIT); + } } setEnabled(allowed.size() > 0); } @@ -88,7 +88,7 @@ public class AddComponentAction extends vtkSwtAction { @Override public void run() { - + ComponentSelectionDialog dialog = new ComponentSelectionDialog(Display.getCurrent().getActiveShell(), allowed, component); if (dialog.open() == ComponentSelectionDialog.CANCEL) return; @@ -169,19 +169,19 @@ public class AddComponentAction extends vtkSwtAction { } public void doInsert(PositionType position) { - try { - InsertInstruction inst = new InsertInstruction(); - inst.typeUri = toAdd.getUri(); - inst.angle = angle; - inst.diameter = diameter; - inst.length = length; - inst.turnRadius = turnRadius; - inst.insertPosition = insertPosition; - inst.position = position; - ComponentUtils.addComponent(root, component, inst); - } catch (Exception e) { - ExceptionUtils.logAndShowError("Cannot add component", e); - } + try { + InsertInstruction inst = new InsertInstruction(); + inst.typeUri = toAdd.getUri(); + inst.angle = angle; + inst.diameter = diameter; + inst.length = length; + inst.turnRadius = turnRadius; + inst.insertPosition = insertPosition; + inst.position = position; + ComponentUtils.addComponent(root, component, inst); + } catch (Exception e) { + ExceptionUtils.logAndShowError("Cannot add component", e); + } // try { // PipelineComponent newComponent = ComponentUtils.createComponent(root,toAdd.getUri()); // PipeControlPoint newPcp = newComponent.getControlPoint(); @@ -360,6 +360,6 @@ public class AddComponentAction extends vtkSwtAction { @Override public boolean mouseWheelMoved(MouseWheelEvent e) { - return getDefaultAction().mouseWheelMoved(e); + return getDefaultAction().mouseWheelMoved(e); } } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/actions/AddNozzleAction.java b/org.simantics.plant3d/src/org/simantics/plant3d/actions/AddNozzleAction.java index e1def918..c7cc4722 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/actions/AddNozzleAction.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/actions/AddNozzleAction.java @@ -26,10 +26,10 @@ public class AddNozzleAction extends Action { this.equipment = equipment; int fixedNozzles = equipment.numberOfFixedNozzles(); if (fixedNozzles > 0) { - int currentNozzles = equipment.getNodes().size(); - setEnabled(currentNozzles < fixedNozzles); + int currentNozzles = equipment.getNodes().size(); + setEnabled(currentNozzles < fixedNozzles); } else { - setEnabled(true); + setEnabled(true); } } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/actions/RoutePipeAction.java b/org.simantics.plant3d/src/org/simantics/plant3d/actions/RoutePipeAction.java index 3c320434..24b6a14b 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/actions/RoutePipeAction.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/actions/RoutePipeAction.java @@ -79,13 +79,13 @@ public class RoutePipeAction extends vtkSwtAction { boolean step = false; PipelineComponent endTo = null; - PositionType endType = null; - PipeControlPoint endPort = null; - - boolean reversed = false; - - private Set allowed = new HashSet(); - + PositionType endType = null; + PipeControlPoint endPort = null; + + boolean reversed = false; + + private Set allowed = new HashSet(); + public RoutePipeAction(InteractiveVtkComposite panel, P3DRootNode root) { super(panel); @@ -234,19 +234,19 @@ public class RoutePipeAction extends vtkSwtAction { } private void update(double x, double y) { switch (state) { - case NOT_ACTIVE: - return; // TODO : throw Exception? - case INITIALIZING: - return; - case SELECTING_POSITION: - return; - case SELECTING_SPLIT: - return; - case ROUTING: - updateRouting(x,y); - break; - } - return; + case NOT_ACTIVE: + return; // TODO : throw Exception? + case INITIALIZING: + return; + case SELECTING_POSITION: + return; + case SELECTING_SPLIT: + return; + case ROUTING: + updateRouting(x,y); + break; + } + return; } boolean startRemovable = false; @@ -494,10 +494,10 @@ public class RoutePipeAction extends vtkSwtAction { @Override public boolean mouseWheelMoved(MouseWheelEvent e) { - if (useDefault) { - getDefaultAction().mouseWheelMoved(e); - } - return true; + if (useDefault) { + getDefaultAction().mouseWheelMoved(e); + } + return true; } @Override @@ -509,31 +509,31 @@ public class RoutePipeAction extends vtkSwtAction { if (state == ToolState.ROUTING) { try { if (e.getClickCount() == 1) { - if (e.getButton() == MouseEvent.BUTTON1) { - if (this.added.size() > 0) { - - setLockType(LockType.NONE,true); - if (endTo != null) { - - endPiping(); - } else { - addPoint(); - } - } else { - throw new RuntimeException("kjf"); + if (e.getButton() == MouseEvent.BUTTON1) { + if (this.added.size() > 0) { + + setLockType(LockType.NONE,true); + if (endTo != null) { + + endPiping(); + } else { + addPoint(); + } + } else { + throw new RuntimeException("kjf"); // // user was selecting position of branch // lastPoint.set(startPoint); // controlPoints.add(new Point3d(startPoint)); // if (selectionLine != null) // selectionLine.removeFromParent(); // selectionLine = null; - } - } else if (e.getButton() ==MouseEvent.BUTTON2){ + } + } else if (e.getButton() ==MouseEvent.BUTTON2){ // detector.updateConstraintReference(); - } else if (e.getButton() == MouseEvent.BUTTON3){ - endPiping(); - } - } + } else if (e.getButton() == MouseEvent.BUTTON3){ + endPiping(); + } + } } catch(Exception err) { err.printStackTrace(); } @@ -627,513 +627,513 @@ public class RoutePipeAction extends vtkSwtAction { return nodes; } - - - private void updateRouting(double x, double y) { -// if(input.keyPressed(KeyEvent.VK_ESCAPE)) { -// controlPoints.clear(); -// end(); -// return; -// } -// if (input.keyPressed(KeyEvent.VK_C)) { -// useCamera = !useCamera; -// cameraAction.setChecked(useCamera); -// } - if (useDefault) { - //panel.getDefaultAction().update(); - return; - } - - endTo = null; - endType = null; - endPort = null; - Ray ray = vtkUtil.createMouseRay(panel.getRenderer(),x, y); - Vector3d o = new Vector3d(ray.pos); - Vector3d d = ray.dir; - - - if (!updateCurrentPoint(o, d)) - return; - //Point3d startPoint = new Point3d(); - double mu[] = new double[2]; - - - - INode hoverObject = null; - - List hover = isOverNode((int)x,(int)y); - if (hover.size() > 0) { - hoverObject = hover.get(0); - } + + private void updateRouting(double x, double y) { +// if(input.keyPressed(KeyEvent.VK_ESCAPE)) { +// controlPoints.clear(); +// end(); +// return; +// } +// if (input.keyPressed(KeyEvent.VK_C)) { +// useCamera = !useCamera; +// cameraAction.setChecked(useCamera); +// } + if (useDefault) { + //panel.getDefaultAction().update(); + return; + } + + endTo = null; + endType = null; + endPort = null; + + Ray ray = vtkUtil.createMouseRay(panel.getRenderer(),x, y); + Vector3d o = new Vector3d(ray.pos); + Vector3d d = ray.dir; + + + if (!updateCurrentPoint(o, d)) + return; + //Point3d startPoint = new Point3d(); + double mu[] = new double[2]; + + + + INode hoverObject = null; + + List hover = isOverNode((int)x,(int)y); + if (hover.size() > 0) { + hoverObject = hover.get(0); + } // System.out.println(hoverObject + " " + getLast()); - if (hoverObject != null) { - if (hoverObject.equals(getLast()) ) { - boolean set = false; - for (int i = 1; i < hover.size(); i++) { - hoverObject = hover.get(i); - if (!getLast().equals(hoverObject)) { - set = true; - break; - } - } - if (!set) - hoverObject = null; - } - } + if (hoverObject != null) { + if (hoverObject.equals(getLast()) ) { + boolean set = false; + for (int i = 1; i < hover.size(); i++) { + hoverObject = hover.get(i); + if (!getLast().equals(hoverObject)) { + set = true; + break; + } + } + if (!set) + hoverObject = null; + } + } // System.out.println(hoverObject); - if (hoverObject != null) { - - if (lock == LockType.NONE) { - if (hoverObject instanceof Nozzle && endingToNozzle(hoverObject,o,d)) { - endTo = (Nozzle)hoverObject; - } else if (hoverObject instanceof InlineComponent && ((InlineComponent)hoverObject).isVariableLength()) { - endTo = (InlineComponent)hoverObject; - endType = endingToStraight(endTo,mu,o,d); - } else if (hoverObject instanceof PipelineComponent && (endPort = endingToComponent(hoverObject,o,d)) != null) { - endTo = (PipelineComponent)hoverObject; - } else { - updateRoute(o,d); - } - } else { - if (hoverObject instanceof InlineComponent && ((InlineComponent)hoverObject).isVariableLength() && (endType = endingLockToStraight(hoverObject,mu)) != null) { - endTo = (InlineComponent)hoverObject; - } else if (hoverObject instanceof Nozzle && endingLockToNozzle(hoverObject)) { - endTo = (Nozzle)hoverObject; - } else if ((hoverObject instanceof PipelineComponent) && ((endPort = endingLockToComponent(hoverObject)) != null)) { - endTo = (PipelineComponent)hoverObject; - } else { - updateRoute(o,d); - } - } - if (added.contains(endTo)) - endTo = null; - - } else { - updateRoute(o,d); - } - - panel.refresh(); - } - - private boolean updateCurrentPoint(Vector3d o, Vector3d d) { + if (hoverObject != null) { + + if (lock == LockType.NONE) { + if (hoverObject instanceof Nozzle && endingToNozzle(hoverObject,o,d)) { + endTo = (Nozzle)hoverObject; + } else if (hoverObject instanceof InlineComponent && ((InlineComponent)hoverObject).isVariableLength()) { + endTo = (InlineComponent)hoverObject; + endType = endingToStraight(endTo,mu,o,d); + } else if (hoverObject instanceof PipelineComponent && (endPort = endingToComponent(hoverObject,o,d)) != null) { + endTo = (PipelineComponent)hoverObject; + } else { + updateRoute(o,d); + } + } else { + if (hoverObject instanceof InlineComponent && ((InlineComponent)hoverObject).isVariableLength() && (endType = endingLockToStraight(hoverObject,mu)) != null) { + endTo = (InlineComponent)hoverObject; + } else if (hoverObject instanceof Nozzle && endingLockToNozzle(hoverObject)) { + endTo = (Nozzle)hoverObject; + } else if ((hoverObject instanceof PipelineComponent) && ((endPort = endingLockToComponent(hoverObject)) != null)) { + endTo = (PipelineComponent)hoverObject; + } else { + updateRoute(o,d); + } + } + if (added.contains(endTo)) + endTo = null; - Vector3d point = new Vector3d(this.previousPosition); - - switch(lock) { - case X: - MathTools.intersectStraightStraight(point, new Vector3d(1.0,0.0,0.0), o,d, currentPosition, new Vector3d()); - if (step) { - currentPosition.x = Math.round(istep * currentPosition.x) / istep; - BigDecimal bx = new BigDecimal(currentPosition.x); - bx.setScale(decimals, BigDecimal.ROUND_HALF_UP); - currentPosition.x = bx.doubleValue(); - } - break; - case Y: - MathTools.intersectStraightStraight(point, new Vector3d(0.0,1.0,0.0), o,d, currentPosition, new Vector3d()); - if (step) { - currentPosition.y = Math.round(istep * currentPosition.y) / istep; - BigDecimal bx = new BigDecimal(currentPosition.y); - bx.setScale(decimals, BigDecimal.ROUND_HALF_UP); - currentPosition.y = bx.doubleValue(); - } - break; - case Z: - MathTools.intersectStraightStraight(point, new Vector3d(0.0,0.0,1.0), o,d, currentPosition, new Vector3d()); - if (step) { - currentPosition.z = Math.round(istep * currentPosition.z) / istep; - BigDecimal bx = new BigDecimal(currentPosition.z); - bx.setScale(decimals, BigDecimal.ROUND_HALF_UP); - currentPosition.z = bx.doubleValue(); - }break; - case XY: - MathTools.intersectStraightPlane(o, d, point, new Vector3d(0.0,0.0,1.0), currentPosition); - break; - case XZ: - MathTools.intersectStraightPlane(o, d, point, new Vector3d(0.0,1.0,0.0), currentPosition); - break; - case YZ: - MathTools.intersectStraightPlane(o, d, point, new Vector3d(1.0,0.0,0.0), currentPosition); - break; - case NONE: - Vector3d normal = new Vector3d(panel.getRenderer().GetActiveCamera().GetDirectionOfProjection()); - normal.normalize(); - - MathTools.intersectStraightPlane(o, d, point, normal, currentPosition); - break; - case CUSTOM: - MathTools.intersectStraightStraight(point, new Vector3d(direction), o,d, currentPosition, new Vector3d()); - double dist = MathTools.distanceFromPlane(new Vector3d(currentPosition), direction, previousPosition); - if (dist < 0.0) - currentPosition.set(previousPosition); - break; - default: - return false; - } - return true; - } - - private Vector3d getLockDir() { - switch (lock) { - case CUSTOM: - return direction; - case X: - return new Vector3d(1,0,0); - case Y: - return new Vector3d(0,1,0); - case Z: - return new Vector3d(0,0,1); - } - return null; - } - - private void updateRoute(Vector3d o, Vector3d d) { - detector.clearConstraintHighlights(); - Point3d previousPipePoint = new Point3d(previousPosition); - String s = ""; - if (lock == LockType.NONE) { - Point3d p = detector.getSnappedPoint(o, d, new Vector3d(previousPipePoint)); - if (p != null) - currentPosition = new Vector3d(p); - s += detector.getSnapString(); + } else { + updateRoute(o,d); + } + + panel.refresh(); + } + + private boolean updateCurrentPoint(Vector3d o, Vector3d d) { - } else { - Vector3d dir = new Vector3d(currentPosition); - dir.sub(previousPipePoint); - Point3d p = detector.getPointSnap(new Vector3d(previousPipePoint), dir); - if (p != null) - currentPosition = new Vector3d(p); - s += detector.getSnapString(); + Vector3d point = new Vector3d(this.previousPosition); + + switch(lock) { + case X: + MathTools.intersectStraightStraight(point, new Vector3d(1.0,0.0,0.0), o,d, currentPosition, new Vector3d()); + if (step) { + currentPosition.x = Math.round(istep * currentPosition.x) / istep; + BigDecimal bx = new BigDecimal(currentPosition.x); + bx.setScale(decimals, BigDecimal.ROUND_HALF_UP); + currentPosition.x = bx.doubleValue(); + } + break; + case Y: + MathTools.intersectStraightStraight(point, new Vector3d(0.0,1.0,0.0), o,d, currentPosition, new Vector3d()); + if (step) { + currentPosition.y = Math.round(istep * currentPosition.y) / istep; + BigDecimal bx = new BigDecimal(currentPosition.y); + bx.setScale(decimals, BigDecimal.ROUND_HALF_UP); + currentPosition.y = bx.doubleValue(); + } + break; + case Z: + MathTools.intersectStraightStraight(point, new Vector3d(0.0,0.0,1.0), o,d, currentPosition, new Vector3d()); + if (step) { + currentPosition.z = Math.round(istep * currentPosition.z) / istep; + BigDecimal bx = new BigDecimal(currentPosition.z); + bx.setScale(decimals, BigDecimal.ROUND_HALF_UP); + currentPosition.z = bx.doubleValue(); + }break; + case XY: + MathTools.intersectStraightPlane(o, d, point, new Vector3d(0.0,0.0,1.0), currentPosition); + break; + case XZ: + MathTools.intersectStraightPlane(o, d, point, new Vector3d(0.0,1.0,0.0), currentPosition); + break; + case YZ: + MathTools.intersectStraightPlane(o, d, point, new Vector3d(1.0,0.0,0.0), currentPosition); + break; + case NONE: + Vector3d normal = new Vector3d(panel.getRenderer().GetActiveCamera().GetDirectionOfProjection()); + normal.normalize(); + + MathTools.intersectStraightPlane(o, d, point, normal, currentPosition); + break; + case CUSTOM: + MathTools.intersectStraightStraight(point, new Vector3d(direction), o,d, currentPosition, new Vector3d()); + double dist = MathTools.distanceFromPlane(new Vector3d(currentPosition), direction, previousPosition); + if (dist < 0.0) + currentPosition.set(previousPosition); + break; + default: + return false; + } + return true; + } + + private Vector3d getLockDir() { + switch (lock) { + case CUSTOM: + return direction; + case X: + return new Vector3d(1,0,0); + case Y: + return new Vector3d(0,1,0); + case Z: + return new Vector3d(0,0,1); + } + return null; + } + + private void updateRoute(Vector3d o, Vector3d d) { + detector.clearConstraintHighlights(); + Point3d previousPipePoint = new Point3d(previousPosition); + String s = ""; + if (lock == LockType.NONE) { + Point3d p = detector.getSnappedPoint(o, d, new Vector3d(previousPipePoint)); + if (p != null) + currentPosition = new Vector3d(p); + s += detector.getSnapString(); - } - //System.out.println(previousPosition + " -> " + currentPosition); -// double dist = MathTools.distance(previousPosition, currentPosition); -// if (dist < pipeRun.getTurnRadius()) { -// s += "Too close"; -// Vector3d v = new Vector3d(currentPosition); -// v.sub(previousPosition); -// double vl = v.length(); -// if (vl > MathTools.NEAR_ZERO) { -// v.scale(1.0/vl); -// } else { -// -// return; -// } -// v.scale(pipeRun.getTurnRadius()); -// v.add(previousPosition); -// currentPosition.set(v); -// } - - updateCurrentPoint(); - s += currentPosition.toString(); - setInfoText(s); - } - - vtkTextActor infoActor; - - private void setInfoText(String text) { - //System.out.println(text); - if (infoActor == null) { - infoActor = new vtkTextActor(); - infoActor.GetTextProperty().SetColor(0.0, 0.0, 0.0); - infoActor.GetTextProperty().ShadowOff(); - infoActor.GetTextProperty().ItalicOff(); - infoActor.GetTextProperty().BoldOff(); - infoActor.GetTextProperty().SetFontSize(18); - infoActor.GetTextProperty().Delete(); - infoActor.GetProperty().SetColor(0.0, 0.0, 0.0); - infoActor.GetProperty().Delete(); + } else { + Vector3d dir = new Vector3d(currentPosition); + dir.sub(previousPipePoint); + Point3d p = detector.getPointSnap(new Vector3d(previousPipePoint), dir); + if (p != null) + currentPosition = new Vector3d(p); + s += detector.getSnapString(); - - infoActor.SetPosition(10,10); - panel.getRenderer().AddActor(infoActor); - } - infoActor.SetInput(text); - } - - private boolean endingToNozzle(INode nozzleNode,Vector3d o, Vector3d d) { - Nozzle nozzle = (Nozzle)nozzleNode; - PipeControlPoint pcp =nozzle.getControlPoint(); - if (pcp != null && (pcp.getNext() != null || - pcp.getPrevious() != null)) - return false; // nozzle is already connected to pipe - currentPosition = pcp.getWorldPosition(); - Point3d previousPipePoint = new Point3d(previousPosition); - Point3d p = detector.getSnappedPoint(o, d, new Vector3d(previousPipePoint)); - if (p != null) { - if (MathTools.distance(p, currentPosition) > NOZZLE_SNAP_DISTANCE) { - return false; - } - } - - updateCurrentPoint(); - - setInfoText("Connect to nozzle " + currentPosition); - return true; - - } - - private PositionType endingToStraight(INode straightNode, double mu[], Vector3d o, Vector3d d) { - InlineComponent s = (InlineComponent)straightNode; - String info = ""; - Point3d sStart = new Point3d(); - Point3d sEnd = new Point3d(); - s.getEnds(sStart, sEnd); - //detector.clearConstraintHighlights(); - - Point3d previousPipePoint = new Point3d(previousPosition); - //String st = ""; - if (lock == LockType.NONE) { - Point3d p = detector.getSnappedPoint(o, d, new Vector3d(previousPipePoint)); - if (p != null) { - currentPosition = new Vector3d(p); - // snapping is detected, check if snapped point can create branch with straight - PositionType t = endingLockToStraight(s, mu); - if (t != null) - return t; - // if not, we'll have to remove highlight that was added when snapped point was detected - detector.clearConstraintHighlights(); - } - + } +// System.out.println(previousPosition + " -> " + currentPosition); +// double dist = MathTools.distance(previousPosition, currentPosition); +// if (dist < pipeRun.getTurnRadius()) { +// s += "Too close"; +// Vector3d v = new Vector3d(currentPosition); +// v.sub(previousPosition); +// double vl = v.length(); +// if (vl > MathTools.NEAR_ZERO) { +// v.scale(1.0/vl); +// } else { +// +// return; +// } +// v.scale(pipeRun.getTurnRadius()); +// v.add(previousPosition); +// currentPosition.set(v); +// } + + updateCurrentPoint(); + s += currentPosition.toString(); + setInfoText(s); + } + + vtkTextActor infoActor; + + private void setInfoText(String text) { + //System.out.println(text); + if (infoActor == null) { + infoActor = new vtkTextActor(); + infoActor.GetTextProperty().SetColor(0.0, 0.0, 0.0); + infoActor.GetTextProperty().ShadowOff(); + infoActor.GetTextProperty().ItalicOff(); + infoActor.GetTextProperty().BoldOff(); + infoActor.GetTextProperty().SetFontSize(18); + infoActor.GetTextProperty().Delete(); + infoActor.GetProperty().SetColor(0.0, 0.0, 0.0); + infoActor.GetProperty().Delete(); - Vector3d sDir = new Vector3d(sEnd); - sDir.sub(sStart); - MathTools.intersectStraightStraight(sStart, sDir, o, d, currentPosition, new Point3d(), mu); - + + infoActor.SetPosition(10,10); + panel.getRenderer().AddActor(infoActor); + } + infoActor.SetInput(text); + } + + private boolean endingToNozzle(INode nozzleNode,Vector3d o, Vector3d d) { + Nozzle nozzle = (Nozzle)nozzleNode; + PipeControlPoint pcp =nozzle.getControlPoint(); + if (pcp != null && (pcp.getNext() != null || + pcp.getPrevious() != null)) + return false; // nozzle is already connected to pipe + currentPosition = pcp.getWorldPosition(); + Point3d previousPipePoint = new Point3d(previousPosition); + Point3d p = detector.getSnappedPoint(o, d, new Vector3d(previousPipePoint)); + if (p != null) { + if (MathTools.distance(p, currentPosition) > NOZZLE_SNAP_DISTANCE) { + return false; + } + } + + updateCurrentPoint(); + + setInfoText("Connect to nozzle " + currentPosition); + return true; + + } + + private PositionType endingToStraight(INode straightNode, double mu[], Vector3d o, Vector3d d) { + InlineComponent s = (InlineComponent)straightNode; + String info = ""; + Point3d sStart = new Point3d(); + Point3d sEnd = new Point3d(); + s.getEnds(sStart, sEnd); + //detector.clearConstraintHighlights(); + + Point3d previousPipePoint = new Point3d(previousPosition); + //String st = ""; + if (lock == LockType.NONE) { + Point3d p = detector.getSnappedPoint(o, d, new Vector3d(previousPipePoint)); + if (p != null) { + currentPosition = new Vector3d(p); + // snapping is detected, check if snapped point can create branch with straight + PositionType t = endingLockToStraight(s, mu); + if (t != null) + return t; + // if not, we'll have to remove highlight that was added when snapped point was detected + detector.clearConstraintHighlights(); + } + - } else { - throw new RuntimeException("Lock shouldn't be on"); + Vector3d sDir = new Vector3d(sEnd); + sDir.sub(sStart); + MathTools.intersectStraightStraight(sStart, sDir, o, d, currentPosition, new Point3d(), mu); + - } - - updateCurrentPoint(); - - // branch point must lie between straight's ends. If connection point is exactly - // on straight end user may want to connect pipes to each other - // TODO : take account sizes of inline components) - // TODO : actually make connection if its detected - boolean connectPrev = false; - boolean connectNext = false; - - if (mu[0] < 0.0) { - currentPosition.set(sStart); - connectPrev = true; - } - else if (mu[0] > 1.0) { - currentPosition.set(sEnd); - connectNext = true; - } - boolean connect = false; - if (connectPrev) { - PipeControlPoint pcp = s.getControlPoint(); - if (pcp.getPrevious() == null) - connect = true; - } else if (connectNext) { - PipeControlPoint pcp = s.getControlPoint(); - if (pcp.getNext() == null) - connect = true; - } - - updateCurrentPoint(); - - if (connect) - info += "Connect pipes :"; - else - info += "Make Branch :"; - - setInfoText(info + currentPosition + " " + Math.max(0.0, Math.min(mu[0], 1.0))); - if (connect) { - if (connectNext) { - return PositionType.NEXT; - } else { - return PositionType.PREVIOUS; - } - - } - return PositionType.SPLIT; - - } - - private PipeControlPoint endingToComponent(INode componentNode, Vector3d o, Vector3d d) { - PipelineComponent component = (PipelineComponent)componentNode; - PipeControlPoint pcp = component.getControlPoint(); - if (component instanceof EndComponent) { - if (pcp.getNext() != null || pcp.getPrevious() != null) - return null; - return pcp; - } else if (component instanceof TurnComponent) { - if (pcp.getNext() == null || pcp.getPrevious() == null) - return pcp; - return null; - } else if (component instanceof InlineComponent) { - // TODO : scan all empty pcps of the component and select closest one. - if (pcp.getNext() == null || pcp.getPrevious() == null) - return pcp; - return null; - } + } else { + throw new RuntimeException("Lock shouldn't be on"); - return null; - } - - private PositionType endingLockToStraight(INode straightNode, double mu[]) { - InlineComponent s = (InlineComponent)straightNode; - Point3d sStart = new Point3d(); - Point3d sEnd = new Point3d(); - s.getControlPoint().getInlineControlPointEnds(sStart, sEnd); - Vector3d sDir = new Vector3d(sEnd); - sDir.sub(sStart); - Vector3d dir = new Vector3d(currentPosition); - Point3d prev = new Point3d(previousPosition); - dir.sub(prev); - // intersection point in pipe where branch would be inserted to - Vector3d branchPoint = new Vector3d(); - // intersection point in straight pipe that is currently routed - Vector3d routePoint = new Vector3d(); - MathTools.intersectStraightStraight(sStart, sDir, new Vector3d(prev), dir, branchPoint, routePoint, mu); - routePoint.sub(branchPoint); - // startPoint of branch must be between pipe ends - // TODO : take account sizes of elbows (or other components) - // branch point must be between pipe ends and intersection points must be quite close to each other - if (mu[0] > 0.0 && mu[0] < 1.0 && routePoint.lengthSquared() < BRANCH_SNAP_DISTANCE) { - currentPosition.set(branchPoint); - - updateCurrentPoint(); - - setInfoText("Make branch (l) :" + currentPosition + " " + Math.max(0.0, Math.min(mu[0], 1.0)) + " " + routePoint.lengthSquared()); - return PositionType.SPLIT; - } - return null; - } - - private boolean endingLockToNozzle(INode nozzleNode) { - Nozzle nozzle = (Nozzle)nozzleNode; - Vector3d dir = new Vector3d(currentPosition); - Point3d prev = new Point3d(previousPosition); - dir.sub(prev); - Vector3d nozzleLoc = nozzle.getWorldPosition(); - double u[] = new double[1]; - Vector3d closest = MathTools.closestPointOnStraight(new Point3d(nozzleLoc), new Point3d(prev), new Vector3d(dir), u); - double dist = MathTools.distanceSquared(nozzleLoc,closest); - if (dist < BRANCH_SNAP_DISTANCE) { - // FIXME : directions should be checked (insert an elbow) - currentPosition.set(nozzleLoc); - updateCurrentPoint(); - setInfoText("Connect to nozzle (l) :" + currentPosition); - return true; - } - //System.out.println(u[0]); - return false; - } - - private PipeControlPoint endingLockToComponent(INode componentNode) { - // we'll must scan all free pcp's and their direction to accept the connection. - return null; - } - - private void addPoint() throws Exception { - InlineComponent previous = (InlineComponent)getLast(); - PipeControlPoint previousCP = previous.getControlPoint(); - TurnComponent turn = ComponentUtils.createTurn(root); - InlineComponent straight = ComponentUtils.createStraight(root); - PipeControlPoint turnCP = turn.getControlPoint(); - PipeControlPoint straightCP = straight.getControlPoint(); - straight.setName(pipeRun.getUniqueName("Pipe")); - turn.setName(pipeRun.getUniqueName("Elbow")); - pipeRun.addChild(turn); - pipeRun.addChild(straight); - added.add(turn); - added.add(straight); - - turnCP.setDeletable(false); // mark turnCP nonDeletable so that PipingRules won't delete it immediately. - - if (!reversed) { - previousCP.setNext(turnCP); - turnCP.setPrevious(previousCP); - turnCP.setNext(straightCP); - straightCP.setPrevious(turnCP); - } else { - previousCP.setPrevious(turnCP); - turnCP.setNext(previousCP); - turnCP.setPrevious(straightCP); - straightCP.setNext(turnCP); - } - - turnCP.setWorldPosition(currentPosition); - turnCP.setTurnAngle(0.0); - turnCP.setLength(0.0); - straightCP.setWorldPosition(currentPosition); - straightCP.setLength(0.0); - - setPreviousPosition(currentPosition); - updateCurrentPoint(); - - - - } - - /** - * Updates tool graphics for current point - */ - private void updateCurrentPoint() { - InlineComponent straight = (InlineComponent)added.get(added.size()-1); - // TODO: the inline length is from previous update step. - double l; - if (!reversed) - l = straight.getPrevious().getControlPoint().getInlineLength(); - else - l = straight.getNext().getControlPoint().getInlineLength(); - Vector3d v = new Vector3d(); - v.sub(currentPosition, previousPosition); - double length = v.length(); - if (length > MathTools.NEAR_ZERO) { - v.scale(1.0/length); - v.scale(0.5*(length+l)); - v.add(previousPosition); - straight.getControlPoint().setWorldPosition(v); - straight.getControlPoint().setLength(length); - } - try { - PipingRules.positionUpdate(straight.getControlPoint(),false); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); + } + + updateCurrentPoint(); + + // branch point must lie between straight's ends. If connection point is exactly + // on straight end user may want to connect pipes to each other + // TODO : take account sizes of inline components) + // TODO : actually make connection if its detected + boolean connectPrev = false; + boolean connectNext = false; + + if (mu[0] < 0.0) { + currentPosition.set(sStart); + connectPrev = true; + } + else if (mu[0] > 1.0) { + currentPosition.set(sEnd); + connectNext = true; + } + boolean connect = false; + if (connectPrev) { + PipeControlPoint pcp = s.getControlPoint(); + if (pcp.getPrevious() == null) + connect = true; + } else if (connectNext) { + PipeControlPoint pcp = s.getControlPoint(); + if (pcp.getNext() == null) + connect = true; + } + + updateCurrentPoint(); + + if (connect) + info += "Connect pipes :"; + else + info += "Make Branch :"; + + setInfoText(info + currentPosition + " " + Math.max(0.0, Math.min(mu[0], 1.0))); + if (connect) { + if (connectNext) { + return PositionType.NEXT; + } else { + return PositionType.PREVIOUS; } - } - - private PipelineComponent getLast() { - if (added.size() == 0) - return startComponent; - return added.get(added.size()-1); - } - - - /** - * Removes last point from pipeline - */ - public void removePoint() { - if (added.size() < 3) - return; - InlineComponent straight = (InlineComponent)added.remove(added.size()-1); - TurnComponent turn = (TurnComponent)added.remove(added.size()-1); - straight.getControlPoint().remove(); - turn.getControlPoint().remove(); - if (added.size() > 1) { - setPreviousPosition(added.get(added.size()-2).getWorldPosition()); - } else { - setPreviousPosition(startComponent.getWorldPosition()); - if (direction != null) - setLockType(LockType.CUSTOM, true); - } - - } - - private void endPiping() throws Exception { - state = ToolState.NOT_ACTIVE; - - if (endTo != null) { - ComponentUtils.connect(getLast(), endTo, endType, currentPosition); - } - panel.useDefaultAction(); - } + + } + return PositionType.SPLIT; + + } + + private PipeControlPoint endingToComponent(INode componentNode, Vector3d o, Vector3d d) { + PipelineComponent component = (PipelineComponent)componentNode; + PipeControlPoint pcp = component.getControlPoint(); + if (component instanceof EndComponent) { + if (pcp.getNext() != null || pcp.getPrevious() != null) + return null; + return pcp; + } else if (component instanceof TurnComponent) { + if (pcp.getNext() == null || pcp.getPrevious() == null) + return pcp; + return null; + } else if (component instanceof InlineComponent) { + // TODO : scan all empty pcps of the component and select closest one. + if (pcp.getNext() == null || pcp.getPrevious() == null) + return pcp; + return null; + } + + return null; + } + + private PositionType endingLockToStraight(INode straightNode, double mu[]) { + InlineComponent s = (InlineComponent)straightNode; + Point3d sStart = new Point3d(); + Point3d sEnd = new Point3d(); + s.getControlPoint().getInlineControlPointEnds(sStart, sEnd); + Vector3d sDir = new Vector3d(sEnd); + sDir.sub(sStart); + Vector3d dir = new Vector3d(currentPosition); + Point3d prev = new Point3d(previousPosition); + dir.sub(prev); + // intersection point in pipe where branch would be inserted to + Vector3d branchPoint = new Vector3d(); + // intersection point in straight pipe that is currently routed + Vector3d routePoint = new Vector3d(); + MathTools.intersectStraightStraight(sStart, sDir, new Vector3d(prev), dir, branchPoint, routePoint, mu); + routePoint.sub(branchPoint); + // startPoint of branch must be between pipe ends + // TODO : take account sizes of elbows (or other components) + // branch point must be between pipe ends and intersection points must be quite close to each other + if (mu[0] > 0.0 && mu[0] < 1.0 && routePoint.lengthSquared() < BRANCH_SNAP_DISTANCE) { + currentPosition.set(branchPoint); + + updateCurrentPoint(); + + setInfoText("Make branch (l) :" + currentPosition + " " + Math.max(0.0, Math.min(mu[0], 1.0)) + " " + routePoint.lengthSquared()); + return PositionType.SPLIT; + } + return null; + } + + private boolean endingLockToNozzle(INode nozzleNode) { + Nozzle nozzle = (Nozzle)nozzleNode; + Vector3d dir = new Vector3d(currentPosition); + Point3d prev = new Point3d(previousPosition); + dir.sub(prev); + Vector3d nozzleLoc = nozzle.getWorldPosition(); + double u[] = new double[1]; + Vector3d closest = MathTools.closestPointOnStraight(new Point3d(nozzleLoc), new Point3d(prev), new Vector3d(dir), u); + double dist = MathTools.distanceSquared(nozzleLoc,closest); + if (dist < BRANCH_SNAP_DISTANCE) { + // FIXME : directions should be checked (insert an elbow) + currentPosition.set(nozzleLoc); + updateCurrentPoint(); + setInfoText("Connect to nozzle (l) :" + currentPosition); + return true; + } + //System.out.println(u[0]); + return false; + } + + private PipeControlPoint endingLockToComponent(INode componentNode) { + // we'll must scan all free pcp's and their direction to accept the connection. + return null; + } + + private void addPoint() throws Exception { + InlineComponent previous = (InlineComponent)getLast(); + PipeControlPoint previousCP = previous.getControlPoint(); + TurnComponent turn = ComponentUtils.createTurn(root); + InlineComponent straight = ComponentUtils.createStraight(root); + PipeControlPoint turnCP = turn.getControlPoint(); + PipeControlPoint straightCP = straight.getControlPoint(); + straight.setName(pipeRun.getUniqueName("Pipe")); + turn.setName(pipeRun.getUniqueName("Elbow")); + pipeRun.addChild(turn); + pipeRun.addChild(straight); + added.add(turn); + added.add(straight); + + turnCP.setDeletable(false); // mark turnCP nonDeletable so that PipingRules won't delete it immediately. + + if (!reversed) { + previousCP.setNext(turnCP); + turnCP.setPrevious(previousCP); + turnCP.setNext(straightCP); + straightCP.setPrevious(turnCP); + } else { + previousCP.setPrevious(turnCP); + turnCP.setNext(previousCP); + turnCP.setPrevious(straightCP); + straightCP.setNext(turnCP); + } + + turnCP.setWorldPosition(currentPosition); + turnCP.setTurnAngle(0.0); + turnCP.setLength(0.0); + straightCP.setWorldPosition(currentPosition); + straightCP.setLength(0.0); + + setPreviousPosition(currentPosition); + updateCurrentPoint(); + + + + } + + /** + * Updates tool graphics for current point + */ + private void updateCurrentPoint() { + InlineComponent straight = (InlineComponent)added.get(added.size()-1); + // TODO: the inline length is from previous update step. + double l; + if (!reversed) + l = straight.getPrevious().getControlPoint().getInlineLength(); + else + l = straight.getNext().getControlPoint().getInlineLength(); + Vector3d v = new Vector3d(); + v.sub(currentPosition, previousPosition); + double length = v.length(); + if (length > MathTools.NEAR_ZERO) { + v.scale(1.0/length); + v.scale(0.5*(length+l)); + v.add(previousPosition); + straight.getControlPoint().setWorldPosition(v); + straight.getControlPoint().setLength(length); + } + try { + PipingRules.positionUpdate(straight.getControlPoint(),false); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + private PipelineComponent getLast() { + if (added.size() == 0) + return startComponent; + return added.get(added.size()-1); + } + + + /** + * Removes last point from pipeline + */ + public void removePoint() { + if (added.size() < 3) + return; + InlineComponent straight = (InlineComponent)added.remove(added.size()-1); + TurnComponent turn = (TurnComponent)added.remove(added.size()-1); + straight.getControlPoint().remove(); + turn.getControlPoint().remove(); + if (added.size() > 1) { + setPreviousPosition(added.get(added.size()-2).getWorldPosition()); + } else { + setPreviousPosition(startComponent.getWorldPosition()); + if (direction != null) + setLockType(LockType.CUSTOM, true); + } + + } + + private void endPiping() throws Exception { + state = ToolState.NOT_ACTIVE; + + if (endTo != null) { + ComponentUtils.connect(getLast(), endTo, endType, currentPosition); + } + panel.useDefaultAction(); + } } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/actions/TranslateInlineAction.java b/org.simantics.plant3d/src/org/simantics/plant3d/actions/TranslateInlineAction.java index c8c86224..1bb2874c 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/actions/TranslateInlineAction.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/actions/TranslateInlineAction.java @@ -62,13 +62,13 @@ public class TranslateInlineAction extends TranslateAction{ // We may have offsets in the path leg, hence we have to project the coordinates. Vector3d wp = node.getWorldPosition(); if (prev.getControlPoint().isVariableLength()) - s = MathTools.closestPointOnStraight(ps, wp, dir); + s = MathTools.closestPointOnStraight(ps, wp, dir); else - s = MathTools.closestPointOnStraight(pe, wp, dir); + s = MathTools.closestPointOnStraight(pe, wp, dir); if (next.getControlPoint().isVariableLength()) - e = MathTools.closestPointOnStraight(ne, wp, dir); + e = MathTools.closestPointOnStraight(ne, wp, dir); else - e = MathTools.closestPointOnStraight(ns, wp, dir); + e = MathTools.closestPointOnStraight(ns, wp, dir); // Remove component's own space from end points to get actual movement range double l = comp.getControlPoint().getInlineLength(); Vector3d ld = new Vector3d(dir); @@ -132,13 +132,13 @@ public class TranslateInlineAction extends TranslateAction{ Vector3d p = node.getWorldPosition(); Vector3d i1 = new Vector3d(); - Vector3d i2 = new Vector3d(); - - double mu[] = new double[2]; - MathTools.intersectStraightStraight( p, dir,ray.pos, ray.dir, i2, i1,mu); - - Vector3d t = MathTools.closestPointOnEdge(i1, s, e); - return t; + Vector3d i2 = new Vector3d(); + + double mu[] = new double[2]; + MathTools.intersectStraightStraight( p, dir,ray.pos, ray.dir, i2, i1,mu); + + Vector3d t = MathTools.closestPointOnEdge(i1, s, e); + return t; } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/dialog/ComponentSelectionDialog.java b/org.simantics.plant3d/src/org/simantics/plant3d/dialog/ComponentSelectionDialog.java index adfd98c9..30f2540d 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/dialog/ComponentSelectionDialog.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/dialog/ComponentSelectionDialog.java @@ -46,8 +46,8 @@ import org.simantics.utils.ui.ExceptionUtils; public class ComponentSelectionDialog extends Dialog implements ISelectionChangedListener{ - private ResourceManager resourceManager; - + private ResourceManager resourceManager; + private Item selected; private Set allowed; private Set filterAllowed; @@ -91,8 +91,8 @@ public class ComponentSelectionDialog extends Dialog implements ISelectionChange @Override protected Control createDialogArea(Composite parent) { - resourceManager = new LocalResourceManager(JFaceResources.getResources(), parent); - + resourceManager = new LocalResourceManager(JFaceResources.getResources(), parent); + Composite composite = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(2,false); layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); @@ -170,42 +170,42 @@ public class ComponentSelectionDialog extends Dialog implements ISelectionChange GridDataFactory.fillDefaults().minSize(500, 500).hint(500, 500).applyTo(composite); Label label = new Label(composite, SWT.NONE); - label.setText("Position"); + label.setText("Position"); Composite buttonComposite = new Composite(composite, SWT.NONE); - startButton = new Button(buttonComposite, SWT.TOGGLE); - middleButton = new Button(buttonComposite, SWT.TOGGLE); - endButton = new Button(buttonComposite, SWT.TOGGLE); - startButton.setImage(resourceManager.createImage(Activator.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/insert_start.png"))); - middleButton.setImage(resourceManager.createImage(Activator.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/insert_middle.png"))); - endButton.setImage(resourceManager.createImage(Activator.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/insert_end.png"))); - GridDataFactory.fillDefaults().grab(true, false).align(SWT.FILL, SWT.TOP).applyTo(buttonComposite); - GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite); + startButton = new Button(buttonComposite, SWT.TOGGLE); + middleButton = new Button(buttonComposite, SWT.TOGGLE); + endButton = new Button(buttonComposite, SWT.TOGGLE); + startButton.setImage(resourceManager.createImage(Activator.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/insert_start.png"))); + middleButton.setImage(resourceManager.createImage(Activator.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/insert_middle.png"))); + endButton.setImage(resourceManager.createImage(Activator.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/insert_end.png"))); + GridDataFactory.fillDefaults().grab(true, false).align(SWT.FILL, SWT.TOP).applyTo(buttonComposite); + GridLayoutFactory.fillDefaults().numColumns(3).applyTo(buttonComposite); + + startButton.setEnabled(false); + middleButton.setEnabled(false); + endButton.setEnabled(false); + + startButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + updateInsertPosition(PositionType.PREVIOUS); + } + }); + + middleButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + updateInsertPosition(PositionType.SPLIT); + } + }); + endButton.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + updateInsertPosition(PositionType.NEXT); + } + }); + endButton.setSelection(true); - startButton.setEnabled(false); - middleButton.setEnabled(false); - endButton.setEnabled(false); - - startButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - updateInsertPosition(PositionType.PREVIOUS); - } - }); - - middleButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - updateInsertPosition(PositionType.SPLIT); - } - }); - endButton.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - updateInsertPosition(PositionType.NEXT); - } - }); - endButton.setSelection(true); - label = new Label(composite, SWT.NONE); label.setText("Length"); lengthText = new Text(composite, SWT.SINGLE|SWT.BORDER); @@ -289,12 +289,12 @@ public class ComponentSelectionDialog extends Dialog implements ISelectionChange private void updateInsertPosition(PositionType type) { - if (insertPosition == type) - return; - endButton.setSelection(type == PositionType.NEXT); - middleButton.setSelection(type == PositionType.SPLIT); - startButton.setSelection(type == PositionType.PREVIOUS); - insertPosition = type; + if (insertPosition == type) + return; + endButton.setSelection(type == PositionType.NEXT); + middleButton.setSelection(type == PositionType.SPLIT); + startButton.setSelection(type == PositionType.PREVIOUS); + insertPosition = type; } @Override @@ -302,18 +302,18 @@ public class ComponentSelectionDialog extends Dialog implements ISelectionChange IStructuredSelection sel = (IStructuredSelection)event.getSelection(); Item i = (Item)sel.getFirstElement(); if (i != null) { - selected = i; - if (event.getSource() == inlineViewer) { - turnViewer.setSelection(new StructuredSelection()); - endViewer.setSelection(new StructuredSelection()); - } else if (event.getSource() == turnViewer) { - inlineViewer.setSelection(new StructuredSelection()); - endViewer.setSelection(new StructuredSelection()); - } else if (event.getSource() == endViewer) { - inlineViewer.setSelection(new StructuredSelection()); - turnViewer.setSelection(new StructuredSelection()); - } - validate(); + selected = i; + if (event.getSource() == inlineViewer) { + turnViewer.setSelection(new StructuredSelection()); + endViewer.setSelection(new StructuredSelection()); + } else if (event.getSource() == turnViewer) { + inlineViewer.setSelection(new StructuredSelection()); + endViewer.setSelection(new StructuredSelection()); + } else if (event.getSource() == endViewer) { + inlineViewer.setSelection(new StructuredSelection()); + turnViewer.setSelection(new StructuredSelection()); + } + validate(); } } @@ -326,66 +326,66 @@ public class ComponentSelectionDialog extends Dialog implements ISelectionChange } else if (selected.isCode()) {// TODO : instead of disabling the button, we should filter the content. ok = false; } else { - lenghtAdjustable = ((selected.getType() == Type.INLINE) && selected.isVariable()); - if (insertAdjustable) { - switch (selected.getType()) { - case END: - startButton.setEnabled(false); - middleButton.setEnabled(false); - endButton.setEnabled(true); - updateInsertPosition(PositionType.NEXT); - break; - case INLINE: - if (!selected.isVariable()) { - startButton.setEnabled(true); - middleButton.setEnabled(true); - endButton.setEnabled(true); - } else { - startButton.setEnabled(false); - middleButton.setEnabled(false); - endButton.setEnabled(true); - updateInsertPosition(PositionType.NEXT); - } - break; - case NOZZLE: - startButton.setEnabled(false); - middleButton.setEnabled(false); - endButton.setEnabled(true); - updateInsertPosition(PositionType.NEXT); - break; - case TURN: - startButton.setEnabled(false); - middleButton.setEnabled(true); - endButton.setEnabled(true); - if (insertPosition == PositionType.PREVIOUS) - updateInsertPosition(PositionType.NEXT); - break; - case EQUIPMENT: - throw new RuntimeException("Expected component, got equipment " + selected); - } - } else if (lenghtAdjustable) { - if (component instanceof InlineComponent) { - startButton.setEnabled(true); - middleButton.setEnabled(true); - endButton.setEnabled(true); - } else if (component instanceof TurnComponent) { - startButton.setEnabled(false); - middleButton.setEnabled(true); - endButton.setEnabled(true); - if (insertPosition == PositionType.PREVIOUS) - updateInsertPosition(PositionType.NEXT); - } else if (component instanceof EndComponent || component instanceof Nozzle) { - startButton.setEnabled(false); - middleButton.setEnabled(false); - endButton.setEnabled(true); - updateInsertPosition(PositionType.NEXT); - } - } else { - startButton.setEnabled(false); - middleButton.setEnabled(false); - endButton.setEnabled(true); - } - if (selected.isVariable()) { + lenghtAdjustable = ((selected.getType() == Type.INLINE) && selected.isVariable()); + if (insertAdjustable) { + switch (selected.getType()) { + case END: + startButton.setEnabled(false); + middleButton.setEnabled(false); + endButton.setEnabled(true); + updateInsertPosition(PositionType.NEXT); + break; + case INLINE: + if (!selected.isVariable()) { + startButton.setEnabled(true); + middleButton.setEnabled(true); + endButton.setEnabled(true); + } else { + startButton.setEnabled(false); + middleButton.setEnabled(false); + endButton.setEnabled(true); + updateInsertPosition(PositionType.NEXT); + } + break; + case NOZZLE: + startButton.setEnabled(false); + middleButton.setEnabled(false); + endButton.setEnabled(true); + updateInsertPosition(PositionType.NEXT); + break; + case TURN: + startButton.setEnabled(false); + middleButton.setEnabled(true); + endButton.setEnabled(true); + if (insertPosition == PositionType.PREVIOUS) + updateInsertPosition(PositionType.NEXT); + break; + case EQUIPMENT: + throw new RuntimeException("Expected component, got equipment " + selected); + } + } else if (lenghtAdjustable) { + if (component instanceof InlineComponent) { + startButton.setEnabled(true); + middleButton.setEnabled(true); + endButton.setEnabled(true); + } else if (component instanceof TurnComponent) { + startButton.setEnabled(false); + middleButton.setEnabled(true); + endButton.setEnabled(true); + if (insertPosition == PositionType.PREVIOUS) + updateInsertPosition(PositionType.NEXT); + } else if (component instanceof EndComponent || component instanceof Nozzle) { + startButton.setEnabled(false); + middleButton.setEnabled(false); + endButton.setEnabled(true); + updateInsertPosition(PositionType.NEXT); + } + } else { + startButton.setEnabled(false); + middleButton.setEnabled(false); + endButton.setEnabled(true); + } + if (selected.isVariable()) { if (selected.getType() == Type.INLINE) { filterAllowed.add(PositionType.NEXT); filterAllowed.add(PositionType.PREVIOUS); @@ -488,15 +488,15 @@ public class ComponentSelectionDialog extends Dialog implements ISelectionChange } public PositionType getInsertPosition() { - return insertPosition; - } + return insertPosition; + } public boolean isInsertAdjustable() { - return insertAdjustable; - } + return insertAdjustable; + } public boolean isLenghtAdjustable() { - return lenghtAdjustable; - } + return lenghtAdjustable; + } } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/editor/P3DContentOutlinePage.java b/org.simantics.plant3d/src/org/simantics/plant3d/editor/P3DContentOutlinePage.java index 5a9e8b01..24a141e4 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/editor/P3DContentOutlinePage.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/editor/P3DContentOutlinePage.java @@ -60,14 +60,14 @@ public class P3DContentOutlinePage extends VTKContentOutlinePage list = new ArrayList(); - list.addAll(((PipeRun)parentElement).getControlPoints()); - list.addAll(((PipeRun)parentElement).getSortedChild()); - return list.toArray(); - } - return ((PipeRun)parentElement).getSortedChild().toArray(); - } + if (DEBUG) { + List list = new ArrayList(); + list.addAll(((PipeRun)parentElement).getControlPoints()); + list.addAll(((PipeRun)parentElement).getSortedChild()); + return list.toArray(); + } + return ((PipeRun)parentElement).getSortedChild().toArray(); + } if (DEBUG) { if (parentElement instanceof PipelineComponent) { return new Object[]{((PipelineComponent) parentElement).getControlPoint()}; @@ -124,14 +124,14 @@ public class P3DContentOutlinePage extends VTKContentOutlinePage { for (vtkProp3D act : node.getActors()) { nodeToActor.add(node, act); - actorToNode.put(act, node); + actorToNode.put(act, node); } if (node instanceof P3DParentNode) { @@ -159,7 +159,7 @@ public class P3DNodeMap extends AbstractVTKNodeMap { updateTransform(node); - view.unlock(); + view.unlock(); } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/editor/Plant3DEditor.java b/org.simantics.plant3d/src/org/simantics/plant3d/editor/Plant3DEditor.java index 5015e6ea..ba56f2f9 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/editor/Plant3DEditor.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/editor/Plant3DEditor.java @@ -158,8 +158,8 @@ public class Plant3DEditor extends ResourceEditorPart { // update control points. // TODO : this should be optimized. try { - P3DUtil.finalizeDBLoad(rootNode); - + P3DUtil.finalizeDBLoad(rootNode); + } catch (Exception e) { throw new DatabaseException(e); } @@ -209,18 +209,18 @@ public class Plant3DEditor extends ResourceEditorPart { } protected void createActions() { - translateAction = new TranslateAction(panel,nodeMap); - translateInlineAction = new TranslateInlineAction(panel, nodeMap); - rotateAction = new RotateAction(panel,nodeMap); - removeAction = new RemoveAction(nodeMap) { - public void setNode(IG3DNode node) { - super.setNode(node); - - - } - }; - routePipeAction = new RoutePipeAction(panel,rootNode); - addComponentAction = new AddComponentAction(panel, rootNode); + translateAction = new TranslateAction(panel,nodeMap); + translateInlineAction = new TranslateInlineAction(panel, nodeMap); + rotateAction = new RotateAction(panel,nodeMap); + removeAction = new RemoveAction(nodeMap) { + public void setNode(IG3DNode node) { + super.setNode(node); + + + } + }; + routePipeAction = new RoutePipeAction(panel,rootNode); + addComponentAction = new AddComponentAction(panel, rootNode); } public void populate() { @@ -240,7 +240,7 @@ public class Plant3DEditor extends ResourceEditorPart { } protected P3DNodeMap createNodeMap(Session session, IMapping mapping, VtkView panel, P3DRootNode rootNode) { - return new P3DNodeMap(session, mapping, panel,rootNode); + return new P3DNodeMap(session, mapping, panel,rootNode); } @Override @@ -283,30 +283,30 @@ public class Plant3DEditor extends ResourceEditorPart { ren1.SetBackground(0.9,0.9,0.9); ren1.SetGradientBackground(true); - // vtkActor grid = vtkShape.createGridActor(8,1.0,1|2|4); - vtkActor grid = vtkShape.createGridActor(8,1.0, 2 ); - grid.SetPickable(0); - ren1.AddActor(grid); - panel.addDeletable(grid); - - AxesDisplay axesDisplay = new AxesDisplay(panel); - axesDisplay.show(); + // vtkActor grid = vtkShape.createGridActor(8,1.0,1|2|4); + vtkActor grid = vtkShape.createGridActor(8,1.0, 2 ); + grid.SetPickable(0); + ren1.AddActor(grid); + panel.addDeletable(grid); + + AxesDisplay axesDisplay = new AxesDisplay(panel); + axesDisplay.show(); } protected Menu contextMenu; protected void hookContextMenu() { - MenuManager menuMgr = new MenuManager("#PopupMenu"); - menuMgr.setRemoveAllWhenShown(true); - menuMgr.addMenuListener(new IMenuListener() { - public void menuAboutToShow(IMenuManager manager) { - createContextMenu(manager); - } - }); + MenuManager menuMgr = new MenuManager("#PopupMenu"); + menuMgr.setRemoveAllWhenShown(true); + menuMgr.addMenuListener(new IMenuListener() { + public void menuAboutToShow(IMenuManager manager) { + createContextMenu(manager); + } + }); - contextMenu = menuMgr.createContextMenu(parent); - } + contextMenu = menuMgr.createContextMenu(parent); + } protected void createContextMenu(IMenuManager m) { List selected = selectionProvider.getSelectedNodes(); @@ -326,11 +326,11 @@ public class Plant3DEditor extends ResourceEditorPart { m.add(add); } } else if (node instanceof Nozzle) { - Nozzle nozzle = (Nozzle)node; - if (!nozzle.isFixed()) { - m.add(translateAction); - m.add(rotateAction); - } + Nozzle nozzle = (Nozzle)node; + if (!nozzle.isFixed()) { + m.add(translateAction); + m.add(rotateAction); + } m.add(routePipeAction); routePipeAction.setComponent(nozzle); routePipeAction.setEnabled(nozzle.getNext() == null && nozzle.getPrevious() == null); @@ -366,8 +366,8 @@ public class Plant3DEditor extends ResourceEditorPart { } } catch (DatabaseException e) { - ExceptionUtils.logAndShowError(e); - } + ExceptionUtils.logAndShowError(e); + } } private IContentOutlinePage createOutline() { diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/geometry/ElbowGeometryProvider.java b/org.simantics.plant3d/src/org/simantics/plant3d/geometry/ElbowGeometryProvider.java index d3af06ad..d4428e49 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/geometry/ElbowGeometryProvider.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/geometry/ElbowGeometryProvider.java @@ -67,11 +67,11 @@ public class ElbowGeometryProvider extends BuiltinMeshProvider { @Override public void updateCalculatedProperties(Map returnProps) { - double t = Math.tan((Math.PI - turnAngle) * 0.5); - double R = 0.0; - if (t > MathTools.NEAR_ZERO) - R = turnRadius / t; - returnProps.put("length", R); + double t = Math.tan((Math.PI - turnAngle) * 0.5); + double R = 0.0; + if (t > MathTools.NEAR_ZERO) + R = turnRadius / t; + returnProps.put("length", R); } } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/geometry/FixedNozzleProvider.java b/org.simantics.plant3d/src/org/simantics/plant3d/geometry/FixedNozzleProvider.java index bf30437c..b5505c94 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/geometry/FixedNozzleProvider.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/geometry/FixedNozzleProvider.java @@ -3,9 +3,9 @@ package org.simantics.plant3d.geometry; import org.simantics.plant3d.scenegraph.Nozzle; public interface FixedNozzleProvider { - - int numberOfNozzles(); - void updateNozzlePosition(int index, Nozzle nozzle); - String getNozzleName(int index); + + int numberOfNozzles(); + void updateNozzlePosition(int index, Nozzle nozzle); + String getNozzleName(int index); } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/geometry/PumpGeometryProvider.java b/org.simantics.plant3d/src/org/simantics/plant3d/geometry/PumpGeometryProvider.java index 47b2d2d1..a34e3468 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/geometry/PumpGeometryProvider.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/geometry/PumpGeometryProvider.java @@ -69,31 +69,31 @@ public class PumpGeometryProvider extends BuiltinGeometryProvider implements Fi @Override public int numberOfNozzles() { - return 2; + return 2; } @Override public void updateNozzlePosition(int index, Nozzle nozzle) { - Double fl = nozzle.getFlowLength(); - if (fl == null) - fl = 0.1; - if (index == 0) { - nozzle.setPosition(new Vector3d(-length*0.5- fl,width*0.6,0.0)); - nozzle.setOrientation(MathTools.getQuat(new AxisAngle4d(0,1,0,Math.PI))); - } else if (index == 1) { - nozzle.setPosition(new Vector3d(-length*0.4,width*1.1+ fl,0.0)); - nozzle.setOrientation(MathTools.getQuat(new AxisAngle4d(0,0,1,Math.PI*0.5))); - } - + Double fl = nozzle.getFlowLength(); + if (fl == null) + fl = 0.1; + if (index == 0) { + nozzle.setPosition(new Vector3d(-length*0.5- fl,width*0.6,0.0)); + nozzle.setOrientation(MathTools.getQuat(new AxisAngle4d(0,1,0,Math.PI))); + } else if (index == 1) { + nozzle.setPosition(new Vector3d(-length*0.4,width*1.1+ fl,0.0)); + nozzle.setOrientation(MathTools.getQuat(new AxisAngle4d(0,0,1,Math.PI*0.5))); + } + } @Override public String getNozzleName(int index) { - switch (index) { - case 0 : return "Input"; - case 1: return "Output"; - default: return null; - } + switch (index) { + case 0 : return "Input"; + case 1: return "Output"; + default: return null; + } } } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/project/P3DProjectFeature.java b/org.simantics.plant3d/src/org/simantics/plant3d/project/P3DProjectFeature.java index a39292f9..1dcb32d9 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/project/P3DProjectFeature.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/project/P3DProjectFeature.java @@ -13,9 +13,9 @@ public class P3DProjectFeature extends AbstractProjectFeature implements IProjec // TODO Auto-generated constructor stub } - @Override - public void configure() throws ProjectException { - getProjectElement().setHint(ProjectKeys.DEFAULT_PERSPECTIVE, DEFAULT_PERSPECTIVE); - } + @Override + public void configure() throws ProjectException { + getProjectElement().setHint(ProjectKeys.DEFAULT_PERSPECTIVE, DEFAULT_PERSPECTIVE); + } } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/property/P3DSelectionProcessor.java b/org.simantics.plant3d/src/org/simantics/plant3d/property/P3DSelectionProcessor.java index 072079c2..3bef85b5 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/property/P3DSelectionProcessor.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/property/P3DSelectionProcessor.java @@ -39,87 +39,87 @@ public class P3DSelectionProcessor implements SelectionProcessor result = new ArrayList(); - Collection resourceCollection = AdaptationUtils.adaptToCollection(selection, Resource.class); - Collection structuralResourceCollection = AdaptationUtils.adaptToCollection(selection, StructuralResource.class); - Collection propCollection = AdaptationUtils.adaptToCollection(selection, vtkProp.class); - Collection nodeCollection = AdaptationUtils.adaptToCollection(selection, IG3DNode.class); - boolean readOnly = false; - if (resourceCollection.size() == 0 && structuralResourceCollection.size() > 0) { - for (StructuralResource sr : structuralResourceCollection) { - if (sr.isStructural() && !sr.isStructuralRoot()) - readOnly = true; - resourceCollection.add(sr.getResource()); - } - } - - - if (nodeCollection.size() == 1) { - IG3DNode node = nodeCollection.iterator().next(); - List contributors = PropertyTabUtil.getContributors(node); - int i = 100; - for (PropertyTabContributor c : contributors) { - result.add(new ComparableTabContributor(c, i--, node, c.getId())); - } - } - - if (DEBUG) { - if (propCollection.size() == 1) { - vtkProp prop = propCollection.iterator().next(); - if (prop == null) - throw new NullPointerException(); - result.add(new ComparableTabContributor(new VTKPropertyTabContributor(SWTThread.getThreadAccess()), -2, prop, "VTK")); - } - - if (resourceCollection.size() > 0) { - if (resourceCollection.size() > 1) - result.add(new ComparableTabContributor(new MultiSelectionTabContibutor(),0, resourceCollection, "Graph")); - else if (resourceCollection.size() == 1){ - try { + Collection result = new ArrayList(); + Collection resourceCollection = AdaptationUtils.adaptToCollection(selection, Resource.class); + Collection structuralResourceCollection = AdaptationUtils.adaptToCollection(selection, StructuralResource.class); + Collection propCollection = AdaptationUtils.adaptToCollection(selection, vtkProp.class); + Collection nodeCollection = AdaptationUtils.adaptToCollection(selection, IG3DNode.class); + boolean readOnly = false; + if (resourceCollection.size() == 0 && structuralResourceCollection.size() > 0) { + for (StructuralResource sr : structuralResourceCollection) { + if (sr.isStructural() && !sr.isStructuralRoot()) + readOnly = true; + resourceCollection.add(sr.getResource()); + } + } + + + if (nodeCollection.size() == 1) { + IG3DNode node = nodeCollection.iterator().next(); + List contributors = PropertyTabUtil.getContributors(node); + int i = 100; + for (PropertyTabContributor c : contributors) { + result.add(new ComparableTabContributor(c, i--, node, c.getId())); + } + } + + if (DEBUG) { + if (propCollection.size() == 1) { + vtkProp prop = propCollection.iterator().next(); + if (prop == null) + throw new NullPointerException(); + result.add(new ComparableTabContributor(new VTKPropertyTabContributor(SWTThread.getThreadAccess()), -2, prop, "VTK")); + } + + if (resourceCollection.size() > 0) { + if (resourceCollection.size() > 1) + result.add(new ComparableTabContributor(new MultiSelectionTabContibutor(),0, resourceCollection, "Graph")); + else if (resourceCollection.size() == 1){ + try { Resource r = resourceCollection.iterator().next(); - result.add(new ComparableTabContributor(new P3DBasicPropertyTab(!readOnly), 0, r, "Graph")); - - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - - if(result.size() == 0) { - result.add(new ComparableTabContributor(new NoneSelectionTabContributor(),0, resourceCollection, "Empty")); - } - + result.add(new ComparableTabContributor(new P3DBasicPropertyTab(!readOnly), 0, r, "Graph")); + + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + + if(result.size() == 0) { + result.add(new ComparableTabContributor(new NoneSelectionTabContributor(),0, resourceCollection, "Empty")); + } + return result; } - + public class P3DBasicPropertyTab extends BasicPropertyTab { - + boolean enabled; public P3DBasicPropertyTab(boolean enabled) { this.enabled = enabled; } - public void updatePartName(ISelection forSelection, Callback updateCallback) { - Read read = getPartNameReadRequest(forSelection); - if (read == null) { - updateCallback.run("Override to control part name (PropertyTabContributorImpl.updatePartName)"); - } else { - Simantics.getSession().asyncRequest(read, new PartNameListener(updateCallback)); - } - } - public Read getPartNameReadRequest(ISelection forSelection) { - final Resource r = AdaptationUtils.adaptToSingle(forSelection, Resource.class); - if (r == null) - return null; - return new Read() { - @Override + public void updatePartName(ISelection forSelection, Callback updateCallback) { + Read read = getPartNameReadRequest(forSelection); + if (read == null) { + updateCallback.run("Override to control part name (PropertyTabContributorImpl.updatePartName)"); + } else { + Simantics.getSession().asyncRequest(read, new PartNameListener(updateCallback)); + } + } + public Read getPartNameReadRequest(ISelection forSelection) { + final Resource r = AdaptationUtils.adaptToSingle(forSelection, Resource.class); + if (r == null) + return null; + return new Read() { + @Override public String perform(ReadGraph graph) throws DatabaseException { return NameUtils.getSafeName(graph, r); } }; - } - - @Override + } + + @Override public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) { // TODO Auto-generated method stub @@ -127,20 +127,20 @@ public class P3DSelectionProcessor implements SelectionProcessor getPartNameReadRequest(ISelection forSelection) { - final Collection coll = AdaptationUtils.adaptToCollection(forSelection, Resource.class); - if (coll.size() == 0) - return null; - return new Read() { - @Override + final Collection coll = AdaptationUtils.adaptToCollection(forSelection, Resource.class); + if (coll.size() == 0) + return null; + return new Read() { + @Override public String perform(ReadGraph graph) throws DatabaseException { String title = ""; for (Resource r : coll) { @@ -150,21 +150,21 @@ public class P3DSelectionProcessor implements SelectionProcessor updateCallback) { updateCallback.run("No Selection"); } } - + } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/Equipment.java b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/Equipment.java index a27e9c50..214b632f 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/Equipment.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/Equipment.java @@ -45,10 +45,10 @@ public class Equipment extends P3DParentGeometryNode { @RelatedElementsAdd(Plant3D.URIs.HasNozzle) public void addChild(Nozzle node) { - Collection children = getChild(); - if (numberOfFixedNozzles() > 0 && children.size() >= numberOfFixedNozzles()) - throw new RuntimeException("Equipment has already all fixed nozzles"); - + Collection children = getChild(); + if (numberOfFixedNozzles() > 0 && children.size() >= numberOfFixedNozzles()) + throw new RuntimeException("Equipment has already all fixed nozzles"); + Set ids = new HashSet(); for (Nozzle n : children) { ids.add(n.getNozzleId()); @@ -59,7 +59,7 @@ public class Equipment extends P3DParentGeometryNode { addNode(Plant3D.URIs.HasNozzle,node); node.setNozzleId(newId); if (fnp != null) - syncNozzles(); + syncNozzles(); } @RelatedElementsGet(Plant3D.URIs.HasNozzle) @@ -89,17 +89,17 @@ public class Equipment extends P3DParentGeometryNode { @Override public void setGeometry(GeometryProvider provider) { - super.setGeometry(provider); - if (provider instanceof FixedNozzleProvider) { - fnp = (FixedNozzleProvider)provider; - syncNozzles(); - } + super.setGeometry(provider); + if (provider instanceof FixedNozzleProvider) { + fnp = (FixedNozzleProvider)provider; + syncNozzles(); + } } public int numberOfFixedNozzles() { - if (fnp == null) - return 0; - return fnp.numberOfNozzles(); + if (fnp == null) + return 0; + return fnp.numberOfNozzles(); } /** @@ -108,19 +108,19 @@ public class Equipment extends P3DParentGeometryNode { * Note: this method does not create nozzles, just sets their positions and names. */ public void syncNozzles() { - if (fnp == null) - return; - updateParameters(); - int count = fnp.numberOfNozzles(); - List currentNozzles = getNodes(); - for (int i = 0; i < count; i++) { - if (i < currentNozzles.size()) { - Nozzle nozzle = currentNozzles.get(i); - nozzle.setName(fnp.getNozzleName(i)); - fnp.updateNozzlePosition(i, nozzle); - nozzle.setFixed(true); - } - } + if (fnp == null) + return; + updateParameters(); + int count = fnp.numberOfNozzles(); + List currentNozzles = getNodes(); + for (int i = 0; i < count; i++) { + if (i < currentNozzles.size()) { + Nozzle nozzle = currentNozzles.get(i); + nozzle.setName(fnp.getNozzleName(i)); + fnp.updateNozzlePosition(i, nozzle); + nozzle.setFixed(true); + } + } } @Override diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/InlineComponent.java b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/InlineComponent.java index fe30c29c..f01e6c58 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/InlineComponent.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/InlineComponent.java @@ -52,7 +52,7 @@ public class InlineComponent extends PipelineComponent { } public boolean isSizeChange() { - return controlPoint.isSizeChange(); + return controlPoint.isSizeChange(); } @RelatedGetValue(Plant3D.URIs.HasRotationAngle) diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/Nozzle.java b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/Nozzle.java index fec8c084..fb184068 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/Nozzle.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/Nozzle.java @@ -54,20 +54,20 @@ public class Nozzle extends PipelineComponent { } private boolean fixed = false; - - @RelatedGetValue(Plant3D.URIs.IsFixedNozzle) - @GetPropertyValue(name="Fixed", value=Plant3D.URIs.IsFixedNozzle, tabId="Default") - public boolean isFixed() { - return fixed; - } - - @RelatedSetValue(Plant3D.URIs.IsFixedNozzle) - public void setFixed(boolean fixed) { - if (fixed == this.fixed) - return; - this.fixed = fixed; - firePropertyChanged(Plant3D.URIs.IsFixedNozzle); - } + + @RelatedGetValue(Plant3D.URIs.IsFixedNozzle) + @GetPropertyValue(name="Fixed", value=Plant3D.URIs.IsFixedNozzle, tabId="Default") + public boolean isFixed() { + return fixed; + } + + @RelatedSetValue(Plant3D.URIs.IsFixedNozzle) + public void setFixed(boolean fixed) { + if (fixed == this.fixed) + return; + this.fixed = fixed; + firePropertyChanged(Plant3D.URIs.IsFixedNozzle); + } private void _createCP() throws Exception{ if (controlPoint != null) diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/P3DParentNode.java b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/P3DParentNode.java index 08c289da..dabae5ac 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/P3DParentNode.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/P3DParentNode.java @@ -190,5 +190,5 @@ public abstract class P3DParentNode extends ParentNode im } } - + } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/PipelineComponent.java b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/PipelineComponent.java index 631894b4..6ddd7a09 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/PipelineComponent.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/PipelineComponent.java @@ -32,8 +32,8 @@ public abstract class PipelineComponent extends GeometryNode { private PipelineComponent previous; public PipeRun getPipeRun() { - return pipeRun; - } + return pipeRun; + } /** * Sets the pipe run. @@ -93,7 +93,7 @@ public abstract class PipelineComponent extends GeometryNode { if (next == comp) return; if (this.next != null) - this.next._removeRef(this); + this.next._removeRef(this); this.next = comp; this.syncnext = false; syncNext(); @@ -114,7 +114,7 @@ public abstract class PipelineComponent extends GeometryNode { if (previous == comp) return; if (this.previous != null) - this.previous._removeRef(this); + this.previous._removeRef(this); this.previous = comp; this.syncprev = false; syncPrevious(); @@ -135,7 +135,7 @@ public abstract class PipelineComponent extends GeometryNode { if (branch0 == comp) return; if (this.branch0 != null) - this.branch0._removeRef(this); + this.branch0._removeRef(this); this.branch0 = comp; this.syncbr0 = false; syncBranch0(); @@ -146,25 +146,25 @@ public abstract class PipelineComponent extends GeometryNode { } @GetPropertyValue(name="Previous",tabId="Debug",value=Plant3D.URIs.HasPrevious) - public String getPreviousDebug() { - if (previous == null) - return null; - return previous.getName(); - } - - @GetPropertyValue(name="Next",tabId="Debug",value=Plant3D.URIs.HasNext) - public String getNextDebug() { - if (next == null) - return null; - return next.getName(); - } - + public String getPreviousDebug() { + if (previous == null) + return null; + return previous.getName(); + } + + @GetPropertyValue(name="Next",tabId="Debug",value=Plant3D.URIs.HasNext) + public String getNextDebug() { + if (next == null) + return null; + return next.getName(); + } + @GetPropertyValue(name="Branch0",tabId="Debug",value=Plant3D.URIs.HasBranch0) - public String getBR0Debug() { - if (branch0 == null) - return null; - return branch0.getName(); - } + public String getBR0Debug() { + if (branch0 == null) + return null; + return branch0.getName(); + } @@ -219,33 +219,33 @@ public abstract class PipelineComponent extends GeometryNode { // When link to a component is removed, also link to the other direction must be removed at the same time, or // Control point structure is left into illegal state. private void _removeRef(PipelineComponent comp) { - if (next == comp) { - next = null; - syncnext = false; - syncNext(); - } else if (previous == comp) { - previous = null; - syncprev = false; - syncPrevious(); - } else if (branch0 == comp) { - branch0 = null; - syncbr0 = false; - syncBranch0(); - } + if (next == comp) { + next = null; + syncnext = false; + syncNext(); + } else if (previous == comp) { + previous = null; + syncprev = false; + syncPrevious(); + } else if (branch0 == comp) { + branch0 = null; + syncbr0 = false; + syncBranch0(); + } } boolean syncnext = false; - private void syncNext() { - if (syncnext) - return; - syncnext = _syncNext(); - } + private void syncNext() { + if (syncnext) + return; + syncnext = _syncNext(); + } private boolean _syncNext() { - PipeControlPoint pcp = getControlPoint(); + PipeControlPoint pcp = getControlPoint(); if (pcp != null) { - + if (next != null ) { if (next.getControlPoint() != null) { @@ -257,15 +257,15 @@ public abstract class PipelineComponent extends GeometryNode { } else if (br0) { return _connectNext(pcp, next.getBranchPoint()); } else { - return false; + return false; } } else { return false; } } else if (pcp.getNext() != null) { - pcp.setNext(null); - return true; + pcp.setNext(null); + return true; } } else { return false; @@ -274,14 +274,14 @@ public abstract class PipelineComponent extends GeometryNode { } boolean syncprev = false; - private void syncPrevious() { - if (syncprev) - return; - syncprev = _syncPrevious(); - } + private void syncPrevious() { + if (syncprev) + return; + syncprev = _syncPrevious(); + } private boolean _syncPrevious() { - PipeControlPoint pcp = getControlPoint(); + PipeControlPoint pcp = getControlPoint(); if (pcp != null) { if (previous != null ) { if (previous.getControlPoint() != null) { @@ -294,15 +294,15 @@ public abstract class PipelineComponent extends GeometryNode { } else if (br0) { return _connectPrev(pcp, previous.getBranchPoint()); } else { - return false; + return false; } } else { return false; } } else if (pcp.getPrevious() != null) { - pcp.setPrevious(null); - return true; + pcp.setPrevious(null); + return true; } } else { return false; @@ -312,9 +312,9 @@ public abstract class PipelineComponent extends GeometryNode { boolean syncbr0 = false; private void syncBranch0() { - if (syncbr0) - return; - syncbr0 = _syncBranch0(); + if (syncbr0) + return; + syncbr0 = _syncBranch0(); } private boolean _syncBranch0() { @@ -327,7 +327,7 @@ public abstract class PipelineComponent extends GeometryNode { if (branch0.getControlPoint() != null) { PipeControlPoint branchPoint = getBranchPoint(); if (branchPoint == null) - return false; + return false; PipeControlPoint pcp = branch0.getControlPoint(); // TODO, relying that the other direction is connected. boolean next = branch0.getPrevious() == this; // this --> branch0 @@ -337,7 +337,7 @@ public abstract class PipelineComponent extends GeometryNode { } else if (prev){ _connectPrev(branchPoint, pcp); } else { - return false; + return false; } } else { @@ -458,8 +458,8 @@ public abstract class PipelineComponent extends GeometryNode { double a = pcp.getTurnAngle(); return a*r; } - default: - return null; + default: + return null; } } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/TurnComponent.java b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/TurnComponent.java index 0205f5a3..ff12143b 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/TurnComponent.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/TurnComponent.java @@ -64,18 +64,18 @@ public class TurnComponent extends PipelineComponent { } public boolean isVariableAngle() { - return !controlPoint.isFixed(); - } + return !controlPoint.isFixed(); + } @Override public void updateParameters() { - super.updateParameters(); - if (!isVariableAngle()) { - Map calculated = getCalculatedParameters(); - if (calculated.containsKey("length")) { - controlPoint.setLength((Double)calculated.get("length")); - } - } + super.updateParameters(); + if (!isVariableAngle()) { + Map calculated = getCalculatedParameters(); + if (calculated.containsKey("length")) { + controlPoint.setLength((Double)calculated.get("length")); + } + } } @RelatedGetValue(Plant3D.URIs.HasTurnAngle) @@ -85,9 +85,9 @@ public class TurnComponent extends PipelineComponent { @RelatedSetValue(Plant3D.URIs.HasTurnAngle) public void setTurnAngle(Double a) { - if (!getControlPoint().isFixed()) - return; - getControlPoint().setTurnAngle(a); + if (!getControlPoint().isFixed()) + return; + getControlPoint().setTurnAngle(a); } @GetPropertyValue(name="Turn Angle", value="turn angle", tabId = "Default") @@ -103,61 +103,61 @@ public class TurnComponent extends PipelineComponent { } @RelatedGetValue(Plant3D.URIs.HasRotationAngle) - @GetPropertyValue(name="Rotation Angle", value=Plant3D.URIs.HasRotationAngle, tabId = "Default") - public Double getRotationAngle() { - if (!controlPoint.isFixed()) - return null; - Double d = controlPoint.getRotationAngle(); - if (d == null) - return 0.0; - return MathTools.radToDeg(d); - } - @RelatedSetValue(Plant3D.URIs.HasRotationAngle) - @SetPropertyValue(value=Plant3D.URIs.HasRotationAngle) - public void setRotationAngle(Double angle) { - if (!controlPoint.isFixed()) - return; - - if (angle == null || Double.isInfinite(angle) || Double.isNaN(angle)) { - return; - } - angle = MathTools.degToRad(angle); - if (controlPoint.getRotationAngle() != null && Math.abs(controlPoint.getRotationAngle()-angle) < MathTools.NEAR_ZERO) - return; - controlPoint.setRotationAngle(angle); - try { - PipingRules.requestUpdate(getControlPoint()); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @RelatedGetValue(Plant3D.URIs.IsReversed) - @GetPropertyValue(name="Reverse", value=Plant3D.URIs.IsReversed, tabId = "Default") - public Boolean isReversed() { - if (!controlPoint.isFixed()) - return null; - Boolean d = controlPoint._getReversed(); - return d; - } - @RelatedSetValue(Plant3D.URIs.IsReversed) - //@SetPropertyValue(value=Plant3D.URIs.IsReversed) - public void setReversed(Boolean reverse) { - if (!controlPoint.isFixed()) - return; - - if (reverse == null) { - return; - } - controlPoint.setReversed(reverse); - try { - PipingRules.requestUpdate(getControlPoint()); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + @GetPropertyValue(name="Rotation Angle", value=Plant3D.URIs.HasRotationAngle, tabId = "Default") + public Double getRotationAngle() { + if (!controlPoint.isFixed()) + return null; + Double d = controlPoint.getRotationAngle(); + if (d == null) + return 0.0; + return MathTools.radToDeg(d); + } + @RelatedSetValue(Plant3D.URIs.HasRotationAngle) + @SetPropertyValue(value=Plant3D.URIs.HasRotationAngle) + public void setRotationAngle(Double angle) { + if (!controlPoint.isFixed()) + return; + + if (angle == null || Double.isInfinite(angle) || Double.isNaN(angle)) { + return; + } + angle = MathTools.degToRad(angle); + if (controlPoint.getRotationAngle() != null && Math.abs(controlPoint.getRotationAngle()-angle) < MathTools.NEAR_ZERO) + return; + controlPoint.setRotationAngle(angle); + try { + PipingRules.requestUpdate(getControlPoint()); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @RelatedGetValue(Plant3D.URIs.IsReversed) + @GetPropertyValue(name="Reverse", value=Plant3D.URIs.IsReversed, tabId = "Default") + public Boolean isReversed() { + if (!controlPoint.isFixed()) + return null; + Boolean d = controlPoint._getReversed(); + return d; + } + @RelatedSetValue(Plant3D.URIs.IsReversed) + //@SetPropertyValue(value=Plant3D.URIs.IsReversed) + public void setReversed(Boolean reverse) { + if (!controlPoint.isFixed()) + return; + + if (reverse == null) { + return; + } + controlPoint.setReversed(reverse); + try { + PipingRules.requestUpdate(getControlPoint()); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } @Override protected double[] getColor() { diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/ControlPointFactory.java b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/ControlPointFactory.java index 4dfe29c7..1b982f07 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/ControlPointFactory.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/ControlPointFactory.java @@ -63,7 +63,7 @@ public class ControlPointFactory { if (inst.isOffset) pcp.setOffset(0.0); if (inst.isSizeChange) - pcp.setSizeChange(true); + pcp.setSizeChange(true); } break; diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/PipeControlPoint.java b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/PipeControlPoint.java index 51addbb0..cb4b57eb 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/PipeControlPoint.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/PipeControlPoint.java @@ -23,15 +23,15 @@ import vtk.vtkRenderer; public class PipeControlPoint extends G3DNode implements IP3DNode { - - private static boolean DEBUG = false; - + + private static boolean DEBUG = false; + public enum PointType{INLINE,TURN,END}; public enum Direction{NEXT,PREVIOUS}; public enum PositionType {SPLIT,NEXT,PREVIOUS,PORT} - + private PipelineComponent component; - + private PointType type; private boolean isFixed = true; private boolean isRotate = false; @@ -39,19 +39,19 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { private boolean isDeletable = true; private boolean isSizeChange = false; private boolean isSub = false; - + public PipeControlPoint(PipelineComponent component) { this.component = component; if (component.getPipeRun() != null) component.getPipeRun().addChild(this); - + } - + public PipeControlPoint(PipelineComponent component, PipeRun piperun) { this.component = component; piperun.addChild(this); } - + @Override public void update(vtkRenderer ren) { try { @@ -59,146 +59,146 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { } catch (Exception e) { e.printStackTrace(); } - + } - + public PipeRun getPipeRun() { return (PipeRun)getParent(); } - + public PipelineComponent getPipelineComponent() { return component; } - + public PointType getType() { return type; } - + public void setType(PointType type) { this.type = type; } - + @GetPropertyValue(name="Fixed",tabId="Debug",value="fixed") public boolean isFixed() { return isFixed; } - - + + public void setFixed(boolean fixed) { this.isFixed = fixed; } - + @GetPropertyValue(name="Rotate",tabId="Debug",value="rotate") public boolean isRotate() { return isRotate; } - + public void setRotate(boolean rotate) { this.isRotate = rotate; } - + @GetPropertyValue(name="Reverse",tabId="Debug",value="reverse") public boolean isReverse() { return isReverse; } - + public void setReverse(boolean reverse) { this.isReverse = reverse; } - + public void setSub(boolean sub) { this.isSub = sub; } - + @GetPropertyValue(name="Deletable",tabId="Debug",value="deletable") public boolean isDeletable() { return isDeletable; } - + public void setDeletable(boolean deletable) { this.isDeletable = deletable; } - + public boolean isPathLegEnd() { return type != PointType.INLINE; } - + public boolean isEnd() { return type == PointType.END; } - + public boolean isTurn() { return type == PointType.TURN; } - + public boolean isInline() { return type == PointType.INLINE; } - + public boolean isDirected() { return isFixed && isEnd(); } - + public boolean isNonDirected() { return !isFixed && isEnd(); } - + public boolean isVariableLength() { return !isFixed && isInline(); } - + public boolean isVariableAngle() { return !isFixed && isTurn(); } - + public boolean isBranchEnd() { return isDeletable && isEnd(); } - + public boolean isOffset() { return offset != null; } - + public boolean isDualSub() { return parent != null && isSub; } - + public boolean isDualInline() { return children.size() == 1 && children.get(0).isDualSub(); } - + public boolean isSizeChange() { - return isSizeChange; -// if (children.size() == 0) -// return false; -// if (!isDualInline()) -// return false; -// return getPipeRun() != children.get(0).getPipeRun(); - } - + return isSizeChange; + // if (children.size() == 0) + // return false; + // if (!isDualInline()) + // return false; + // return getPipeRun() != children.get(0).getPipeRun(); + } + public void setSizeChange(boolean isSizeChange) { - this.isSizeChange = isSizeChange; - } + this.isSizeChange = isSizeChange; + } + - private PipeControlPoint next; private PipeControlPoint previous; - + public PipeControlPoint getNext() { return next; } - + public PipeControlPoint getPrevious() { return previous; } - + public void setNext(PipeControlPoint next) { if (isEnd() && previous != null && next != null) throw new RuntimeException("End control points are allowed to have only one connection"); if (next == this) - throw new RuntimeException("Cannot connect to self"); + throw new RuntimeException("Cannot connect to self"); if (this.next == next) - return; + return; if (DEBUG) System.out.println(this + " next " + next); this.next = next; if (component != null) { @@ -208,16 +208,16 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { component.setBranch0(next != null ? next.component : null); updateSubPoint(); } - + } - + public void setPrevious(PipeControlPoint previous) { if (isEnd() && next != null && previous != null) throw new RuntimeException("End control points are allowed to have only one connection"); if (previous == this) - throw new RuntimeException("Cannot connect to self"); + throw new RuntimeException("Cannot connect to self"); if (this.previous == previous) - return; + return; if (DEBUG) System.out.println(this + " previous " + previous); this.previous = previous; if (component != null) { @@ -227,21 +227,21 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { component.setBranch0(previous != null ? previous.component : null); updateSubPoint(); } - + } - + public PipeControlPoint parent; public List children = new ArrayList(); - + public List getSubPoint() { return children; } - + public PipeControlPoint getParentPoint() { return parent; } - + private double length; private Double turnAngle; private Vector3d turnAxis; @@ -249,12 +249,12 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { private Double offset; private Double rotationAngle; private Boolean reversed; - + @GetPropertyValue(name="Length",tabId="Debug",value="length") public double getLength() { return length; } - + public void setLength(double l) { if (Double.isInfinite(l) || Double.isNaN(l)) { return; @@ -266,38 +266,38 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { if (isDualInline()) getSubPoint().get(0).setLength(l); } - + @GetPropertyValue(name="Turn Angle",tabId="Debug",value="turnAngle") public Double getTurnAngle() { return turnAngle; } - + @GetPropertyValue(name="Turn Axis",tabId="Debug",value="turnAxis") public Vector3d getTurnAxis() { return turnAxis; } - + @GetPropertyValue(name="Offset",tabId="Debug",value="offset") public Double getOffset() { return offset; } - + @GetPropertyValue(name="Rotation Angle",tabId="Debug",value="rotationAngle") public Double getRotationAngle() { return rotationAngle; } - + @GetPropertyValue(name="Reversed",tabId="Debug",value="reversed") public Boolean getReversed() { return reversed; } - + public boolean _getReversed() { - if (reversed == null) - return false; - return reversed; - } - + if (reversed == null) + return false; + return reversed; + } + public void setTurnAngle(Double turnAngle) { if (turnAngle == null || Double.isInfinite(turnAngle) || Double.isNaN(turnAngle)) { return; @@ -307,14 +307,14 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { this.turnAngle = turnAngle; firePropertyChanged("turnAngle"); } - + public void setTurnAxis(Vector3d turnAxis) { - if (this.turnAxis != null && MathTools.equals(turnAxis, this.turnAxis)) - return; - this.turnAxis = turnAxis; + if (this.turnAxis != null && MathTools.equals(turnAxis, this.turnAxis)) + return; + this.turnAxis = turnAxis; firePropertyChanged("turnAxis"); } - + public void setOffset(Double offset) { if (Double.isInfinite(offset) || Double.isNaN(offset)) { return; @@ -324,7 +324,7 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { this.offset = offset; firePropertyChanged("offset"); } - + public void setRotationAngle(Double rotationAngle) { if (Double.isInfinite(rotationAngle) || Double.isNaN(rotationAngle)) { return; @@ -334,12 +334,12 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { this.rotationAngle = rotationAngle; firePropertyChanged("rotationAngle"); } - + public void setReversed(Boolean reversed) { this.reversed = reversed; firePropertyChanged("reversed"); } - + public Vector3d getSizeChangeOffsetVector(Vector3d dir) { Quat4d q; if (rotationAngle == null) @@ -347,11 +347,11 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { else q = getControlPointOrientationQuat(dir, rotationAngle); Vector3d v = new Vector3d(0.0,offset,0.0); - Vector3d offset = new Vector3d(); - MathTools.rotate(q, v, offset); - return offset; + Vector3d offset = new Vector3d(); + MathTools.rotate(q, v, offset); + return offset; } - + public Vector3d getSizeChangeOffsetVector() { Quat4d q; if (rotationAngle == null) @@ -359,175 +359,175 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { else q = getControlPointOrientationQuat(rotationAngle); Vector3d v = new Vector3d(0.0,offset,0.0); - Vector3d offset = new Vector3d(); - MathTools.rotate(q, v, offset); - return offset; + Vector3d offset = new Vector3d(); + MathTools.rotate(q, v, offset); + return offset; } - + @GetPropertyValue(name="Next",tabId="Debug",value="next") private String getNextString() { if (next == null) return null; return next.toString(); } - + @GetPropertyValue(name="Previous",tabId="Debug",value="previous") private String getPrevString() { if (previous == null) return null; return previous.toString(); } - + @GetPropertyValue(name="Sub",tabId="Debug",value="sub") private String getSubString() { if (children.size() == 0) return ""; return Arrays.toString(children.toArray()); } - + @GetPropertyValue(name="Type",tabId="Debug",value="type") public String getTypeString() { return type.name(); } - + public Quat4d getControlPointOrientationQuat(double angle) { - - if (turnAxis == null) { - Vector3d dir = getPathLegDirection(Direction.NEXT); - if (dir.lengthSquared() > MathTools.NEAR_ZERO) - dir.normalize(); - return getControlPointOrientationQuat(dir, angle); - } else { - Vector3d dir = getPathLegDirection(Direction.PREVIOUS); - dir.negate(); - if (dir.lengthSquared() > MathTools.NEAR_ZERO) - dir.normalize(); - return getControlPointOrientationQuat(dir, turnAxis, angle); - } - } - - public Quat4d getControlPointOrientationQuat(double angle, boolean reversed) { - - if (turnAxis == null) { - Vector3d dir = getPathLegDirection(Direction.NEXT); - if (dir.lengthSquared() > MathTools.NEAR_ZERO) - dir.normalize(); - Quat4d q = getControlPointOrientationQuat(dir, angle); - if (reversed) { + + if (turnAxis == null) { + Vector3d dir = getPathLegDirection(Direction.NEXT); + if (dir.lengthSquared() > MathTools.NEAR_ZERO) + dir.normalize(); + return getControlPointOrientationQuat(dir, angle); + } else { + Vector3d dir = getPathLegDirection(Direction.PREVIOUS); + dir.negate(); + if (dir.lengthSquared() > MathTools.NEAR_ZERO) + dir.normalize(); + return getControlPointOrientationQuat(dir, turnAxis, angle); + } + } + + public Quat4d getControlPointOrientationQuat(double angle, boolean reversed) { + + if (turnAxis == null) { + Vector3d dir = getPathLegDirection(Direction.NEXT); + if (dir.lengthSquared() > MathTools.NEAR_ZERO) + dir.normalize(); + Quat4d q = getControlPointOrientationQuat(dir, angle); + if (reversed) { Quat4d q2 = new Quat4d(); q2.set(new AxisAngle4d(MathTools.Y_AXIS, Math.PI)); q.mulInverse(q2); - } - return q; - } else { - Vector3d dir = getPathLegDirection(Direction.PREVIOUS); - dir.negate(); - if (dir.lengthSquared() > MathTools.NEAR_ZERO) - dir.normalize(); - return getControlPointOrientationQuat(dir, turnAxis, angle); - } - } - - - - public static Quat4d getControlPointOrientationQuat(Vector3d dir, double angle) { - if (dir.lengthSquared() < MathTools.NEAR_ZERO) - return MathTools.getIdentityQuat(); - - - Vector3d up = new Vector3d(0.0, 1.0, 0.0); - double a = up.angle(dir); - if (a < 0.1 || (Math.PI - a) < 0.1) { - up.set(1.0, 0.0, 0.0); } - - - return getControlPointOrientationQuat(dir, up, angle); - } - - public static Quat4d getControlPointOrientationQuat(Vector3d dir, Vector3d up, double angle) { - if (dir.lengthSquared() < MathTools.NEAR_ZERO) - return MathTools.getIdentityQuat(); - - final Vector3d front = new Vector3d(1.0,0.0,0.0); - - Quat4d q1 = new Quat4d(); - - - Vector3d right = new Vector3d(); - - right.cross(dir, up); - up.cross(right, dir); - right.normalize(); - up.normalize(); - - Matrix3d m = new Matrix3d(); - m.m00 = dir.x; - m.m10 = dir.y; - m.m20 = dir.z; - m.m01 = up.x; - m.m11 = up.y; - m.m21 = up.z; - m.m02 = right.x; - m.m12 = right.y; - m.m22 = right.z; - - //q1.set(m); MathTools contains more stable conversion - MathTools.getQuat(m, q1); - -// if (DEBUG) System.out.println("PipingTools.getPipeComponentOrientationQuat() " + dir+ " " + up + " " + right); - - Quat4d q2 = new Quat4d(); - q2.set(new AxisAngle4d(front, angle)); - q1.mul(q2); - return q1; - } - + return q; + } else { + Vector3d dir = getPathLegDirection(Direction.PREVIOUS); + dir.negate(); + if (dir.lengthSquared() > MathTools.NEAR_ZERO) + dir.normalize(); + return getControlPointOrientationQuat(dir, turnAxis, angle); + } + } + + + + public static Quat4d getControlPointOrientationQuat(Vector3d dir, double angle) { + if (dir.lengthSquared() < MathTools.NEAR_ZERO) + return MathTools.getIdentityQuat(); + + + Vector3d up = new Vector3d(0.0, 1.0, 0.0); + double a = up.angle(dir); + if (a < 0.1 || (Math.PI - a) < 0.1) { + up.set(1.0, 0.0, 0.0); + } + + + return getControlPointOrientationQuat(dir, up, angle); + } + + public static Quat4d getControlPointOrientationQuat(Vector3d dir, Vector3d up, double angle) { + if (dir.lengthSquared() < MathTools.NEAR_ZERO) + return MathTools.getIdentityQuat(); + + final Vector3d front = new Vector3d(1.0,0.0,0.0); + + Quat4d q1 = new Quat4d(); + + + Vector3d right = new Vector3d(); + + right.cross(dir, up); + up.cross(right, dir); + right.normalize(); + up.normalize(); + + Matrix3d m = new Matrix3d(); + m.m00 = dir.x; + m.m10 = dir.y; + m.m20 = dir.z; + m.m01 = up.x; + m.m11 = up.y; + m.m21 = up.z; + m.m02 = right.x; + m.m12 = right.y; + m.m22 = right.z; + + //q1.set(m); MathTools contains more stable conversion + MathTools.getQuat(m, q1); + + // if (DEBUG) System.out.println("PipingTools.getPipeComponentOrientationQuat() " + dir+ " " + up + " " + right); + + Quat4d q2 = new Quat4d(); + q2.set(new AxisAngle4d(front, angle)); + q1.mul(q2); + return q1; + } + public Vector3d getDirection(Direction direction) { - if (isDirected()) - return getDirectedControlPointDirection(); - if (isTurn() && isFixed()) { - if (direction == Direction.NEXT) { - if (previous != null) { - PipeControlPoint pcp = this; - Vector3d dir = new Vector3d(); - dir.sub(pcp.getWorldPosition(),previous.getWorldPosition()); - if (dir.lengthSquared() > MathTools.NEAR_ZERO) - dir.normalize(); - else - return null; - Quat4d q = getControlPointOrientationQuat(dir, pcp.getRotationAngle() != null ? pcp.getRotationAngle() : 0.0); - AxisAngle4d aa = new AxisAngle4d(MathTools.Y_AXIS,pcp.getTurnAngle() == null ? 0.0 : pcp.getTurnAngle()); - Quat4d q2 = MathTools.getQuat(aa); - Vector3d v = new Vector3d(1.,0.,0.); - Vector3d offset = new Vector3d(); - MathTools.rotate(q2, v, offset); - MathTools.rotate(q, offset, dir); - return dir; - } - } else { - if (next != null) { - PipeControlPoint pcp = this; - Vector3d dir = new Vector3d(); - dir.sub(next.getWorldPosition(),pcp.getWorldPosition()); - if (dir.lengthSquared() > MathTools.NEAR_ZERO) - dir.normalize(); - else - return null; - Quat4d q = getControlPointOrientationQuat(dir, pcp.getRotationAngle() != null ? pcp.getRotationAngle() : 0.0); - AxisAngle4d aa = new AxisAngle4d(MathTools.Y_AXIS,pcp.getTurnAngle() == null ? 0.0 : pcp.getTurnAngle()); - Quat4d q2 = MathTools.getQuat(aa); - Vector3d v = new Vector3d(1.,0.,0.); - Vector3d offset = new Vector3d(); - MathTools.rotate(q2, v, offset); - MathTools.rotate(q, offset, dir); - return dir; - } - } - } - return null; - } - + if (isDirected()) + return getDirectedControlPointDirection(); + if (isTurn() && isFixed()) { + if (direction == Direction.NEXT) { + if (previous != null) { + PipeControlPoint pcp = this; + Vector3d dir = new Vector3d(); + dir.sub(pcp.getWorldPosition(),previous.getWorldPosition()); + if (dir.lengthSquared() > MathTools.NEAR_ZERO) + dir.normalize(); + else + return null; + Quat4d q = getControlPointOrientationQuat(dir, pcp.getRotationAngle() != null ? pcp.getRotationAngle() : 0.0); + AxisAngle4d aa = new AxisAngle4d(MathTools.Y_AXIS,pcp.getTurnAngle() == null ? 0.0 : pcp.getTurnAngle()); + Quat4d q2 = MathTools.getQuat(aa); + Vector3d v = new Vector3d(1.,0.,0.); + Vector3d offset = new Vector3d(); + MathTools.rotate(q2, v, offset); + MathTools.rotate(q, offset, dir); + return dir; + } + } else { + if (next != null) { + PipeControlPoint pcp = this; + Vector3d dir = new Vector3d(); + dir.sub(next.getWorldPosition(),pcp.getWorldPosition()); + if (dir.lengthSquared() > MathTools.NEAR_ZERO) + dir.normalize(); + else + return null; + Quat4d q = getControlPointOrientationQuat(dir, pcp.getRotationAngle() != null ? pcp.getRotationAngle() : 0.0); + AxisAngle4d aa = new AxisAngle4d(MathTools.Y_AXIS,pcp.getTurnAngle() == null ? 0.0 : pcp.getTurnAngle()); + Quat4d q2 = MathTools.getQuat(aa); + Vector3d v = new Vector3d(1.,0.,0.); + Vector3d offset = new Vector3d(); + MathTools.rotate(q2, v, offset); + MathTools.rotate(q, offset, dir); + return dir; + } + } + } + return null; + } + public void insert(PipeControlPoint previous, PipeControlPoint next) { // inserting an offsetpoint is error, if (isDualSub()) @@ -543,11 +543,11 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { } else { piperun.addChild(this); } - + // insert new BranchControlPoint between straight's control points PipeControlPoint previousNext = previous.getNext(); PipeControlPoint previousPrevious = previous.getPrevious(); - + PipeControlPoint offsetCP = null; if (isOffset()) { offsetCP = getSubPoint().get(0); @@ -565,7 +565,7 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { previous.getParentPoint().setNext(this); } this.setNext(next); - + if (offsetCP == null) { next.setPrevious(this); } else { @@ -573,17 +573,17 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { offsetCP.setNext(next); offsetCP.setPrevious(previous); } - + if (next.isDualInline()) { next.getSubPoint().get(0).setPrevious(this); } } else if (previousPrevious != null && previousPrevious == next) { - // control point were given in reverse order + // control point were given in reverse order if (next.isDualInline()) throw new RuntimeException(); if (previous.isDualSub()) throw new RuntimeException(); - + this.setNext(previous); if (offsetCP == null) { previous.setNext(this); @@ -600,16 +600,16 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { if (next.isDualSub()) { next.getParentPoint().setNext(this); } - + } else { throw new RuntimeException(); } - + PipingRules.validate(piperun); } - - - + + + public void insert(PipeControlPoint pcp, Direction direction) { if (isDualSub()) throw new RuntimeException(); @@ -651,11 +651,11 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { else ocp.setPrevious(nocp); } - + } PipingRules.validate(getPipeRun()); } - + public Vector3d getDirectedControlPointDirection() { assert (isDirected()); Vector3d dir = new Vector3d(); @@ -663,7 +663,7 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { dir.normalize(); return dir; } - + public Vector3d getPathLegDirection(Direction direction) { if (direction == Direction.NEXT) { if (next != null) { @@ -679,10 +679,10 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { if (!isDirected()) throw new RuntimeException("Cannot calculate path leg direction for unconnected control point"); return getDirectedControlPointDirection(); - + } else { - if (isVariableAngle()) - throw new RuntimeException("Cannot calculate path leg direction for unconnected variable angle control point"); + if (isVariableAngle()) + throw new RuntimeException("Cannot calculate path leg direction for unconnected variable angle control point"); if (isInline()) { PipeControlPoint pcp = this; if (pcp.isDualSub()) { @@ -698,7 +698,7 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { v.sub(getWorldPosition(),previous.getWorldPosition()); return v; } else if (isTurn() && isFixed() && !_getReversed()) { - return getDirection(Direction.NEXT); + return getDirection(Direction.NEXT); } throw new RuntimeException("Missing implementation"); } @@ -719,9 +719,9 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { v.negate(); return v; } else { - if (isVariableAngle()) - throw new RuntimeException("Cannot calculate path leg direction for unconnected variable angle control point"); - if (isInline()) { + if (isVariableAngle()) + throw new RuntimeException("Cannot calculate path leg direction for unconnected variable angle control point"); + if (isInline()) { PipeControlPoint pcp = this; if (pcp.isDualInline()) { pcp = pcp.getSubPoint().get(0); @@ -738,17 +738,17 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { v.sub(getWorldPosition(),next.getWorldPosition()); return v; } else if (isTurn() && isFixed() && _getReversed()) { - return getDirection(Direction.PREVIOUS); - } + return getDirection(Direction.PREVIOUS); + } throw new RuntimeException("Missing implementation"); } } } } - + public void getInlineControlPointEnds(Tuple3d p1, Tuple3d p2) { assert (isInline()); - + Vector3d pos = getWorldPosition(); Vector3d dir = getPathLegDirection(Direction.NEXT); dir.normalize(); @@ -758,7 +758,7 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { p1.sub(dir); p2.add(dir); } - + public void getControlPointEnds(Tuple3d p1, Tuple3d p2) { Vector3d pos = getWorldPosition(); Vector3d dir1 = getPathLegDirection(Direction.PREVIOUS); @@ -777,10 +777,10 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { p1.add(dir1); p2.add(dir2); } - + public void getInlineControlPointEnds(Tuple3d p1, Tuple3d p2, Vector3d dir) { assert (isInline()); - + Vector3d pos = getWorldPosition(); dir.set(getPathLegDirection(Direction.NEXT)); dir.normalize(); @@ -790,10 +790,10 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { p1.sub(dir); p2.add(dir); } - + public void getInlineControlPointEnds(Tuple3d center, Tuple3d p1, Tuple3d p2, Vector3d dir) { assert (isInline()); - + Vector3d pos = getWorldPosition(); center.set(pos); dir.set(getPathLegDirection(Direction.NEXT)); @@ -804,7 +804,7 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { p1.sub(dir); p2.add(dir); } - + public double getInlineLength() { if (type == PointType.TURN) return length; @@ -812,7 +812,7 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { return length * 0.5; return 0; } - + public Vector3d getRealPosition(PositionType type) { Vector3d pos = getWorldPosition(); switch (type) { @@ -839,11 +839,11 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { case SPLIT: // do nothing break; - + } return pos; } - + public void getInlineMovement(Tuple3d start, Tuple3d end) { // FIXME : check type of neighbor components and allow movement on top of variable length components, // find proper range for movement (pcp's position is not) @@ -852,46 +852,46 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { start.set(p.getWorldPosition()); end.set(n.getWorldPosition()); } - + public PipeControlPoint findNextEnd() { ArrayList t = new ArrayList(); - return findNextEnd( t); + return findNextEnd( t); } - + public PipeControlPoint findPreviousEnd() { ArrayList t = new ArrayList(); - return findPreviousEnd(t); + return findPreviousEnd(t); } - + public PipeControlPoint findNextEnd(List nextList) { - while (true) { - PipeControlPoint pcp = null; - PipeControlPoint p = null; - if (nextList.size() == 0) - p = this; - - else - p = nextList.get(nextList.size() - 1); - - pcp = p.getNext(); - if (pcp == null) { - pcp = p; - if (nextList.size() > 0) - nextList.remove(nextList.size() - 1); -// if (DEBUG) System.out.println(" " + pcp.getResource() + " not full"); - return pcp; - //break; - } - if (pcp.isPathLegEnd()) { - //if (DEBUG) System.out.println(" " + pcp.getResource()); - return pcp; - } else { - nextList.add(pcp); - // if (DEBUG) System.out.print(" " + pcp.getResource()); - } - } - } - + while (true) { + PipeControlPoint pcp = null; + PipeControlPoint p = null; + if (nextList.size() == 0) + p = this; + + else + p = nextList.get(nextList.size() - 1); + + pcp = p.getNext(); + if (pcp == null) { + pcp = p; + if (nextList.size() > 0) + nextList.remove(nextList.size() - 1); + // if (DEBUG) System.out.println(" " + pcp.getResource() + " not full"); + return pcp; + //break; + } + if (pcp.isPathLegEnd()) { + //if (DEBUG) System.out.println(" " + pcp.getResource()); + return pcp; + } else { + nextList.add(pcp); + // if (DEBUG) System.out.print(" " + pcp.getResource()); + } + } + } + public PipeControlPoint findPreviousEnd(List prevList) { while (true) { PipeControlPoint pcp = null; @@ -907,19 +907,19 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { pcp = p; if (prevList.size() > 0) prevList.remove(prevList.size() - 1); -// if (DEBUG) System.out.println(" " + pcp.getResource() + " not full"); + // if (DEBUG) System.out.println(" " + pcp.getResource() + " not full"); return pcp; } if (pcp.isPathLegEnd()) { -// if (DEBUG) System.out.println(" " + pcp.getResource()); + // if (DEBUG) System.out.println(" " + pcp.getResource()); return pcp; } else { prevList.add(pcp); -// if (DEBUG)System.out.print(" " + pcp.getResource()); + // if (DEBUG)System.out.print(" " + pcp.getResource()); } } } - + public void _remove() { if (component == null && next == null && previous == null) return; @@ -930,7 +930,7 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { PipeRun pipeRun = getPipeRun(); if (pipeRun == null) return; - + PipeControlPoint additionalRemove = null; if (!PipingRules.isEnabled()) { setPrevious(null); @@ -948,16 +948,16 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { boolean link = true; if (currentNext.isBranchEnd()) { link = false; -// currentNext.setPrevious(null); -// currentNext.setNext(null); + // currentNext.setPrevious(null); + // currentNext.setNext(null); currentNext.remove(); currentNext = null; setNext(null); } if (currentPrev.isBranchEnd()) { link = false; -// currentPrev.setPrevious(null); -// currentPrev.setNext(null); + // currentPrev.setPrevious(null); + // currentPrev.setNext(null); currentPrev.remove(); currentPrev = null; setPrevious(null); @@ -1015,7 +1015,7 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { currentPrev.setNext(currentNext); else currentPrev.setNext(null); - + setPrevious(null); } else { throw new RuntimeException("Removing PipeControlPoint " + this + " structure damaged"); @@ -1026,9 +1026,9 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { additionalRemove = currentPrev; // combine lengths and set the location of remaining control point to the center. Point3d ps = new Point3d(); - Point3d pe = new Point3d(); - Point3d ns = new Point3d(); - Point3d ne = new Point3d(); + Point3d pe = new Point3d(); + Point3d ns = new Point3d(); + Point3d ne = new Point3d(); currentPrev.getInlineControlPointEnds(ps, pe); currentNext.getInlineControlPointEnds(ns, ne); double l = currentPrev.getLength() + currentNext.getLength(); @@ -1081,9 +1081,9 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { } else if (parent!= null) { removeParentPoint(); } - + } - + removeComponent(); pipeRun.remChild(this); checkRemove(pipeRun); @@ -1092,7 +1092,7 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { if (additionalRemove != null) additionalRemove.remove(); } - + public void remove() { PipeControlPoint currentPrev = previous; PipeControlPoint currentNext = next; @@ -1106,7 +1106,7 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { e.printStackTrace(); } } - + private void checkRemove(PipeRun pipeRun) { Collection points = pipeRun.getControlPoints(); if (points.size() == 0) { @@ -1117,7 +1117,7 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { pcp._remove(); } } - + private void removeDualPoint() { if (previous != null) previous.setNext(null); @@ -1134,15 +1134,15 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { } PipeRun p1 = ocp.getPipeRun(); PipeRun p2 = sccp.getPipeRun(); - + ocp.removeComponent(); sccp.removeComponent(); - + if (p1 != null) - p1.remChild(ocp); + p1.remChild(ocp); if (p2 != null) - p2.remChild(sccp); - + p2.remChild(sccp); + // TODO : now we assume that this is size change, and we do if (ocp.next != null) ocp.next.setPrevious(null); @@ -1156,13 +1156,13 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { ocp.setPrevious(null); sccp.setNext(null); sccp.setPrevious(null); - + if (p1 != null) - checkRemove(p1); + checkRemove(p1); if (p2 != null) - checkRemove(p2); + checkRemove(p2); } - + private void removeSubPoints() { for (PipeControlPoint p : children) { // TODO : this may affect delete routine, since classification of the point changes. @@ -1171,11 +1171,11 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { } children.clear(); } - + private void removeParentPoint() { throw new RuntimeException("Child points cannot be removed directly"); } - + private void removeComponent() { if (component == null) return; @@ -1191,7 +1191,7 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { else if (next.getPrevious() == component) next.setPrevious(null); else if (next.getBranch0() == component) - next.setBranch0(null); + next.setBranch0(null); } if (prev != null) { if (prev.getNext() == component) @@ -1199,22 +1199,22 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { else if (prev.getPrevious() == component) prev.setPrevious(null); else if (prev.getBranch0() == component) - prev.setBranch0(null); + prev.setBranch0(null); } if (br0 != null) { - if (br0.getNext() == component) - br0.setNext(null); - else if (br0.getPrevious() == component) - br0.setPrevious(null); - else if (br0.getBranch0() == component) - br0.setBranch0(null); + if (br0.getNext() == component) + br0.setNext(null); + else if (br0.getPrevious() == component) + br0.setPrevious(null); + else if (br0.getBranch0() == component) + br0.setBranch0(null); } PipelineComponent comp = component; component = null; - + comp.remove(); } - + @Override public void setOrientation(Quat4d orientation) { if (MathTools.equals(orientation, getOrientation())) @@ -1224,7 +1224,7 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { component._setWorldOrientation(getWorldOrientation()); updateSubPoint(); } - + @Override public void setPosition(Vector3d position) { if (MathTools.equals(position, getPosition())) @@ -1236,7 +1236,7 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { component._setWorldPosition(getWorldPosition()); updateSubPoint(); } - + private void updateSubPoint() { if (isOffset()) { if (next == null && previous == null) { @@ -1260,19 +1260,19 @@ public class PipeControlPoint extends G3DNode implements IP3DNode { } } - + public void _setWorldPosition(Vector3d position) { Vector3d localPos = getLocalPosition(position); super.setPosition(localPos); updateSubPoint(); } - + public void _setWorldOrientation(Quat4d orientation) { Quat4d localOr = getLocalOrientation(orientation); super.setOrientation(localOr); updateSubPoint(); } - + @Override public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/PipingRules.java b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/PipingRules.java index 7b0d3bf7..854b265d 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/PipingRules.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/scenegraph/controlpoint/PipingRules.java @@ -53,8 +53,8 @@ public class PipingRules { public static void requestUpdate(PipeControlPoint pcp) { if (DEBUG) System.out.println("PipingRules request " + pcp); synchronized (updateMutex) { - if (!requestUpdates.contains(pcp)) - requestUpdates.add(pcp); + if (!requestUpdates.contains(pcp)) + requestUpdates.add(pcp); } } @@ -64,19 +64,19 @@ public class PipingRules { List temp = new ArrayList(requestUpdates.size()); synchronized(updateMutex) { - temp.addAll(requestUpdates); - requestUpdates.clear(); + temp.addAll(requestUpdates); + requestUpdates.clear(); } synchronized (ruleMutex) { - currentUpdates.clear(); - currentUpdates.addAll(temp); - // TODO : we should remove already processed control points from currentUpdates after each _positionUpdate call. - for (PipeControlPoint pcp : currentUpdates) - _positionUpdate(pcp, true); - currentUpdates.clear(); - } + currentUpdates.clear(); + currentUpdates.addAll(temp); + // TODO : we should remove already processed control points from currentUpdates after each _positionUpdate call. + for (PipeControlPoint pcp : currentUpdates) + _positionUpdate(pcp, true); + currentUpdates.clear(); + } synchronized(updateMutex) { - requestUpdates.removeAll(temp); + requestUpdates.removeAll(temp); } return true; @@ -88,13 +88,13 @@ public class PipingRules { } public static boolean positionUpdate(PipeControlPoint pcp, boolean allowIR) throws Exception { - synchronized (ruleMutex) { - currentUpdates.add(pcp); - boolean b = _positionUpdate(pcp, allowIR); - currentUpdates.clear(); - return b; - } - + synchronized (ruleMutex) { + currentUpdates.add(pcp); + boolean b = _positionUpdate(pcp, allowIR); + currentUpdates.clear(); + return b; + } + } private static boolean _positionUpdate(PipeControlPoint pcp, boolean allowIR) throws Exception { @@ -297,26 +297,26 @@ public class PipingRules { private static void updatePathLegNext(PipeControlPoint start, PipeControlPoint updated, PathLegUpdateType lengthChange) throws Exception { - UpdateStruct2 us = createUS(start, Direction.NEXT, 0, new ArrayList(), updated); - if (lengthChange == PathLegUpdateType.NONE) { - if (start.equals(updated)) - lengthChange = PathLegUpdateType.NEXT; - else if (us.end.equals(updated)) - lengthChange = PathLegUpdateType.PREV; - } + UpdateStruct2 us = createUS(start, Direction.NEXT, 0, new ArrayList(), updated); + if (lengthChange == PathLegUpdateType.NONE) { + if (start.equals(updated)) + lengthChange = PathLegUpdateType.NEXT; + else if (us.end.equals(updated)) + lengthChange = PathLegUpdateType.PREV; + } updatePathLeg(us, lengthChange); } private static void updatePathLegPrev(PipeControlPoint start, PipeControlPoint updated, PathLegUpdateType lengthChange) throws Exception { // TODO: this method is not symmetric with updatePathLegNext, which may alter lengthChange parameter? - UpdateStruct2 us = createUS(start, Direction.PREVIOUS, 0, new ArrayList(), updated); + UpdateStruct2 us = createUS(start, Direction.PREVIOUS, 0, new ArrayList(), updated); // if (lengthChange == PathLegUpdateType.NONE) { // if (start.equals(updated)) // lengthChange = PathLegUpdateType.NEXT; // else if (us.end.equals(updated)) // lengthChange = PathLegUpdateType.PREV; // } - updatePathLeg(us, lengthChange); + updatePathLeg(us, lengthChange); } private static class UpdateStruct2 { @@ -417,48 +417,48 @@ public class PipingRules { } private static UpdateStruct2 createUS(PipeControlPoint start, Direction direction, int iter, ArrayList toRemove, PipeControlPoint updated) { - ArrayList list = new ArrayList(); - PipeControlPoint end = null; - if (direction == Direction.NEXT) { - end = start.findNextEnd(list); - } else { - ArrayList prevList = new ArrayList(); - PipeControlPoint tend = start.findPreviousEnd(prevList); - for (PipeControlPoint icp : prevList) { - if (icp.isDualSub()) { - list.add(0, icp.getParentPoint()); - } else { - list.add(0, icp); - } - } - end = start; - start = tend; - } - if (start == end) - return null; - boolean hasOffsets = false; - Vector3d offset = new Vector3d(); - Vector3d startPoint = start.getWorldPosition(); - Vector3d endPoint = end.getWorldPosition(); - Vector3d dir = new Vector3d(); - hasOffsets = calculateOffset(startPoint, endPoint, list, dir, offset); - return new UpdateStruct2(start, startPoint, list, end, endPoint, dir, offset, hasOffsets, iter, direction == Direction.PREVIOUS, toRemove, updated); + ArrayList list = new ArrayList(); + PipeControlPoint end = null; + if (direction == Direction.NEXT) { + end = start.findNextEnd(list); + } else { + ArrayList prevList = new ArrayList(); + PipeControlPoint tend = start.findPreviousEnd(prevList); + for (PipeControlPoint icp : prevList) { + if (icp.isDualSub()) { + list.add(0, icp.getParentPoint()); + } else { + list.add(0, icp); + } + } + end = start; + start = tend; + } + if (start == end) + return null; + boolean hasOffsets = false; + Vector3d offset = new Vector3d(); + Vector3d startPoint = start.getWorldPosition(); + Vector3d endPoint = end.getWorldPosition(); + Vector3d dir = new Vector3d(); + hasOffsets = calculateOffset(startPoint, endPoint, list, dir, offset); + return new UpdateStruct2(start, startPoint, list, end, endPoint, dir, offset, hasOffsets, iter, direction == Direction.PREVIOUS, toRemove, updated); } private static boolean asDirected(PipeControlPoint pcp, Direction direction) { - if (pcp.isDirected()) - return true; - if (pcp.isTurn() && pcp.isFixed()) { - if (!pcp._getReversed()) - return direction == Direction.NEXT; - else - return direction == Direction.PREVIOUS; - } - return false; + if (pcp.isDirected()) + return true; + if (pcp.isTurn() && pcp.isFixed()) { + if (!pcp._getReversed()) + return direction == Direction.NEXT; + else + return direction == Direction.PREVIOUS; + } + return false; } private static Vector3d direction(PipeControlPoint pcp, Direction direction) { - return pcp.getDirection(direction); + return pcp.getDirection(direction); } private static void updatePathLeg(UpdateStruct2 u, PathLegUpdateType lengthChange) throws Exception { @@ -593,8 +593,8 @@ public class PipingRules { PipeControlPoint icp = pathLegPoints.get(i); PipeControlPoint prev = i > 0 ? pathLegPoints.get(i - 1) : null; - PipeControlPoint next = i < pathLegPoints.size() - 1 ? pathLegPoints.get(i + 1) : null; - + PipeControlPoint next = i < pathLegPoints.size() - 1 ? pathLegPoints.get(i + 1) : null; + if (prev != null && prev.isDualInline()) prev = prev.getSubPoint().get(0); @@ -710,49 +710,49 @@ public class PipingRules { } private static void updateVariableLengthEnd(PipeControlPoint icp, PipeControlPoint prev) { - Vector3d currentPos = icp.getWorldPosition(); - Vector3d prevPos = prev.getWorldPosition(); - - Vector3d dir = new Vector3d(); - dir.sub(currentPos, prevPos); - - boolean simple = currentUpdates.contains(icp); - if (simple) { - // Update based on position -> adjust length - double currentLength = (dir.length() - prev.getInlineLength()) * 2.0; - icp.setLength(currentLength); - } else { - // Update based on neighbour movement -> adjust length and position, so that free end stays in place. - double currentLength = icp.getLength(); - if (currentLength < MathTools.NEAR_ZERO) { - currentLength = (dir.length() - prev.getInlineLength()) * 2.0; - } - - if (dir.lengthSquared() > MathTools.NEAR_ZERO) - dir.normalize(); - Point3d endPos = new Point3d(dir); - endPos.scale(currentLength * 0.5); - endPos.add(currentPos); // this is the free end of the component - - double offset = prev.getInlineLength(); - Point3d beginPos = new Point3d(dir); - beginPos.scale(offset); - beginPos.add(prevPos); // this is the connected end of the component - - double l = beginPos.distance(endPos); - - if (Double.isNaN(l)) - System.out.println("Length for " + icp + " is NaN"); - - dir.scale(l * 0.5); - beginPos.add(dir); // center position - - if (DEBUG) - System.out.println("PipingRules.updateInlineControlPoints() setting variable length to " + l); - icp.setLength(l); - - icp.setWorldPosition(new Vector3d(beginPos)); - } + Vector3d currentPos = icp.getWorldPosition(); + Vector3d prevPos = prev.getWorldPosition(); + + Vector3d dir = new Vector3d(); + dir.sub(currentPos, prevPos); + + boolean simple = currentUpdates.contains(icp); + if (simple) { + // Update based on position -> adjust length + double currentLength = (dir.length() - prev.getInlineLength()) * 2.0; + icp.setLength(currentLength); + } else { + // Update based on neighbour movement -> adjust length and position, so that free end stays in place. + double currentLength = icp.getLength(); + if (currentLength < MathTools.NEAR_ZERO) { + currentLength = (dir.length() - prev.getInlineLength()) * 2.0; + } + + if (dir.lengthSquared() > MathTools.NEAR_ZERO) + dir.normalize(); + Point3d endPos = new Point3d(dir); + endPos.scale(currentLength * 0.5); + endPos.add(currentPos); // this is the free end of the component + + double offset = prev.getInlineLength(); + Point3d beginPos = new Point3d(dir); + beginPos.scale(offset); + beginPos.add(prevPos); // this is the connected end of the component + + double l = beginPos.distance(endPos); + + if (Double.isNaN(l)) + System.out.println("Length for " + icp + " is NaN"); + + dir.scale(l * 0.5); + beginPos.add(dir); // center position + + if (DEBUG) + System.out.println("PipingRules.updateInlineControlPoints() setting variable length to " + l); + icp.setLength(l); + + icp.setWorldPosition(new Vector3d(beginPos)); + } } private static void ppNoOffset(UpdateStruct2 u) throws Exception { @@ -833,12 +833,12 @@ public class PipingRules { Vector3d directedDirection = direction(dcp, dcpStart ? Direction.NEXT : Direction.PREVIOUS); if (directedDirection == null) { - //updateTurnControlPointTurn(dcp, dcp.getPrevious(), dcp.getNext()); - updateTurnControlPointTurn(dcp, null, null); - directedDirection = direction(dcp, dcpStart ? Direction.NEXT : Direction.PREVIOUS); - if (directedDirection == null) { - return; - } + //updateTurnControlPointTurn(dcp, dcp.getPrevious(), dcp.getNext()); + updateTurnControlPointTurn(dcp, null, null); + directedDirection = direction(dcp, dcpStart ? Direction.NEXT : Direction.PREVIOUS); + if (directedDirection == null) { + return; + } } Point3d directedEndPoint = new Point3d(u.endPoint); if (u.hasOffsets) @@ -860,8 +860,8 @@ public class PipingRules { double distance = t.length(); boolean aligned = (distance < ALLOWED_OFFSET); if (aligned) { - if (u.start.isInline() || u.end.isInline() || u.start.isFixed() || u.end.isFixed()) - processPathLeg(u, true, false); + if (u.start.isInline() || u.end.isInline() || u.start.isFixed() || u.end.isFixed()) + processPathLeg(u, true, false); checkExpandPathLeg(u, lengthChange, inlineEnd); } else { @@ -1011,7 +1011,7 @@ public class PipingRules { p1 = dcp.getWorldPosition(); Vector3d v = new Vector3d(); if (!u.reversed) - v.set(dir1); + v.set(dir1); else v.set(dir2); @@ -1028,7 +1028,7 @@ public class PipingRules { // By default, the elbows are placed next to each other, by using 90 deg angles. // If the distance between elbows is not enough, we must move the other elbow (and create more shallow angle elbows) if (MathTools.distance(p1, p2) < off*2.05) { - p2.add(v); + p2.add(v); } PipeControlPoint tcp1 = insertElbow(dcp, next, p1); @@ -1146,7 +1146,7 @@ public class PipingRules { PipeControlPoint endNext = u.end.getNext(); if (endNext != null) { - // TODO: u.end, u.dir, null + // TODO: u.end, u.dir, null double a = updateTurnControlPointTurn(u.end, null, null); if (a < MIN_TURN_ANGLE && u.end.isDeletable()) endRemoved = true; @@ -1315,7 +1315,7 @@ public class PipingRules { if (updateEnds) { if (u.start.isTurn()) { //updateTurnControlPointTurn(u.start, u.start.getPrevious(), u.start.getNext()); - updateTurnControlPointTurn(u.start, null, null); + updateTurnControlPointTurn(u.start, null, null); // updatePathLegPrev(u.start, u.start, PathLegUpdateType.NONE); } else if (u.start.isEnd()) { updateEndComponentControlPoint(u.start, u.startPoint, u.endPoint); @@ -1324,7 +1324,7 @@ public class PipingRules { } if (u.end.isTurn()) { //updateTurnControlPointTurn(u.end, u.end.getPrevious(), u.end.getNext()); - updateTurnControlPointTurn(u.end, null, null); + updateTurnControlPointTurn(u.end, null, null); // updatePathLegNext(u.end, u.end, PathLegUpdateType.NONE); } else if (u.end.isEnd()) { updateEndComponentControlPoint(u.end, u.startPoint, u.endPoint); @@ -1538,85 +1538,85 @@ public class PipingRules { } private static double updateTurnControlPointTurn(PipeControlPoint tcp, Vector3d prev, Vector3d next) { - if (next == null) { - UpdateStruct2 us = createUS(tcp, Direction.NEXT, 0, new ArrayList(), tcp); - if (us != null) - next = us.dir; - } - if (prev == null) { - UpdateStruct2 us = createUS(tcp, Direction.PREVIOUS, 0, new ArrayList(), tcp); - if (us != null) { - prev = us.dir; - } - } - - if (!tcp.isFixed()) { - - - if (next == null || prev == null) { - if (tcp.getTurnAngle() != null) - return tcp.getTurnAngle(); - return Math.PI; // FIXME : argh - } - double turnAngle = prev.angle(next); - - double angle = Math.PI - turnAngle; - - Vector3d turnAxis = new Vector3d(); - turnAxis.cross(prev, next); - if (turnAxis.lengthSquared() > MathTools.NEAR_ZERO) { - double elbowRadius = tcp.getPipelineComponent().getPipeRun().getTurnRadius(); - double R = elbowRadius / Math.tan(angle * 0.5); - - turnAxis.normalize(); - tcp.setTurnAngle(turnAngle); - tcp.setLength(R);// setComponentOffsetValue(R); - tcp.setTurnAxis(turnAxis); - // tcp.setPosition(tcp.getPosition()); - } else { - turnAngle = 0.0; - tcp.setTurnAngle(0.0); - tcp.setLength(0.0); - tcp.setTurnAxis(new Vector3d(MathTools.Y_AXIS)); - } - - updateControlPointOrientation(tcp); - - if (DEBUG) - System.out.println("PipingTools.updateTurnControlPointTurn " + prev + " " + next + " " + turnAngle + " " + turnAxis); - return turnAngle; - } else { - - if (prev != null && next != null) { - // Nothing to do - } else if (prev == null) { - if (!tcp._getReversed()) - tcp.setReversed(true); - } else if (next == null) { - if (tcp._getReversed()) - tcp.setReversed(false); - } - - Vector3d dir = null; - if (!tcp._getReversed()) { - dir = prev; - } else { - dir = next; - dir.negate(); - } - if (dir == null) { - return Math.PI; // FIXME : argh - } - - Quat4d q = PipeControlPoint.getControlPointOrientationQuat(dir, tcp.getRotationAngle() != null ? tcp.getRotationAngle() : 0.0); - Vector3d v = new Vector3d(); - MathTools.rotate(q, MathTools.Y_AXIS,v); - tcp.setTurnAxis(v); - tcp.setWorldOrientation(q); - if (tcp.getTurnAngle() != null) - return tcp.getTurnAngle(); - return Math.PI; // FIXME : argh - } + if (next == null) { + UpdateStruct2 us = createUS(tcp, Direction.NEXT, 0, new ArrayList(), tcp); + if (us != null) + next = us.dir; + } + if (prev == null) { + UpdateStruct2 us = createUS(tcp, Direction.PREVIOUS, 0, new ArrayList(), tcp); + if (us != null) { + prev = us.dir; + } + } + + if (!tcp.isFixed()) { + + + if (next == null || prev == null) { + if (tcp.getTurnAngle() != null) + return tcp.getTurnAngle(); + return Math.PI; // FIXME : argh + } + double turnAngle = prev.angle(next); + + double angle = Math.PI - turnAngle; + + Vector3d turnAxis = new Vector3d(); + turnAxis.cross(prev, next); + if (turnAxis.lengthSquared() > MathTools.NEAR_ZERO) { + double elbowRadius = tcp.getPipelineComponent().getPipeRun().getTurnRadius(); + double R = elbowRadius / Math.tan(angle * 0.5); + + turnAxis.normalize(); + tcp.setTurnAngle(turnAngle); + tcp.setLength(R);// setComponentOffsetValue(R); + tcp.setTurnAxis(turnAxis); + // tcp.setPosition(tcp.getPosition()); + } else { + turnAngle = 0.0; + tcp.setTurnAngle(0.0); + tcp.setLength(0.0); + tcp.setTurnAxis(new Vector3d(MathTools.Y_AXIS)); + } + + updateControlPointOrientation(tcp); + + if (DEBUG) + System.out.println("PipingTools.updateTurnControlPointTurn " + prev + " " + next + " " + turnAngle + " " + turnAxis); + return turnAngle; + } else { + + if (prev != null && next != null) { + // Nothing to do + } else if (prev == null) { + if (!tcp._getReversed()) + tcp.setReversed(true); + } else if (next == null) { + if (tcp._getReversed()) + tcp.setReversed(false); + } + + Vector3d dir = null; + if (!tcp._getReversed()) { + dir = prev; + } else { + dir = next; + dir.negate(); + } + if (dir == null) { + return Math.PI; // FIXME : argh + } + + Quat4d q = PipeControlPoint.getControlPointOrientationQuat(dir, tcp.getRotationAngle() != null ? tcp.getRotationAngle() : 0.0); + Vector3d v = new Vector3d(); + MathTools.rotate(q, MathTools.Y_AXIS,v); + tcp.setTurnAxis(v); + tcp.setWorldOrientation(q); + if (tcp.getTurnAngle() != null) + return tcp.getTurnAngle(); + return Math.PI; // FIXME : argh + } } @@ -1648,118 +1648,118 @@ public class PipingRules { public static void reverse(PipeRun pipeRun) { while (true) { - List points = getControlPoints(pipeRun); - PipeControlPoint pcp = points.get(0); - if (pcp.isSizeChange() && pcp.getSubPoint().size() > 0) { - pipeRun = pcp.getPipeRun(); - } else { - break; - } + List points = getControlPoints(pipeRun); + PipeControlPoint pcp = points.get(0); + if (pcp.isSizeChange() && pcp.getSubPoint().size() > 0) { + pipeRun = pcp.getPipeRun(); + } else { + break; + } } List all = new ArrayList(); List> pcps = new ArrayList>(); while (true) { - all.add(pipeRun); - List points = getControlPoints(pipeRun); - pcps.add(points); - PipeControlPoint pcp = points.get(points.size()-1); - if (pcp.getSubPoint().size() > 0) { - pipeRun = pcp.getSubPoint().get(0).getPipeRun(); - } else { - break; - } + all.add(pipeRun); + List points = getControlPoints(pipeRun); + pcps.add(points); + PipeControlPoint pcp = points.get(points.size()-1); + if (pcp.getSubPoint().size() > 0) { + pipeRun = pcp.getSubPoint().get(0).getPipeRun(); + } else { + break; + } } for (int i = 0 ; i < all.size(); i++) { - List list = pcps.get(i); - _reverse(list); + List list = pcps.get(i); + _reverse(list); } for (int i = 0 ; i < all.size(); i++) { - boolean last = i == all.size() - 1; - List list = pcps.get(i); - - if (!last) { - List list2 = pcps.get(i+1); - PipeControlPoint prev = list.get(list.size()-1); - PipeControlPoint next = list2.get(0); - System.out.println(); - if (prev == next) { - // Reverse the component on the boundary. - InlineComponent ic = (InlineComponent)prev.getPipelineComponent(); - PipeRun r1 = ic.getPipeRun(); - PipeRun r2 = ic.getAlternativePipeRun(); - if (r1 == null || r2 == null) - throw new RuntimeException("Components on PipeRun changes should refer to bot PipeRuns"); - ic.deattach(); - r2.addChild(ic); - ic.setPipeRun(r2); - ic.setAlternativePipeRun(r1); - } else { - throw new RuntimeException("PipeRun changes should contain shared control points"); - } - - } - } - + boolean last = i == all.size() - 1; + List list = pcps.get(i); + + if (!last) { + List list2 = pcps.get(i+1); + PipeControlPoint prev = list.get(list.size()-1); + PipeControlPoint next = list2.get(0); + System.out.println(); + if (prev == next) { + // Reverse the component on the boundary. + InlineComponent ic = (InlineComponent)prev.getPipelineComponent(); + PipeRun r1 = ic.getPipeRun(); + PipeRun r2 = ic.getAlternativePipeRun(); + if (r1 == null || r2 == null) + throw new RuntimeException("Components on PipeRun changes should refer to bot PipeRuns"); + ic.deattach(); + r2.addChild(ic); + ic.setPipeRun(r2); + ic.setAlternativePipeRun(r1); + } else { + throw new RuntimeException("PipeRun changes should contain shared control points"); + } + + } + } + } private static void _reverse(List list) { - if (list.size() <= 1) - return; // nothing to do. - - for (int i = 0 ; i < list.size(); i++) { - boolean first = i == 0; - boolean last = i == list.size() - 1; - PipeControlPoint current = list.get(i); - PipeControlPoint currentSub = null; - if (current.isDualInline()) - currentSub = current.getSubPoint().get(0); - if (first) { - PipeControlPoint next = list.get(i+1); - if (next.isDualInline()) - next = next.getSubPoint().get(0); - if (current.getNext() == next) - current.setNext(null); - current.setPrevious(next); - if (currentSub != null) { - if (currentSub.getNext() == next) - currentSub.setNext(null); - currentSub.setPrevious(next); - } - } else if (last) { - PipeControlPoint prev = list.get(i-1); - - if (current.getPrevious() == prev) - current.setPrevious(null); - current.setNext(prev); - - if (currentSub != null) { - if (currentSub.getPrevious() == prev) - currentSub.setPrevious(null); - currentSub.setNext(prev); - } - } else { - PipeControlPoint prev = list.get(i-1); - PipeControlPoint next = list.get(i+1); - if (next.isDualInline()) - next = next.getSubPoint().get(0); - - - current.setPrevious(next); - current.setNext(prev); - - if (currentSub != null) { - currentSub.setPrevious(next); - currentSub.setNext(prev); - } - - } - if (current.isTurn() && current.isFixed()) { - current.setReversed(!current._getReversed()); - } - if (current.isInline() && current.isReverse()) { - current.setReversed(!current._getReversed()); - } - } + if (list.size() <= 1) + return; // nothing to do. + + for (int i = 0 ; i < list.size(); i++) { + boolean first = i == 0; + boolean last = i == list.size() - 1; + PipeControlPoint current = list.get(i); + PipeControlPoint currentSub = null; + if (current.isDualInline()) + currentSub = current.getSubPoint().get(0); + if (first) { + PipeControlPoint next = list.get(i+1); + if (next.isDualInline()) + next = next.getSubPoint().get(0); + if (current.getNext() == next) + current.setNext(null); + current.setPrevious(next); + if (currentSub != null) { + if (currentSub.getNext() == next) + currentSub.setNext(null); + currentSub.setPrevious(next); + } + } else if (last) { + PipeControlPoint prev = list.get(i-1); + + if (current.getPrevious() == prev) + current.setPrevious(null); + current.setNext(prev); + + if (currentSub != null) { + if (currentSub.getPrevious() == prev) + currentSub.setPrevious(null); + currentSub.setNext(prev); + } + } else { + PipeControlPoint prev = list.get(i-1); + PipeControlPoint next = list.get(i+1); + if (next.isDualInline()) + next = next.getSubPoint().get(0); + + + current.setPrevious(next); + current.setNext(prev); + + if (currentSub != null) { + currentSub.setPrevious(next); + currentSub.setNext(prev); + } + + } + if (current.isTurn() && current.isFixed()) { + current.setReversed(!current._getReversed()); + } + if (current.isInline() && current.isReverse()) { + current.setReversed(!current._getReversed()); + } + } } public static void merge(PipeRun run1, PipeRun r2) { @@ -1842,19 +1842,19 @@ public class PipingRules { /* there are many different cases to insert new component when it splits existing VariableLengthinlineComponent. - - 1. VariableLengthComponet is connected from both sides: - - insert new component between VariableLength component and component connected to it - - insert new VariableLengthComponent between inserted component and component selected in previous step + + 1. VariableLengthComponet is connected from both sides: + - insert new component between VariableLength component and component connected to it + - insert new VariableLengthComponent between inserted component and component selected in previous step 2. VariableLengthComponent is connected from one side - - Use previous case or: - - Insert new component to empty end - - Insert new VariableLength component to inserted components empty end - + - Use previous case or: + - Insert new component to empty end + - Insert new VariableLength component to inserted components empty end + 3. VariableLength is not connected to any component. - - Should not be possible, at least in current implementation. - - Could be done using second case + - Should not be possible, at least in current implementation. + - Could be done using second case */ diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/scl/P3DScriptNodeMap.java b/org.simantics.plant3d/src/org/simantics/plant3d/scl/P3DScriptNodeMap.java index b9826ff0..e5726d60 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/scl/P3DScriptNodeMap.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/scl/P3DScriptNodeMap.java @@ -25,155 +25,155 @@ import org.simantics.plant3d.scenegraph.controlpoint.PipingRules; import vtk.vtkProp3D; public class P3DScriptNodeMap extends ScriptNodeMap{ - - private static final boolean DEBUG = false; - - public P3DScriptNodeMap(Session session, IMapping mapping, P3DRootNode rootNode) { - super(session,mapping,rootNode); - //rootNode.setNodeMap(this); - } - - @Override - protected void updateActor(INode n, Set ids) { - if (DEBUG) System.out.println("P3DNodeMap update " + n); - if (!(n instanceof IP3DVisualNode)) { - if (n instanceof PipeControlPoint) { - n = ((PipeControlPoint)n).getPipelineComponent(); - if (n == null) - return; - } else { - return; - } - } - - IP3DVisualNode node = (IP3DVisualNode)n; - - if (DEBUG) { - System.out.print("P3DNodeMap update " + node); - for (String s : ids) - System.out.print(" " + s); - System.out.println(); - } - - if (ids.contains(Plant3D.URIs.hasGeometry)) { - //node.visualize(view); - //updateRenderObjectsFor(node); - updateTransform(node); - } - if (n instanceof ParameterizedNode) { - ParameterizedNode geom = (ParameterizedNode)n; - for (String id : geom.getParameterMap().keySet()) { - if (ids.contains(id)) { + + private static final boolean DEBUG = false; + + public P3DScriptNodeMap(Session session, IMapping mapping, P3DRootNode rootNode) { + super(session,mapping,rootNode); + //rootNode.setNodeMap(this); + } + + @Override + protected void updateActor(INode n, Set ids) { + if (DEBUG) System.out.println("P3DNodeMap update " + n); + if (!(n instanceof IP3DVisualNode)) { + if (n instanceof PipeControlPoint) { + n = ((PipeControlPoint)n).getPipelineComponent(); + if (n == null) + return; + } else { + return; + } + } + + IP3DVisualNode node = (IP3DVisualNode)n; + + if (DEBUG) { + System.out.print("P3DNodeMap update " + node); + for (String s : ids) + System.out.print(" " + s); + System.out.println(); + } + + if (ids.contains(Plant3D.URIs.hasGeometry)) { + //node.visualize(view); + //updateRenderObjectsFor(node); + updateTransform(node); + } + if (n instanceof ParameterizedNode) { + ParameterizedNode geom = (ParameterizedNode)n; + for (String id : geom.getParameterMap().keySet()) { + if (ids.contains(id)) { // node.visualize(view); // updateRenderObjectsFor(node); - updateTransform(node); - break; - } - } - } else if (n instanceof PipeRun) { - // FIXME: may require rule based update! - PipeRun run = (PipeRun)n; - Set ids2 = new HashSet(); - ids2.add(Plant3D.URIs.hasGeometry); - for (PipeControlPoint pcp : run.getControlPoints()) { - updateActor(pcp, ids2); - } - } - - if (ids.contains(G3D.URIs.hasPosition) || - ids.contains(G3D.URIs.hasOrientation) || - ids.contains(G3D.URIs.hasWorldPosition) || - ids.contains(G3D.URIs.hasWorldOrientation)) { - updateTransform(node); - } - } - - private void updateTransform(IP3DNode node) { - if (DEBUG) System.out.println("P3DNodeMap update Transform " + node); + updateTransform(node); + break; + } + } + } else if (n instanceof PipeRun) { + // FIXME: may require rule based update! + PipeRun run = (PipeRun)n; + Set ids2 = new HashSet(); + ids2.add(Plant3D.URIs.hasGeometry); + for (PipeControlPoint pcp : run.getControlPoints()) { + updateActor(pcp, ids2); + } + } + + if (ids.contains(G3D.URIs.hasPosition) || + ids.contains(G3D.URIs.hasOrientation) || + ids.contains(G3D.URIs.hasWorldPosition) || + ids.contains(G3D.URIs.hasWorldOrientation)) { + updateTransform(node); + } + } + + private void updateTransform(IP3DNode node) { + if (DEBUG) System.out.println("P3DNodeMap update Transform " + node); - - if (node instanceof ParentNode) { - ParentNode p = (ParentNode)node; - for (IP3DNode n : p.getNodes()) - updateTransform(n); - } - } - - @Override - protected void removeActor(INode n) { - if (DEBUG) System.out.println("P3DNodeMap.removeActor " + n); - if (!(n instanceof IP3DVisualNode)) - return; - IP3DVisualNode node = (IP3DVisualNode)n; + + if (node instanceof ParentNode) { + ParentNode p = (ParentNode)node; + for (IP3DNode n : p.getNodes()) + updateTransform(n); + } + } + + @Override + protected void removeActor(INode n) { + if (DEBUG) System.out.println("P3DNodeMap.removeActor " + n); + if (!(n instanceof IP3DVisualNode)) + return; + IP3DVisualNode node = (IP3DVisualNode)n; // remActor(node); - - if (node instanceof P3DParentNode) { - for (IP3DNode n2 : ((P3DParentNode)node).getNodes()) - if (n2 instanceof IP3DVisualNode) - removeActor((IP3DVisualNode)n2); - } - } - - @Override - protected void addActor(INode n) { - if (DEBUG) System.out.println("P3DNodeMap.addActor " + n); - if (!(n instanceof IP3DVisualNode)) - return; - IP3DVisualNode node = (IP3DVisualNode)n; - + + if (node instanceof P3DParentNode) { + for (IP3DNode n2 : ((P3DParentNode)node).getNodes()) + if (n2 instanceof IP3DVisualNode) + removeActor((IP3DVisualNode)n2); + } + } + + @Override + protected void addActor(INode n) { + if (DEBUG) System.out.println("P3DNodeMap.addActor " + n); + if (!(n instanceof IP3DVisualNode)) + return; + IP3DVisualNode node = (IP3DVisualNode)n; + // if (hasActor(node)) // return; - - if (node instanceof P3DParentNode) { - for (IP3DNode n2 : ((P3DParentNode)node).getNodes()) - if (n2 instanceof IP3DVisualNode) - addActor((IP3DVisualNode)n2); - } - - updateTransform(node); - } - - @Override - protected void update(ReadGraph graph) throws DatabaseException { - validate(); + + if (node instanceof P3DParentNode) { + for (IP3DNode n2 : ((P3DParentNode)node).getNodes()) + if (n2 instanceof IP3DVisualNode) + addActor((IP3DVisualNode)n2); + } + + updateTransform(node); + } + + @Override + protected void update(ReadGraph graph) throws DatabaseException { + validate(); // System.out.println("Graph updates"); - super.update(graph); - validate(); - } - - @Override - public void commit(String commitMessage) { - validate(); + super.update(graph); + validate(); + } + + @Override + public void commit(String commitMessage) { + validate(); // System.out.println("Graph commit"); - super.commit(commitMessage); - - } - @Override - protected void doCommit() throws DatabaseException{ + super.commit(commitMessage); + + } + @Override + protected void doCommit() throws DatabaseException{ // System.out.println("Do commit"); - validate(); - super.doCommit(); - } - - private void validate() { - for (INode node : rootNode.getNodes()) { - if (node instanceof PipeRun) - PipingRules.validate((PipeRun)node); - } - } - - @Override - public void update() throws DatabaseException { - try { - boolean b = true; - while (b) { - updateCycle(); - b = PipingRules.update(); - } - } catch (Exception e) { - e.printStackTrace(); - } - super.update(); - } + validate(); + super.doCommit(); + } + + private void validate() { + for (INode node : rootNode.getNodes()) { + if (node instanceof PipeRun) + PipingRules.validate((PipeRun)node); + } + } + + @Override + public void update() throws DatabaseException { + try { + boolean b = true; + while (b) { + updateCycle(); + b = PipingRules.update(); + } + } catch (Exception e) { + e.printStackTrace(); + } + super.update(); + } } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/scl/SCLUtil.java b/org.simantics.plant3d/src/org/simantics/plant3d/scl/SCLUtil.java index 9007432b..ae6bac4b 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/scl/SCLUtil.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/scl/SCLUtil.java @@ -17,57 +17,57 @@ import org.simantics.plant3d.utils.ComponentUtils; import org.simantics.plant3d.utils.P3DUtil; public class SCLUtil { - - public static P3DScriptNodeMap load(final Resource root) throws DatabaseException { - try { - ControlPointFactory.preloadCache(); - ComponentUtils.preloadCache(); - } catch (Exception e) { - throw new DatabaseException(e); - } - return Simantics.getSession().syncRequest(new Read() { - @Override - public P3DScriptNodeMap perform(ReadGraph graph) throws DatabaseException { - PipingRules.setEnabled(false); - IMappingSchema schema = SchemaBuilder.getSchema(graph); - IMapping mapping = Mappings.createWithListening(schema); - P3DRootNode rootNode = (P3DRootNode)mapping.map(graph, root); - try { - P3DUtil.finalizeDBLoad(rootNode); - } catch (Exception e) { - throw new DatabaseException(e); - } - P3DScriptNodeMap nodeMap = new P3DScriptNodeMap(Simantics.getSession(), mapping, rootNode); - return nodeMap; - - } - }); - - } - - public static P3DRootNode loadReadOnly(final Resource root) throws DatabaseException { - try { - ControlPointFactory.preloadCache(); - ComponentUtils.preloadCache(); - } catch (Exception e) { - throw new DatabaseException(e); - } - return Simantics.getSession().syncRequest(new Read() { - @Override - public P3DRootNode perform(ReadGraph graph) throws DatabaseException { - PipingRules.setEnabled(false); - IMappingSchema schema = SchemaBuilder.getSchema(graph); - IMapping mapping = Mappings.createWithoutListening(schema); - P3DRootNode rootNode = (P3DRootNode)mapping.map(graph, root); - try { - P3DUtil.finalizeDBLoad(rootNode); - } catch (Exception e) { - throw new DatabaseException(e); - } - return rootNode; - - } - }); - } + + public static P3DScriptNodeMap load(final Resource root) throws DatabaseException { + try { + ControlPointFactory.preloadCache(); + ComponentUtils.preloadCache(); + } catch (Exception e) { + throw new DatabaseException(e); + } + return Simantics.getSession().syncRequest(new Read() { + @Override + public P3DScriptNodeMap perform(ReadGraph graph) throws DatabaseException { + PipingRules.setEnabled(false); + IMappingSchema schema = SchemaBuilder.getSchema(graph); + IMapping mapping = Mappings.createWithListening(schema); + P3DRootNode rootNode = (P3DRootNode)mapping.map(graph, root); + try { + P3DUtil.finalizeDBLoad(rootNode); + } catch (Exception e) { + throw new DatabaseException(e); + } + P3DScriptNodeMap nodeMap = new P3DScriptNodeMap(Simantics.getSession(), mapping, rootNode); + return nodeMap; + + } + }); + + } + + public static P3DRootNode loadReadOnly(final Resource root) throws DatabaseException { + try { + ControlPointFactory.preloadCache(); + ComponentUtils.preloadCache(); + } catch (Exception e) { + throw new DatabaseException(e); + } + return Simantics.getSession().syncRequest(new Read() { + @Override + public P3DRootNode perform(ReadGraph graph) throws DatabaseException { + PipingRules.setEnabled(false); + IMappingSchema schema = SchemaBuilder.getSchema(graph); + IMapping mapping = Mappings.createWithoutListening(schema); + P3DRootNode rootNode = (P3DRootNode)mapping.map(graph, root); + try { + P3DUtil.finalizeDBLoad(rootNode); + } catch (Exception e) { + throw new DatabaseException(e); + } + return rootNode; + + } + }); + } } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/utils/ComponentUtils.java b/org.simantics.plant3d/src/org/simantics/plant3d/utils/ComponentUtils.java index 58b9f1e0..574206da 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/utils/ComponentUtils.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/utils/ComponentUtils.java @@ -98,7 +98,7 @@ public class ComponentUtils { if (provider != null || graph.hasStatement(type,p3d.NonVisibleComponent)) { providers.put(typeURI, provider); if (graph.isInheritedFrom(type, p3d.PipelineComponent)) - clazzes.put(typeURI,getClazz(graph, type)); + clazzes.put(typeURI,getClazz(graph, type)); names.put(typeURI, NameUtils.getSafeName(graph, type)); return; } @@ -160,17 +160,17 @@ public class ComponentUtils { */ public static Equipment createEquipment(P3DRootNode root, String typeURI) throws Exception { - GeometryProvider provider = providers.get(typeURI); - if (provider == null) { - load(typeURI); - provider = providers.get(typeURI); - } - Equipment equipment = root.createEquipment(); - equipment.setType(typeURI); - equipment.setGeometry(provider); - root.addChild(equipment); - return equipment; - } + GeometryProvider provider = providers.get(typeURI); + if (provider == null) { + load(typeURI); + provider = providers.get(typeURI); + } + Equipment equipment = root.createEquipment(); + equipment.setType(typeURI); + equipment.setGeometry(provider); + root.addChild(equipment); + return equipment; + } public static InlineComponent createStraight(P3DRootNode root) throws Exception{ InlineComponent component = root.createInline(); @@ -200,287 +200,287 @@ public class ComponentUtils { } public static Equipment createEquipment(P3DRootNode root, Item equipmentType) throws Exception { - Equipment equipment = createEquipment(root, equipmentType.getUri()); - String n = root.getUniqueName(equipmentType.getName()); - equipment.setName(n); - root.addChild(equipment); - return equipment; + Equipment equipment = createEquipment(root, equipmentType.getUri()); + String n = root.getUniqueName(equipmentType.getName()); + equipment.setName(n); + root.addChild(equipment); + return equipment; } public static Nozzle createDefaultNozzle(P3DRootNode root, Equipment equipment) throws Exception { - return createNozzle(root, equipment, new Item(Plant3D.URIs.Builtin_Nozzle, "Nozzle")); + return createNozzle(root, equipment, new Item(Plant3D.URIs.Builtin_Nozzle, "Nozzle")); } public static Nozzle createNozzle(P3DRootNode root, Equipment equipment, Item nozzleType) throws Exception { - Nozzle nozzle = root.createNozzle(); - nozzle.setType(nozzleType.getUri()); - String n = root.getUniqueName(nozzleType.getName()); - nozzle.setName(n); - PipeRun pipeRun = new PipeRun(); - n = root.getUniqueName("PipeRun"); - pipeRun.setName(n); - nozzle.setPipeRun(pipeRun); - - equipment.addChild(nozzle); - root.addChild(pipeRun); - // root.getNodeMap().commit("Add nozzle " + n); - return nozzle; + Nozzle nozzle = root.createNozzle(); + nozzle.setType(nozzleType.getUri()); + String n = root.getUniqueName(nozzleType.getName()); + nozzle.setName(n); + PipeRun pipeRun = new PipeRun(); + n = root.getUniqueName("PipeRun"); + pipeRun.setName(n); + nozzle.setPipeRun(pipeRun); + + equipment.addChild(nozzle); + root.addChild(pipeRun); + // root.getNodeMap().commit("Add nozzle " + n); + return nozzle; } public static class InsertInstruction { - public String typeUri; - - public PositionType position = PositionType.NEXT; - public PositionType insertPosition = PositionType.NEXT; - - // Reducer requires pipe specs - public Double diameter; - public Double turnRadius; - - // Variable length - public Double length; - - // Variable angle - public Double angle; + public String typeUri; + + public PositionType position = PositionType.NEXT; + public PositionType insertPosition = PositionType.NEXT; + + // Reducer requires pipe specs + public Double diameter; + public Double turnRadius; + + // Variable length + public Double length; + + // Variable angle + public Double angle; - public String getTypeUri() { - return typeUri; - } + public String getTypeUri() { + return typeUri; + } - public void setTypeUri(String typeUri) { - this.typeUri = typeUri; - } + public void setTypeUri(String typeUri) { + this.typeUri = typeUri; + } - public PositionType getPosition() { - return position; - } + public PositionType getPosition() { + return position; + } - public void setPosition(PositionType position) { - this.position = position; - } + public void setPosition(PositionType position) { + this.position = position; + } - public PositionType getInsertPosition() { - return insertPosition; - } + public PositionType getInsertPosition() { + return insertPosition; + } - public void setInsertPosition(PositionType insertPosition) { - this.insertPosition = insertPosition; - } + public void setInsertPosition(PositionType insertPosition) { + this.insertPosition = insertPosition; + } - public Double getDiameter() { - return diameter; - } + public Double getDiameter() { + return diameter; + } - public void setDiameter(Double diameter) { - this.diameter = diameter; - } + public void setDiameter(Double diameter) { + this.diameter = diameter; + } - public Double getTurnRadius() { - return turnRadius; - } + public Double getTurnRadius() { + return turnRadius; + } - public void setTurnRadius(Double turnRadius) { - this.turnRadius = turnRadius; - } + public void setTurnRadius(Double turnRadius) { + this.turnRadius = turnRadius; + } - public Double getLength() { - return length; - } + public Double getLength() { + return length; + } - public void setLength(Double length) { - this.length = length; - } + public void setLength(Double length) { + this.length = length; + } - public Double getAngle() { - return angle; - } + public Double getAngle() { + return angle; + } - public void setAngle(Double angle) { - this.angle = angle; - } + public void setAngle(Double angle) { + this.angle = angle; + } } public static PipelineComponent addComponent(P3DRootNode root, PipelineComponent component, InsertInstruction inst) throws Exception { - - PipelineComponent newComponent = ComponentUtils.createComponent(root, inst.typeUri); - PipeControlPoint newPcp = newComponent.getControlPoint(); - - PipeControlPoint toPcp = component.getControlPoint(); - PipeRun pipeRun = toPcp.getPipeRun(); - - String typeName = names.get(inst.typeUri); - if (typeName == null) - typeName = "Component"; - - Vector3d dir = null; - Vector3d pos = null; - - PositionType position = inst.position; - PositionType insertPosition = inst.insertPosition; - boolean lengthAdjustable = false; - if (newComponent instanceof InlineComponent) { - lengthAdjustable = ((InlineComponent)newComponent).isVariableLength(); - } - boolean insertAdjustable = false; - if (component instanceof InlineComponent) { - insertAdjustable = ((InlineComponent)component).isVariableLength(); - } - boolean sizeChange = false; - if (newComponent instanceof InlineComponent) { - sizeChange = ((InlineComponent)newComponent).isSizeChange(); - } - - if (toPcp.isInline()) { - switch (position) { - case NEXT: - if (toPcp.isDualInline()) { - toPcp = toPcp.getSubPoint().get(0); - pipeRun = toPcp.getPipeRun(); - } - - break; - case PREVIOUS: - if (toPcp.isDualSub()) { - toPcp = toPcp.parent; - pipeRun = toPcp.getPipeRun(); - } - break; - } - Vector3d start = new Vector3d(); - Vector3d end = new Vector3d(); - dir = new Vector3d(); - toPcp.getInlineControlPointEnds(start, end, dir); - dir.normalize(); - switch (position) { - case NEXT: - pos = new Vector3d(end); - break; - case PREVIOUS: - pos = new Vector3d(start); - break; - case SPLIT: - pos = new Vector3d(toPcp.getWorldPosition()); - break; - } - - } else if (toPcp.isDirected()) { - dir = new Vector3d(toPcp.getDirection(Direction.NEXT)); - pos = new Vector3d(toPcp.getWorldPosition()); - } else if (toPcp.isTurn() && toPcp.isFixed()) { - dir = new Vector3d(toPcp.getDirection(position == PositionType.NEXT ? Direction.NEXT : Direction.PREVIOUS)); - pos = new Vector3d(toPcp.getWorldPosition()); - if (!lengthAdjustable) { - Vector3d v = new Vector3d(dir); - v.scale(toPcp.getInlineLength()); - pos.add(v); - } else { - if (insertPosition == PositionType.NEXT) { - Vector3d v = new Vector3d(dir); - v.scale(toPcp.getInlineLength()); - pos.add(v); - } else if (insertPosition == PositionType.SPLIT) { - // scale 0.5*length so that we don't remove the length twice from the new component - Vector3d v = new Vector3d(dir); - v.scale(toPcp.getInlineLength()*0.5); - pos.add(v); - } - } - } - - - if (!sizeChange) { - String name = component.getPipeRun().getUniqueName(typeName); - newComponent.setName(name); + + PipelineComponent newComponent = ComponentUtils.createComponent(root, inst.typeUri); + PipeControlPoint newPcp = newComponent.getControlPoint(); + + PipeControlPoint toPcp = component.getControlPoint(); + PipeRun pipeRun = toPcp.getPipeRun(); + + String typeName = names.get(inst.typeUri); + if (typeName == null) + typeName = "Component"; + + Vector3d dir = null; + Vector3d pos = null; + + PositionType position = inst.position; + PositionType insertPosition = inst.insertPosition; + boolean lengthAdjustable = false; + if (newComponent instanceof InlineComponent) { + lengthAdjustable = ((InlineComponent)newComponent).isVariableLength(); + } + boolean insertAdjustable = false; + if (component instanceof InlineComponent) { + insertAdjustable = ((InlineComponent)component).isVariableLength(); + } + boolean sizeChange = false; + if (newComponent instanceof InlineComponent) { + sizeChange = ((InlineComponent)newComponent).isSizeChange(); + } + + if (toPcp.isInline()) { + switch (position) { + case NEXT: + if (toPcp.isDualInline()) { + toPcp = toPcp.getSubPoint().get(0); + pipeRun = toPcp.getPipeRun(); + } + + break; + case PREVIOUS: + if (toPcp.isDualSub()) { + toPcp = toPcp.parent; + pipeRun = toPcp.getPipeRun(); + } + break; + } + Vector3d start = new Vector3d(); + Vector3d end = new Vector3d(); + dir = new Vector3d(); + toPcp.getInlineControlPointEnds(start, end, dir); + dir.normalize(); + switch (position) { + case NEXT: + pos = new Vector3d(end); + break; + case PREVIOUS: + pos = new Vector3d(start); + break; + case SPLIT: + pos = new Vector3d(toPcp.getWorldPosition()); + break; + } + + } else if (toPcp.isDirected()) { + dir = new Vector3d(toPcp.getDirection(Direction.NEXT)); + pos = new Vector3d(toPcp.getWorldPosition()); + } else if (toPcp.isTurn() && toPcp.isFixed()) { + dir = new Vector3d(toPcp.getDirection(position == PositionType.NEXT ? Direction.NEXT : Direction.PREVIOUS)); + pos = new Vector3d(toPcp.getWorldPosition()); + if (!lengthAdjustable) { + Vector3d v = new Vector3d(dir); + v.scale(toPcp.getInlineLength()); + pos.add(v); + } else { + if (insertPosition == PositionType.NEXT) { + Vector3d v = new Vector3d(dir); + v.scale(toPcp.getInlineLength()); + pos.add(v); + } else if (insertPosition == PositionType.SPLIT) { + // scale 0.5*length so that we don't remove the length twice from the new component + Vector3d v = new Vector3d(dir); + v.scale(toPcp.getInlineLength()*0.5); + pos.add(v); + } + } + } + + + if (!sizeChange) { + String name = component.getPipeRun().getUniqueName(typeName); + newComponent.setName(name); - pipeRun.addChild(newComponent); - // TODO: these options are not stored into DB. Should they?! - if (newComponent instanceof InlineComponent && ((InlineComponent)newComponent).isVariableLength()) { - newPcp.setLength(inst.length); - } else if (newComponent instanceof TurnComponent && ((TurnComponent)newComponent).isVariableAngle()) { - newPcp.setTurnAngle(inst.angle); - } - - newComponent.updateParameters(); - - Vector3d v = new Vector3d(dir); - if (insertAdjustable) { - if (insertPosition == PositionType.NEXT) - v.scale(newComponent.getControlPoint().getInlineLength()); - else if (insertPosition == PositionType.SPLIT) - v.set(0, 0, 0); - else if (insertPosition == PositionType.PREVIOUS) - v.scale(-newComponent.getControlPoint().getInlineLength()); - } else { - v.scale(newComponent.getControlPoint().getInlineLength()); - } - switch (position) { - case NEXT: - pos.add(v); - break; - case PREVIOUS: - pos.sub(v); - break; - case SPLIT: - break; - } - - switch (position) { - case NEXT: - if (toPcp.isDualInline()) - toPcp = toPcp.getSubPoint().get(0); - newPcp.insert(toPcp, Direction.NEXT); - newPcp.setWorldPosition(pos); - break; - case PREVIOUS: - if (toPcp.isDualSub()) - toPcp = toPcp.parent; - newPcp.insert(toPcp, Direction.PREVIOUS); - newPcp.setWorldPosition(pos); - break; - case SPLIT: - PipingRules.splitVariableLengthComponent(newComponent, (InlineComponent)component, true); - } - } else { - PipeRun other = new PipeRun(); - String n = root.getUniqueName("PipeRun"); - other.setName(n); - other.setPipeDiameter(inst.diameter); - other.setTurnRadius(inst.turnRadius); - root.addChild(other); - - - if (position == PositionType.NEXT) { - PipingRules.addSizeChange(false, pipeRun, other, (InlineComponent)newComponent, toPcp, null); - } else if (position == PositionType.PREVIOUS){ - PipingRules.addSizeChange(true, pipeRun, other, (InlineComponent)newComponent, toPcp, null); - } - newPcp.setWorldPosition(pos); - // TODO : chicken-egg problem - newComponent.updateParameters(); - Vector3d v = new Vector3d(dir); - v.scale(newComponent.getControlPoint().getLength()*0.5); - switch (position) { - case NEXT: - pos.add(v); - break; - case PREVIOUS: - pos.sub(v); - break; - case SPLIT: - break; - } - newPcp.setWorldPosition(pos); - - } - - - return newComponent; + pipeRun.addChild(newComponent); + // TODO: these options are not stored into DB. Should they?! + if (newComponent instanceof InlineComponent && ((InlineComponent)newComponent).isVariableLength()) { + newPcp.setLength(inst.length); + } else if (newComponent instanceof TurnComponent && ((TurnComponent)newComponent).isVariableAngle()) { + newPcp.setTurnAngle(inst.angle); + } + + newComponent.updateParameters(); + + Vector3d v = new Vector3d(dir); + if (insertAdjustable) { + if (insertPosition == PositionType.NEXT) + v.scale(newComponent.getControlPoint().getInlineLength()); + else if (insertPosition == PositionType.SPLIT) + v.set(0, 0, 0); + else if (insertPosition == PositionType.PREVIOUS) + v.scale(-newComponent.getControlPoint().getInlineLength()); + } else { + v.scale(newComponent.getControlPoint().getInlineLength()); + } + switch (position) { + case NEXT: + pos.add(v); + break; + case PREVIOUS: + pos.sub(v); + break; + case SPLIT: + break; + } + + switch (position) { + case NEXT: + if (toPcp.isDualInline()) + toPcp = toPcp.getSubPoint().get(0); + newPcp.insert(toPcp, Direction.NEXT); + newPcp.setWorldPosition(pos); + break; + case PREVIOUS: + if (toPcp.isDualSub()) + toPcp = toPcp.parent; + newPcp.insert(toPcp, Direction.PREVIOUS); + newPcp.setWorldPosition(pos); + break; + case SPLIT: + PipingRules.splitVariableLengthComponent(newComponent, (InlineComponent)component, true); + } + } else { + PipeRun other = new PipeRun(); + String n = root.getUniqueName("PipeRun"); + other.setName(n); + other.setPipeDiameter(inst.diameter); + other.setTurnRadius(inst.turnRadius); + root.addChild(other); + + + if (position == PositionType.NEXT) { + PipingRules.addSizeChange(false, pipeRun, other, (InlineComponent)newComponent, toPcp, null); + } else if (position == PositionType.PREVIOUS){ + PipingRules.addSizeChange(true, pipeRun, other, (InlineComponent)newComponent, toPcp, null); + } + newPcp.setWorldPosition(pos); + // TODO : chicken-egg problem + newComponent.updateParameters(); + Vector3d v = new Vector3d(dir); + v.scale(newComponent.getControlPoint().getLength()*0.5); + switch (position) { + case NEXT: + pos.add(v); + break; + case PREVIOUS: + pos.sub(v); + break; + case SPLIT: + break; + } + newPcp.setWorldPosition(pos); + + } + + + return newComponent; } public static boolean connect(PipelineComponent current, PipelineComponent endTo) throws Exception { - return connect(current, endTo, null, null); + return connect(current, endTo, null, null); } /** @@ -493,141 +493,141 @@ public class ComponentUtils { * @throws Exception */ public static boolean connect(PipelineComponent current, PipelineComponent endTo, PositionType endType, Vector3d position) throws Exception{ - PipeControlPoint endCP = endTo.getControlPoint(); - boolean reversed; - if (current.getNext() == null) - reversed = false; - else if (current.getPrevious() == null) - reversed = true; - else - return false; - - PipeRun pipeRun = current.getPipeRun(); - P3DRootNode root = (P3DRootNode)current.getRootNode(); - PipeControlPoint currentCP = current.getControlPoint(); - - if (endType == null || endType == PositionType.NEXT || endType == PositionType.PREVIOUS) { - - - - boolean requiresReverse = false; - if (!reversed && endCP.getPrevious() != null) { - if (endCP.getNext() != null) - return false; - requiresReverse = true; - } else if (reversed && endCP.getNext() != null) { - if (endCP.getPrevious() != null) - return false; - requiresReverse = true; - } - PipeRun other = endCP.getPipeRun(); - boolean mergeRuns = other == null ? true : pipeRun.equalSpecs(other); - - if (requiresReverse) { - // Pipe line must be traversible with next/previous relations without direction change. - // Now the component, where we are connecting the created pipeline is defined in different order. - PipingRules.reverse(other); - - } - if (mergeRuns) { - // Runs have compatible specs and must be merged - if (other != null && pipeRun != other) - PipingRules.merge(pipeRun, other); - else if (other == null) { - if (!(endTo instanceof Nozzle)) { - pipeRun.addChild(endTo); - } else { - endTo.setPipeRun(pipeRun); - } - } - if (!reversed) { - currentCP.setNext(endCP); - endCP.setPrevious(currentCP); - } else { - currentCP.setPrevious(endCP); - endCP.setNext(currentCP); - } - } else { - // Runs do not have compatible specs, and a reducer must be attached in between. - InlineComponent reducer = ComponentUtils.createReducer(root); - PipeControlPoint pcp = reducer.getControlPoint(); - PipeControlPoint ocp = pcp.getSubPoint().get(0); - - Vector3d endPos = endCP.getWorldPosition(); - Vector3d currentPos = currentCP.getWorldPosition(); - Vector3d v = new Vector3d(endPos); - v.sub(currentPos); - v.scale(0.5); - v.add(currentPos); - - PipingRules.addSizeChange(reversed, pipeRun, other, reducer, currentCP, endCP); - - pcp.setWorldPosition(v); - reducer.updateParameters(); - } - PipingRules.positionUpdate(endCP); - return true; - - } else if (endType == PositionType.SPLIT) { - InlineComponent branchSplit = createBranchSplit((InlineComponent)endTo, position); - if (branchSplit == null) - return false; - PipeControlPoint branchSplitCP = branchSplit.getControlPoint(); - PipeControlPoint pcp = new PipeControlPoint(branchSplit,pipeRun); - branchSplitCP.children.add(pcp); - pcp.parent = branchSplitCP; - pcp.setWorldOrientation(branchSplitCP.getWorldOrientation()); - pcp.setWorldPosition(branchSplitCP.getWorldPosition()); - - - if(!reversed) { - pcp.setPrevious(currentCP); - currentCP.setNext(pcp); - } else { - pcp.setNext(currentCP); - currentCP.setPrevious(pcp); - } - PipingRules.positionUpdate(endCP); - return true; - } - return false; + PipeControlPoint endCP = endTo.getControlPoint(); + boolean reversed; + if (current.getNext() == null) + reversed = false; + else if (current.getPrevious() == null) + reversed = true; + else + return false; + + PipeRun pipeRun = current.getPipeRun(); + P3DRootNode root = (P3DRootNode)current.getRootNode(); + PipeControlPoint currentCP = current.getControlPoint(); + + if (endType == null || endType == PositionType.NEXT || endType == PositionType.PREVIOUS) { + + + + boolean requiresReverse = false; + if (!reversed && endCP.getPrevious() != null) { + if (endCP.getNext() != null) + return false; + requiresReverse = true; + } else if (reversed && endCP.getNext() != null) { + if (endCP.getPrevious() != null) + return false; + requiresReverse = true; + } + PipeRun other = endCP.getPipeRun(); + boolean mergeRuns = other == null ? true : pipeRun.equalSpecs(other); + + if (requiresReverse) { + // Pipe line must be traversible with next/previous relations without direction change. + // Now the component, where we are connecting the created pipeline is defined in different order. + PipingRules.reverse(other); + + } + if (mergeRuns) { + // Runs have compatible specs and must be merged + if (other != null && pipeRun != other) + PipingRules.merge(pipeRun, other); + else if (other == null) { + if (!(endTo instanceof Nozzle)) { + pipeRun.addChild(endTo); + } else { + endTo.setPipeRun(pipeRun); + } + } + if (!reversed) { + currentCP.setNext(endCP); + endCP.setPrevious(currentCP); + } else { + currentCP.setPrevious(endCP); + endCP.setNext(currentCP); + } + } else { + // Runs do not have compatible specs, and a reducer must be attached in between. + InlineComponent reducer = ComponentUtils.createReducer(root); + PipeControlPoint pcp = reducer.getControlPoint(); + PipeControlPoint ocp = pcp.getSubPoint().get(0); + + Vector3d endPos = endCP.getWorldPosition(); + Vector3d currentPos = currentCP.getWorldPosition(); + Vector3d v = new Vector3d(endPos); + v.sub(currentPos); + v.scale(0.5); + v.add(currentPos); + + PipingRules.addSizeChange(reversed, pipeRun, other, reducer, currentCP, endCP); + + pcp.setWorldPosition(v); + reducer.updateParameters(); + } + PipingRules.positionUpdate(endCP); + return true; + + } else if (endType == PositionType.SPLIT) { + InlineComponent branchSplit = createBranchSplit((InlineComponent)endTo, position); + if (branchSplit == null) + return false; + PipeControlPoint branchSplitCP = branchSplit.getControlPoint(); + PipeControlPoint pcp = new PipeControlPoint(branchSplit,pipeRun); + branchSplitCP.children.add(pcp); + pcp.parent = branchSplitCP; + pcp.setWorldOrientation(branchSplitCP.getWorldOrientation()); + pcp.setWorldPosition(branchSplitCP.getWorldPosition()); + + + if(!reversed) { + pcp.setPrevious(currentCP); + currentCP.setNext(pcp); + } else { + pcp.setNext(currentCP); + currentCP.setPrevious(pcp); + } + PipingRules.positionUpdate(endCP); + return true; + } + return false; } public static InlineComponent createBranchSplit(InlineComponent component, Vector3d pos) throws Exception{ - if (!component.isVariableLength()) - return null; - PipeRun pipeRun = component.getPipeRun(); - Vector3d sStart = new Vector3d(); - Vector3d sEnd = new Vector3d(); - component.getControlPoint().getInlineControlPointEnds(sStart, sEnd); - - if (MathTools.distance(sStart, sEnd) < (pipeRun.getPipeDiameter()*0.5)) - return null; - - - Vector3d p = MathTools.closestPointOnEdge(new Vector3d(pos), sStart, sEnd); - if (p == sStart) { - Vector3d v = new Vector3d(sEnd); - v.sub(sStart); - v.normalize(); - v.scale(component.getPipeRun().getPipeDiameter()*0.5); - p.add(v); - } else if (p == sEnd) { - Vector3d v = new Vector3d(sStart); - v.sub(sEnd); - v.normalize(); - v.scale(component.getPipeRun().getPipeDiameter()*0.5); - p.add(v); - } - - P3DRootNode root = (P3DRootNode)component.getRootNode(); - InlineComponent branchSplit = ComponentUtils.createBranchSplit(root); - String branchName = component.getPipeRun().getUniqueName("Branch"); - branchSplit.setName(branchName); - component.getPipeRun().addChild(branchSplit); - PipeControlPoint branchSplitCP = branchSplit.getControlPoint(); - branchSplitCP.setWorldPosition(p); - PipingRules.splitVariableLengthComponent(branchSplit, component, false); - return branchSplit; - } + if (!component.isVariableLength()) + return null; + PipeRun pipeRun = component.getPipeRun(); + Vector3d sStart = new Vector3d(); + Vector3d sEnd = new Vector3d(); + component.getControlPoint().getInlineControlPointEnds(sStart, sEnd); + + if (MathTools.distance(sStart, sEnd) < (pipeRun.getPipeDiameter()*0.5)) + return null; + + + Vector3d p = MathTools.closestPointOnEdge(new Vector3d(pos), sStart, sEnd); + if (p == sStart) { + Vector3d v = new Vector3d(sEnd); + v.sub(sStart); + v.normalize(); + v.scale(component.getPipeRun().getPipeDiameter()*0.5); + p.add(v); + } else if (p == sEnd) { + Vector3d v = new Vector3d(sStart); + v.sub(sEnd); + v.normalize(); + v.scale(component.getPipeRun().getPipeDiameter()*0.5); + p.add(v); + } + + P3DRootNode root = (P3DRootNode)component.getRootNode(); + InlineComponent branchSplit = ComponentUtils.createBranchSplit(root); + String branchName = component.getPipeRun().getUniqueName("Branch"); + branchSplit.setName(branchName); + component.getPipeRun().addChild(branchSplit); + PipeControlPoint branchSplitCP = branchSplit.getControlPoint(); + branchSplitCP.setWorldPosition(p); + PipingRules.splitVariableLengthComponent(branchSplit, component, false); + return branchSplit; + } } diff --git a/org.simantics.plant3d/src/org/simantics/plant3d/utils/P3DUtil.java b/org.simantics.plant3d/src/org/simantics/plant3d/utils/P3DUtil.java index 0d656b05..e5d1768a 100644 --- a/org.simantics.plant3d/src/org/simantics/plant3d/utils/P3DUtil.java +++ b/org.simantics.plant3d/src/org/simantics/plant3d/utils/P3DUtil.java @@ -23,10 +23,10 @@ import org.simantics.plant3d.scenegraph.controlpoint.PipingRules; import org.simantics.plant3d.utils.Item.Type; public class P3DUtil { - - public static List getEquipments() throws DatabaseException { - return getEquipments(Plant3D.URIs.Builtin); - } + + public static List getEquipments() throws DatabaseException { + return getEquipments(Plant3D.URIs.Builtin); + } public static List getEquipments(final String libUri) throws DatabaseException { return Simantics.getSession().syncRequest(new Read>() { @@ -74,17 +74,17 @@ public class P3DUtil { @Override public boolean equals(Object obj) { - if (obj.getClass() != this.getClass()) - return false; - ItemQuery other = (ItemQuery)obj; - if (!type.equals(other.type)) - return false; - return libUri.equals(other.libUri); + if (obj.getClass() != this.getClass()) + return false; + ItemQuery other = (ItemQuery)obj; + if (!type.equals(other.type)) + return false; + return libUri.equals(other.libUri); } @Override public int hashCode() { - return type.hashCode() + libUri.hashCode(); + return type.hashCode() + libUri.hashCode(); } } @@ -122,12 +122,12 @@ public class P3DUtil { } public static List filterUserComponents(List items) { - List result = new ArrayList(items.size()); - for (Item i : items) { - if (!i.isCode()) - result.add(i); - } - return result; + List result = new ArrayList(items.size()); + for (Item i : items) { + if (!i.isCode()) + result.add(i); + } + return result; } private static List getItems(ReadGraph graph, Resource lib, Resource type) throws DatabaseException{ @@ -156,11 +156,11 @@ public class P3DUtil { } } Collections.sort(result, new Comparator() { - @Override - public int compare(Item o1, Item o2) { - return o1.getName().compareTo(o2.getName()); - } - }); + @Override + public int compare(Item o1, Item o2) { + return o1.getName().compareTo(o2.getName()); + } + }); return result; } @@ -186,7 +186,7 @@ public class P3DUtil { if (graph.hasStatement(r, p3d.CodeComponent)) item.setCode(true); if (graph.hasStatement(r, p3d.VariableAngleTurnComponent) || - graph.hasStatement(r, p3d.VariableLengthInlineComponent)) + graph.hasStatement(r, p3d.VariableLengthInlineComponent)) item.setVariable(true); if (graph.hasStatement(r, p3d.SizeChangeComponent)) item.setSizeChange(true); @@ -204,38 +204,38 @@ public class P3DUtil { } public static void finalizeDBLoad(P3DRootNode rootNode) throws Exception{ - for (INode node : rootNode.getChild()) { - if (node instanceof PipeRun) { - for (PipelineComponent pc : ((PipeRun) node).getChild()) - pc.sync(); - } else if (node instanceof Equipment) { - for (PipelineComponent pc : ((Equipment) node).getChild()) - pc.sync(); - } - } - - for (INode node : rootNode.getChild()) { - if (node instanceof PipeRun) { - for (PipelineComponent pc : ((PipeRun) node).getChild()) - pc.sync2(); - } else if (node instanceof Equipment) { - for (PipelineComponent pc : ((Equipment) node).getChild()) - pc.sync2(); - } - } - for (INode node : rootNode.getChild()) { - if (node instanceof PipeRun) { - PipingRules.validate((PipeRun)node); - } - } - PipingRules.setEnabled(true); - for (INode node : rootNode.getChild()) { - if (node instanceof PipeRun) { - PipeRun run = (PipeRun)node; - for (PipeControlPoint pcp : run.getControlPoints()) - PipingRules.positionUpdate(pcp); - } - } + for (INode node : rootNode.getChild()) { + if (node instanceof PipeRun) { + for (PipelineComponent pc : ((PipeRun) node).getChild()) + pc.sync(); + } else if (node instanceof Equipment) { + for (PipelineComponent pc : ((Equipment) node).getChild()) + pc.sync(); + } + } + + for (INode node : rootNode.getChild()) { + if (node instanceof PipeRun) { + for (PipelineComponent pc : ((PipeRun) node).getChild()) + pc.sync2(); + } else if (node instanceof Equipment) { + for (PipelineComponent pc : ((Equipment) node).getChild()) + pc.sync2(); + } + } + for (INode node : rootNode.getChild()) { + if (node instanceof PipeRun) { + PipingRules.validate((PipeRun)node); + } + } + PipingRules.setEnabled(true); + for (INode node : rootNode.getChild()) { + if (node instanceof PipeRun) { + PipeRun run = (PipeRun)node; + for (PipeControlPoint pcp : run.getControlPoints()) + PipingRules.positionUpdate(pcp); + } + } } } -- 2.47.0