-
Notifications
You must be signed in to change notification settings - Fork 2
/
Wikibinator203DirectedGraphUI.html
2128 lines (1939 loc) · 95.3 KB
/
Wikibinator203DirectedGraphUI.html
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
<!DOCTYPE html><html><head>
<meta charset="UTF-8">
<script src="Wikibinator203VM.js" charset="UTF-8"></script>
<script>
//This script is under the Wikibinator203 license.
//directed graph ui...
let U = Wikibinator203; //the universal function
let vm = Wikibinator203().vm;
//let S = vm.ops.S;
//let T = vm.ops.T;
//let F = vm.ops.F;
//let Pair = vm.ops.Pair;
if(!vm) throw 'No vm';
for(let op in vm.ops){
if(window[op]) throw 'Already have var window.'+op;
window[op] = vm.ops[op];
console.log('Created var for opcode as lambda: window.'+op);
}
var cssPositionType = 'absolute';
var randInt = n=>Math.floor(Math.random()*n);
var between = (min, val, max)=>Math.max(min, Math.min(val, max));
var betweenInt = (min, val, max)=>Math.floor(Math.max(min, Math.min(val, max)));
var asByte = num=>betweenInt(0,num,255);
var colorStr = function(redFraction, greenFraction, blueFraction){
let r = asByte(redFraction*256);
let g = asByte(greenFraction*256);
let b = asByte(blueFraction*256);
let s = '000000'+(r*65536+g*256+b).toString(16);
return '#'+s.substring(s.length-6);
};
var randColorStr = ()=>colorStr(.45+.55*Math.random(), .45+.55*Math.random(), .45+.55*Math.random());
var Dob = (parentDob,tag,optionalInnerHtml)=>{
let ret = document.createElement(tag);
if(parentDob) parentDob.appendChild(ret);
if(optionalInnerHtml) ret.innerHTML = optionalInnerHtml;
return ret;
};
var typeToPic = {
//TODO ls: which is oftel (R (L x)) for any x, and is other times just (L x),
//depending how it would normally e displayed in code strings (see "syntax type" syty etc).
l: 'pic/greenSawTooth.png', //left child
r: 'pic/blueSawTooth.png', //right child
s: 'pic/sSawTooth.png', //sCurryList aka {...} syntax. {a b c} means (S (S a b) c) aka {{a b} c}.
e: 'pic/redSawTooth.png', //evalsto
};
//from and to are UINOdes. type is (TODO choose an edge
var UIEdge = function(from, type, to){
//dom object, a div whose background shows direction like saw teeth, and css is used to make it a line at an angle between 2 UINodes.
this.dob = null;
this.from = from;
this.type = type;
this.from.outs[type] = this;
this.to = to;
this.display();
};
var angle = 0;
var edgeBackgroundOffset = 0;
var displayUiedges = true;
//var displayUiedges = false;
UIEdge.prototype.display = function(){
if(!displayUiedges) return;
if(!this.dob){
let parentDob = mainDiv;
//let parentDob = document.body;
//let parentDob = this.from.dob;
//if(!parentDob) throw 'UINode hasnt displayed yet so cant display edge from it, this='+this;
//this.dob = Dob(parentDob,'div'); //put edge's div it in the div of the UINode its from.
this.dob = Dob(parentDob,'div');
this.dob.style.position = cssPositionType;
//this.dob.style.height = '50px';
//this.dob.style.width = '13px';
//this.dob.style.width = '5px';
//this.dob.style.width = '2px';
//this.dob.style.height = '154px';
//TODO css for angle
//this.dob.style['background-color'] = randColorStr();
this.dob.style.background = 'url('+typeToPic[this.type]+')';
this.dob.style['z-index'] = -1;
}
//https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/matrix
let diffY = this.to.pos[0]-this.from.pos[0];
let diffX = this.to.pos[1]-this.from.pos[1];
let diffLen = Math.hypot(diffY,diffX);
this.dob.style.height = '2px';
this.dob.style.width = Math.ceil(diffLen)+'px';
let normY = between(-1,diffY/diffLen,1);
let normX = between(-1,diffX/diffLen,1);
//let angle = Math.asin(normY);
let a = normX;
let b = normY;
let c = -normY;
let d = normX;
//let a = 1/Math.sqrt(2), b = 0, c = 0, d = 1/Math.sqrt(2);
//let a = 1, b = 0, c = 0, d = 1;
//let a = Math.sin(angle), b = Math.cos(angle), c = -Math.cos(angle), d = Math.sin(angle);
//this.dob.style.width = '90px';
//let a = -1, b = 0, c = 0, d = -1;
//let a = 5, b = 0, c = 0, d = 5;
/*let a = 1;
let b = 2.1;//let b = .3;
let c = 0; //let c = -.1;
let d = 1;
*/
//let tx = 0;
//let ty = 0;
//midpoint cuz [style.transform matrix or matrix3d] uses center of dob as (0,0,0) instead of top left corner as usual in html and as usual in opengl and other 3d frameworks.
//let ty = this.from.pos[0]+diffY/2;
//let tx = this.from.pos[1]+diffX/2;
let ty = (this.from.pos[0]+this.to.pos[0])/2;
let tx = (this.from.pos[1]+this.to.pos[1])/2;
//let ty = this.from.pos[0];
//let tx = this.from.pos[1];
//let ty = this.to.pos[0];
//let tx = this.to.pos[1];
tx -= diffLen/2; //without this, it appears to the right of where it should be, in some strange coordinate system that rotates around the middle of a div, or something.
//a = diffY*.01;
//d = diffX*.01;
//if(this.type == 'l'){ ty += 20; tx += 20; }
//if(this.type == 'r'){ ty += 35; tx += 35; }
//if(this.type == 'e'){ ty += 50; tx += 50; }
this.dob.style.transform = 'matrix('+a+','+b+','+c+','+d+','+tx+','+ty+')';
//this.dob.style.transform = 'matrix3d('+a+','+b+',0,0, '+c+','+d+',0,0, 0,0,1,0, '+tx+','+ty+',0,1)';
this.dob.style['background-position'] = edgeBackgroundOffset+'px';
};
var Rnd = ()=>Math.random();
//var countTemp = 0;
let countUINodes = 0;
var repelMult = 3;
var farAttractMult = 125;
var speedDecay = .85;
var pushParentAboveChild = 22.3;
var pushLToBeLeftOfRRegardlessOfHeight = 30;
var getEdges = function(){
let ret = [];
for(let node of nodes){
for(let edgeType in node.outs){
let edge = node.outs[edgeType];
ret.push(edge);
}
}
return ret;
};
//from is l. to is r. todo rename those vars.
var potentialEnergyOfLR = (yFrom, xFrom, sizeFrom, yTo, xTo, sizeTo)=>{
let en = 0;
//let dy = yTo-yFrom;
let dx = xTo-xFrom;
let repelDist = sizeFrom+sizeTo;
//let distSq = dy*dy + dx*dx;
//let dist = Math.sqrt(distSq);
if(dx < repelDist){
let diff = repelDist-dx;
en += diff*diff*pushLToBeLeftOfRRegardlessOfHeight;
}
return en;
};
var potentialEnergyOfPairOfNodesForRepel = (yFrom, xFrom, sizeFrom, yTo, xTo, sizeTo)=>{
let en = 0;
let dy = yTo-yFrom;
let dx = xTo-xFrom;
//let distSq = dy*dy + dx*dx;
//let dist = Math.sqrt(distSq);
let dist = Math.hypot(dy,dx);
let repelDist = sizeFrom+sizeTo;
if(dist < repelDist){
let diff = repelDist-dist;
en += diff*diff*repelMult;
}
return en;
};
/** This is used for spring-like positioning of uinodes on screen.
y and x are screen positions. nodeTypes are what kind of icon it is, such as evaling vs this kind of list [...] etc.
edgeType is 'l' for left child, 'r' for right child, 'e' for evals to what, etc.
Sizes are approx radius, even though radius doesnt describe a rectangle well, it will tend to give things more or less space on screen.
FIXME should this be called even if there is no edge? cuz they could overlap otherwise.
*/
var potentialEnergyOfEdge = (yFrom, xFrom, sizeFrom, fromType, edgeType, toType, yTo, xTo, sizeTo)=>{
let en = 0;
let dy = yTo-yFrom;
let dx = xTo-xFrom;
//let distSq = dy*dy + dx*dx;
//let dist = Math.sqrt(distSq);
let dist = Math.hypot(dy,dx);
let repelDist = sizeFrom+sizeTo;
/*do this in potentialEnergyOfPairOfNodesForRepel instead...
if(dist < repelDist){
let diff = repelDist-dist;
en += diff*diff*repelMult;
}*/
if(pushParentAboveChild){ //can set pushParentAboveChild to 0 as an optimiziation to not do this code
let diff = dy-repelDist;
if(diff < 0){
//child is near same height as parent or above parent.
//move child down and parent up, so the forest shape is more intuitively displayed.
en += diff*diff*pushParentAboveChild;
}
}
//TODO optimize, only do this part if edgeType is a kind that exists (have 1 kind that means "noEdge", but use a shorter name?)
en += dist*farAttractMult; //attract, but weaker than repelDist
//en += dist*dist*farAttractMult; //attract, but weaker than repelDist
return en;
};
const dims = 2;
var doPhysics = dt=>{
let edges = getEdges();
for(let edge of edges){ //edges attract and in some cases TODO try to be at certain angles and distances relative to eachother.
updateUinodeAccelsForEdge(dt,edge);
}
for(let i=1; i<nodes.length; i++){ //repel all pairs of nodes if closer than sum of their nodeA.size+nodeB.size
let ni = nodes[i];
for(let j=0; j<i; j++){ //all pairs of nodes, excluding self and self, and not again for the reverse pair
let nj = nodes[j];
updateUinodeAccelsForRepelPairIfTooClose(dt, ni, nj);
//updateUinodeAccelsForRepelPairIfTooClose(ni.pos[0], ni.pos[1], ni.size, nj.pos[0], nj.pos[1], nj.size);
}
}
for(let node of nodes){
//forces between childs of each node (all edge types) such as node.l and node.r
//but TODO also the other edge types
updateUinodeAccelsBetweenChildsOfNode(dt,node);
}
let minY = 0; //FIXME leave some room at top for textareas of code, buttons, etc.
let maxY = 1200; //FIXME what should this be?
let minX = 0;
let maxX = 900; //FIXME get from screen
for(let node of nodes){ //dont let nodes get too far from main area of screen.
let newY = between(minY, node.pos[0], maxY);
let newX = between(minX, node.pos[1], maxX);
if(node.pos[0] != newY){
node.pos[0] = newY;
node.vel[0] = 0; //if hit a wall, set velocity to 0
}
if(node.pos[1] != newX){
node.pos[1] = newX;
node.vel[1] = 0; //if hit a wall, set velocity to 0
}
}
let speedMul = between(0,1-dt*speedDecay,1);
for(let node of nodes){
for(let d=0; d<dims; d++){
node.vel[d] += node.accel[d]; //FIXME if put *dt here then dont *dt in updateUinodeAccelsForEdge.
node.accel[d] = 0;
node.vel[d] *= speedMul;
if(draggingNode == node){
node.vel[d] = 0; //dont move node by physics while mouse is dragging it
}
node.pos[d] += dt*node.vel[d];
}
}
};
/*
//potential-energy, to be measured +dy +dx and +0, for each end, and take derivatives so know which direction to accelerate,
//then put the x and y positions back.
var edgeEnergyFunc = edge=>{
return Math.random(); //FIXME
};
var updateUinodeAccels = function(){
TODO loop over all edges
};
*/
const epsilon = .000001;
var updateUinodeAccelsBetweenChildsOfNode = function(dt,node){
let halfEpsilon = epsilon/2;
let l = node.outs.l;
let r = node.outs.r;
if(l && r){
l = l.to; //change from edge to node
r = r.to;
let enAtHere = potentialEnergyOfLR(l.pos[0], l.pos[1], l.size, r.pos[0], r.pos[1], r.size);
let enAtHerePlusDy = potentialEnergyOfLR(l.pos[1]+halfEpsilon, l.pos[1], l.size, r.pos[0]-halfEpsilon, r.pos[1], r.size);
let enAtHerePlusDx = potentialEnergyOfLR(l.pos[0], l.pos[1]+halfEpsilon, l.size, r.pos[0], r.pos[1]-halfEpsilon, r.size);
let dEnergyOverDy = (enAtHerePlusDy-enAtHere)/epsilon;
let dEnergyOverDx = (enAtHerePlusDx-enAtHere)/epsilon;
let ay = dt*dEnergyOverDy/2; //FIXME is /2 right?
let ax = dt*dEnergyOverDx/2;
l.accel[0] -= ay;
l.accel[1] -= ax;
r.accel[0] += ay; //FIXME did i get the += and -= backward?
r.accel[1] += ax;
}
};
var updateUinodeAccelsForRepelPairIfTooClose = function(dt, nodeA, nodeB){
let halfEpsilon = epsilon/2;
let fr = nodeA;
let to = nodeB;
let enAtHere = potentialEnergyOfPairOfNodesForRepel(fr.pos[0], fr.pos[1], fr.size, to.pos[0], to.pos[1], to.size);
let enAtHerePlusDy = potentialEnergyOfPairOfNodesForRepel(fr.pos[0]+halfEpsilon, fr.pos[1], fr.size, to.pos[0]-halfEpsilon, to.pos[1], to.size);
let enAtHerePlusDx = potentialEnergyOfPairOfNodesForRepel(fr.pos[0], fr.pos[1]+halfEpsilon, fr.size, to.pos[0], to.pos[1]-halfEpsilon, to.size);
let dEnergyOverDy = (enAtHerePlusDy-enAtHere)/epsilon;
let dEnergyOverDx = (enAtHerePlusDx-enAtHere)/epsilon;
let ay = dt*dEnergyOverDy/2; //FIXME is /2 right?
let ax = dt*dEnergyOverDx/2;
fr.accel[0] -= ay;
fr.accel[1] -= ax;
to.accel[0] += ay; //FIXME did i get the += and -= backward?
to.accel[1] += ax;
/*
let dy = nodeB.pos[0]-nodeA.pos[0];
let dx = nodeB.pos[1]-nodeA.pos[1];
let distSq = dy*dy+dx*dx;
let maxDistToRepel = nodeA.size+nodeB.size;
let maxDistSqToRepel = maxDistToRepel*maxDistToRepel;
if(distSq < maxDistToRepel){
let dist = Math.sqrt(distSq);
let diff = maxDistToRepel-dist;
}
let halfEpsilon = epsilon/2;
*/
};
//dt is change in time (seconds).
var updateUinodeAccelsForEdge = function(dt, edge){
let halfEpsilon = epsilon/2;
let fr = edge.from;
let to = edge.to;
//var potentialEnergyOfEdge = (yFrom, xFrom, sizeFrom, fromType, edgeType, toType, yTo, xTo, sizeTo)=>{
let enAtHere = potentialEnergyOfEdge(fr.pos[0], fr.pos[1], fr.size, fr.type, edge.type, to.type, to.pos[0], to.pos[1], to.size);
let enAtHerePlusDy = potentialEnergyOfEdge(fr.pos[0]+halfEpsilon, fr.pos[1], fr.size, fr.type, edge.type, to.type, to.pos[0]-halfEpsilon, to.pos[1], to.size);
let enAtHerePlusDx = potentialEnergyOfEdge(fr.pos[0], fr.pos[1]+halfEpsilon, fr.size, fr.type, edge.type, to.type, to.pos[0], to.pos[1]-halfEpsilon, to.size);
let dEnergyOverDy = (enAtHerePlusDy-enAtHere)/epsilon;
let dEnergyOverDx = (enAtHerePlusDx-enAtHere)/epsilon;
let ay = dt*dEnergyOverDy/2; //FIXME is /2 right?
let ax = dt*dEnergyOverDx/2;
fr.accel[0] -= ay;
fr.accel[1] -= ax;
to.accel[0] += ay; //FIXME did i get the += and -= backward?
to.accel[1] += ax;
};
/*
var worldCenterY = 400;
let worldCenterX = 400;
let worldSoftRadius = 300; //how far from center nodes can be before they start being attracted to the center.
let worldSoftRadiusForce = 70; //tries to keep nodes in worldSoftRadius or not too far past it
*/
//fn is a wikibinator203 lambda.
//TODO this might instead be a "pointer into a Human mind", like a temporary mutable variable that sometimes generates fns (which are immutable),
//since Humans seem to need the ability to edit inside a code string without replacing their own thoughts about code outside that {...} or (...) or [...] block.
//Mutable stuff would be in UI only, not part of Wikibinator203 spec.
var UINode = function(fn){
countUINodes++;
//dom object, maybe a div. It may contain text (of parts of wikibinator203 code), canvas (pixels chosen by wikibinator203), or other UI parts.
this.dob = null;
this.type = 'TODO theres less than 20 node types, including leaf, float64, evaling, etc';
//this.size = 100; //similar to radius, but its actually a rectangle so that doesnt exactly describe it.
//this.size = 30;
//this.size = 50;
this.size = 45;
this.pos = [Rnd()*600, Rnd()*900]; //screen position
//this.pos = [Rnd()*500, Rnd()*500]; //screen position
//this.pos = [100, Rnd()*500]; //screen position
//this.pos = [100, 100]; //screen position
//this.pos = [100, countUINodes*400-300]; //screen position
//this.pos = [100+countUINodes*50, countUINodes*400-300]; //screen position
//this.pos = [countTemp+=100,0]; //FIXME
this.vel = [0, 0]; //change of this.pos per second
this.accel = [0, 0]; //change of this.vel per second. this is set by TODO some code that calls edgeEnergyFunc
this.fn = fn; //display this.fn.localName or vm.eval(...) but modified to limit how big a code string it can generate and leave some branches closed.
//this.edges = {};
this.outs = {}; //edges out. theres less than 10 edge types, and at most 1 of each kind, from fns anyways, but mindmap nodes (if i add those later) might have weighted edges and many of the same kind outward.
//this.ins = //can have many incoming edges.
fn.ui = this;
this.display();
if(!fn().isLeaf()){
//recurse to create UINodes in left and right childs. FIXME if theres alot of nodes, or if theres big bigstrings,
//this should be done sparsely instead, to only display parts that open/close when look deeper.
let lUI = uiOf(fn().l);
let rUI = uiOf(fn().r);
//FIXME display overlapping edges (from and to the same node) different by a few pixels side by side so one isnt hidden by the other.
new UIEdge(this,'l',lUI); //sets this.outs.l = lUI
new UIEdge(this,'r',rUI); //sets this.outs.r = rUI
if(fn().l().l == S){ //uses {...} syntax, the sCurryList syntax.
let to = fn().l().r;
let sUI = uiOf(to);
new UIEdge(this,'s',sUI); //sets this.outs.s = sUI
}
}
nodes.push(this);
let fnStr = ''+fn;
console.log('Created uinode nodes['+(nodes.length-1)+'] for fn: '+fnStr);
if(!fnStr){
//let fnStr2 = ''+fn;
throw 'Empty fnStr at nodes['+(nodes.length-1)+']';
}
};
UINode.prototype.width = function(){
if(!this.dob) return 1;
return this.dob.clientWidth;
};
UINode.prototype.height = function(){
if(!this.dob) return 1;
return this.dob.clientHeight;
};
UINode.prototype.display = function(){
if(!this.dob){
this.dob = Dob(mainDiv,'div',''+this.fn);
this.dob.style['user-select'] = 'none'; //prevent selecting node since selecting text in it interferes with dragging node
this.dob.style.color = 'black';
//this.dob = Dob(document.body,'div',''+this.fn);
this.dob.style.position = cssPositionType; //relative to mainDiv?
this.dob.style['background-color'] = randColorStr();
//this.dob.style.height = '30px';
//this.dob.style.height = '50px';
//this.dob.style.width = '200px';
//this.dob.style.width = '10px';
//this.dob.style.background = 'url(redSawTooth.png)';
}
//this.dob.style.top = Math.floor(this.pos[0])+'px';
//this.dob.style.left = Math.floor(this.pos[1])+'px';
let a = 1, b = 0, c = 0, d = 1;
let ty = this.pos[0];
let tx = this.pos[1];
this.dob.style.transform = 'matrix('+a+','+b+','+c+','+d+','+tx+','+ty+')';
//this.dob.style.transform = 'matrix3d('+a+','+b+',0,0, '+c+','+d+',0,0, 0,0,1,0, '+tx+','+ty+',0,1)';
for(key in this.outs){
this.outs[key].display(); //display edge from this UINode
}
};
var nodes = [];
var uiOf = function(fn){
if(fn.ui) return fn.ui; //store it in field in the lambda (or whatever it is).
if(vm.isLambda(fn)){
return new UINode(fn); //sets fn.ui to that
}else{
throw 'TODO wrap other kind of object, thats not a wikibinator203 lambda';
}
};
var edgeBackgroundOffset_speed = .4;
//directedGraph of UINodes
var nextState = ()=>{
angle += .01;
//edgeBackgroundOffset = (edgeBackgroundOffset+1)%32; //cuz pics are 1x32
edgeBackgroundOffset = (edgeBackgroundOffset+edgeBackgroundOffset_speed)%32; //cuz pics are 1x32
//uuUI.display(); //test
let dt = 1/60; //FIXME measure time instead of hardcoding this
doPhysics(1e-1);
for(let node of nodes){
node.display();
}
requestAnimationFrame(nextState);
};
//canvas
var lastTimeOf_doGraphicsDtAgeByterectAndMore = 0;
//var lastTimeOf_doGraphicsDtAgeByterectAndMore = time();
//canvas
var canv = null;
let canvH = 1024;
let canvW = canvH;
//canvas
var doGraphicsDtAgeByterectAndMore = function(){
if(canv == null){
canv = new FullScreenCanvas(document.body, canvH, canvW);
//TODO the canvas moved on page faster (same update speed per video frame, but its rectangle on scree) as 'fixed' than 'absolute'
canv.dom.style.position = 'fixed'; //relative to scroll position, always displayed nomatter where you scroll
//canv.dom.style.position = 'absolute';
canv.dom.style.left = '0px';
canv.dom.style.top = '0px';
//canv.dom.style.left = '470px';
//canv.dom.style.top = '270px';
canv.dom.style['z-index'] = -1000; //behind other stuff
}
//canv.resizeCanvas(window.innerHeight,window.innerWidth); //to screen size, if no params. change number of canvas pixels.
let scaleCanvY = window.innerHeight/canv.dom.height;
let scaleCanvX = window.innerWidth/canv.dom.width;
//let scaleCanvY = 1;
//let scaleCanvX = 1;
///canv.dom.style.left = (canv.dom.width/2)+'px';
//scaleCanvX = 4;
//console.log('scaleCanvX = '+scaleCanvX+' window.innerWidth='+window.innerWidth+' canv.dom.width='+canv.dom.width);
//canv.dom.style.transform = 'scale('+scaleCanvX+','+scaleCanvY+')'; //dont change number of canvas pixels. stretch it instead.
//canv.dom.style.transform = 'matrix('+scaleCanvX+',0,0,'+scaleCanvY+','+((window.innerWidth-canv.dom.width)/2)+','+((window.innerHeight-canv.dom.height)/2+window.scrollY)+')'; //dont change number of canvas pixels. stretch it instead.
//canv.dom.style.transform = 'matrix('+scaleCanvX+',0,0,'+scaleCanvY+','+(0)+','+(0)+')'; //dont change number of canvas pixels. stretch it instead.
canv.dom.style.transform = 'matrix('+scaleCanvX+',0,0,'+scaleCanvY+','+((window.innerWidth-canv.dom.width)/2)+','+((window.innerHeight-canv.dom.height)/2)+')'; //dont change number of canvas pixels. stretch it instead.
let now = time();
let age = now-timeStarted; //how many seconds ago did this page transition start?
let dt = Math.max(0, Math.min(now-lastTimeOf_doGraphicsDtAgeByterectAndMore, .2));
lastTimeOf_doGraphicsDtAgeByterectAndMore = now;
canv.beforePaint();
doGraphicsDtAgeByterect(dt, age, canv.byteRect);
canv.afterPaint();
//setTimeout(doGraphicsDtAgeByterectAndMore, 1);
//setTimeout(doGraphicsDtAgeByterectAndMore, 5);
requestAnimationFrame(doGraphicsDtAgeByterectAndMore); //TODO optimize, only update canvas if pixels changed. store pixels as a fn/lambda.
//setTimeout(doGraphicsDtAgeByterectAndMore, 30);
};
//canvas
var bootCanvas = ()=>{
console.log('bootCanvas');
doGraphicsDtAgeByterectAndMore();
};
//On-screen icon of the universal lambda, which you can dragAndDrop to make all possible lambdas,
//but will also make lambdas by evaling textarea and wrapping Float64Array etc.
var rootUI = null;
var mainDiv = null;
var uuUI = null;
window.onload = ()=>{
//mainDiv = Dob(document.body,'div');
mainDiv = document.getElementById('mainDiv');
mainDiv.style['background-color'] = 'gray';
dom('extraTests').innerHTML = vm.htmlForExtraTests();
rootUI = uiOf(U);
uuUI = uiOf(U(U));
//uiOf(U(U(U)));
console.log('rootUI = '+rootUI);
nextState();
bootCanvas();
};
///////end directed graph ui///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
</script>
<script>
var dom = id=>document.getElementById(id);
//var h = '';
/*
h += 'Wikibinator203='+Wikibinator203+' Push F12 to see some tests in browser console.';
h += '\n\n<br><br>In the ops list below, from vm.opInfo, you can use op name, such as S, T, Pair, (F U) is identityFunc, etc. Some ops arent working yet. More ops will be filled in later. This is early into the wikibinator203 prototype. Try it in the textareas. When you change text in the top textarea, it evals and puts the output into the bottom textarea, which you should be able to copy into the top textarea and edit more. This will be easier once these low level basics are worked out and you can do everything (TODO) by drag and drop across the internet with your friends in realtime.';
for(let op of vm.opInfo){
h += '\n\n<br><br>'+JSON.stringify(op);
}
*/
let prevOnload = window.onload;
window.onload = ()=>{
prevOnload();
//dom('mainDiv').innerHTML = h;
//let firstCode = '(S (F U) (F U) Pair)';
//let firstCode = '[(CallParamOnItself#(S I#(F U) I) Pair) (CallParamOnItself F)]';
//let firstCode = '[(CallParamOnItself#(S I#(F U) I) Pair) (CallParamOnItself F) CallParamOnItself]';
//let firstCode = '[(CallParamOnItself#(S I#(F U) I) (S こんにちは世界)) (CallParamOnItself F) CallParamOnItself]';
let firstCode =
`[
I#(F U)
Sqr#{(T *) I I}
Hypot#(
λ [x y]
[this is [a comment] with a function Sqr in it]
{
(T Sqrt)
{
(T +)
{(T Sqr) (P x)}
{(T Sqr) (P y)}
}
}
)
the hypotenuse of a right triangle of sides 6 and 8 is (Hypot 6 8) and that func is Hypot and as a 1 param func is (Hypot 6)
]`;
//let firstCode = '[(Pair (T T))]';
//let firstCode = '[the first half is (Typeval U (L (R Abc#こんにちは世界))) and the second half is (Typeval U (R (R Abc))) but that seems to have a problem with the padding]';
//let firstCode = '[(CallParamOnItself#(S I#(F U) I) (Pair こんにちは世界)) (CallParamOnItself F) CallParamOnItself]';
dom('codeIn').value = firstCode;
evalTextAreas();
};
//var displayDirectedGraphOfCodeInTextarea = false;
var displayDirectedGraphOfCodeInTextarea = true;
var evalTextAreas = ()=>{
vm.refill();
let throwE = null;
let textOut = 'ERROR';
try{
let wikibinator203CodeIn = dom('codeIn').value;
if(dom('isEvalElseOnlyParse').checked){
console.log('Eval');
let fnOut = Eval(wikibinator203CodeIn);
textOut = ''+fnOut;
if(displayDirectedGraphOfCodeInTextarea) uiOf(fnOut); //create it on screen, deeply all its l and r childs
}else{
console.log('Parse');
let parseTree = Parse(wikibinator203CodeIn)
textOut = ''+parseTree;
}
}catch(e){
throwE = e;
textOut = 'ERROR: '+e;
}
dom('codeOut').value = textOut;
if(throwE) throw throwE;
};
//of wikibinator203 code string -> fn. fn means a wikibinator203 lambda that is a javascript function of 1 param.
//var Eval = vm.eval;
var Eval = (wikibinator203CodeString,optionalNamespace)=>{
lastEval = vm.eval(wikibinator203CodeString,optionalNamespace);
console.log('set lastEval');
return lastEval;
};
var lastParseTree = null;
var lastEval = null;
var Parse = code=>(lastParseTree=vm.parse(code));
var mouseY = 0;
var mouseX = 0;
var dragOffsetY = 0;
var dragOffsetX = 0;
var draggingNode = null;
var nodeAtYXOrNull = (y,x)=>{
for(let node of nodes){
if(
node.pos[0] <= y
&& y < node.pos[0]+node.height()
&& node.pos[1] <= x
&& x < node.pos[1]+node.width()
){
if(1<=vm.loglev)console.log('nodeAtYXOrNull found '+node+' at y'+y+' x'+x);
return node;
}
}
return null;
};
var onMouseMove = event=>{
mouseY = event.pageY-(mainDiv.offsetTop+mainDiv.clientHeight);
mouseX = event.pageX-mainDiv.offsetLeft;
//mouseY = event.clientY-mainDiv.offsetTop;
//mouseX = event.clientX-mainDiv.offsetLeft;
//mouseY = event.offsetY-mainDiv.offsetTop;
//mouseX = event.offsetX-mainDiv.offsetLeft;
logMouseAndButtonsEtc();
if(draggingNode){
if(1<=vm.loglev)console.log('dragging '+draggingNode);
draggingNode.pos[0] = mouseY+dragOffsetY;
draggingNode.pos[1] = mouseX+dragOffsetX;
}
/*if(rootUI){
rootUI.pos[0] = mouseY; //just testing. fixme remove this
rootUI.pos[1] = mouseX;
}*/
};
var onMouseUp = event=>{
delete buttons[event.button];
//logMouseAndButtonsEtc();
draggingNode = null;
};
var onMouseDown = event=>{
buttons[event.button] = 1;
//logMouseAndButtonsEtc();
draggingNode = nodeAtYXOrNull(mouseY,mouseX);
if(draggingNode && dom('isEditCodeWhenClickGraphNodeBelow').checked){
console.log('Editing draggingNode='+draggingNode);
startEditingUinode(draggingNode);
}
};
var startEditingUinode = uinode=>{
dom('codeOut').value = '';
dom('codeIn').value = ''+uinode.fn;
};
var logMouseAndButtonsEtc = ()=>{
if(2<=vm.loglev)console.log('y'+mouseY+' x'+mouseX+' buttons='+JSON.stringify(buttons));
};
var buttons = {};
//The above script is under the Wikibinator203 license.
</script>
<script>
//Canvas and ByteRect code are opensource MIT licensed
//(parts from benrayfield's various other projects including https://jsfiddle.net/q687fcrk/1/ and
//https://github.com/benrayfield/smartblob/blob/master/data/smartblob/WebcamSeesBendableLoopAsGameControllerAjaxToServer.html )
//and some parts from https://github.com/benrayfield/jsutils/blob/master/src/arvox/arvox.html
var dom = id=>document.getElementById(id);
//byte offsets for ByteRect, canvas, etc, in js.
const RED = 0, GREEN = 1, BLUE = 2, ALPHA = 3;
var colorDimRed = RED;
var colorDimGreen = GREEN;
var colorDimBlue = BLUE;
var colorDimAlpha = ALPHA;
var FullScreenCanvas = function(parentDom, optionalHeight, optionalWidth){
if(parentDom === undefined) parentDom = document.body;
this.dom = document.createElement('canvas');
//TODO z order, in front of everything else.
//this.dom = document.getElementById('canv'); //FIXME remove this line, use createElement instead.
this.context = null;
this.imageData = null;
this.pixels = null;
this.byteRect = null;
parentDom.appendChild(this.dom);
if(!optionalHeight){ //full screen, positioned absolute, else it normally goes in a div
this.dom.style.position = 'absolute';
this.dom.style.left = '0px';
this.dom.style.top = '0px';
}
this.resizeCanvas = function(optionalHeight, optionalWidth){
if(this.dom.width != window.innerWidth) this.dom.width = (optionalWidth || window.innerWidth);
if(this.dom.height != window.innerHeight) this.dom.height = (optionalHeight || window.innerHeight);
};
//TODO optimize, if you're not reading from the canvas, maybe can skip parts of this or only call this once?
this.beforePaint = function(){
if(this.dom == null) throw 'No canvas';
this.context = this.dom.getContext('2d');
//console.log('this.dom.width = '+this.dom.width);
this.imageData = this.context.getImageData(0, 0, this.dom.width, this.dom.height);
this.pixels = this.imageData.data;
this.byteRect = new ByteRect(this.pixels, this.dom.height, this.dom.width);
};
//call this after modify byteRect.bytes which contains pixel colors to write to Canvas.
this.afterPaint = function(){
if(this.dom == null) throw 'No canvas';
//this.context.drawImage(this.dom, 0, 0, this.dom.width, this.dom.height);
this.context.putImageData(this.imageData, 0, 0);
};
this.removeFromScreen = function(){
this.dom.remove();
this.dom = null;
this.context = null;
this.imageData = null;
this.pixels = null;
this.byteRect = null;
};
this.resizeCanvas(optionalHeight, optionalWidth);
this.beforePaint();
};
var between = (min,val,max)=>Math.max(min,Math.min(val,max));
//readable and writable pixels as Uint8Array. A canvas is a kind of Uint8Array.
//Single pixel read and write funcs are slow unless you just do a few places.
//TODO Write horizontal lines of same color or 2 colors on end interpolating between,
//and these lines can be derived from triangle which has different color at each corner.
var ByteRect = function(bytes, height, width){
this.bytes = bytes;
this.height = height;
this.width = width;
};
//TODO choose [y x] vs [x y z scale] order. Swap y and x in ByteRect params order? aftrans is [x y z scale].
ByteRect.prototype.index = function(y, x, colorDim){
return (y*this.width+x)*4+colorDim;
};
ByteRect.prototype.read = function(y, x, colorDim){
return this.bytes[(y*this.width+x)*4+colorDim];
};
ByteRect.prototype.readSafe = function(y, x, colorDim){
return this.bytes[between(0,(y*this.width+x)*4+colorDim,this.bytes.length-1)];
};
ByteRect.prototype.write = function(y, x, colorDim, bright){
this.bytes[(y*this.width+x)*4+colorDim] = bright;
};
ByteRect.prototype.writeSafe = function(y, x, colorDim, bright){
this.bytes[between(0,(y*this.width+x)*4+colorDim,this.bytes.length-1)] = bright;
};
ByteRect.prototype.writeSafeRGBA = function(y, x, redByte, greenByte, blueByte, optionalAlphaByte){
if(optionalAlphaByte === undefined) optionalAlphaByte = 255; //visible
let index = between(0,(y*this.width+x)*4,this.bytes.length-4);
this.bytes[index+RED] = redByte;
this.bytes[index+GREEN] = greenByte;
this.bytes[index+BLUE] = blueByte;
this.bytes[index+ALPHA] = optionalAlphaByte;
};
ByteRect.prototype.atYXWriteRGB = function(y, x, redByte, greenByte, blueByte){
if(x < 0 || this.width <= x || y < 0 || this.height <= y) return;
let ind = (y*this.width+x)*4;
this.bytes[ind+RED] = redByte;
this.bytes[ind+GREEN] = greenByte;
this.bytes[ind+BLUE] = blueByte;
};
ByteRect.prototype.writeHoriz = function(y, fromX, toXExclusive, colorDim, fromBright, toBright){
var indexStart = this.index(y, fromX, colorDim);
var pixelSiz = toXExclusive-fromX;
var siz = pixelSiz*4;
var bright = fromBright;
var brightAdd = (toBright-fromBright)/pixelSiz;
for(var i=0; i<siz; i+=4){
bright += brightAdd;
this.bytes[indexStart+i] = Math.floor(bright) & 0xff;
}
};
//modifies this ByteRect
ByteRect.prototype.flipHorizontal = function(){
let bytes = this.bytes;
for(let y=0; y<this.height; y++){
let xMid = Math.floor(this.width/2);
let offsetA = y*this.width*4; //first byte index of first pixel in row
let offsetB = ((y+1)*this.width-1)*4; //first byte of last pixel in row
for(let x=0; x<xMid; x++){
for(let colorDim=0; colorDim<4; colorDim++){ //swap 2 pixels as 4 bytes each
let temp = bytes[offsetA+colorDim];
bytes[offsetA+colorDim] = bytes[offsetB+colorDim];
bytes[offsetB+colorDim] = temp;
}
offsetA += 4;
offsetB -= 4;
}
}
};
//modifies this ByteRect
ByteRect.prototype.flipVertical = function(){
let bytes = this.bytes;
for(let y=0; y<this.height/2; y++){
let oppY = this.height-1-y;
let len = this.width*4;
let offsetA = y*len;
let offsetB = oppY*len;
for(let i=0; i<len; i++){
let temp = bytes[offsetA+i];
bytes[offsetA+i] = bytes[offsetB+i];
bytes[offsetB+i] = temp;
}
}
};
ByteRect.prototype.verifySameSizeAs = function(byteRect){
if(!byteRect) throw 'Param ByteRect = '+byteRect;
if(this.height != byteRect.height) throw this.height+' == this.height != byteRect.height == '+byteRect.height;
if(this.width != byteRect.width) throw this.width+' == this.width != byteRect.width == '+byteRect.width;
};
/*
//returns a new ByteRect of given size
ByteRect.prototype.resize = function(newHeight, newWidth){
let newBytes = new Uint8Array(newHeight*newWidth*4);
let ret = new ByteRect(newBytes, newHeight, newWidth);
for(let newY=0; newY<newHeight; newY++){
//let oldYSmooth = newY*this.height/newHeight; //smooth for bilinear interpolation
let oldY = Math.floor(newY*this.height/newHeight);
for(let newX=0; newX<newWidth; newX++){
//let oldXSmooth = newX*this.width/newWidth;
//let oldXLow = Math.floor(oldXSmooth);
//let oldXHigh = Math.min();
let oldX = Math.floor(newX*this.width/newWidth);
//let oldIndex = (oldY*this.width+oldX)*4;
//let newIndex = (newY*newWidth+newX)*4;
//let oldIndex = this.index(oldY, oldX, colorDim);
//let newIndex = ret.index(newY, newX, colorDim);
for(let colorDim=0; colorDim<4; colorDim++){
ret.bytes[newIndex+colorDim] = this.bytes[oldIndex+colorDim];
}
}
}
return ret;
};*/
//returns a new ByteRect of given size
ByteRect.prototype.resize = function(newHeight, newWidth){
let newBytes = new Uint8Array(newHeight*newWidth*4);
let ret = new ByteRect(newBytes, newHeight, newWidth);
for(let newY=0; newY<newHeight; newY++){
let oldY = Math.floor(newY*this.height/newHeight);
for(let newX=0; newX<newWidth; newX++){
let oldX = Math.floor(newX*this.width/newWidth);
let oldIndex = (oldY*this.width+oldX)*4;
let newIndex = (newY*newWidth+newX)*4;
//let oldIndex = this.index(oldY, oldX, colorDim);
//let newIndex = ret.index(newY, newX, colorDim);
for(let colorDim=0; colorDim<4; colorDim++){
ret.bytes[newIndex+colorDim] = this.bytes[oldIndex+colorDim];
}
}
}
return ret;
};
ByteRect.prototype.paintLineYXYXRGB = function(fromY, fromX, toY, toX, redByte, greenByte, blueByte){
let diffY = toY-fromY;
let diffX = toX-fromX;
let len = Math.hypot(diffY, diffX);
let numPoints = Math.ceil(len*1.5);
for(let i=0; i<numPoints; i++){
//TODO optimize
let y = Math.round(fromY+diffY*i/numPoints);
let x = Math.round(fromX+diffX*i/numPoints);
this.atYXWriteRGB(y, x, redByte, greenByte, blueByte);
}
};
ByteRect.picDataUrlToByterect = function(dataUrl_or_url,asyncGetByteRect){
const img = document.createElement('img');
//img.crossOrigin = "Anonymous";
let func = function(event){
const canv = document.createElement('canvas');
canv.width = img.width;
canv.height = img.height;
document.body.appendChild(canv);
let cx = canv.getContext('2d');