Browse Source

NewUnitGraph not finished jet.

Tom Troppmann 5 years ago
parent
commit
8885fc275f

+ 69 - 33
src/classes/HolonElement.java

@@ -12,6 +12,7 @@ import java.awt.*;
 import java.awt.geom.Point2D;
 import java.awt.geom.Point2D.Double;
 import java.util.LinkedList;
+import java.util.ListIterator;
 
 /**
  * The class "HolonElement" represents any possible element that can be added to
@@ -21,9 +22,6 @@ import java.util.LinkedList;
  */
 public class HolonElement implements IGraphedElement, GraphEditable{
 
-    /** Points on the UnitGraph */
-    private LinkedList<Point> graphPoints;
-    
     /** Points of new TestGraph 
      * Represent the Graph 
      * the X component from a Point is period from 0..1
@@ -86,6 +84,7 @@ public class HolonElement implements IGraphedElement, GraphEditable{
      * @param model Model
      */
     public HolonElement(String eleName, int amount, float energy, Model model) {
+    	
     	this(eleName, amount, energy, IdCounterElem.nextId(),model);
     }
     
@@ -94,17 +93,16 @@ public class HolonElement implements IGraphedElement, GraphEditable{
      * same as standard constructor, but with already given id (so the counter is not increased twice)
      */
     public HolonElement(String eleName, int amount, float energy, int id, Model model){
-    	setLocalPeriod(model==null? UnitGraph.STANDARD_GRAPH_ACCURACY : model.getGraphIterations());
+    	setLocalPeriod(model==null? IGraphedElement.STANDARD_GRAPH_ACCURACY : model.getGraphIterations());
     	setStretching(IGraphedElement.STRETCH_BY_DEFAULT);
     	setEleName(eleName);
         setAmount(amount);
         setEnergyPerElement(energy);
         setActive(true);
-        setAvailableEnergyPerElementAt(energy);
-        setGraphPoints(new LinkedList<>());
         System.out.println("heiNEW");
         setTestGraphPoints(new LinkedList<>());
         initTestGraphPoints(1);
+        sampleGraph();
         setId(id);
         setFlexibleEnergyAvailable(0);
         setFlexible(false);
@@ -123,19 +121,15 @@ public class HolonElement implements IGraphedElement, GraphEditable{
         setAmount(element.getAmount());
         setEnergyPerElement(element.getEnergyPerElement());
         setActive(element.isActive());
-        setAvailableEnergyPerElementAt(element.getEnergyPerElement());
-        for (int i = 0; i < curveSample.length; i++) {
-            curveSample[i] = element.getAvailableEnergyAt(i);
-        }
-        setGraphPoints(new LinkedList<>());
         setTestGraphPoints(new LinkedList<>());
-        for (Point p : element.getGraphPoints()) {
-            this.graphPoints.add(new Point((int) p.getX(), (int) p.getY()));
-        }
         System.out.println("hei");
         for (Point2D.Double p : element.getTestGraphPoints()) {
             this.testGraphPoints.add(new Point2D.Double(p.getX(), p.getY()));
         }
+        for (Point2D.Double p : getTestGraphPoints()) {
+            System.out.println(testGraphPoints);
+        }
+        sampleGraph();
         setSaving(null);
         setId(IdCounterElem.nextId());
         setFlexibleEnergyAvailable(0);
@@ -167,23 +161,10 @@ public class HolonElement implements IGraphedElement, GraphEditable{
      * Get the energyPerElement currently(at given time step) available
      */
     public float getAvailableEnergyAt(int timestep) {
-        return this.curveSample[IndexTranslator.getEffectiveIndex(this, timestep)];
+    	System.out.println("getAvailableEnergyAt");
+        return amount * energyPerElement * this.curveSample[IndexTranslator.getEffectiveIndex(this, timestep)];
     }
 
-    
-    /**
-     * 
-     * @param timestep
-     * @return
-     */
-    public float testFunctiongetAvailableEnergyAt(int timestep) {
-		if(getTestGraphPoints()==null)return 0;
-		for(Point2D.Double p : getTestGraphPoints())
-		{
-			System.out.println(p);
-		}
-    	return 0;
-    }
     /**
      * Set energyPerElement to any value at a given position.
      *
@@ -292,7 +273,7 @@ public class HolonElement implements IGraphedElement, GraphEditable{
      * @return totalEnergy (actual)
      */
     public float getOverallEnergy() {
-        float totalEnergy = ((float) amount) * energyPerElement;
+        float totalEnergy =  amount * energyPerElement;
         return totalEnergy;
     }
 
@@ -306,7 +287,7 @@ public class HolonElement implements IGraphedElement, GraphEditable{
         if (flexible) {
             return ((float) amount) * energyPerElement;
         } else {
-            return ((float) amount) * curveSample[IndexTranslator.getEffectiveIndex(this, timestep)];
+            return ((float) amount) * energyPerElement * curveSample[IndexTranslator.getEffectiveIndex(this, timestep)];
         }
     }
 
@@ -317,7 +298,8 @@ public class HolonElement implements IGraphedElement, GraphEditable{
      * @return the Graph Points
      */
     public LinkedList<Point> getGraphPoints() {
-        return graphPoints;
+        return null;
+        //TODO DELETE
     }
 
     /**
@@ -326,7 +308,7 @@ public class HolonElement implements IGraphedElement, GraphEditable{
      * @param points the Graph points
      */
     public void setGraphPoints(LinkedList<Point> points) {
-        this.graphPoints = points;
+    	//TODO DELETE
     }
 
     /**
@@ -467,4 +449,58 @@ public class HolonElement implements IGraphedElement, GraphEditable{
 	public LinkedList<Double> getStateGraph() {
 		return getTestGraphPoints();
 	}
+
+	
+	private Point.Double getBezierPoint(double t, Point.Double p0, Point.Double p1,Point.Double p2,Point.Double p3) {
+    	/*
+    	 * Calculate Beziér:
+    	 * B(t) = (1-t)^3 * P0 + 3*(1-t)^2 * t * P1 + 3*(1-t)*t^2 * P2 + t^3 * P3 , 0 < t < 1
+    	 * 
+    	 * Source: //http://www.theappguruz.com/blog/bezier-curve-in-games
+    	 */
+		Point.Double bezier = new Point.Double();
+		double OneSubT =  1-t;
+		double OneSubT2 = Math.pow(OneSubT, 2);
+		double OneSubT3 = Math.pow(OneSubT, 3);
+		double t2 = Math.pow(t , 2);
+		double t3 = Math.pow(t , 3);
+	
+		bezier.x = OneSubT3 * p0.x + 3 * OneSubT2 * t * p1.x + 3 * OneSubT * t2 * p2.x + t3 * p3.x;
+		bezier.y = OneSubT3 * p0.y + 3 * OneSubT2 * t * p1.y + 3 * OneSubT * t2 * p2.y + t3 * p3.y;
+		return bezier;
+		
+	}
+	private double getYBetweenTwoPoints(double t, Point.Double start, Point.Double end) {
+		
+	    double mitte = (start.x + end.x)* 0.5;
+	    Point.Double bezier = getBezierPoint(t, start, new Point.Double(mitte, start.y), new Point.Double(mitte, end.y), end);
+		return bezier.y;
+	}
+	
+	private float[] sampleGraph(int sampleLength)
+	{		
+		ListIterator<Point2D.Double> iter = this.testGraphPoints.listIterator();
+		Point.Double before = iter.next();
+		Point.Double after = iter.next();
+		float [] sampleCurve = new float[sampleLength];	
+		for(int i = 0; i<sampleLength ; i++)
+		{
+			double graphX = (double)i / (double) (sampleLength - 1); //from 0.0 to 1.0
+			if(graphX > after.x)
+			{
+				before = after;
+				after = iter.next();
+			}
+			//inverseLerp(valueBetween, min, max) (valueBetween - min) / (max - min)
+			// e.g. old.x = 0.4, actual.x = 0.8 and graphX = 0.6 then t is 0.5
+			double t = (after.x -before.x > 0)? (graphX - before.x) / (after.x -before.x) : 0.0;			
+			sampleCurve[i] = (float) getYBetweenTwoPoints(t, before, after);
+		}
+		return sampleCurve;
+	}
+	
+	@Override
+	public void sampleGraph() {
+		curveSample = sampleGraph(100);
+	}
 }

+ 9 - 3
src/classes/HolonSwitch.java

@@ -71,9 +71,9 @@ public class HolonSwitch extends AbstractCpsObject implements IGraphedElement, G
 	public HolonSwitch(String objName) {
 		super(objName);
 		setStretching(IGraphedElement.STRETCH_BY_DEFAULT);
-		activeAt=new boolean[UnitGraph.STANDARD_GRAPH_ACCURACY];
+		activeAt=new boolean[IGraphedElement.STANDARD_GRAPH_ACCURACY];
 		setLocalPeriod(SingletonControl.getInstance().getControl()==null?
-				UnitGraph.STANDARD_GRAPH_ACCURACY:
+				IGraphedElement.STANDARD_GRAPH_ACCURACY:
 				SingletonControl.getInstance().getControl().getModel().getGraphIterations()
 		);
 		setManualState(true);
@@ -94,7 +94,7 @@ public class HolonSwitch extends AbstractCpsObject implements IGraphedElement, G
 		HolonSwitch copyObj = (HolonSwitch)obj;
 		setLocalPeriod(copyObj.getLocalPeriod());
 		setStretching(copyObj.isStretching());
-		activeAt=new boolean[UnitGraph.STANDARD_GRAPH_ACCURACY];
+		activeAt=new boolean[IGraphedElement.STANDARD_GRAPH_ACCURACY];
 		super.setName(obj.getName());
 		setManualState(copyObj.getActiveManual());
 		setAutoState(true);
@@ -289,4 +289,10 @@ public class HolonSwitch extends AbstractCpsObject implements IGraphedElement, G
 		// TODO no Double List
 		return null;
 	}
+
+	@Override
+	public void sampleGraph() {
+		// TODO Auto-generated method stub
+		
+	}
 }

+ 5 - 0
src/classes/UnitGraphPoint.java

@@ -1,5 +1,6 @@
 package classes;
 
+import java.awt.Point;
 import java.awt.geom.Point2D;
 
 /**
@@ -43,6 +44,10 @@ public class UnitGraphPoint {
 		displayedPosition =  new Position((int) (x * widthWithBorder) + border, (int) ((1-y) * heightWithBorder) + border);
     }
 	
+	public Point.Double getPoint()
+	{
+		 return new Point2D.Double(x, y);
+	}
 	@Override
 	public String toString() {
 		return "[" + x + ":" + y + "]";

+ 5 - 0
src/interfaces/GraphEditable.java

@@ -26,4 +26,9 @@ public interface GraphEditable {
 	 * @return The list of all graph points.
 	 */
 	LinkedList<Point2D.Double> getStateGraph();
+	
+	/**
+	 * Sample the Graph on the object.
+	 */
+	void sampleGraph();
 }

+ 1 - 1
src/interfaces/IGraphedElement.java

@@ -3,7 +3,7 @@ package interfaces;
 public interface IGraphedElement {
 	
 	public static final boolean STRETCH_BY_DEFAULT=false;
-	
+	public static final int STANDARD_GRAPH_ACCURACY=100;
 	/**
 	 * Sets the local period of the element. 
 	 * If the simulation has 100 steps and the local period is 50,

+ 18 - 13
src/ui/controller/ClipboardController.java

@@ -256,22 +256,26 @@ public class ClipboardController {
         List<String> keys = load.getKeys(object);
         String p;
         int mid, x, y;
-        System.out.println("loadcontroller");
+        System.out.println("loadcontroller:loadUnitGraph");
         LinkedList<Point> graphpoint = new LinkedList<>();
         int sav = 0;
         // foreach Point in the graph restore it
-        for (String k : keys) {
-            if (!k.equals("ID")) {
-                p = object.get(k).getAsString();
-                mid = p.indexOf(':');
-                x = Integer.parseInt(p.substring(0, mid));
-                y = Integer.parseInt(p.substring(mid + 1, p.length()));
-                graphpoint.add(new Point(x, y));
-            } else
-                // else its an ID
-                sav = object.get(k).getAsInt();
-
+        if(type != GRAPHTYPE.TESTELEMENT)
+        {
+	        	for (String k : keys) {
+	            if (!k.equals("ID")) {
+	                p = object.get(k).getAsString();
+	                mid = p.indexOf(':');
+	                x = Integer.parseInt(p.substring(0, mid));
+	                y = Integer.parseInt(p.substring(mid + 1, p.length()));
+	                graphpoint.add(new Point(x, y));
+	            } else
+	                // else its an ID
+	                sav = object.get(k).getAsInt();
+	
+	        	}
         }
+       
 
         switch (type) {
             case SWITCH:
@@ -291,7 +295,7 @@ public class ClipboardController {
                         p = object.get(k).getAsString();
                         mid = p.indexOf(':');
                         double x1 = Double.parseDouble(p.substring(0, mid));
-                        double y1 = Integer.parseInt(p.substring(mid + 1, p.length()));
+                        double y1 = Double.parseDouble(p.substring(mid + 1, p.length()));
                         graphpointTEST.add(new Point2D.Double(x1, y1));
                     } else
                         // else its an ID
@@ -302,6 +306,7 @@ public class ClipboardController {
                 sav = eleIDMap.get(sav);
                 HolonElement ele1 = eleDispatch.get(sav);
                 ele1.setTestGraphPoints(graphpointTEST);
+                ele1.sampleGraph();
                 break;
             default:
                 break;

+ 22 - 17
src/ui/controller/LoadController.java

@@ -178,7 +178,7 @@ public class LoadController {
             if (key.contains("ELEUNITGRAPH"))
                 loadUnitGraph(GRAPHTYPE.ELEMENT, json.get(key), null, eleDispatch);
             if (key.contains("ELETESTUNITGRAPH"))
-                loadUnitGraph(GRAPHTYPE.ELEMENT, json.get(key), null, eleDispatch);
+                loadUnitGraph(GRAPHTYPE.TESTELEMENT, json.get(key), null, eleDispatch);
             if (key.contains("TRACKED"))
                 loadTracked(json.get(key), objDispatch);
             if (key.contains("STATSGRAPH"))
@@ -298,7 +298,7 @@ public class LoadController {
                                     HashMap<Integer, HolonElement> eleDispatch) {
 
         JsonObject object = jsonElement.getAsJsonObject();
-
+        System.out.println("loadCanvasElements");
         HolonElement temp = model.getGson().fromJson(object.get("properties"), HolonElement.class);
         initElements(temp);
         // id which Object it was stored before
@@ -372,26 +372,31 @@ public class LoadController {
      */
     private void loadUnitGraph(GRAPHTYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
                                HashMap<Integer, HolonElement> eleDispatch) {
-
+    	//TODO Make UnitGraphChnages RDY
         JsonObject object = jsonElement.getAsJsonObject();
         List<String> keys = getKeys(object);
         String p;
         int mid, x, y;
-
-        LinkedList<Point> graphpoint = new LinkedList<>();
         int sav = 0;
-        // foreach Point in the graph restore it
-        for (String k : keys) {
-            if (!k.equals("ID")) {
-                p = object.get(k).getAsString();
-                mid = p.indexOf(':');
-                x = Integer.parseInt(p.substring(0, mid));
-                y = Integer.parseInt(p.substring(mid + 1, p.length()));
-                graphpoint.add(new Point(x, y));
-            } else
-                // else its an ID
-                sav = object.get(k).getAsInt();
+        LinkedList<Point> graphpoint = new LinkedList<>();
+        if(type != GRAPHTYPE.TESTELEMENT)
+        {
+	        // foreach Point in the graph restore it
+	        for (String k : keys) {
+	            if (!k.equals("ID")) {
+	                p = object.get(k).getAsString();
+	                mid = p.indexOf(':');
+	                x = Integer.parseInt(p.substring(0, mid));
+	                y = Integer.parseInt(p.substring(mid + 1, p.length()));
+	                graphpoint.add(new Point(x, y));
+	            } else
+	                // else its an ID
+	                sav = object.get(k).getAsInt();
+	        }
         }
+        
+        
+       
 
         switch (type) {
             case SWITCH:
@@ -409,7 +414,7 @@ public class LoadController {
                         p = object.get(k).getAsString();
                         mid = p.indexOf(':');
                         double x1 = Double.parseDouble(p.substring(0, mid));
-                        double y1 = Integer.parseInt(p.substring(mid + 1, p.length()));
+                        double y1 = Double.parseDouble(p.substring(mid + 1, p.length()));
                         graphpointTEST.add(new Point2D.Double(x1, y1));
                     } else
                         // else its an ID

+ 0 - 2
src/ui/controller/SaveController.java

@@ -267,8 +267,6 @@ public class SaveController {
             }
             file.add(key, model.getGson().toJsonTree(temp));
             // if there are gps add them into
-            if (!ele.getGraphPoints().isEmpty())
-                unitgraphToJson(GRAPHTYPE.ELEMENT, file, ele.getId(), ele.getGraphPoints());
             if (!ele.getTestGraphPoints().isEmpty())
             	unitgraphTESTToJson(file, ele.getId(), ele.getTestGraphPoints());
             temp = new JsonObject();

+ 0 - 5
src/ui/view/GUI.java

@@ -2149,7 +2149,6 @@ public class GUI implements CategoryListener {
 				if (temp instanceof HolonSwitch) {
 					showScrollGraph();
 					repaintGraphAux((HolonSwitch)temp);
-					unitGraph.fillArrayofBooleans();
 				}
 				// Write new data in the PropertyTable
 				triggerUpdateController(temp);
@@ -2554,7 +2553,6 @@ public class GUI implements CategoryListener {
 	private void hideScrollGraph() {
 		System.out.println("GUI->hideScrollGraph");
 		scrollGraph.setVisible(false);
-		unitGraph.empty();
 		splitGraphHolonEl.remove(scrollGraph);
 		splitGraphHolonEl.setDividerLocation(0);
 	}
@@ -2857,7 +2855,6 @@ public class GUI implements CategoryListener {
 					}
 					if (temp instanceof HolonSwitch) {
 						repaintGraphAux((HolonSwitch)temp);
-						unitGraph.fillArrayofBooleans();
 					}
 				}
 
@@ -3080,7 +3077,6 @@ public class GUI implements CategoryListener {
 		}
 	}
 	private void repaintGraphAux(ArrayList<HolonElement> o){//TODO: 
-		unitGraph.repaintWithNewElement((ArrayList<HolonElement>)o);
 		//TODO -> just in Progress 
 		unitGraph.initNewElement(o.get(o.size()-1));
 //		unitGraphLocalPeriod.setText(""+unitGraph.getLocalPeriod());
@@ -3088,7 +3084,6 @@ public class GUI implements CategoryListener {
 	}
 	
 	private void repaintGraphAux(HolonSwitch o){//TODO: 
-		unitGraph.repaintWithNewSwitch(o);
 //		unitGraphLocalPeriod.setText(""+unitGraph.getLocalPeriod());
 //		unitGraphStretchMode.setSelected(unitGraph.isStretching());
 	}

+ 170 - 484
src/ui/view/UnitGraph.java

@@ -13,14 +13,9 @@ import ui.model.Model;
 import javax.swing.*;
 import java.awt.*;
 import java.awt.event.*;
-import java.awt.geom.CubicCurve2D;
-import java.awt.geom.GeneralPath;
-import java.awt.geom.Line2D;
 import java.awt.geom.Path2D;
 import java.awt.geom.Point2D;
-import java.util.ArrayDeque;
 import java.util.ArrayList;
-import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.ListIterator;
 
@@ -28,48 +23,17 @@ import java.util.ListIterator;
  * This Class represents a Graph where the User can model the behavior of
  * elements and switches over time.
  *
- * @author Gruppe14
+ * @author Tom Troppmann
  */
 public class UnitGraph extends JPanel implements MouseListener, MouseMotionListener, ComponentListener {
 
     private static final long serialVersionUID = 1L;
-	public static final int STANDARD_GRAPH_ACCURACY = 100;
-    private GeneralPath graphCurve = new GeneralPath();
-    private float maximum = 0;
-    // Information shown when a Point is Dragged
-    private String dragInformation = "";
-    // Points
-    private Point recSize = new Point(8, 8); // Point Size
-    private Graphics2D g2;
-    private CubicCurve2D c = new CubicCurve2D.Double();
-    private CubicCurve2D cr = new CubicCurve2D.Double();
-    private CubicCurve2D cl = new CubicCurve2D.Double();
-    private LinkedList<Point> pointList;
-    // Scale for the Graph
-    private double scaleX;
-    private double scaleY;
-    private double width = -1;
-    private double height = -1;
-    private boolean isElement = false;
-    private boolean isSwitch = false;
-    private ArrayList<HolonElement> tempElements = new ArrayList<>();
-    private Model model;
-    private Control controller;
-    private Line2D.Double line = null;
-    private boolean pointDrag = false;
-    private boolean init = true;
-    private Point tempP = null;
-    private double x = 0, y = 0;
-    private int x1, x2, y1, y2, ctrlx1, ctrly1, ctrlx2, ctrly2;
-    
-    private int textWidth = 0;
-    
-	private IGraphedElement current;
 	
-	//NEW ERA
+	
 	// Normal Settings
 	private int border = 4;
 	private int clickThreshholdSquared = 25;
+	
 	// Display Settings
 	/**
 	 * The size of a dot in the graph.
@@ -79,14 +43,22 @@ public class UnitGraph extends JPanel implements MouseListener, MouseMotionListe
 	/** The Color of a dot in the graph. */
 	Color dotColor = Color.blue;
 	Color editDotColor = new Color(255, 119, 0);
+	
 	//Intern Variables
 	//TODO: JavaDoc
 	private LinkedList<UnitGraphPoint> actualGraphPoints = new LinkedList<UnitGraphPoint>();
 	private Graphtype actualGraphType;
 	private GraphEditable actualElement;
-	Position currentPosition; //outDated
 	Position editPosition;
-	boolean released = false;
+	boolean editMode = false;
+	private enum pointType {Normal, StartPoint, EndPoint};
+	pointType editPoint = pointType.Normal;
+	
+	//Maybe Needed
+	private Model model;
+	private Control controller;
+	
+	
 	private int widthWithBorder, heightWithBorder;
 	
 	
@@ -104,8 +76,6 @@ public class UnitGraph extends JPanel implements MouseListener, MouseMotionListe
         setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
         this.controller = control;
         this.model = model;
-
-        this.pointList = new LinkedList<>();
         this.setBackground(Color.WHITE);
 
         this.addMouseListener(this);
@@ -126,19 +96,38 @@ public class UnitGraph extends JPanel implements MouseListener, MouseMotionListe
         g2D.setColor(Color.BLACK);
         g2D.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
         g2D.setStroke(new BasicStroke(2));
-        printDebugRepresentive();
         drawUnitGraph(g2D);
         g2D.setColor(dotColor);
-        if(released)
+        if(editMode)
         {
         	drawUnitGraphPointsReleased(g2D);
         }else
         {
         	 drawUnitGraphPoints(g2D);
         }
+        g2D.setStroke(new BasicStroke(1));
+        drawCurrentIterartionLine(g2D);
     }
     //TODO -> New Section
     
+    private void drawCurrentIterartionLine(Graphics2D g)
+    {
+    	int cur = model.getCurIteration();
+    	int max = model.getIterations();
+    	double where = ((double) cur)/((double) max);
+    	Position oben = new Position(border + (int)(where * widthWithBorder), 0);
+    	Position unten = new Position(border + (int)(where * widthWithBorder), 2 * border + heightWithBorder);
+    	drawLine(g,oben,unten);
+    }
+    
+    private void drawLine(Graphics2D g, Position start, Position end)
+    {
+    	Path2D.Double path = new Path2D.Double();
+    	path.moveTo(start.x, start.y);
+    	path.lineTo(end.x, end.y);
+    	g.draw(path);
+    }
+    
     private Path2D.Double initBezier(Position start) {
     	//Good Source for basic understanding for Bezier Curves
         //http://www.theappguruz.com/blog/bezier-curve-in-games
@@ -161,7 +150,7 @@ public class UnitGraph extends JPanel implements MouseListener, MouseMotionListe
 			drawBoolGraph(g);
 			break;
 		case doubleGraph:
-			if(released)
+			if(editMode)
 				drawDoubleGraphWithEditPosition(g);
 			else
 				drawDoubleGraph(g);
@@ -177,6 +166,15 @@ public class UnitGraph extends JPanel implements MouseListener, MouseMotionListe
     	}
     }
     
+	private void saveGraph() {
+		LinkedList<Point2D.Double> actual = actualElement.getStateGraph();
+		actual.clear();
+		for(UnitGraphPoint p: actualGraphPoints)
+		{
+			actual.add(p.getPoint());
+		}
+		actualElement.sampleGraph();
+	}
     private void drawUnitGraphPointsReleased(Graphics2D g) {
     	drawUnitGraphPoints(g);
     	g.setColor(editDotColor);
@@ -199,19 +197,6 @@ public class UnitGraph extends JPanel implements MouseListener, MouseMotionListe
     		actual = target;
     	}
     	g.draw(path);
-    	//Maybe New Feature
-    	g.setColor(Color.darkGray);
-    	//Start
-    	Path2D.Double path2 = new Path2D.Double();
-    	Position startpunkt = actualGraphPoints.getFirst().displayedPosition;
-    	path2.moveTo(0,startpunkt.y);
-    	path2.lineTo(startpunkt.x, startpunkt.y);
-    	g.draw(path2);
-    	//Ende
-    	Position endpunkt = actualGraphPoints.getLast().displayedPosition;
-    	path2.moveTo(endpunkt.x,endpunkt.y);
-    	path2.lineTo(2 * border + border+widthWithBorder, endpunkt.y);
-    	g.draw(path2);
     	
     }
     private void drawDoubleGraphWithEditPosition(Graphics2D g) {
@@ -279,36 +264,34 @@ public class UnitGraph extends JPanel implements MouseListener, MouseMotionListe
     	actualElement = element;
     	repaint();
     }
-
-    private void printDebugRepresentive(){
-    	if(this.actualGraphPoints.isEmpty()) return;
-    	System.out.print("{");
-    	for(UnitGraphPoint p: actualGraphPoints){
-    		System.out.print(p.displayedPosition);
-    	}
-    	System.out.println("}");
-    }
     
-    private void detectPointUnderCurserAndRemove(MouseEvent mEvent) {
-		//get mouse Position
-    	Position mPosition = new Position(mEvent.getPoint());
-    	ListIterator<UnitGraphPoint> iter2 = actualGraphPoints.listIterator();
-    	while (iter2.hasNext())
+    
+    private void removePointNearPosition(Position mPosition) {
+    	ListIterator<UnitGraphPoint> iter = actualGraphPoints.listIterator();
+    	while (iter.hasNext())
     	{
-    		if(mPosition.squareDistance(iter2.next().displayedPosition) < clickThreshholdSquared)
+    		if(mPosition.squareDistance(iter.next().displayedPosition) < clickThreshholdSquared)
     		{
-    			iter2.remove();
+    			iter.remove();
     			break;
     		}
     	}
     }
     
+    private void  detectStartEndPoint(Position mPosition)
+    {
+    	UnitGraphPoint first = actualGraphPoints.getFirst();
+    	UnitGraphPoint last = actualGraphPoints.getLast();
+    	if((mPosition.squareDistance(first.displayedPosition) < clickThreshholdSquared)) editPoint = pointType.StartPoint;
+    	else if(mPosition.squareDistance(last.displayedPosition) < clickThreshholdSquared)  editPoint = pointType.EndPoint;
+    	else editPoint = pointType.Normal;
+    }
     
     private void updateEditPointPosition(Position newPosition) {
     	//make it in the bounds of the UnitGraph no Point out of the Border
-    	currentPosition = setInBounds(newPosition);
+    	Position currentPosition = setInBounds(newPosition);
+    	if(editPoint != pointType.Normal) attachToBorder(currentPosition);
     	this.editPosition = currentPosition;
-		repaint();
     }
     
 	private Position setInBounds(Position p) {
@@ -317,6 +300,71 @@ public class UnitGraph extends JPanel implements MouseListener, MouseMotionListe
 		return p;
 	}
     
+	private Point.Double getBezierPoint(double t, Point.Double p0, Point.Double p1,Point.Double p2,Point.Double p3) {
+    	/*
+    	 * Calculate Beziér:
+    	 * B(t) = (1-t)^3 * P0 + 3*(1-t)^2 * t * P1 + 3*(1-t)*t^2 * P2 + t^3 * P3 , 0 < t < 1
+    	 * 
+    	 * Source: //http://www.theappguruz.com/blog/bezier-curve-in-games
+    	 */
+		Point.Double bezier = new Point.Double();
+		double OneSubT =  1-t;
+		double OneSubT2 = Math.pow(OneSubT, 2);
+		double OneSubT3 = Math.pow(OneSubT, 3);
+		double t2 = Math.pow(t , 2);
+		double t3 = Math.pow(t , 3);
+	
+		bezier.x = OneSubT3 * p0.x + 3 * OneSubT2 * t * p1.x + 3 * OneSubT * t2 * p2.x + t3 * p3.x;
+		bezier.y = OneSubT3 * p0.y + 3 * OneSubT2 * t * p1.y + 3 * OneSubT * t2 * p2.y + t3 * p3.y;
+		return bezier;
+		
+	}
+	private double getYBetweenTwoPoints(double t, Point.Double start, Point.Double end) {
+		
+	    double mitte = (start.x + end.x)* 0.5;
+	    Point.Double bezier = getBezierPoint(t, start, new Point.Double(mitte, start.y), new Point.Double(mitte, end.y), end);
+		return bezier.y;
+	}
+	
+	private float[] sampleGraph(int sampleLength)
+	{		
+		ListIterator<UnitGraphPoint> iter = actualGraphPoints.listIterator();
+		Point.Double before = iter.next().getPoint();
+		Point.Double after = iter.next().getPoint();
+		float [] sampleCurve = new float[sampleLength];	
+		for(int i = 0; i<sampleLength ; i++)
+		{
+			double graphX = (double)i / (double) (sampleLength - 1); //from 0.0 to 1.0
+			if(graphX > after.x)
+			{
+				before = after;
+				after = iter.next().getPoint();
+			}
+			//inverseLerp(valueBetween, min, max) (valueBetween - min) / (max - min)
+			// e.g. old.x = 0.4, actual.x = 0.8 and graphX = 0.6 then t is 0.5
+			double t = (after.x -before.x > 0)? (graphX - before.x) / (after.x -before.x) : 0.0;			
+			sampleCurve[i] = (float) getYBetweenTwoPoints(t, before, after);
+		}
+		return sampleCurve;
+	}
+	
+	
+	private Position attachToBorder(Position p)
+	{
+		switch(editPoint)
+		{
+		case StartPoint:
+			p.x = border;
+			break;
+		case EndPoint:
+			p.x = border + widthWithBorder;
+			break;
+		default:
+			break;
+		}
+		return p;
+	}
+	
     private void insertNewGraphPoint(Position pos)
     {
     	System.out.println("insertNewGraphPoint");
@@ -338,16 +386,20 @@ public class UnitGraph extends JPanel implements MouseListener, MouseMotionListe
     		iter2.add(generateUnitGraphPoint(pos));
     	}
     }
-    private UnitGraphPoint generateUnitGraphPoint(Position pos) {
-    	UnitGraphPoint temp = new UnitGraphPoint((double)(pos.x - border)/(double)widthWithBorder,1 - (double) (pos.y - border)/(double)heightWithBorder,true);
+
+	private UnitGraphPoint generateUnitGraphPoint(Position pos) {
+		UnitGraphPoint temp = new UnitGraphPoint((double) (pos.x - border) / (double) widthWithBorder,
+				1 - (double) (pos.y - border) / (double) heightWithBorder, true);
 		temp.displayedPosition = pos;
-    	return temp;
+		return temp;
 	}
 
+    
 	@Override
     public void mouseDragged(MouseEvent e) {
     	System.out.println("MouseDragged");
     	updateEditPointPosition(new Position(e.getPoint()));
+    	repaint();
     }
 
     @Override
@@ -368,19 +420,37 @@ public class UnitGraph extends JPanel implements MouseListener, MouseMotionListe
 
     @Override
     public void mousePressed(MouseEvent e) {
-    	System.out.println("mousePressed");
-    	detectPointUnderCurserAndRemove(e);
-		updateEditPointPosition(new Position(e.getPoint()));
-		released = true;
-		repaint();
-    }
+		System.out.println("mousePressed");
+		Position mPosition = new Position(e.getPoint());
+		if (e.getButton() == MouseEvent.BUTTON3) {
+			// RightMouseButtonEvent
+			detectStartEndPoint(mPosition);
+			if (editPoint == pointType.Normal) {
+				removePointNearPosition(mPosition);
+				repaint();
+			}
+			editMode = false;
+
+		} else if (e.getButton() == MouseEvent.BUTTON1) {
+			// LeftMouseButtonEvent
+			detectStartEndPoint(mPosition);
+			removePointNearPosition(mPosition);
+			updateEditPointPosition(mPosition);
+			editMode = true;
+			repaint();
+		}
+	}
 
     @Override
     public void mouseReleased(MouseEvent e) {
     	System.out.println("mouseReleased");
-    	this.insertNewGraphPoint(editPosition);
-    	released = false;
-    	repaint();
+    	if(editMode)
+    	{
+    		this.insertNewGraphPoint(editPosition);
+    		editMode = false;
+    		repaint();
+    	}
+    	saveGraph();
     }
 
     /**
@@ -392,27 +462,6 @@ public class UnitGraph extends JPanel implements MouseListener, MouseMotionListe
     	System.out.println("componentResized");
     	calculateWidthHeight();
     	updateRepresentativePositions();
-        // Wenn ein anderes Element genommen wird
-    	/*
-        if (init) {
-            init = false;
-            // for scale on the first initialisation
-            if (width == -1 && height == -1) {
-                width = this.getWidth() - (border * 2);
-                height = this.getHeight() - (border * 2);
-            }
-            // Scale
-            scaleX = (this.getWidth() - (border * 2)) / width;
-            scaleY = (this.getHeight() - (border * 2)) / height;
-
-            // set the scroll graph invisible
-            this.getParent().getParent().setVisible(false);
-        }
-
-        // Scale
-        scaleX = (this.getWidth() - (border * 2)) / width;
-        scaleY = (this.getHeight() - (border * 2)) / height;
-        */
         repaint();
     }
 
@@ -429,391 +478,28 @@ public class UnitGraph extends JPanel implements MouseListener, MouseMotionListe
     public void componentShown(ComponentEvent e) {
     }
 
-    /**
-     * Empty the Graph.
-     */
-    public void empty() {
-    	System.out.println("empty");
-        pointList = null;
-        tempElements = null;
-        current = null;
-        isSwitch = false;
-        isElement = false;
-        repaint();
-    }
-
-    /**
-     * Resets the Points for the Element.
-     */
     public void reset() {
        	System.out.println("reset");
-//        pointList.removeAll(pointList);
-//        if (isSwitch) {
-//            pointList.addFirst(new Point(-border, (int) (height / 6)));
-//            pointList.addLast(new Point((int) ((this.getWidth()) / scaleX), (int) (height / 6)));
-//        } else {
-//            pointList.addFirst(new Point(0, 0));
-//            pointList.addLast(new Point((int) ((this.getWidth() - (border * 2)) / scaleX), 0));
-//        }
-//        repaint();
-    }
-
-    /**
-     * converts the number to fit the canvas.
-     *
-     * @param d the number to convert
-     * @return the converted number
-     */
-    public double convertToCanvasY(float d) {
-       	System.out.println("convertToCanvasY");
-        return (height - (d * (height / maximum)));
-    }
-
-    /**
-     * converts the number to fit the value.
-     *
-     * @param d the number to convert
-     * @return the converted number
-     */
-    public float convertToValueY(double d) {
-    	System.out.println("convertToValueY");
-        return (float) Math.round(((height - (height * (d / height))) / (height / maximum)) * 10) / 10;
-    }
 
-    /**
-     * Visualize the HolonElement on the Graph.
-     *
-     * @param selectedElement which should be visualized
-     */
-    public void repaintWithNewElement(ArrayList<HolonElement> selectedElement) {
-    	System.out.println("repaintWithNewElement");
-//    	//maybe linkedlist better?
-//        //arrayOfFloats = selectedElement.get(selectedElement.size() - 1).getAvailableEnergyPerElementAt();
-//        current = selectedElement.get(selectedElement.size()-1);
-//        tempElements=selectedElement;
-//        pointList = selectedElement.get(selectedElement.size() - 1).getGraphPoints();
-//        isSwitch = false;
-//        isElement = true;
-//        maximum = getMaximum(selectedElement.get(selectedElement.size() - 1));
-//        // First time clicked on the Element
-//        if (pointList.isEmpty()) {
-//            pointList.addFirst(new Point(0, 0));
-//            pointList.addLast(new Point((int) ((this.getWidth() - (border * 2)) / scaleX), 0));
-//        }
-//        repaint();
     }
 
-    /**
-     * Visualize the Switch on the Graph.
-     *
-     * @param s which should be visualized
-     */
-    public void repaintWithNewSwitch(HolonSwitch s) {
-    	System.out.println("repaintWithNewSwitch");
-    	
-//        //arrayOfBooleans = s.getValueArray();
-//    	current=s;
-//        pointList = s.getGraphPoints();
-//        isSwitch = true;
-//        isElement = false;
-//        // First time clicked on the Element
-//        if (pointList.isEmpty()) {
-//            pointList.addFirst(new Point(-border, (int) (height / 6)));
-//            pointList.addLast(new Point((int) ((this.getWidth()) / scaleX), (int) (height / 6)));
-//        }
-//        repaint();
-    }
-
-    /**
-     * Build a Curve for the Graph.
-     *
-     * @param p1 startpoint
-     * @param p2 endpoint
-     * @return the CubicCurve2D for the Graph
-     */
-    public CubicCurve2D buildCurve(Point p1, Point p2) {
-    	System.out.println("buildCurve");
-        x1 = (int) p1.getX();
-        y1 = (int) p1.getY();
-        x2 = (int) p2.getX();
-        y2 = (int) p2.getY();
-
-        // calculate the controllpoints
-        ctrlx1 = x1 + (x2 - x1) / 2;
-        ctrlx2 = x2 - (x2 - x1) / 2;
-        if (y1 < y2) {
-            ctrly1 = y1 + (y2 - y1) / 10;
-            ctrly2 = y2 - (y2 - y1) / 10;
-        } else {
-            ctrly1 = y1 - (y1 - y2) / 10;
-            ctrly2 = y2 + (y1 - y2) / 10;
-        }
-
-        // set the curve
-        c.setCurve(x1 * scaleX, y1 * scaleY, ctrlx1 * scaleX, ctrly1 * scaleY, ctrlx2 * scaleX, ctrly2 * scaleY,
-                x2 * scaleX, y2 * scaleY);
-        return c;
-    }
-
-    /**
-     * Fills the Arrays with booleans.
-     */
-    public void fillArrayofBooleans() {
-    	System.out.println("fillArrayofBooleans");
-        for (int i = 0; i < STANDARD_GRAPH_ACCURACY; i++) {
-            int t = (int) getYValueAt((int) (i * width / (STANDARD_GRAPH_ACCURACY - 1)));
-            if (t <= height / 2) {
-            	((HolonSwitch)current).setActiveAt(i, true);
-            } else {
-            	((HolonSwitch)current).setActiveAt(i, false);
-            }
-        }
-    }
-
-    /**
-     * Fills the Arrays of each HolonElement.
-     */
-    @SuppressWarnings("unchecked")
-	public void generateSampleCurves() {
-      	System.out.println("generateSampleCurves");
-        for (HolonElement he : tempElements) {
-            maximum = getMaximum(he);
-            he.setGraphPoints((LinkedList<Point>) pointList.clone());
-            //foreach(Point p: pointList)
-            System.out.println("------------");
-            System.out.println("pointList[");
-            for(Point p: pointList)
-    		{
-    			System.out.println(p);
-    		}
-            System.out.println("]");
-            for (int i = 0; i < STANDARD_GRAPH_ACCURACY; i++) {//!!!!!
-            	he.setAvailableEnergyPerElementAt(i, convertToValueY(getYValueAt2((int) (i * width / (100 - 1)))));
-            }
-            
-            
-            System.out.println("TestgraphPoints:");
-            he.testFunctiongetAvailableEnergyAt(0);
-        }
-    }
-
-    
-    
-    /**
-     * Convert the graph widget point to a pointlist from a holon element
-     * @param unitgraph 
-     */
-    public LinkedList<Point> convertUnitGraphToHolonElemntPointList(LinkedList<Point> unitgraph)
-    {
-    	LinkedList<Point> graphpoints = new LinkedList<Point>();
-    	if(width == 0 || height == 0) return graphpoints;
-    	for(Point p: unitgraph)
- 		{
- 			//CalcX
- 			int x = (int )((p.getX() / width)* 100.0); 
- 			//CalcY 
- 			int y = (int )((1.0-(p.getY() / height))* 100.0); //1.0- because 0 is at the top, width is at the bottom
- 			//AddPoint 
- 			graphpoints.add(new Point(x, y));
- 		}
-    	return graphpoints;
-    }
-    
-    
-    public LinkedList<Point> convertHolonElementPointListToUnitGraph(LinkedList<Point> graphPoints)
-    {
-    	LinkedList<Point> unitgraph = new LinkedList<Point>();
-    	for(Point p: graphPoints)
-    	{
-    		//CalcX
-    		int x = (int )((p.getX() / 100.0)* width); 
-    		//CalcY
-    		int y = (int )((1.0-(p.getY() / 100.0))* height); //1.0- because 0 is at the top, width is at the bottom
-    		//AddPoint
-    		unitgraph.add(new Point(x, y));
-    	}
-    	return unitgraph;
-    }
-    /**
-     * Get the Y Value at the x Coordination.
-     *
-     * @param xVal the x value for the y value
-     * @return y, the value at x
-     */
-    public float getYValueAt(int xVal) {
-     	System.out.println("getYValueAt");
-        for (int i = 0; i < pointList.size() - 1; i++) {
-            // get the Points
-            if (xVal <= pointList.get(i + 1).getX()) {
-                // Curve erstellen
-                Line2D l1 = new Line2D.Double(pointList.get(i).getX(), pointList.get(i).getY(),
-                        pointList.get(i + 1).getX(), pointList.get(i + 1).getY());
-                Line2D l2 = new Line2D.Double(xVal, 0, xVal, height);
-                return getIntersectionPoint(l1, l2);
-            }
-        }
-        return 0;
-    }
-
-    /**
-     * Get y value at the x Coordination via curves.
-     *
-     * @param xVal the x value for the y value
-     * @return y value at x
-     */
-    public float getYValueAt2(int xVal) {
-    	System.out.println("getYValueAt2");
-        for (int i = 0; i < pointList.size() - 1; i++) {
-            // get the Points
-            if (xVal >= pointList.get(i).getX()) {
-                // Curve erstellen
-                c = buildCurve(pointList.get(i), pointList.get(i + 1));
-                c.subdivide(cl, cr);
-                // Teil der Kurve aussuchen
-                if (cl.getX1() <= xVal * scaleX && cl.getX2() > xVal * scaleX) {
-                    c = cl;
-                    // Kurve Links von "unten"
-                    if (pointList.get(i).getY() >= pointList.get(i + 1).getY()) {
-                        for (float j = (float) (height - 1); j >= 0; j -= 0.1f) {
-                            if (c.contains(xVal * scaleX, j * scaleY)) {
-                                return (float) (j);
-                            }
-                        }
-                    } else {// Kurve Links von "oben"
-                        for (float j = 0; j < height; j += 0.1f) {
-                            if (c.contains(xVal * scaleX, j * scaleY)) {
-                                return (float) (j);
-                            }
-                        }
-                    }
-                } else {
-                    c = cr;
-                    // Kurve Links von "unten"
-                    if (pointList.get(i).getY() >= pointList.get(i + 1).getY()) {
-                        for (float j = 0; j < height; j += 0.1f) {
-                            if (c.contains(xVal * scaleX, j * scaleY)) {
-                                return (float) (j);
-                            }
-                        }
-                    } else {// Kurve Links von "oben"
-                        for (float j = (float) (height - 1); j >= 0; j -= 0.1f) {
-                            if (c.contains(xVal * scaleX, j * scaleY)) {
-                                return (float) (j);
-                            }
-                        }
-                    }
-                }
-            }
-        }
-        // else
-        return getYValueAt(xVal);
-    }
-
-    /**
-     * Get the Intersection Point of 2 Lines.
-     *
-     * @param l1 the first Line
-     * @param l2 the second Line
-     * @return The Intersection Point
-     */
-    public float getIntersectionPoint(Line2D l1, Line2D l2) {
-     	System.out.println("getIntersectionPoint");
-        if (!l1.intersectsLine(l2)) {
-            return 0;// null;
-        }
-        double px = l1.getX1(), py = l1.getY1(), rx = l1.getX2() - px, ry = l1.getY2() - py;
-        double qx = l2.getX1(), qy = l2.getY1(), sx = l2.getX2() - qx, sy = l2.getY2() - qy;
-
-        double det = sx * ry - sy * rx;
-        if (det == 0) {
-            return 0;// null;
-        } else {
-            double z = (sx * (qy - py) + sy * (px - qx)) / det;
-            if (z < 0 || z > 1) {
-                return 0;// new Point(0, 0); // intersection at end point!
-            }
-            return (float) (py + z * ry);// new Point((int) (px + z * rx), (int)
-            // (py + z * ry));
-        }
-    } // end intersection line-line
-
     public void update(ArrayList<AbstractCpsObject> obj) {
     	System.out.println("update");
-        ArrayDeque<AbstractCpsObject> queue = new ArrayDeque<>();
-
-        AbstractCpsObject u = null;
-        queue.addAll(obj);
-
-        while (!queue.isEmpty()) {
-            u = queue.pop();
-
-            repaintGraph(u);
-        }
-        empty();
-
-        if (u instanceof CpsUpperNode)
-            for (AbstractCpsObject adjacent : ((CpsUpperNode) u).getNodes()) {
-                queue.add(adjacent);
-            }
     }
 
-    void repaintGraph(AbstractCpsObject u) {
-    	System.out.println("repaintGraph");
-        ArrayList<HolonElement> list = new ArrayList<>();
+	public void setStretching(boolean selected) {
+		System.out.println("setStretching");
+	}
 
-        if (u instanceof HolonObject) {
-            for (HolonElement ele : ((HolonObject) u).getElements()) {
-                list.add(ele);
-                repaintWithNewElement(list);
-                generateSampleCurves();
-                list.remove(0);
-            }
-        } else if (u instanceof HolonSwitch) {
-            repaintWithNewSwitch((HolonSwitch) u);
-            fillArrayofBooleans();
-        }
-    }
+	public void setLocalPeriod(int localLength) {
+		System.out.println("setLocalPeriod");
+	}
 
-    float getMaximum(HolonElement ele) {
-    	System.out.println("getMaximum");
-        if (ele.isFlexible()) {
-            return ele.getFlexibleEnergyAvailablePerElement();
-        } else {
-            return ele.getEnergyPerElement();
-        }
-    }
-    
-    /**
-     * sets the localPeriod of the Current Graph
-     * @param localPeriod
-     */
-    public void setLocalPeriod(int localPeriod){
-    	System.out.println("setLocalPeriod");
-    	if(isElement)for(IGraphedElement e:tempElements)e.setLocalPeriod(localPeriod);
-    	else if(isSwitch)current.setLocalPeriod(localPeriod);
-    }
-    
-    /**
-     * gets the LocalPeriod of the CurrentGraph
-     * @return localPeriod of the current Element or Switch
-     */
-    public int getLocalPeriod(){
-    	System.out.println("getLocalPeriod");
-    	if(current!=null)return current.getLocalPeriod();
-    	else return model.getGraphIterations();//TODO: maybe rename
-    }
-    
-    public boolean isStretching(){
-    	System.out.println("isStretching");
-    	return current.isStretching();
-    }
-    
-    public void setStretching(boolean b){
-    	System.out.println("setStretching");
-    	if(isElement)for(IGraphedElement e:tempElements)e.setStretching(b);
-    	else if(isSwitch)current.setStretching(b);
-    }
-    
+	public void repaintGraph(AbstractCpsObject cps) {
+		// TODO Auto-generated method stub
+		System.out.println("repaintGraph");
+	}
+   
     
 
 }