813f06dd4bb01a2116d69d597e6ed175baec4098
[Mograsim.git] / plugins / net.mograsim.logic.model / src / net / mograsim / logic / model / model / wires / ModelWire.java
1 package net.mograsim.logic.model.model.wires;
2
3 import static net.mograsim.logic.model.preferences.RenderPreferences.DEFAULT_LINE_WIDTH;
4 import static net.mograsim.logic.model.preferences.RenderPreferences.WIRE_WIDTH_MULTIBIT;
5 import static net.mograsim.logic.model.preferences.RenderPreferences.WIRE_WIDTH_SINGLEBIT;
6
7 import java.util.ArrayList;
8 import java.util.Arrays;
9 import java.util.List;
10 import java.util.function.Consumer;
11
12 import org.eclipse.swt.SWT;
13
14 import net.haspamelodica.swt.helper.gcs.GeneralGC;
15 import net.haspamelodica.swt.helper.swtobjectwrappers.Point;
16 import net.haspamelodica.swt.helper.swtobjectwrappers.Rectangle;
17 import net.mograsim.logic.core.LogicObserver;
18 import net.mograsim.logic.core.types.BitVector;
19 import net.mograsim.logic.core.wires.CoreWire;
20 import net.mograsim.logic.core.wires.CoreWire.ReadEnd;
21 import net.mograsim.logic.model.BitVectorFormatter;
22 import net.mograsim.logic.model.model.LogicModelModifiable;
23 import net.mograsim.logic.model.preferences.RenderPreferences;
24 import net.mograsim.preferences.ColorDefinition;
25 import net.mograsim.preferences.ColorManager;
26
27 /**
28  * A wire connecting exactly two {@link Pin}s.
29  * 
30  * @author Daniel Kirschten
31  */
32 public class ModelWire
33 {
34         /**
35          * The model this wire is a part of.
36          */
37         private final LogicModelModifiable model;
38         /**
39          * The name of this wire. Is unique for all wires in its model.
40          */
41         public final String name;
42         /**
43          * The logical width of this wire. Is equal to the logical width of {@link #pin1} and {@link #pin2}.
44          */
45         public final int logicWidth;
46         /**
47          * The {@link Pin} on one side of this wire, usually the signal source.
48          */
49         private Pin pin1;
50         /**
51          * The {@link Pin} on one side of this wire, usually the signal target.
52          */
53         private Pin pin2;
54         /**
55          * The user-defined path between {@link #pin1} and {@link #pin2}.<br>
56          * Special cases: <code>null</code> means "choose an interpolation as fits", and an empty array means "direct connection without any
57          * interpolation".
58          */
59         private Point[] path;
60         /**
61          * The bounds of this wire, excluding line width (and line joins, if the line join is {@link SWT#JOIN_MITER})
62          */
63         private final Rectangle bounds;
64         /**
65          * The effective path of this wire, including automatic interpolation and the position of both {@link Pin}s. Is never null.
66          */
67         private double[] effectivePath;
68
69         private final List<Consumer<ModelWire>> pathChangedListeners;
70
71         /**
72          * A LogicObserver calling redrawListeners. Used for core model bindings.
73          */
74         private final LogicObserver logicObs;
75         /**
76          * A ReadEnd of the core wire this model wire currently is bound to.
77          */
78         private ReadEnd end;
79
80         // creation and destruction
81
82         /**
83          * Creates a new {@link ModelWire} with automatic interpolation and using the default name.
84          * 
85          * @author Daniel Kirschten
86          */
87         public ModelWire(LogicModelModifiable model, ModelWireCrossPoint pin1, ModelWireCrossPoint pin2)
88         {
89                 this(model, null, pin1, pin2);
90         }
91
92         /**
93          * Creates a new {@link ModelWire} with automatic interpolation and using the default name.
94          * 
95          * @author Daniel Kirschten
96          */
97         public ModelWire(LogicModelModifiable model, ModelWireCrossPoint pin1, Pin pin2)
98         {
99                 this(model, null, pin1, pin2);
100         }
101
102         /**
103          * Creates a new {@link ModelWire} with automatic interpolation and using the default name.
104          * 
105          * @author Daniel Kirschten
106          */
107         public ModelWire(LogicModelModifiable model, Pin pin1, ModelWireCrossPoint pin2)
108         {
109                 this(model, null, pin1, pin2);
110         }
111
112         /**
113          * Creates a new {@link ModelWire} with automatic interpolation and using the default name.
114          * 
115          * @author Daniel Kirschten
116          */
117         public ModelWire(LogicModelModifiable model, Pin pin1, Pin pin2)
118         {
119                 this(model, null, pin1, pin2);
120         }
121
122         /**
123          * Creates a new {@link ModelWire} without automatic interpolation and using the default name.
124          * 
125          * @author Daniel Kirschten
126          */
127         public ModelWire(LogicModelModifiable model, ModelWireCrossPoint pin1, ModelWireCrossPoint pin2, Point... path)
128         {
129                 this(model, null, pin1, pin2, path);
130         }
131
132         /**
133          * Creates a new {@link ModelWire} without automatic interpolation and using the default name.
134          * 
135          * @author Daniel Kirschten
136          */
137         public ModelWire(LogicModelModifiable model, ModelWireCrossPoint pin1, Pin pin2, Point... path)
138         {
139                 this(model, null, pin1, pin2, path);
140         }
141
142         /**
143          * Creates a new {@link ModelWire} without automatic interpolation and using the default name.
144          * 
145          * @author Daniel Kirschten
146          */
147         public ModelWire(LogicModelModifiable model, Pin pin1, ModelWireCrossPoint pin2, Point... path)
148         {
149                 this(model, null, pin1, pin2, path);
150         }
151
152         /**
153          * Creates a new {@link ModelWire} without automatic interpolation and using the default name.
154          * 
155          * @author Daniel Kirschten
156          */
157         public ModelWire(LogicModelModifiable model, Pin pin1, Pin pin2, Point... path)
158         {
159                 this(model, null, pin1, pin2, path);
160         }
161
162         /**
163          * Creates a new {@link ModelWire} with automatic interpolation.
164          * 
165          * @author Daniel Kirschten
166          */
167         public ModelWire(LogicModelModifiable model, String name, ModelWireCrossPoint pin1, ModelWireCrossPoint pin2)
168         {
169                 this(model, name, pin1, pin2, (Point[]) null);
170         }
171
172         /**
173          * Creates a new {@link ModelWire} with automatic interpolation.
174          * 
175          * @author Daniel Kirschten
176          */
177         public ModelWire(LogicModelModifiable model, String name, ModelWireCrossPoint pin1, Pin pin2)
178         {
179                 this(model, name, pin1, pin2, (Point[]) null);
180         }
181
182         /**
183          * Creates a new {@link ModelWire} with automatic interpolation.
184          * 
185          * @author Daniel Kirschten
186          */
187         public ModelWire(LogicModelModifiable model, String name, Pin pin1, ModelWireCrossPoint pin2)
188         {
189                 this(model, name, pin1, pin2, (Point[]) null);
190         }
191
192         /**
193          * Creates a new {@link ModelWire} with automatic interpolation.
194          * 
195          * @author Daniel Kirschten
196          */
197         public ModelWire(LogicModelModifiable model, String name, Pin pin1, Pin pin2)
198         {
199                 this(model, name, pin1, pin2, (Point[]) null);
200         }
201
202         /**
203          * Creates a new {@link ModelWire} without automatic interpolation.
204          * 
205          * @author Daniel Kirschten
206          */
207         public ModelWire(LogicModelModifiable model, String name, ModelWireCrossPoint pin1, ModelWireCrossPoint pin2, Point... path)
208         {
209                 this(model, name, pin1.getPin(), pin2.getPin(), path);
210         }
211
212         /**
213          * Creates a new {@link ModelWire} without automatic interpolation.
214          * 
215          * @author Daniel Kirschten
216          */
217         public ModelWire(LogicModelModifiable model, String name, ModelWireCrossPoint pin1, Pin pin2, Point... path)
218         {
219                 this(model, name, pin1.getPin(), pin2, path);
220         }
221
222         /**
223          * Creates a new {@link ModelWire} without automatic interpolation.
224          * 
225          * @author Daniel Kirschten
226          */
227         public ModelWire(LogicModelModifiable model, String name, Pin pin1, ModelWireCrossPoint pin2, Point... path)
228         {
229                 this(model, name, pin1, pin2.getPin(), path);
230         }
231
232         /**
233          * Creates a new {@link ModelWire} without automatic interpolation.
234          * 
235          * @author Daniel Kirschten
236          */
237         public ModelWire(LogicModelModifiable model, String name, Pin pin1, Pin pin2, Point... path)
238         {
239                 this.model = model;
240                 this.name = name == null ? model.getDefaultWireName() : name;
241                 this.logicWidth = pin1.logicWidth;
242                 if (pin2.logicWidth != pin1.logicWidth)
243                         throw new IllegalArgumentException("Can't connect pins of different logic width");
244
245                 this.pin1 = pin1;
246                 this.pin2 = pin2;
247
248                 this.path = path == null ? null : Arrays.copyOf(path, path.length);
249                 this.bounds = new Rectangle(0, 0, -1, -1);
250
251                 pathChangedListeners = new ArrayList<>();
252
253                 logicObs = (i) -> model.requestRedraw();
254
255                 pin1.addPinMovedListener(p -> pinMoved());
256                 pin2.addPinMovedListener(p -> pinMoved());
257
258                 recalculateEffectivePath();
259
260                 model.wireCreated(this, this::destroyed);
261         }
262
263         /**
264          * Destroys this wire. This method is called from {@link LogicModelModifiable#wireDestroyed(ModelWire) wireDestroyed()} of the model
265          * this wire is a part of.
266          * 
267          * @author Daniel Kirschten
268          */
269         private void destroyed()
270         {
271                 // nothing to do
272         }
273
274         // pins
275
276         /**
277          * Returns the {@link Pin} on one side of this wire, usually the signal source.
278          * 
279          * @author Daniel Kirschten
280          */
281         public Pin getPin1()
282         {
283                 return pin1;
284         }
285
286         /**
287          * Returns the {@link Pin} on one side of this wire, usually the signal target.
288          * 
289          * @author Daniel Kirschten
290          */
291         public Pin getPin2()
292         {
293                 return pin2;
294         }
295
296         /**
297          * Called when {@link #pin1} or {@link #pin2} were moved.
298          * 
299          * @author Daniel Kirschten
300          */
301         private void pinMoved()
302         {
303                 recalculateEffectivePath();
304                 model.requestRedraw();
305         }
306
307         // "graphical" operations
308
309         /**
310          * Recalculates {@link #effectivePath} "from scratch". Also updates {@link #bounds}.
311          * 
312          * @author Daniel Kirschten
313          */
314         private void recalculateEffectivePath()
315         {
316                 Point pos1 = pin1.getPos(), pos2 = pin2.getPos();
317
318                 double boundsX1 = Math.min(pos1.x, pos2.x);
319                 double boundsY1 = Math.min(pos1.y, pos2.y);
320                 double boundsX2 = Math.max(pos1.x, pos2.x);
321                 double boundsY2 = Math.max(pos1.y, pos2.y);
322
323                 if (path == null)
324                         effectivePath = new double[] { pos1.x, pos1.y, (pos1.x + pos2.x) / 2, pos1.y, (pos1.x + pos2.x) / 2, pos2.y, pos2.x, pos2.y };
325                 else
326                 {
327                         effectivePath = new double[path.length * 2 + 4];
328                         effectivePath[0] = pos1.x;
329                         effectivePath[1] = pos1.y;
330                         for (int srcI = 0, dstI = 2; srcI < path.length; srcI++, dstI += 2)
331                         {
332                                 double pathX = path[srcI].x;
333                                 double pathY = path[srcI].y;
334                                 effectivePath[dstI + 0] = pathX;
335                                 effectivePath[dstI + 1] = pathY;
336                                 if (pathX < boundsX1)
337                                         boundsX1 = pathX;
338                                 if (pathX > boundsX2)
339                                         boundsX2 = pathX;
340                                 if (pathY < boundsY1)
341                                         boundsY1 = pathY;
342                                 if (pathY > boundsY2)
343                                         boundsY2 = pathY;
344                         }
345                         effectivePath[effectivePath.length - 2] = pos2.x;
346                         effectivePath[effectivePath.length - 1] = pos2.y;
347                 }
348
349                 bounds.x = boundsX1;
350                 bounds.y = boundsY1;
351                 bounds.width = boundsX2 - boundsX1;
352                 bounds.height = boundsY2 - boundsY1;
353         }
354
355         /**
356          * Returns the bounds of this wire, excluding line width (and line joins, if the line join is {@link SWT#JOIN_MITER})
357          * 
358          * @author Daniel Kirschten
359          */
360         public Rectangle getBounds()
361         {
362                 return new Rectangle(bounds.x, bounds.y, bounds.width, bounds.height);
363         }
364
365         /**
366          * Render this wire to the given gc, in absoulute coordinates.
367          * 
368          * @author Daniel Kirschten
369          */
370         public void render(GeneralGC gc, RenderPreferences renderPrefs)
371         {
372                 ColorDefinition wireColor = BitVectorFormatter.formatAsColor(renderPrefs, end);
373                 if (wireColor != null)
374                         gc.setForeground(ColorManager.current().toColor(wireColor));
375                 gc.setLineWidth(renderPrefs.getDouble(logicWidth == 1 ? WIRE_WIDTH_SINGLEBIT : WIRE_WIDTH_MULTIBIT));
376                 gc.drawPolyline(effectivePath);
377                 gc.setLineWidth(renderPrefs.getDouble(DEFAULT_LINE_WIDTH));
378         }
379
380         // operations concerning the path
381
382         /**
383          * The user-defined path between {@link #pin1} and {@link #pin2}. Note that this is not neccessarily equal to the effective path drawn
384          * in {@link #render(GeneralGC)}.<br>
385          * Special cases: <code>null</code> means "choose an interpolation as fits", and an empty array means "direct connection without any
386          * interpolation".
387          * 
388          * @author Daniel Kirschten
389          */
390         public Point[] getPath()
391         {
392                 return deepPathCopy(path);
393         }
394
395         public void setPath(Point... path)
396         {
397                 this.path = deepPathCopy(path);
398                 recalculateEffectivePath();
399                 callPathChangedListeners();
400                 model.requestRedraw();
401         }
402
403         public Point getPathPoint(int index)
404         {
405                 return pointCopy(path[index]);
406         }
407
408         public void setPathPoint(Point p, int index)
409         {
410                 path[index] = pointCopy(p);
411                 recalculateEffectivePath();
412                 callPathChangedListeners();
413                 model.requestRedraw();
414         }
415
416         public void insertPathPoint(Point p, int index)
417         {
418                 if (path == null)
419                         path = new Point[] { pointCopy(p) };
420                 else
421                 {
422                         Point[] oldPath = path;
423                         path = new Point[oldPath.length + 1];
424                         System.arraycopy(oldPath, 0, path, 0, index);
425                         if (index < oldPath.length)
426                                 System.arraycopy(oldPath, index, path, index + 1, oldPath.length - index);
427                         path[index] = pointCopy(p);
428                 }
429                 recalculateEffectivePath();
430                 callPathChangedListeners();
431         }
432
433         public void removePathPoint(int index)
434         {
435                 if (path.length == 0)
436                         path = null;
437                 else
438                 {
439                         Point[] oldPath = path;
440                         path = new Point[oldPath.length - 1];
441                         System.arraycopy(oldPath, 0, path, 0, index);
442                         if (index < oldPath.length - 1)
443                                 System.arraycopy(oldPath, index + 1, path, index, oldPath.length - index - 1);
444                 }
445                 recalculateEffectivePath();
446                 callPathChangedListeners();
447         }
448
449         public double[] getEffectivePath()
450         {
451                 return Arrays.copyOf(effectivePath, effectivePath.length);
452         }
453
454         private static Point[] deepPathCopy(Point[] path)
455         {
456                 if (path == null)
457                         return null;
458                 Point[] copy = new Point[path.length];
459                 for (int i = 0; i < path.length; i++)
460                         copy[i] = pointCopy(path[i]);
461                 return copy;
462         }
463
464         private static Point pointCopy(Point p)
465         {
466                 return new Point(p.x, p.y);
467         }
468
469         // core model binding
470
471         /**
472          * Binds this {@link ModelWire} to the given {@link ReadEnd}: The color of this {@link ModelWire} will now depend on the state of the
473          * given {@link ReadEnd}, and further changes of the given {@link ReadEnd} will result in readrawListeners being called.<br>
474          * The argument can be null, in which case the old binding is stopped.
475          * 
476          * @author Daniel Kirschten
477          */
478         public void setCoreModelBinding(ReadEnd end)
479         {
480                 if (this.end != null)
481                         this.end.deregisterObserver(logicObs);
482                 this.end = end;
483                 if (end != null)
484                         end.registerObserver(logicObs);
485         }
486
487         /**
488          * Returns whether this {@link ModelWire} has a core model binding or not.
489          * 
490          * @author Daniel Kirschten
491          */
492         public boolean hasCoreModelBinding()
493         {
494                 return end != null;
495         }
496
497         /**
498          * If this {@link ModelWire} has a core model binding, delegates to {@link CoreWire#forceValues(BitVector)} for the {@link CoreWire}
499          * corresponding to this {@link ModelWire}.
500          * 
501          * @author Daniel Kirschten
502          */
503         public void forceWireValues(BitVector values)
504         {
505                 end.getWire().forceValues(values);
506         }
507
508         /**
509          * If this {@link ModelWire} has a core model binding, delegates to {@link ReadEnd#getValues()} for the {@link ReadEnd} corresponding to
510          * this {@link ModelWire}.
511          * 
512          * @author Daniel Kirschten
513          */
514         public BitVector getWireValues()
515         {
516                 return end.getValues();
517         }
518
519         /**
520          * Registers the given {@link LogicObserver} for the {@link ReadEnd} this {@link ModelWire} is bound to.
521          * 
522          * @see ReadEnd#registerObserver(LogicObserver)
523          * @author Daniel Kirschten
524          */
525         public void addObserver(LogicObserver obs)
526         {
527                 end.registerObserver(obs);
528         }
529
530         /**
531          * Deregisters the given {@link LogicObserver} for the {@link ReadEnd} this {@link ModelWire} is bound to.
532          * 
533          * @see ReadEnd#deregisterObserver(LogicObserver)
534          * @author Daniel Kirschten
535          */
536         public void removeObserver(LogicObserver obs)
537         {
538                 end.deregisterObserver(obs);
539         }
540
541         // listeners
542
543         // @formatter:off
544         public void addPathChangedListener   (Consumer<ModelWire> listener) {pathChangedListeners.add    (listener);}
545
546         public void removePathChangedListener(Consumer<ModelWire> listener) {pathChangedListeners.remove(listener);}
547
548         private void callPathChangedListeners() {pathChangedListeners.forEach(l -> l.accept(this));}
549         // @formatter:on
550
551         @Override
552         public String toString()
553         {
554                 return "ModelWire [" + pin1 + "---" + pin2 + ", value=" + (end == null ? "null" : end.getValues()) + "]";
555         }
556 }