-
Notifications
You must be signed in to change notification settings - Fork 1
/
neural_nets.js
1696 lines (1358 loc) · 42.8 KB
/
neural_nets.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
// Created by Justin Meiners
// LICENSE GPL v2.0
// SIMULATION
// ------------------------
var INPUT_EXCITE = 0;
var INPUT_INHIBIT = 1;
function Cell(i) {
this.index = i;
this.inputs = [];
this.inputTypes = [];
this.outputs = [];
this.threshold = 1;
}
function Label(i) {
this.text = "";
this.index = i;
}
function Fiber(i) {
this.index = i;
this.from = null;
this.to = null;
}
function Branch(i) {
this.index = i;
this.input = null;
this.outputs = [];
}
function Net() {
this.cells = [];
this.fibers = [];
this.branches = [];
this.labels = [];
}
function visitFibers(fiber, f) {
var b;
var i;
// apply function
f(fiber);
// if its connected to a branch
// we need to visit the other fibers
if (fiber.to instanceof Branch) {
b = fiber.to;
for (i = 0; i < b.outputs.length; ++i) {
visitFibers(b.outputs[i], f);
}
}
}
function sendSignals(net, state) {
var i, j;
var firing;
var cell;
var fiber;
var signals = [];
var fiberVisitor = function(fiber) {
signals[fiber.index] = true;
};
// send signals from cells to fibers
for (i = 0; i < net.cells.length; ++i) {
firing = state[i];
if (firing) {
cell = net.cells[i];
for (j = 0; j < cell.outputs.length; ++j) {
fiber = cell.outputs[j];
visitFibers(fiber, fiberVisitor);
}
}
}
return signals;
}
function applySignals(net, state, signals) {
var i, j;
var newState = [];
var cell;
var inputFiber;
var inputType;
var activated;
var inhibited;
// mark which cells are firing
for (i = 0; i < net.cells.length; ++i) {
cell = net.cells[i];
// count up activated
// and check for inhibit
activated = 0;
inhibited = false;
for (j = 0; j < cell.inputs.length; ++j) {
inputFiber = cell.inputs[j];
inputType = cell.inputTypes[j];
if (signals[inputFiber.index]) {
if (inputType === INPUT_INHIBIT) {
inhibited = true;
break;
} else {
++activated;
}
}
}
// ignore inhibited cells
if (!inhibited && activated >= cell.threshold) {
// fire this cell
newState[i] = true;
}
}
return newState;
}
// VIEW
// ------------------------
function Vec(x, y) {
this.x = x;
this.y = y;
}
Vec.prototype.lenSqr = function() {
return this.x * this.x + this.y * this.y;
};
Vec.prototype.len = function() {
return Math.sqrt(this.lenSqr());
};
Vec.prototype.inBounds = function(min, max) {
return this.x >= min.x && this.y >= min.y &&
this.x <= max.x && this.y <= max.y;
};
Vec.prototype.inCircle = function(o, r) {
return Vec.distSqr(this, o) < r * r;
};
Vec.prototype.add = function(b) {
this.x += b.x;
this.y += b.y;
return this;
};
Vec.add = function(a, b) {
return new Vec(a.x + b.x, a.y + b.y);
};
Vec.sub = function(a, b) {
return new Vec(a.x - b.x, a.y - b.y);
};
Vec.scale = function(a, s) {
return new Vec(a.x * s, a.y * s);
};
Vec.distSqr = function(a, b) {
return Vec.sub(a, b).lenSqr();
};
Vec.dist = function(a, b) {
return Math.sqrt(Vec.distSqr(a, b));
};
Vec.min = function(a, b) {
return new Vec(Math.min(a.x, b.x), Math.min(a.y, b.y));
};
Vec.max = function(a, b) {
return new Vec(Math.max(a.x, b.x), Math.max(a.y, b.y));
};
Vec.dot = function(a, b) {
return a.x * b.x + a.y * b.y;
};
Vec.bezier = function(t, p1, cp1, cp2, p2) {
var tInv = 1.0 - t;
var a = Vec.scale(p1, tInv * tInv * tInv);
var b = Vec.scale(cp1, 3.0 * tInv * tInv * t);
var c = Vec.scale(cp2, 3.0 * tInv * t * t);
var d = Vec.scale(p2, t * t * t);
return Vec.add(a, Vec.add(b, Vec.add(c, d)));
};
var ANGLE_EAST = 0;
var ANGLE_WEST = 1;
Vec.fromAngle = function(angle) {
if (angle === ANGLE_EAST) {
return new Vec(1.0, 0.0);
} else if (angle === ANGLE_WEST) {
return new Vec(-1.0, 0.0);
} else {
return new Vec(0.0, 0.0);
}
};
function CellView(i) {
Cell.call(this, i);
this.pos = new Vec(0, 0);
this.angle = ANGLE_EAST;
}
CellView.radius = 15.0;
CellView.prototype = Object.create(Cell.prototype);
CellView.prototype.constructor = CellView;
CellView.prototype.radius = CellView.radius;
CellView.prototype.connectorPadding = 11.0;
CellView.prototype.hits = function(p) {
return p.inCircle(this.pos, this.radius);
};
CellView.prototype.hitsConnectors = function(p) {
var OUTSIDE_PADDING = 6;
return p.inCircle(this.pos, this.radius + this.connectorPadding + OUTSIDE_PADDING);
};
CellView.prototype.isPositionOnOutputSide = function(mousePos) {
var dir = Vec.sub(mousePos, this.pos);
return Vec.dot(dir, Vec.fromAngle(this.angle)) > 0.0;
}
function LabelView(i) {
Label.call(this, i);
this.pos = new Vec(0,0);
}
LabelView.prototype.bounds = function(fontsize) {
var width = this.text.length * fontsize;
var height = fontsize;
var pad = 2;
return {
min: new Vec(this.pos.x - width / 2.0 - pad, this.pos.y - height / 2.0 - pad),
max: new Vec(this.pos.x + width / 2.0 + pad, this.pos.y + height / 2.0 + pad)
}
};
LabelView.prototype.hits = function(mousePos, fontsize) {
var bounds = this.bounds(fontsize);
return mousePos.inBounds(bounds.min, bounds.max);
}
function FiberView(i) {
Fiber.call(this, i);
// don't set this.
// Its driven by the inputTypes
// on cell
this.outputIndex = -1;
// cache of
// bezier curve points
// [p0, cp0, cp1, p1]
this.bezierPoints = new Array(4);
}
FiberView.prototype = Object.create(Fiber.prototype);
// ATTEMPT 1: minimize distance between curve and point
// I did the math for this one.
// It is relatively easy to get the derivative of
// D(t) = || B(t) - q ||^2
// however actually minimizing that
// requires solving a cubic polynomial
// and I don't want to mess around with Newton's method.
// ATTEMPT 2: Use isPointInStroke
// Maintaining the ctx state is awkward.
// It also doesn't seem to account for lineWidth
// correctly so its not very usable
// ATTEMPT 3: Chop the bezier curve into line segments
// and minimize the distance along each line.
FiberView.prototype.hits = function(q) {
var p = this.bezierPoints;
// early rejection
// with a bounding box
var min = p.reduce(Vec.min);
var max = p.reduce(Vec.max);
if (!q.inBounds(min, max)) {
return false;
}
// number of segments
var N = 50;
// collision radius
// around path
var r = 9.0;
// cache this
var rSqr = r * r;
var x0 = p[0];
var x1;
var t;
// l: vector in direction of line segment
// d: delta from x0 to q
// c: component of delta on l
var l;
var d;
var c;
for (var i = 1; i <= N; ++i) {
t = i / N;
// line segment from x0 to x1 along the path
x1 = Vec.bezier(t, p[0], p[1], p[2], p[3]);
l = Vec.sub(x1, x0);
d = Vec.sub(q, x0);
// project delta onto seg
// two Inv sqrt :(
c = Vec.scale(l, Vec.dot(l, d) / (l.len() * d.len()));
// subtract projection
// check if below distance
if (Vec.sub(d, c).lenSqr() < rSqr) {
return true;
}
// save previous point
x0 = x1;
}
return false;
};
function BranchView() {
Branch.call(this);
this.pos = new Vec(0, 0);
}
BranchView.prototype = Object.create(Branch.prototype);
BranchView.prototype.constructor = BranchView;
BranchView.prototype.radius = 5.0;
function NetView() {
Net.call(this);
// since the NetView
// is the visual component
// we will store the state here
// even though the underlying
// structure is immutable over time
this.state = [];
this.signals = [];
this.time = 0;
}
NetView.prototype = Object.create(Net.prototype);
NetView.prototype.constructor = NetView;
NetView.prototype.step = function() {
var newState = applySignals(this, this.state, this.signals);
var nextSignals = sendSignals(this, newState, this.signals);
this.state = newState;
this.signals = nextSignals;
++this.time;
};
NetView.prototype.restart = function() {
this.state = [];
this.signals = [];
this.time = 0;
};
NetView.prototype.addTextLabel = function() {
var label = new LabelView(this.labels.length);
this.labels.push(label);
return label;
};
NetView.prototype.removeLabel = function(toDelete) {
var last = this.labels.pop();
if (last !== toDelete) {
this.labels[toDelete.index] = last;
last.index = toDelete.index;
}
};
NetView.prototype.addCell = function() {
var cell = new CellView(this.cells.length);
this.cells.push(cell);
return cell;
};
NetView.prototype.removeCell = function(toDelete) {
// detach all fibers
//
// slicing is to make sure
// the array isn't modified underneath us
toDelete.inputs.slice().forEach(this.removeFiber.bind(this));
toDelete.outputs.slice().forEach(this.removeFiber.bind(this));
// algorithm Ryan thought up
// 1. when you delete an item
// there is one unused index.
// (at the slot you deleted.)
// 2. set the last cells index
// to the available one.
// 3. Shrink the array length by one
var last = this.cells.pop();
if (last !== toDelete) {
this.cells[toDelete.index] = last;
last.index = toDelete.index;
}
// now toDelete is no good
};
NetView.prototype.addFiber = function(from, to) {
var fiber = new FiberView(this.fibers.length);
fiber.from = from;
fiber.to = to;
this.fibers.push(fiber);
return fiber;
};
NetView.prototype.removeFiber = function(toDelete) {
var i;
// remove from "from" outputs
i = toDelete.from.outputs.indexOf(toDelete);
toDelete.from.outputs.splice(i, 1);
// remove from "to" inputs
i = toDelete.to.inputs.indexOf(toDelete);
toDelete.to.inputs.splice(i, 1);
toDelete.to.inputTypes.splice(i, 1);
// see removeCell
var last = this.fibers.pop();
if (last !== toDelete) {
this.fibers[toDelete.index] = last;
last.index = toDelete.index;
}
};
NetView.prototype.addBranch = function() {
var branch = new BranchView();
this.branches.push(branch);
return branch;
};
// SERIALIZATION
// =====================
var SERIALIZATION_VERSION = 2;
var SERIALIZATION_SUCCESS = true;
var SERIALIZATION_INVALID_BASE64 = -1;
var SERIALIZATION_INVALID_LENGTH = -2;
var SERIALIZATION_INVALID_VERSION = -3;
NetView.prototype.save = function() {
var d = [];
var i, j;
function write(val) {
d.push(val);
}
// add a placeholder for the data length
write(0);
write(SERIALIZATION_VERSION);
write(this.cells.length);
write(this.fibers.length);
write(this.labels.length);
for (i = 0; i < this.cells.length; ++i) {
var cell = this.cells[i];
write(cell.pos.x);
write(cell.pos.y);
write(cell.threshold);
write(cell.angle);
write(cell.inputs.length);
for (j = 0; j < cell.inputs.length; ++j) {
write(cell.inputs[j].index);
write(cell.inputTypes[j] === INPUT_INHIBIT ? INPUT_INHIBIT : INPUT_EXCITE);
}
write(cell.outputs.length);
for (j = 0; j < cell.outputs.length; ++j) {
write(cell.outputs[j].index);
}
}
for (i = 0; i < this.fibers.length; ++i) {
var fiber = this.fibers[i];
write(fiber.from.index);
write(fiber.to.index);
}
for (i = 0; i < this.labels.length; ++i) {
var label = this.labels[i];
write(label.pos.x);
write(label.pos.y);
write(label.text.length);
}
this.labels.forEach(function(l) {
for (i = 0; i < l.text.length; ++i) {
write(l.text.charCodeAt(i));
}
});
// prefix the data with the number of bytes so that load can detect malformed data
d[0] = d.length * 2;
var arr16 = new Uint16Array(d);
var arr8 = new Uint8Array(arr16.buffer);
var str = String.fromCharCode.apply(null, arr8);
return btoa(str);
};
NetView.prototype.load = function(base64) {
var str;
var i, j;
var cell;
var fiber;
var label;
try {
str = atob(base64);
} catch (e) {
return SERIALIZATION_INVALID_BASE64;
}
var arr8 = new Uint8Array(str.length);
for (i = 0; i < str.length; ++i) {
arr8[i] = str.charCodeAt(i);
}
var d = new Uint16Array(arr8.buffer);
var cursor = -1;
function read() {
return d[++cursor];
}
function readBlock(length) {
var x = d.slice(cursor + 1, cursor + 1 + length);
cursor += length;
return x;
}
if (read() !== d.length * 2) {
return SERIALIZATION_INVALID_LENGTH;
}
var version = read();
if (version < 1 || version > SERIALIZATION_VERSION) {
return SERIALIZATION_INVALID_VERSION;
}
this.cells = new Array(read());
this.fibers = new Array(read());
for (i = 0; i < this.cells.length; ++i) {
this.cells[i] = new CellView(i);
}
for (i = 0; i < this.fibers.length; ++i) {
this.fibers[i] = new FiberView(i);
}
if (version > 1) {
this.labels = new Array(read());
for (i = 0; i < this.labels.length; ++i) {
this.labels[i] = new LabelView(i);
}
}
for (i = 0; i < this.cells.length; ++i) {
cell = this.cells[i];
cell.pos.x = read();
cell.pos.y = read();
cell.threshold = read();
cell.angle = read();
cell.inputs = new Array(read());
for (j = 0; j < cell.inputs.length; ++j) {
cell.inputs[j] = this.fibers[read()];
cell.inputTypes[j] = read();
}
cell.outputs = new Array(read());
for (j = 0; j < cell.outputs.length; ++j) {
cell.outputs[j] = this.fibers[read()];
}
}
for (i = 0; i < this.fibers.length; ++i) {
fiber = this.fibers[i];
fiber.from = this.cells[read()];
fiber.to = this.cells[read()];
}
if (version > 1) {
var textLengths = [];
for (i = 0; i < this.labels.length; ++i) {
label = this.labels[i];
label.pos.x = read();
label.pos.y = read();
textLengths.push(read());
}
for (i = 0; i < textLengths.length; ++i) {
var characters = readBlock(textLengths[i]);
this.labels[i].text = String.fromCharCode.apply(null, characters);
}
}
return SERIALIZATION_SUCCESS;
};
function messageForSerializationError(error) {
switch (error) {
case SERIALIZATION_SUCCESS:
return null;
case SERIALIZATION_INVALID_BASE64:
return 'Could not load net. Failed to base64 decode.';
case SERIALIZATION_INVALID_LENGTH:
return 'Could not load net. Incorrect checksum or length.';
case SERIALIZATION_INVALID_VERSION:
return 'Could not load net. Unsupported serialization version.';
default:
return 'Could not load net. Unexpected serialization error.';
}
}
// TOOLS
// =====================
function SelectTool(sim, e) {
this.dragInitial = sim.mousePos;
this.sim = sim;
}
SelectTool.prototype.mouseUp = function(e) {
var min = Vec.min(this.dragInitial, this.sim.mousePos);
var max = Vec.max(this.dragInitial, this.sim.mousePos);
var all = this.sim.net.cells.concat(this.sim.net.labels);
this.sim.selection = all.filter(function (obj) {
return obj.pos.inBounds(min, max);
});
};
function MoveTool(sim, e) {
this.sim = sim;
this.initial = this.sim.mousePos;
this.previous = this.sim.mousePos;
}
MoveTool.prototype.mouseMove = function(e) {
var i;
var object;
var delta = Vec.sub(this.sim.mousePos, this.previous);
for (i = 0; i < this.sim.selection.length; ++i) {
object = this.sim.selection[i];
object.pos.add(delta);
}
this.previous = this.sim.mousePos;
};
MoveTool.prototype.mouseUp = function(e) {
};
MoveTool.prototype.cancel = function() {
var i;
var object;
var invDelta = Vec.sub(this.initial, this.sim.mousePos);
for (i = 0; i < this.sim.selection.length; ++i) {
object = this.sim.selection[i];
object.pos.add(invDelta);
}
};
function CreateTool(sim, e) {
var menu = document.getElementById('new-menu');
this.menu = menu;
this.menu.style.left = e.pageX + 'px';
this.menu.style.top = e.pageY + 'px';
this.menu.classList.add('active');
this.menu.onclick = function(e) {
var action;
var added;
var canvasLoc = sim.mousePos;
if (e.target.matches('li')) {
action = e.target.getAttribute('data-action');
if (action === 'new-cell') {
added = sim.net.addCell();
added.pos = canvasLoc;
} else if (action === 'new-branch') {
added = sim.net.addBranch();
added.pos = canvasLoc;
} else if (action == 'new-label') {
added = sim.net.addTextLabel();
added.pos = canvasLoc;
sim.editLabelText(added);
}
menu.classList.remove('active');
}
};
}
CreateTool.prototype.mouseUp = function(e) {
this.cancel();
};
CreateTool.prototype.cancel = function() {
this.menu.classList.remove('active');
};
function EditTextTool(sim, text, callback) {
this.input = EditTextTool.createTextInputElement(sim);
this.input.value = text;
this.input.focus();
this.input.select();
this.input.addEventListener("keyup", (function(e) {
if (e.key === 'Enter' || e.key === 'Return') {
this.input.blur();
callback(e.target.value);
} else if (e.key == 'Escape') {
this.input.blur();
}
}).bind(this));
this.input.addEventListener("focusout", this.cancel.bind(this));
}
EditTextTool.prototype.cancel = function() {
this.input.remove();
};
EditTextTool.createTextInputElement = function(sim){
var dom = document.createElement("INPUT");
dom.setAttribute("type", "text");
dom.style.position = "absolute";
var rect = sim.canvas.getBoundingClientRect();
dom.style.top = (sim.mousePos.y + rect.top).toString() + "px";
dom.style.left = (sim.mousePos.x + rect.left).toString() + "px";
document.body.appendChild(dom);
return dom;
};
function EditLabelTool(sim, e, label){
var menu = document.getElementById('label-menu');
this.menu = menu;
this.menu.style.left = e.pageX + 'px';
this.menu.style.top = e.pageY + 'px';
this.menu.classList.add('active');
this.menu.onclick = function(e) {
var action;
if(e.target.matches('li')){
action = e.target.getAttribute('data-action');
if (action === 'edit'){
sim.editLabelText(label);
} else if (action === 'delete') {
sim.net.removeLabel(label);
}
}
menu.classList.remove('active');
}
this.input = null;
}
EditLabelTool.prototype.mouseUp = function(e) {
this.cancel();
};
EditLabelTool.prototype.cancel = function() {
this.menu.classList.remove('active');
};
function EditCellTool(sim, e, obj) {
var menu = document.getElementById('cell-menu');
this.obj = obj;
this.menu = menu;
this.menu.style.left = e.pageX + 'px';
this.menu.style.top = e.pageY + 'px';
this.menu.classList.add('active');
this.menu.onclick = function(e) {
var action;
if (e.target.matches('li')) {
action = e.target.getAttribute('data-action');
if (action === 'delete') {
// delete selected cells
sim.deleteSelection();
} else if (action === 'flip') {
sim.selection.forEach(function(fiber) {
if (fiber.angle === ANGLE_EAST) {
fiber.angle = ANGLE_WEST;
} else {
fiber.angle = ANGLE_EAST;
}
});
}
}
menu.classList.remove('active');
};
}
EditCellTool.prototype.mouseUp = function(e) {
this.cancel();
};
EditCellTool.prototype.cancel = function() {
this.menu.classList.remove('active');
};
function EditFiberTool(sim, e, obj) {
var inputType;
var menu = document.getElementById('fiber-menu');
this.obj = obj;
this.menu = menu;
this.menu.style.left = e.pageX + 'px';
this.menu.style.top = e.pageY + 'px';
this.menu.classList.add('active');
this.menu.onclick = function(e) {
var action;
if (e.target.matches('li')) {
action = e.target.getAttribute('data-action');
if (action === 'delete') {
sim.net.removeFiber(obj);
} else if (action === 'toggle') {
// find index in cell
if (obj.to.inputTypes[obj.outputIndex] === INPUT_INHIBIT) {
inputType = INPUT_EXCITE;
} else {
inputType = INPUT_INHIBIT;
}
obj.to.inputTypes[obj.outputIndex] = inputType;
}
}
menu.classList.remove('active');
};
}
EditFiberTool.prototype.mouseUp = function(e) {
this.cancel();
};
EditFiberTool.prototype.cancel = function() {
this.menu.classList.remove('active');
};
function FiberTool(sim, e, cell) {
this.sim = sim;
this.initial = this.sim.mousePos;
var dir = Vec.sub(this.sim.mousePos, cell.pos);
if (cell.isPositionOnOutputSide(this.sim.mousePos)) {
this.from = cell;
} else {
this.to = cell;
}
}
FiberTool.prototype.mouseUp = function(e) {
var mousePos = this.sim.mousePos;
var hit = this.sim.net.cells.find(function (cell) {
return cell.hitsConnectors(mousePos);
});
if (!hit) {
// didn't click anything
return;
}
if (this.from) {
this.to = hit;
} else {
this.from = hit;
}
if (this.from === this.to) {
// connecting to ourselves
// we need some distance to make sure this isn't
// an accidental click
if (Vec.sub(this.sim.mousePos, this.initial).lenSqr() <
CellView.radius * CellView.radius) {
return;
}
}
var f = this.sim.net.addFiber(this.from, this.to);
this.from.outputs.push(f);
this.to.inputs.push(f);
this.to.inputTypes.push(INPUT_EXCITE);
};
// WINDOW AND CONTEXT
// -------------------------
function getMousePos(canvas, e) {
var rect = canvas.getBoundingClientRect();
return new Vec(e.clientX - rect.left, e.clientY - rect.top);
}
var DefaultNet = "dgICAAgACAAGAEoB6QAAAAAAAQAFAAEAAwAAAAEABgASAmsAAQAAAAEAAAAAAAEAAgDqAbIAAQAAAAEAAQAAAAEAAwB6AtwAAwAAAAMAAgAAAAMAAAAHAAAAAQAEAAABLAEBAAEAAQAEAAAAAQAFAAcC8AABAAAAAQAGAAAAAQAHALwBLQIAAAAAAAAAAFgCFQIBAAAAAAAAAAAAAQAAAAIAAQADAAIAAwADAAQABAAAAAAABQAFAAMAAgIzACsA7gBlACQAxQDfAA4AfgGtAS0A8gHoASUA1ABOAR0AUwBlAGwAZQBjAHQAIABhAG4AZAAgAGQAcgBhAGcAIABuAGUAdQByAG8AbgBzACAAdwBpAHQAaAAgAHQAaABlACAAbABlAGYAdAAgAG0AbwB1AHMAZQBTAGUAdAAgAHQAaAByAGUAcwBoAG8AbABkACAAdwBpAHQAaAAgAG4AdQBtAGIAZQByACAAawBlAHkAcwAgACgAMAAtADkAKQAwACAAYQBsAHcAYQB5AHMAIABmAGkAcgBlAHMAUgBpAGcAaAB0ACAAYwBsAGkAYwBrACAAbwBuACAAZgBpAGIAZQByAHMAIABhAG4AZAAgAG4AZQB1AHIAbwBuAHMAIABmAG8AcgAgAG8AcAB0AGkAbwBuAHMAQwBsAGkAYwBrACAAYQBuAGQAIABkAHIAYQBnACAAZgBpAGIAZQByAHMAIABiAGUAdAB3AGUAZQBuACAAbgBlAHUAcgBvAG4AcwB1AG4AbABlAHMAcwAgAGkAdAAgAHIAZQBjAGUAaQB2AGUAcwAgAGEAbgAgAGkAbgBoAGkAYgBpAHQA";
function Sim() {
this.selection = [];
this.play = true;
this.mousePos = new Vec(0, 0);
this.fontsize = 14.0;
this.playBtn = document.getElementById('play-btn');
this.playBtn.onclick = this.togglePlay.bind(this);
this.stepBtn = document.getElementById('step-btn');
this.stepBtn.onclick = this.step.bind(this);
this.restartBtn = document.getElementById('restart-btn');
this.restartBtn.onclick = this.restart.bind(this);
this.timeDisplay = document.getElementById('time');
this.storageInput = document.getElementById('storage-input');
this.loadBtn = document.getElementById('load-btn');
this.loadBtn.onclick = this.load.bind(this);
this.saveBtn = document.getElementById('save-btn');
this.saveBtn.onclick = this.save.bind(this);
this.canvas = document.getElementById('main-canvas');
this.ctx = this.canvas.getContext('2d', { alpha: false });
this.canvas.onmousedown = this.mouseDown.bind(this);
this.canvas.onmouseup = this.mouseUp.bind(this);
this.canvas.onmousemove = this.mouseMove.bind(this);