]> gerrit.simantics Code Review - simantics/sysdyn.git/commitdiff
Gradient options for playback experiments & polarity location selection
authorlempinen <lempinen@ac1ea38d-2e2b-0410-8846-a27921b304fc>
Wed, 26 Oct 2011 12:13:58 +0000 (12:13 +0000)
committerlempinen <lempinen@ac1ea38d-2e2b-0410-8846-a27921b304fc>
Wed, 26 Oct 2011 12:13:58 +0000 (12:13 +0000)
git-svn-id: https://www.simantics.org/svn/simantics/sysdyn/trunk@22963 ac1ea38d-2e2b-0410-8846-a27921b304fc

12 files changed:
org.simantics.sysdyn.ontology/graph.tg
org.simantics.sysdyn.ontology/graph/Sysdyn.pgraph
org.simantics.sysdyn.ontology/src/org/simantics/sysdyn/SysdynResource.java
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements2/connections/DependencyEdgeClass.java
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements2/connections/DependencyNode.java
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/elements2/profiles/SimulationPlaybackStyle.java
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/menu/PlaybackSliderContribution.java
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/DependencyTab.java
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/PlaybackExperimentTab.java [new file with mode: 0644]
org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/ResourceSelectionProcessor.java
org.simantics.sysdyn/src/org/simantics/sysdyn/manager/SysdynPlaybackExperiment.java
org.simantics.sysdyn/src/org/simantics/sysdyn/representation/expressions/StockExpression.java

index f0c4675e4baf3507637315fcfb9182d388fcab2a..156c62e506d1b9adabdb1cdeeaf0d6b9b1e0395a 100644 (file)
Binary files a/org.simantics.sysdyn.ontology/graph.tg and b/org.simantics.sysdyn.ontology/graph.tg differ
index 397a99be6bb055bc8a4da2ae450261ec96721c88..1e2942e37745e27e3e560822960ed31c8d688dee 100644 (file)
@@ -350,8 +350,17 @@ SYSDYN.GameExperiment <T SYSDYN.Experiment
 
 SYSDYN.SimulateOnChangeExperiment <T SYSDYN.Experiment
 
+SYSDYN.defaultGradient : G2D.ColorGradient
+    G2D.HasColorPlacement _ : G2D.ColorPlacement
+        G2D.HasGradientPosition 0.0 : L0.Double
+        G2D.HasColor [0.0, 0.24313726, 0.52156866, 0.0] : L0.FloatArray
+    G2D.HasColorPlacement _ : G2D.ColorPlacement
+        G2D.HasGradientPosition 1.0 : L0.Double
+        G2D.HasColor [1.0, 0.9019608, 0.0, 0.0] : L0.FloatArray
+        
 SYSDYN.PlaybackExperiment <T SYSDYN.Experiment
-
+    @L0.assert G2D.HasColorGradient SYSDYN.defaultGradient
+            
 SYSDYN.HasResult <R L0.IsComposedOf
     L0.HasRange SYSDYN.Result
 
@@ -475,6 +484,9 @@ SYSDYN.angle <R L0.HasProperty : L0.FunctionalRelation
     
 SYSDYN.Polarity <R L0.HasProperty : L0.FunctionalRelation
     L0.HasRange L0.String
+    
+SYSDYN.PolarityLocation <R L0.HasProperty : L0.FunctionalRelation
+    L0.HasRange L0.String
 
 SYSDYN.FlowConnection <T DIA.Connection
     MOD.DiagramConnectionTypeToConnectionType
@@ -483,6 +495,7 @@ SYSDYN.FlowConnection <T DIA.Connection
 SYSDYN.DependencyConnection <T DIA.Connection
     @L0.singleProperty SYSDYN.angle
     @L0.optionalProperty SYSDYN.Polarity
+    @L0.optionalProperty SYSDYN.polarityLocation
     @L0.assert SYSDYN.angle 0.1
     MOD.DiagramConnectionTypeToConnectionType
         SYSDYN.Dependency
index 69d3b6371e9eb89bb6faa436fffaeab8a9052009..a586773db3c93b90cada72b669f221dcd31fe6cb 100644 (file)
@@ -147,6 +147,8 @@ public class SysdynResource {
     public final Resource ParameterExpression;\r
     public final Resource PlaybackExperiment;\r
     public final Resource Polarity;\r
+    public final Resource PolarityLocation;\r
+    public final Resource PolarityLocation_Inverse;\r
     public final Resource Polarity_Inverse;\r
     public final Resource Profiles;\r
     public final Resource Profiles_IssueWarnings;\r
@@ -216,6 +218,8 @@ public class SysdynResource {
     public final Resource WithLookupExpression;\r
     public final Resource angle;\r
     public final Resource angle_Inverse;\r
+    public final Resource defaultGradient;\r
+    public final Resource polarityLocation;\r
         \r
     public static class URIs {\r
         public static final String AdditionalSymbols = "http://www.simantics.org/Sysdyn-1.0/AdditionalSymbols";\r
@@ -357,6 +361,8 @@ public class SysdynResource {
         public static final String ParameterExpression = "http://www.simantics.org/Sysdyn-1.0/ParameterExpression";\r
         public static final String PlaybackExperiment = "http://www.simantics.org/Sysdyn-1.0/PlaybackExperiment";\r
         public static final String Polarity = "http://www.simantics.org/Sysdyn-1.0/Polarity";\r
+        public static final String PolarityLocation = "http://www.simantics.org/Sysdyn-1.0/PolarityLocation";\r
+        public static final String PolarityLocation_Inverse = "http://www.simantics.org/Sysdyn-1.0/PolarityLocation/Inverse";\r
         public static final String Polarity_Inverse = "http://www.simantics.org/Sysdyn-1.0/Polarity/Inverse";\r
         public static final String Profiles = "http://www.simantics.org/Sysdyn-1.0/Profiles";\r
         public static final String Profiles_IssueWarnings = "http://www.simantics.org/Sysdyn-1.0/Profiles/IssueWarnings";\r
@@ -426,6 +432,8 @@ public class SysdynResource {
         public static final String WithLookupExpression = "http://www.simantics.org/Sysdyn-1.0/WithLookupExpression";\r
         public static final String angle = "http://www.simantics.org/Sysdyn-1.0/angle";\r
         public static final String angle_Inverse = "http://www.simantics.org/Sysdyn-1.0/angle/Inverse";\r
+        public static final String defaultGradient = "http://www.simantics.org/Sysdyn-1.0/defaultGradient";\r
+        public static final String polarityLocation = "http://www.simantics.org/Sysdyn-1.0/polarityLocation";\r
     }\r
     \r
     public static Resource getResourceOrNull(ReadGraph graph, String uri) {\r
@@ -577,6 +585,8 @@ public class SysdynResource {
         ParameterExpression = getResourceOrNull(graph, URIs.ParameterExpression);\r
         PlaybackExperiment = getResourceOrNull(graph, URIs.PlaybackExperiment);\r
         Polarity = getResourceOrNull(graph, URIs.Polarity);\r
+        PolarityLocation = getResourceOrNull(graph, URIs.PolarityLocation);\r
+        PolarityLocation_Inverse = getResourceOrNull(graph, URIs.PolarityLocation_Inverse);\r
         Polarity_Inverse = getResourceOrNull(graph, URIs.Polarity_Inverse);\r
         Profiles = getResourceOrNull(graph, URIs.Profiles);\r
         Profiles_IssueWarnings = getResourceOrNull(graph, URIs.Profiles_IssueWarnings);\r
@@ -646,6 +656,8 @@ public class SysdynResource {
         WithLookupExpression = getResourceOrNull(graph, URIs.WithLookupExpression);\r
         angle = getResourceOrNull(graph, URIs.angle);\r
         angle_Inverse = getResourceOrNull(graph, URIs.angle_Inverse);\r
+        defaultGradient = getResourceOrNull(graph, URIs.defaultGradient);\r
+        polarityLocation = getResourceOrNull(graph, URIs.polarityLocation);\r
     }\r
     \r
     public static SysdynResource getInstance(ReadGraph graph) {\r
index e527e0a4c769553e73d8a5560b6e13c2e4ade384..45d4e7aee80f9ae8a49626c83e93215d4ca35dc3 100644 (file)
@@ -122,8 +122,16 @@ public class DependencyEdgeClass {
             \r
             HashMap<String, Object> properties = e.getHint(DiagramHints.PROPERTIES);\r
             Pair<?, ?> polarityPair =  (Pair<?, ?>)properties.get("Polarity");\r
+            Pair<?, ?> polarityLocationPair =  (Pair<?, ?>)properties.get("PolarityLocation");\r
+            \r
+            String location;\r
+            if(polarityLocationPair == null)\r
+                location = DependencyNode.INSIDE;\r
+            else\r
+                location = (String) polarityLocationPair.second;\r
+            \r
             if(polarityPair != null)\r
-                node.init((String)  polarityPair.second, font, color, 0, 0, 0.235);\r
+                node.init((String)  polarityPair.second, location, font, color, 0, 0, 0.235);\r
             \r
             update(e);\r
         }\r
index 780d8f1ae51d1e4cfb2abb1ae1c5421d4d889a09..529ca158889e3fcb469ce11c737e4e6515534efe 100644 (file)
@@ -13,6 +13,7 @@ package org.simantics.sysdyn.ui.elements2.connections;
 \r
 import java.awt.BasicStroke;\r
 import java.awt.Color;\r
+import java.awt.Font;\r
 import java.awt.Graphics2D;\r
 import java.awt.Stroke;\r
 import java.awt.event.MouseEvent;\r
@@ -34,6 +35,9 @@ import org.simantics.utils.datastructures.Pair;
 \r
 public class DependencyNode extends TextNode implements ISelectionPainterNode, MouseListener, MouseMotionListener {\r
 \r
+    public static final String INSIDE = "Inside";\r
+    public static final String OUTSIDE = "Outside";\r
+    \r
     private static final long serialVersionUID = 1294351381209071074L;\r
 \r
     private static final BasicStroke STROKE = new BasicStroke(1.0f);\r
@@ -43,6 +47,7 @@ public class DependencyNode extends TextNode implements ISelectionPainterNode, M
     private Rectangle2D beginBounds;\r
     private Rectangle2D endBounds;\r
     private double angle = 0.1;\r
+    private String side;\r
     private transient Pair<Arc2D, Path2D> shapes = new Pair<Arc2D, Path2D>(new Arc2D.Double(), new Path2D.Double());\r
 \r
     transient public boolean hover = false;\r
@@ -55,6 +60,12 @@ public class DependencyNode extends TextNode implements ISelectionPainterNode, M
         NodeUtil.getEventDelegator(this).addMouseListener(this);\r
         NodeUtil.getEventDelegator(this).addMouseMotionListener(this);\r
     }\r
+    \r
+    \r
+    public void init(String text, String side, Font font, Color color, double x, double y, double scale) {\r
+        super.init(text, font, color, x, y, scale);\r
+        this.side = side;\r
+    }\r
 \r
     @Override\r
     public void cleanup() {\r
@@ -177,7 +188,13 @@ public class DependencyNode extends TextNode implements ISelectionPainterNode, M
                     Math.toRadians(shapes.first.getAngleStart());\r
         Point2D point = angle > 0 ? shapes.first.getEndPoint() : shapes.first.getStartPoint();\r
         \r
-        double a = Math.toRadians(angle < 0 ? 255 : -75);\r
+        int angle1 = 225;\r
+        int angle2 = -75;\r
+        if(OUTSIDE.equals(side)) {\r
+            angle1 *= -1;\r
+            angle2 *= -1;\r
+        }\r
+        double a = Math.toRadians(angle < 0 ? angle1 : angle2);\r
         double s = Math.sin(a) * 2;\r
         double c = Math.cos(a) * 3;\r
         \r
index 8a68153acbff8c2c1c01ec2213eb6919fbaa22cf..44816700d7d6333bc0e5d8f633bfb7c68b7bb497 100644 (file)
  *******************************************************************************/\r
 package org.simantics.sysdyn.ui.elements2.profiles;\r
 \r
-import java.awt.Color;\r
+//import java.awt.Color;\r
 import java.awt.geom.AffineTransform;\r
 import java.awt.geom.Rectangle2D;\r
+import java.util.ArrayList;\r
 \r
 import org.simantics.databoard.Bindings;\r
 import org.simantics.db.ReadGraph;\r
 import org.simantics.db.Resource;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
 import org.simantics.db.exception.DatabaseException;\r
 import org.simantics.db.layer0.variable.Variable;\r
 import org.simantics.diagram.elements.TextNode;\r
@@ -40,12 +42,19 @@ import org.simantics.simulation.project.IExperimentManager;
 import org.simantics.sysdyn.adapter.SysdynVariableProperties;\r
 import org.simantics.sysdyn.manager.SysdynPlaybackExperiment;\r
 import org.simantics.ui.SimanticsUI;\r
-import org.simantics.utils.datastructures.Pair;\r
+import org.simantics.utils.datastructures.Triple;\r
+import org.simantics.utils.ui.color.Color;\r
+import org.simantics.utils.ui.color.ColorGradient;\r
+import org.simantics.utils.ui.color.ColorValue;\r
 \r
-public class SimulationPlaybackStyle extends StyleBase<Pair<AffineTransform, Double>> {\r
+public class SimulationPlaybackStyle extends StyleBase<Triple<AffineTransform, Double, ColorGradient>> {\r
+    \r
+    Resource gradientResource;\r
+    ColorGradient cg;\r
+    byte[] gradient;\r
     \r
     @Override\r
-    public Pair<AffineTransform, Double> calculateStyle(ReadGraph graph, Resource runtimeDiagram, Resource entry, Resource element, Variable configuration) throws DatabaseException {\r
+    public Triple<AffineTransform, Double, ColorGradient> calculateStyle(ReadGraph graph, Resource runtimeDiagram, Resource entry, Resource element, Variable configuration) throws DatabaseException {\r
         \r
         IProject project = SimanticsUI.getProject();\r
         IExperimentManager em = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);\r
@@ -56,6 +65,8 @@ public class SimulationPlaybackStyle extends StyleBase<Pair<AffineTransform, Dou
         ModelingResources mr = ModelingResources.getInstance(graph);\r
         DiagramResource dr = DiagramResource.getInstance(graph);\r
 \r
+        ColorGradient cg = null;\r
+        \r
         Resource component = graph.getPossibleObject(element, mr.ElementToComponent);\r
         if (component == null)\r
             return null;\r
@@ -113,7 +124,21 @@ public class SimulationPlaybackStyle extends StyleBase<Pair<AffineTransform, Dou
 \r
             AffineTransform at = (AffineTransform) DiagramGraphUtil.getAffineTransform(graph, element,  G2DResource.getInstance(graph).HasTransform, true).clone();\r
             \r
-            return new Pair<AffineTransform, Double>(at, multiplier);\r
+            G2DResource g2d = G2DResource.getInstance(graph);\r
+            Resource gradient = graph.getPossibleObject(experiment.getResource(), g2d.HasColorGradient);\r
+            if(this.gradientResource == null || !this.gradientResource.equals(gradient)) {\r
+                ArrayList<ColorValue> colorValues = new ArrayList<ColorValue>();\r
+                for(Resource placement : graph.syncRequest(new ObjectsWithType(gradient, g2d.HasColorPlacement, g2d.ColorPlacement))) {\r
+                    Double position = graph.getPossibleRelatedValue(placement, g2d.HasGradientPosition, Bindings.DOUBLE);\r
+                    float[] rgba = graph.getPossibleRelatedValue(placement, g2d.HasColor, Bindings.FLOAT_ARRAY);\r
+                    colorValues.add(new ColorValue(new Color(new java.awt.Color(rgba[0], rgba[1], rgba[2])), position));\r
+                }\r
+                cg = new ColorGradient(colorValues, ColorGradient.HSV);\r
+            } else {\r
+                cg = this.cg;\r
+            }\r
+            \r
+            return new Triple<AffineTransform, Double, ColorGradient>(at, multiplier, cg);\r
             \r
         } catch(Exception ignore) {\r
             ignore.printStackTrace();\r
@@ -122,7 +147,7 @@ public class SimulationPlaybackStyle extends StyleBase<Pair<AffineTransform, Dou
     }\r
 \r
     @Override\r
-    public void styleResultChanged(Observer observer, Resource element, Pair<AffineTransform, Double> result) {\r
+    public void styleResultChanged(Observer observer, Resource element, Triple<AffineTransform, Double, ColorGradient> result) {\r
         if (result != null)\r
             values.put(element, result);\r
         else\r
@@ -131,7 +156,7 @@ public class SimulationPlaybackStyle extends StyleBase<Pair<AffineTransform, Dou
     }\r
 \r
     @Override\r
-    public void applyStyleForNode(EvaluationContext observer, INode _node, Pair<AffineTransform, Double> result) {\r
+    public void applyStyleForNode(EvaluationContext observer, INode _node, Triple<AffineTransform, Double, ColorGradient> result) {\r
         Double multiplier;\r
         if (result != null && (multiplier = result.second) != null && !multiplier.isNaN()) {\r
             \r
@@ -141,7 +166,18 @@ public class SimulationPlaybackStyle extends StyleBase<Pair<AffineTransform, Dou
                 return;\r
 \r
             AffineTransform at = result.first;\r
-            Color c = new Color(multiplier.floatValue(), (float)(0), (float) (1 - multiplier), (float)0.5);\r
+\r
+            if(this.cg == null || !this.cg.equals(result.third)) {\r
+                this.cg = result.third;\r
+                this.gradient = cg.getGradientArray(101);\r
+            }\r
+            int i = (int)(multiplier * 100);\r
+            int r = (int)(gradient[i * 3 + 0]  & 0xff);\r
+            int g = (int)(gradient[i * 3 + 1]  & 0xff);\r
+            int b = (int)(gradient[i * 3 + 2]  & 0xff);\r
+\r
+            java.awt.Color c = new java.awt.Color(r, g, b, 200);\r
+\r
             int zIndex = -1;\r
             INode n = NodeUtil.getNearestChildByClass((SingleElementNode)_node, TextNode.class);\r
             if(n != null) {\r
index a0c15aab2beebc102466cbeacf4f904307b9d54b..cdb54df42b4fba09f1a0123c30eb20a97f8958fc 100644 (file)
@@ -1,3 +1,14 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
 package org.simantics.sysdyn.ui.menu;\r
 \r
 import java.text.DecimalFormat;\r
@@ -119,6 +130,10 @@ public class PlaybackSliderContribution extends ToolBarContributionItem {
 \r
                         @Override\r
                         public void run() {\r
+                            if(!startTime.equals(spe.getStartTime()) || !endTime.equals(spe.getEndTime())) {\r
+                                startTime = spe.getStartTime();\r
+                                endTime = spe.getEndTime();\r
+                            }\r
                             int value = (int) ((spe.getTime() - startTime) / (endTime - startTime) * 99);\r
                             s.setSelection(value);\r
                             label.setText(format.format(spe.getTime()));\r
index 125fe3ac49c1d71635f267cc6e2c9626f2042ed7..a57da158df8aa3e8de0321c5298b2d9b40a458e3 100644 (file)
@@ -15,6 +15,7 @@ import org.eclipse.jface.layout.GridDataFactory;
 import org.eclipse.jface.layout.GridLayoutFactory;\r
 import org.eclipse.swt.SWT;\r
 import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Group;\r
 import org.eclipse.ui.IWorkbenchSite;\r
 import org.simantics.browsing.ui.swt.widgets.Button;\r
 import org.simantics.browsing.ui.swt.widgets.StringPropertyFactory;\r
@@ -31,43 +32,107 @@ import org.simantics.db.WriteGraph;
 import org.simantics.db.exception.DatabaseException;\r
 import org.simantics.db.management.ISessionContext;\r
 import org.simantics.sysdyn.SysdynResource;\r
+import org.simantics.sysdyn.ui.elements2.connections.DependencyNode;\r
 import org.simantics.utils.datastructures.Pair;\r
 import org.simantics.utils.datastructures.Triple;\r
 \r
 public class DependencyTab  extends LabelPropertyTabContributor {\r
 \r
-    Button none, plus, minus, other;\r
-    TrackedText polarityText;\r
+    Button none, plus, minus, other, inside, outside;\r
+    TrackedText polarityText, polarityLocationText;\r
     \r
     @Override\r
     public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
         Composite composite = new Composite(body, SWT.NONE);\r
         GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
-        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(6).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).numColumns(2).applyTo(composite);\r
         \r
-        none = new Button(composite, support, SWT.RADIO);\r
+        Group polarityGroup = new Group(composite, SWT.NONE);\r
+        polarityGroup.setText("Polarity");\r
+        GridDataFactory.fillDefaults().grab(true, false).applyTo(polarityGroup);\r
+        GridLayoutFactory.fillDefaults().numColumns(5).applyTo(polarityGroup);\r
+        \r
+        none = new Button(polarityGroup, support, SWT.RADIO);\r
         none.setText("None");\r
         none.setSelectionFactory(new PolarityRadioSelectionFactory(""));\r
         none.addSelectionListener(new PolaritySelectionListener(context, ""));\r
         \r
-        plus = new Button(composite, support, SWT.RADIO);\r
+        plus = new Button(polarityGroup, support, SWT.RADIO);\r
         plus.setText("+");\r
         plus.setSelectionFactory(new PolarityRadioSelectionFactory("+"));\r
         plus.addSelectionListener(new PolaritySelectionListener(context, "+"));\r
         \r
-        minus = new Button(composite, support, SWT.RADIO);\r
+        minus = new Button(polarityGroup, support, SWT.RADIO);\r
         minus.setText("-");\r
         minus.setSelectionFactory(new PolarityRadioSelectionFactory("-"));\r
         minus.addSelectionListener(new PolaritySelectionListener(context, "-"));\r
         \r
-        other = new Button(composite, support, SWT.RADIO);\r
+        other = new Button(polarityGroup, support, SWT.RADIO);\r
         other.setText("other");\r
         other.setSelectionFactory(new OtherPolaritySelectionFactory(new String[] {null, "+", "-", ""}));\r
         \r
-        polarityText = new TrackedText(composite, support, SWT.BORDER);\r
+        polarityText = new TrackedText(polarityGroup, support, SWT.BORDER);\r
         polarityText.setTextFactory(new StringPropertyFactory(SysdynResource.URIs.Polarity));\r
         polarityText.addModifyListener(new StringPropertyModifier(context, SysdynResource.URIs.Polarity));\r
         GridDataFactory.fillDefaults().grab(true, false).applyTo(polarityText.getWidget());\r
+        \r
+        Group locationGroup = new Group(composite, SWT.NONE);\r
+        GridDataFactory.fillDefaults().applyTo(locationGroup);\r
+        GridLayoutFactory.fillDefaults().applyTo(locationGroup);\r
+        locationGroup.setText("Location");\r
+        \r
+        inside = new Button(locationGroup, support, SWT.RADIO);\r
+        inside.setText("Inside");\r
+        inside.setSelectionFactory(new PolarityLocationRadioSelectionFactory(DependencyNode.INSIDE));\r
+        inside.addSelectionListener(new PolarityLocationSelectionListener(context, DependencyNode.INSIDE));\r
+        \r
+        outside = new Button(locationGroup, support, SWT.RADIO);\r
+        outside.setText("Outside");\r
+        outside.setSelectionFactory(new PolarityLocationRadioSelectionFactory(DependencyNode.OUTSIDE));\r
+        outside.addSelectionListener(new PolarityLocationSelectionListener(context, DependencyNode.OUTSIDE));\r
+    }\r
+    \r
+    class PolarityLocationSelectionListener extends SelectionListenerImpl<Resource> {\r
+        private String location;\r
+\r
+        public PolarityLocationSelectionListener(ISessionContext context, String location) {\r
+            super(context);\r
+            this.location = location;\r
+        }\r
+        \r
+        @Override\r
+        public void apply(WriteGraph graph, Resource connectionElement) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            graph.claimLiteral(connectionElement, sr.PolarityLocation, location);\r
+        }\r
+        \r
+    }\r
+    \r
+    class PolarityLocationRadioSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {\r
+        private String location;\r
+\r
+        public PolarityLocationRadioSelectionFactory(String location) {\r
+            this.location = location;\r
+        }\r
+\r
+        @Override\r
+        public Object getIdentity(Object inputContents) {\r
+            return new Triple<Object, Object, Class<?>>(inputContents, location, getClass());\r
+        }\r
+\r
+        @Override\r
+        public Boolean perform(ReadGraph graph, Resource dependencyConnection) throws DatabaseException {\r
+            SysdynResource sr = SysdynResource.getInstance(graph);\r
+            String location = graph.getPossibleRelatedValue(dependencyConnection, sr.PolarityLocation, Bindings.STRING);  \r
+            if(DependencyNode.OUTSIDE.equals(this.location)) {\r
+                return ObjectUtils.objectEquals(this.location, location);\r
+            } else {\r
+                if(location == null)\r
+                    return true;\r
+                else\r
+                    return ObjectUtils.objectEquals(this.location, location);\r
+            }\r
+        }\r
     }\r
     \r
     class PolaritySelectionListener extends SelectionListenerImpl<Resource> {\r
diff --git a/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/PlaybackExperimentTab.java b/org.simantics.sysdyn.ui/src/org/simantics/sysdyn/ui/properties/PlaybackExperimentTab.java
new file mode 100644 (file)
index 0000000..f2eb35e
--- /dev/null
@@ -0,0 +1,206 @@
+/*******************************************************************************\r
+ * Copyright (c) 2007, 2011 Association for Decentralized Information Management in\r
+ * Industry THTH ry.\r
+ * All rights reserved. This program and the accompanying materials\r
+ * are made available under the terms of the Eclipse Public License v1.0\r
+ * which accompanies this distribution, and is available at\r
+ * http://www.eclipse.org/legal/epl-v10.html\r
+ *\r
+ * Contributors:\r
+ *     VTT Technical Research Centre of Finland - initial API and implementation\r
+ *******************************************************************************/\r
+package org.simantics.sysdyn.ui.properties;\r
+\r
+import java.util.ArrayList;\r
+\r
+import org.eclipse.jface.layout.GridDataFactory;\r
+import org.eclipse.jface.layout.GridLayoutFactory;\r
+import org.eclipse.swt.SWT;\r
+import org.eclipse.swt.graphics.Image;\r
+import org.eclipse.swt.widgets.Composite;\r
+import org.eclipse.swt.widgets.Group;\r
+import org.eclipse.ui.IWorkbenchSite;\r
+import org.simantics.browsing.ui.swt.widgets.Button;\r
+import org.simantics.browsing.ui.swt.widgets.impl.ReadFactoryImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.SelectionListenerImpl;\r
+import org.simantics.browsing.ui.swt.widgets.impl.WidgetSupport;\r
+import org.simantics.databoard.Bindings;\r
+import org.simantics.db.ReadGraph;\r
+import org.simantics.db.Resource;\r
+import org.simantics.db.WriteGraph;\r
+import org.simantics.db.common.request.ObjectsWithType;\r
+import org.simantics.db.exception.DatabaseException;\r
+import org.simantics.db.layer0.util.RemoverUtil;\r
+import org.simantics.db.management.ISessionContext;\r
+import org.simantics.diagram.stubs.G2DResource;\r
+import org.simantics.layer0.utils.direct.GraphUtils;\r
+import org.simantics.utils.datastructures.Triple;\r
+import org.simantics.utils.ui.color.Color;\r
+import org.simantics.utils.ui.color.ColorGradient;\r
+import org.simantics.utils.ui.color.ColorValue;\r
+\r
+public class PlaybackExperimentTab extends LabelPropertyTabContributor {\r
+\r
+    private static int gradientWidth = 250;\r
+    private static int gradientHeight = 20;\r
+\r
+    @Override\r
+    public void createControls(Composite body, IWorkbenchSite site, ISessionContext context, WidgetSupport support) {\r
+        Composite composite = new Composite(body, SWT.NONE);\r
+        GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(composite);\r
+\r
+        Group gradientGroup = new Group(composite, SWT.NONE);\r
+        gradientGroup.setText("Color scale");\r
+        GridDataFactory.fillDefaults().applyTo(gradientGroup);\r
+        GridLayoutFactory.fillDefaults().margins(3, 3).applyTo(gradientGroup);\r
+\r
+\r
+        ColorValue cv1 = new ColorValue(new Color(0, 62, 133), 0.0);\r
+        ColorValue cv2 = new ColorValue(new Color(255, 230, 0), 1.0);\r
+        ColorValue[] values = new ColorValue[] {cv1, cv2};\r
+        ColorGradient cg = new ColorGradient(values, ColorGradient.HSV);\r
+        Image image = cg.getGradientImage(gradientWidth, gradientHeight, SWT.HORIZONTAL);\r
+        Button b = new Button(gradientGroup, support, SWT.RADIO);\r
+        GridDataFactory.fillDefaults().hint(gradientWidth, gradientHeight).applyTo(b.getWidget());\r
+        b.setImage(image);\r
+        b.addSelectionListener(new GradientSelectionListener(context, values));\r
+        b.setSelectionFactory(new GradientSelectionFactory(values));\r
+\r
+        cv1 = new ColorValue(new Color(255, 230, 0), 0.0);\r
+        cv2 = new ColorValue(new Color(0, 62, 133), 1.0);\r
+        values = new ColorValue[] {cv1, cv2};\r
+        cg = new ColorGradient(values, ColorGradient.HSV);\r
+        image = cg.getGradientImage(gradientWidth, gradientHeight, SWT.HORIZONTAL);\r
+        b = new Button(gradientGroup, support, SWT.RADIO);\r
+        GridDataFactory.fillDefaults().hint(gradientWidth, gradientHeight).applyTo(b.getWidget());\r
+        b.setImage(image);\r
+        b.addSelectionListener(new GradientSelectionListener(context, values));\r
+        b.setSelectionFactory(new GradientSelectionFactory(values));\r
+        \r
+        cv1 = new ColorValue(new Color(0, 0, 0), 0.0);\r
+        cv2 = new ColorValue(new Color(255, 255, 255), 1.0);\r
+        values = new ColorValue[] {cv1, cv2};\r
+        cg = new ColorGradient(values, ColorGradient.HSV);\r
+        image = cg.getGradientImage(gradientWidth, gradientHeight, SWT.HORIZONTAL);\r
+        b = new Button(gradientGroup, support, SWT.RADIO);\r
+        GridDataFactory.fillDefaults().hint(gradientWidth, gradientHeight).applyTo(b.getWidget());\r
+        b.setImage(image);\r
+        b.addSelectionListener(new GradientSelectionListener(context, values));\r
+        b.setSelectionFactory(new GradientSelectionFactory(values));\r
+        \r
+        cv1 = new ColorValue(new Color(0, 0, 255), 0.0);\r
+        cv2 = new ColorValue(new Color(255, 0, 0), 1.0);\r
+        values = new ColorValue[] {cv1, cv2};\r
+        cg = new ColorGradient(values, ColorGradient.HSV);\r
+        image = cg.getGradientImage(gradientWidth, gradientHeight, SWT.HORIZONTAL);\r
+        b = new Button(gradientGroup, support, SWT.RADIO);\r
+        GridDataFactory.fillDefaults().hint(gradientWidth, gradientHeight).applyTo(b.getWidget());\r
+        b.setImage(image);\r
+        b.addSelectionListener(new GradientSelectionListener(context, values));\r
+        b.setSelectionFactory(new GradientSelectionFactory(values));\r
+        \r
+      \r
+        cv1 = new ColorValue(new Color(255, 0, 0), 0.0);\r
+        cv2 = new ColorValue(new Color(0, 0, 255), 1.0);\r
+        values = new ColorValue[] {cv1, cv2};\r
+        cg = new ColorGradient(values, ColorGradient.HSV);\r
+        image = cg.getGradientImage(gradientWidth, gradientHeight, SWT.HORIZONTAL);\r
+        b = new Button(gradientGroup, support, SWT.RADIO);\r
+        GridDataFactory.fillDefaults().hint(gradientWidth, gradientHeight).applyTo(b.getWidget());\r
+        b.setImage(image);\r
+        b.addSelectionListener(new GradientSelectionListener(context, values));\r
+        b.setSelectionFactory(new GradientSelectionFactory(values));\r
+    }\r
+\r
+\r
+    class GradientSelectionListener extends SelectionListenerImpl<Resource> {\r
+        private ArrayList<ColorValue> colorValues;\r
+\r
+        public GradientSelectionListener(ISessionContext context, ColorValue[] colorValues) {\r
+            super(context);\r
+            this.colorValues = new ArrayList<ColorValue>();\r
+            for(ColorValue cv : colorValues)\r
+                this.colorValues.add(cv);\r
+        }\r
+\r
+        @Override\r
+        public void apply(WriteGraph graph, Resource experiment) throws DatabaseException {\r
+            G2DResource g2d = G2DResource.getInstance(graph);\r
+\r
+            Resource gradient = graph.getPossibleObject(experiment, g2d.HasColorGradient);\r
+\r
+            if(gradient != null) {\r
+                graph.denyStatement(experiment, g2d.HasColorGradient, gradient);\r
+                RemoverUtil.remove(graph, gradient);\r
+            }\r
+\r
+            gradient = GraphUtils.create2(graph, g2d.ColorGradient);\r
+            graph.claim(experiment, g2d.HasColorGradient, gradient);\r
+\r
+            for(ColorValue cv : colorValues) {\r
+                Resource placement = GraphUtils.create2(graph, g2d.ColorPlacement, \r
+                        g2d.HasGradientPosition, cv.getValue());\r
+                graph.claimLiteral(placement, g2d.HasColor, cv.getColor().getAWTColor().getColorComponents(new float[4]), Bindings.FLOAT_ARRAY);\r
+                graph.claim(gradient, g2d.HasColorPlacement, placement);\r
+            }\r
+        }\r
+\r
+    }\r
+\r
+    class GradientSelectionFactory extends ReadFactoryImpl<Resource, Boolean> {\r
+        private ArrayList<ColorValue> colorValues;\r
+\r
+        public GradientSelectionFactory(ColorValue[] colorValues) {\r
+            this.colorValues = new ArrayList<ColorValue>();\r
+            for(ColorValue cv : colorValues)\r
+                this.colorValues.add(cv);\r
+        }\r
+\r
+        @Override\r
+        public Object getIdentity(Object inputContents) {\r
+            return new Triple<Object, Object, Class<?>>(inputContents, colorValues, getClass());\r
+        }\r
+\r
+        @Override\r
+        public Boolean perform(ReadGraph graph, Resource experiment) throws DatabaseException {\r
+            G2DResource g2d = G2DResource.getInstance(graph);\r
+            Resource gradient = graph.getPossibleObject(experiment, g2d.HasColorGradient);\r
+            if(gradient == null) {\r
+                return Boolean.FALSE;\r
+            }\r
+            \r
+            for(Resource placement : graph.syncRequest(new ObjectsWithType(gradient, g2d.HasColorPlacement, g2d.ColorPlacement))) {\r
+                Double position = graph.getPossibleRelatedValue(placement, g2d.HasGradientPosition);\r
+                if(position == null) \r
+                    return Boolean.FALSE;\r
+                int index = -1;\r
+                \r
+                // First look for a color with matching value\r
+                for(int i = 0; i < colorValues.size(); i++) {\r
+                    if(position.equals(colorValues.get(i).getValue())) {\r
+                        \r
+                        index = i;\r
+                        break;\r
+                    }\r
+                }\r
+                \r
+                // If matching value was found, see if the color is the same\r
+                if(index >= 0) {\r
+                    Color c = colorValues.get(index).getColor();\r
+                    float[] cArray = c.getAWTColor().getColorComponents(new float[4]);\r
+                    float[] color = graph.getPossibleRelatedValue(placement, g2d.HasColor, Bindings.FLOAT_ARRAY);\r
+                    for(int i = 0; i < color.length; i++) {\r
+                        if(cArray[i] != color[i])\r
+                            // Some inconsistency found in colors, return false\r
+                            return Boolean.FALSE;\r
+                    }\r
+                }\r
+            }\r
+            \r
+            // Everything matched\r
+            return Boolean.TRUE;\r
+        }\r
+    }\r
+\r
+}\r
index 058d265ad9c644f0faa0648db51c84d15a5c1156..c453dd7964c8ac843bd7dcd66550822666bf8d9e 100644 (file)
@@ -1,5 +1,5 @@
 /*******************************************************************************\r
- * Copyright (c) 2010 Association for Decentralized Information Management in\r
+ * Copyright (c) 2010, 2011 Association for Decentralized Information Management in\r
  * Industry THTH ry.\r
  * All rights reserved. This program and the accompanying materials\r
  * are made available under the terms of the Eclipse Public License v1.0\r
@@ -197,6 +197,13 @@ public class ResourceSelectionProcessor implements SelectionProcessor<Object, Re
                                "Outputs"));\r
                                return tabs;\r
                        }\r
+                if (backend.isInstanceOf(r, sr.PlaybackExperiment))\r
+                       return Collections.singleton(\r
+                               new ComparableTabContributor(\r
+                                       new PlaybackExperimentTab(),\r
+                                       0,\r
+                                       r,\r
+                               "Experiment Properties"));\r
                        if (backend.isInstanceOf(r, simu.Experiment))\r
                                return Collections.singleton(\r
                                                new ComparableTabContributor(\r
index 615c7020bd6176829f12803329e3941f57711d3e..814c0beb1132550c6e2699a150eecaee1fffbeee 100644 (file)
@@ -30,17 +30,17 @@ import org.simantics.simulation.ontology.SimulationResource;
 import org.simantics.sysdyn.SysdynResource;\r
 \r
 public class SysdynPlaybackExperiment extends SysdynExperiment implements IDynamicExperiment {\r
-    \r
+\r
     public static long DURATION_SLOW = 20000;\r
     public static long DURATION_NORMAL = 10000;\r
     public static long DURATION_FAST = 5000;\r
-    \r
-    double time;\r
+\r
+    double time, startTime, endTime;\r
     public static final long VARIABLE_UPDATE_INTERVAL = 500000000;\r
     private static final double UPDATES_PER_TIME_UNIT = 0.015;\r
     private long playbackDuration = DURATION_NORMAL;\r
     private Collection<Runnable> timeListeners = new ArrayList<Runnable>();\r
-    \r
+\r
     ScheduledExecutorService playbackExecutionService;\r
     PlaybackConfiguration playbackConfiguration;\r
 \r
@@ -48,8 +48,8 @@ public class SysdynPlaybackExperiment extends SysdynExperiment implements IDynam
         super(experiment, model);\r
         this.time = 0;\r
     }\r
-    \r
-    \r
+\r
+\r
     /**\r
      * Interrupts a possible ongoing playback\r
      * \r
@@ -59,7 +59,7 @@ public class SysdynPlaybackExperiment extends SysdynExperiment implements IDynam
         stopPlayback();\r
         setTime(time);\r
     }\r
-    \r
+\r
     /**\r
      * Sets a new time and continues playback from that point if \r
      * playback was running  \r
@@ -74,16 +74,24 @@ public class SysdynPlaybackExperiment extends SysdynExperiment implements IDynam
             setTime(time);\r
         }\r
     }\r
-    \r
+\r
     private void setTime(double time) {\r
         this.time = time;\r
         fireValuesChanged(); \r
     }\r
-    \r
+\r
     public double getTime() {\r
         return this.time;\r
     }\r
-    \r
+\r
+    public double getStartTime() {\r
+        return this.startTime;\r
+    }\r
+\r
+    public double getEndTime() {\r
+        return this.endTime;\r
+    }\r
+\r
     public void setPlaybackDuration(long duration) {\r
         this.playbackDuration = duration;\r
         if(isPlaybackRunning()) {\r
@@ -91,11 +99,11 @@ public class SysdynPlaybackExperiment extends SysdynExperiment implements IDynam
             startPlayback();\r
         }\r
     }\r
-    \r
+\r
     public long getPlaybackDuration() {\r
         return this.playbackDuration;\r
     }\r
-    \r
+\r
     @Override\r
     public void init(ReadGraph g) {\r
         this.session = g.getSession();\r
@@ -107,12 +115,13 @@ public class SysdynPlaybackExperiment extends SysdynExperiment implements IDynam
                 final Resource configuration = graph.getPossibleObject(model, SimulationResource.getInstance(graph).HasConfiguration);\r
                 sysdynModel = SysdynModelManager.getInstance(session).getModel(graph, configuration);\r
                 toggleActivation(graph, true);\r
+                getPlaybackConfiguration(graph);\r
                 startSimulation();\r
             }\r
         });\r
     }\r
-    \r
-    \r
+\r
+\r
     // PLAYBACK CONTROLS\r
     public void startPlayback() {\r
         startPlayback(0);\r
@@ -128,24 +137,24 @@ public class SysdynPlaybackExperiment extends SysdynExperiment implements IDynam
             setTime(playbackConfiguration.startTime);\r
             playbackConfiguration = getPlaybackConfiguration();\r
         }\r
-        \r
+\r
         Runnable playbackSimulationTask = new PlaybackSimulationTask(time, playbackConfiguration.simulationStepLength);\r
-        \r
+\r
         long delay = (long) (playbackConfiguration.playbackDuration / playbackConfiguration.intervals);\r
         ScheduledFuture<?> stepper = playbackExecutionService.scheduleWithFixedDelay(\r
                 playbackSimulationTask, initialDelay, delay, TimeUnit.MILLISECONDS\r
-        );\r
-        \r
+                );\r
+\r
         Runnable stopSimulationTask = new StopSimulationTask(stepper, playbackConfiguration.endTime);\r
         playbackExecutionService.schedule(stopSimulationTask, playbackConfiguration.playbackDuration + initialDelay, TimeUnit.MILLISECONDS);\r
-        \r
+\r
         changeState(ExperimentState.RUNNING);\r
     }\r
-    \r
+\r
     public boolean isPlaybackRunning() {\r
         return playbackExecutionService != null && !playbackExecutionService.isShutdown();\r
     }\r
-    \r
+\r
     public void resetPlayback() {\r
         double startTime = 0.0;\r
         if(isPlaybackRunning() && playbackConfiguration != null) {\r
@@ -155,7 +164,7 @@ public class SysdynPlaybackExperiment extends SysdynExperiment implements IDynam
         }\r
         setTimeInterrupting(startTime);\r
     }\r
-    \r
+\r
     public void stopPlayback() {\r
         if(isPlaybackRunning()) {\r
             playbackExecutionService.shutdownNow();\r
@@ -165,29 +174,29 @@ public class SysdynPlaybackExperiment extends SysdynExperiment implements IDynam
             changeState(ExperimentState.STOPPED);\r
         }\r
     }\r
-    \r
-   \r
+\r
+\r
     private class PlaybackSimulationTask implements Runnable {\r
         private int stepCount;\r
         private double startTime, stepLength;\r
-        \r
+\r
         public PlaybackSimulationTask(double startTime, double stepLength) {\r
             this.startTime = startTime;\r
             this.stepLength = stepLength;\r
         }\r
-        \r
+\r
         public void run() {\r
-          ++stepCount;\r
-          setTime(startTime + stepCount * stepLength);\r
+            ++stepCount;\r
+            setTime(startTime + stepCount * stepLength);\r
 //          System.out.println("Playback step at time: " + (startTime + stepCount * stepLength) + " (step: " + stepCount + ")");\r
         }\r
-      }\r
+    }\r
 \r
     private class StopSimulationTask implements Runnable {\r
 \r
         private ScheduledFuture<?> scheduledFuture;\r
         private double endTime;\r
-        \r
+\r
         public StopSimulationTask(ScheduledFuture<?> aSchedFuture, double endTime){\r
             scheduledFuture = aSchedFuture;\r
             this.endTime = endTime;\r
@@ -200,26 +209,31 @@ public class SysdynPlaybackExperiment extends SysdynExperiment implements IDynam
         }\r
 \r
     }\r
-    \r
+\r
     private PlaybackConfiguration getPlaybackConfiguration() {\r
-        Double[] numbers = new Double[3];\r
+        PlaybackConfiguration config = null;\r
         try {\r
-            numbers = Simantics.getSession().syncRequest(new Read<Double[]>() {\r
+            config = Simantics.getSession().syncRequest(new Read<PlaybackConfiguration>() {\r
+\r
                 @Override\r
-                public Double[] perform(ReadGraph graph) throws DatabaseException {\r
-                    Double[] numbers = new Double[3];\r
-                    Resource model = getModel();\r
-                    SysdynResource sr = SysdynResource.getInstance(graph);\r
-                    numbers[0] = graph.getRelatedValue(model, sr.HasStartTime);\r
-                    numbers[1] = graph.getRelatedValue(model, sr.HasStopTime);\r
-                    numbers[2] = graph.getPossibleRelatedValue(model, sr.HasOutputInterval);\r
-                    return numbers;\r
+                public PlaybackConfiguration perform(ReadGraph graph) throws DatabaseException {\r
+                    return getPlaybackConfiguration(graph);\r
                 }\r
+\r
             });\r
-        } catch (DatabaseException e1) {\r
-            e1.printStackTrace();\r
+        } catch (DatabaseException e) {\r
+            e.printStackTrace();\r
         }\r
-        \r
+        return config;\r
+    }\r
+    private PlaybackConfiguration getPlaybackConfiguration(ReadGraph graph) throws DatabaseException {\r
+        Double[] numbers = new Double[3];\r
+        Resource model = getModel();\r
+        SysdynResource sr = SysdynResource.getInstance(graph);\r
+        numbers[0] = graph.getRelatedValue(model, sr.HasStartTime);\r
+        numbers[1] = graph.getRelatedValue(model, sr.HasStopTime);\r
+        numbers[2] = graph.getPossibleRelatedValue(model, sr.HasOutputInterval);\r
+\r
         PlaybackConfiguration config = new PlaybackConfiguration();\r
         config.simulationDuration = numbers[1] - numbers[0] - time;\r
         config.playbackDuration = (long) (config.simulationDuration / (config.simulationDuration + time) * playbackDuration);\r
@@ -227,37 +241,40 @@ public class SysdynPlaybackExperiment extends SysdynExperiment implements IDynam
         config.simulationStepLength = config.simulationDuration / config.intervals;\r
         config.endTime = numbers[1];\r
         config.startTime = numbers[0];\r
+\r
+        this.startTime = config.startTime;\r
+        this.endTime = config.endTime;\r
         return config;\r
     }\r
-    \r
+\r
     private class PlaybackConfiguration {\r
         public double simulationDuration, simulationStepLength, intervals, endTime, startTime;\r
         public long playbackDuration;\r
     }\r
-    \r
+\r
     protected void localStateChange() {\r
         super.localStateChange();\r
-        \r
+\r
         ExperimentState state = getState();\r
         if(ExperimentState.DISPOSED.equals(state)) {\r
             stopPlayback();\r
         }\r
     }\r
-    \r
+\r
     // TIME LISTENERS\r
     public void addTimeListener(Runnable timeListener) {\r
         if(!this.timeListeners.contains(timeListener))\r
             this.timeListeners.add(timeListener);\r
     }\r
-    \r
+\r
     public Collection<Runnable> getTimeListeners() {\r
         return this.timeListeners;\r
     }\r
-    \r
+\r
     public void removeTimeListener(Runnable timeListener) {\r
         this.timeListeners.remove(timeListener);\r
     }\r
-    \r
+\r
     @Override\r
     public void fireValuesChanged() {\r
         for(Runnable listener : timeListeners) {\r
@@ -266,5 +283,5 @@ public class SysdynPlaybackExperiment extends SysdynExperiment implements IDynam
         super.fireValuesChanged();\r
 \r
     }\r
-    \r
+\r
 }\r
index f0030c8c2ed235c7432244f97b19c685876d6319..f95cde940d82a34ae9fc71697dea93e776de2074 100644 (file)
  *******************************************************************************/\r
 package org.simantics.sysdyn.representation.expressions;\r
 \r
+import java.io.StringReader;\r
 import java.util.ArrayList;\r
 import java.util.Iterator;\r
 \r
 import org.simantics.objmap.annotations.GraphType;\r
 import org.simantics.objmap.annotations.RelatedValue;\r
+import org.simantics.sysdyn.expressionParser.ExpressionParser;\r
+import org.simantics.sysdyn.expressionParser.ParseException;\r
 import org.simantics.sysdyn.representation.ArrayIndexes;\r
 import org.simantics.sysdyn.representation.Enumeration;\r
 import org.simantics.sysdyn.representation.IndependentVariable;\r
@@ -32,7 +35,10 @@ public class StockExpression extends Expression {
 \r
     @Override\r
     public String getDeclaration(IndependentVariable variable) {\r
-        Double value = getStartValue(variable);\r
+//        Double value = getStartValue(variable);\r
+        String value = null;\r
+        if(useStartValue())\r
+            value = initialEquation;\r
         \r
        ArrayIndexes ai = variable.getArrayIndexes();\r
        ArrayList<Enumeration> enumerations = null;\r
@@ -55,11 +61,13 @@ public class StockExpression extends Expression {
        }\r
         \r
        String each = "";\r
-       if(ai != null && !ai.getEnumerations().isEmpty())\r
-               each = "each";\r
         if (value == null) {\r
+            if(ai != null && !ai.getEnumerations().isEmpty())\r
+                each = "each";\r
             return "    " + variable.getType() + " " + variable.getName() + range + "(" + each + " fixed=false);\n";\r
         } else {\r
+            if(ai != null && !ai.getEnumerations().isEmpty() && getStartValue(variable) != null)\r
+                each = "each";\r
             return "    " + variable.getType() + " " + variable.getName() + range + "(" + each+ " start=" + value + "," + each + " fixed=true);\n";\r
         }\r
     }\r
@@ -101,15 +109,27 @@ public class StockExpression extends Expression {
         b.append(";\n");\r
         return b.toString();\r
     }\r
+    \r
+    private boolean useStartValue() {\r
+        ExpressionParser parser = new ExpressionParser(new StringReader(initialEquation));\r
+        try {\r
+            parser.expr();\r
+            return parser.getReferences().isEmpty();\r
+        } catch (ParseException e) {\r
+        }\r
+        return false;\r
+    }\r
 \r
     @Override\r
     public String getInitialEquation(IndependentVariable variable) {\r
-       try {\r
-               Double.parseDouble(initialEquation);\r
-               return null;\r
-       } catch (Exception e){\r
-               // Has an initial equation\r
-       } \r
+//     try {\r
+//             Double.parseDouble(initialEquation);\r
+//             return null;\r
+//     } catch (Exception e){\r
+//             // Has an initial equation\r
+//     } \r
+        if(useStartValue())\r
+            return null;\r
         String equation = FormatUtils.formatExpressionForModelica(variable, initialEquation);\r
        String range = IndexUtils.rangeToIndexes(variable, this.getArrayRange());\r
        if(range == null)\r
@@ -125,8 +145,11 @@ public class StockExpression extends Expression {
        if(expressions.size() == 1) {\r
                IExpression e = expressions.get(0);\r
             if(e.getInitialEquation(variable) == null) {\r
-               // Has start value\r
-               value = Double.parseDouble(initialEquation);\r
+                try {\r
+                    value = Double.parseDouble(initialEquation);\r
+                } catch(NumberFormatException e1) {\r
+                    \r
+                }\r
             }\r
        }\r
        return value;\r