-
Notifications
You must be signed in to change notification settings - Fork 0
/
a-cellular-automata.html
3053 lines (2309 loc) · 97.4 KB
/
a-cellular-automata.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 hidden lang="en">
<head>
<link rel="icon" href="data:,">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
<meta name="theme-color" content="transparent">
<meta name="format-detection" content="telephone=no">
<script>'use strict';
console.log(document.lastModified);
const launchedAt = performance.now();
/*
window.addEventListener('error', e => {
// TODO: tune in to delay until re-connected
// window.g_app.ws.send(e.error);
//e.preventDefault();
//e.stopPropagation();
window.console.error(e.error ? e.error.stack : e); //e.error.message, e.lineno, e.colno);
/* setTimeout(function () {
if (window.g_upstream.socket.readyState === 1) {
window.g_upstream.socket.send(e.error ? e.error.message : e.target + ' at ' + e.lineno + ':' + e.colno);
}
}, 5000); * /
}, true); */
document.cookie = 'abc';
window.g_app = { launchedAt, ws: new WebSocket('wss://demo.epicmeetapp.com/api/') };
window.g_app.ws.binaryType = 'arraybuffer';
</script>
<script type="module">
const app = window.g_app;
window.addEventListener('load', () => {
const s = window.document.createElement('script');
s.setAttribute('async', '');
s.setAttribute('id', 'REMOVE');
s.setAttribute('src', 'data:text/javascript;base64,d2luZG93LmdfYXBwLm1haW4oKTsKLy8jIHNvdXJjZVVSTD1odHRwczovL2RlbW8uY3Jvc3NwbGF0Zm9ybXVpLmNvbS8obG9hZHNwbGl0KQ==');
window.document.head.appendChild(s);
});
const socket = app.ws;
{ // UUID Generator
const lut = Array(256).fill().map((_, i) => (i < 16 ? '0' : '') + (i).toString(16));
const _ = app.uuid = {
random128: () => {
const dvals = new Uint32Array(4);
crypto.getRandomValues(dvals);
return dvals;
},
formatUuid: ([d0, d1, d2, d3]) =>
lut[d0 & 0xff] + lut[d0 >> 8 & 0xff] + lut[d0 >> 16 & 0xff] + lut[d0 >> 24 & 0xff] + '-' +
lut[d1 & 0xff] + lut[d1 >> 8 & 0xff] + '-' +
lut[d1 >> 16 & 0x0f | 0x40] + lut[d1 >> 24 & 0xff] + '-' +
lut[d2 & 0x3f | 0x80] + lut[d2 >> 8 & 0xff] + '-' +
lut[d2 >> 16 & 0xff] + lut[d2 >> 24 & 0xff] +
lut[d3 & 0xff] + lut[d3 >> 8 & 0xff] +
lut[d3 >> 16 & 0xff] + lut[d3 >> 24 & 0xff],
uuid: () => _.formatUuid(_.random128())
};
}
console.log(app.uuid, app.uuid.uuid(), app.uuid.lut, app.uuid.formatUuid, app.uuid.uuid);
app.runId = app.uuid.random128();
console.log(performance.now(), 'AppRunId: ', app.uuid.formatUuid(app.runId), location.hash);
if (location.hash) {
// Load state from server
} else {
// Generate new state from scratch
}
{ // Preserve WS events
const empty = new ArrayBuffer();
const wsEvents = app.wsEvents = {
close: [],
error: [],
message: [],
open: []
};
const preserveWsEvent = event => {
wsEvents[event.type].push(event);
// console.log(performance.now() - launchedAt, event);
/*if (event.data) {
self.postMessage({ at: performance.timeOrigin + performance.now(), safariAt: Date.now(), msg: event.data }, [event.data]);
} else {
self.postMessage({ at: performance.timeOrigin + performance.now(), safariAt: Date.now(), msg: event.type });
}*/
if (event.type === 'open') {
// socket.send(window.g_app.runId.buffer);
// Developer editor source code push if source hash is different
if (location.href.startsWith('file:///')) {
socket.send(['devCodePush', location.href,
document.documentElement.innerHTML]);
} else {
setInterval(() => socket.send(empty), 25000);
}
} else if (event.type === 'message') {
// const parsed = JSON.parse(event.data);
const commaPos = event.data.indexOf(',');
const msgId = event.data.substr(0, commaPos);
const msgBody = event.data.substr(commaPos + 1);
switch (msgId) {
case 'version':
const serverVer = msgBody;
if (document.documentElement.getAttribute('data-version') !== serverVer) {
// In client browser, refresh the page automatically
if (!location.href.startsWith('file:///')) {
//console.log('New version is available. Refresh page to see', serverVer);
location.reload(true);
}
}
}
}
}
socket.onclose = preserveWsEvent;
socket.onerror = preserveWsEvent;
socket.onmessage = preserveWsEvent;
socket.onopen = preserveWsEvent;
}
app.main = () => {
const s = window.document.getElementById('REMOVE');
document.head.removeChild(s);
const app = window.g_app;
app.panX = 0;
app.panY = 0;
const canvasElt = window.g_app.canvasElt = window.document.getElementById('0');
// Note that WebGL can only run on the main thread.
const webGlSettings = {
//depth: true,
//stencil: true,
depth: false,
stencil: false,
// When enabling CSS "transparency", please, avoid using
// any transparent colorful values, because of the composition browsers do is not natural.
// For example, if you want to achieve the effect of a blue optical filtering glass
// on top of a red object, expecting that the red object will become colored
// in the shades of very dark blue or black, it's not going to work in web browser,
// it will add the red color into the mix.
// For layers on top of standard controls (AR on top of live video)
// Because of the impossibility to control the blend function of
// the browser compositor, we do not support any value of transparency but 0 or 1.
// It also drops performance a little bit.
alpha: false,
// The remaining parameters should be fixed:
// We are not touching the default value, assuming it always 'true'
// (it's impossible to set it to 'false' on mobile Safari)
//premultipliedAlpha: false,
// Always false, because it makes pixel to become platform-dependent,
// and is not supported on all systems. And it is very expensive (10 times slower)
antialias: false,
// gl.clear() old or buggy WebGL Androids leads to garbage when this is false.
// We want maximum performance and optimal memory use.
preserveDrawingBuffer: false,
// WebGL is the only our chance
failIfMajorPerformanceCaveat: false,
// We manage the rendering frequency.
// Faster it'll be done, more battery will be saved.
powerPreference: 'high-performance',
desynchronized: true
};
const gl = app.gl = window.g_app.canvasElt.getContext('webgl', webGlSettings);
// Split script here so other microtasks can be run after a lenghty OpenGL init
setTimeout(() => {
// At start, window.document.activeElement equals null
// window.document.activeElement equals body starting from here
console.log('document.activeElement:', window.document.activeElement, window.document.hasFocus());
// Enabling drag and drop support
window.document.getElementById('0').addEventListener('dragover', e => {
e.preventDefault();
});
window.document.body.addEventListener('keyup', e => {
if (e.key === 'f') {
e.preventDefault();
e.stopPropagation();
const rfs = document.documentElement.requestFullscreen || document.documentElement.webkitRequestFullscreen;
if (rfs) {
rfs.apply(document.documentElement);
}
} else if (e.key === ' ') {
window.g_app.createAnotherRandomLattice();
}
}, true);
window.addEventListener('unload', () => {
window.g_app.canvasElt.parentElement.replaceChild(document.createElement('div'), window.g_app.canvasElt);
window.g_app = null;
// In mobile Safari, we have to call takeHeapSnapshot in order to unload WASM
if (console.takeHeapSnapshot) {
console.takeHeapSnapshot('unload');
}
console.log(performance.now(), 'unload');
}, true);
window.addEventListener('blur', e => {
console.log('blur', window.document.activeElement, window.document.hasFocus());
}, true);
window.addEventListener('focus', e => {
console.log('focus', window.document.activeElement, window.document.hasFocus());
}, true);
const getPoint = (e) => {
// TODO: update rect dynamically
const rect = window.g_app.canvasElt.getBoundingClientRect();
return { x: e.clientX - rect.left, y: e.clientY - rect.top };
}
let point = null;
window.addEventListener('touchstart', e => {
if (e.target === window.g_app.canvasElt || e.target === window.document.body || e.target === window.document.documentElement) {
point = getPoint(e.touches[0]);
e.stopPropagation();
e.preventDefault();
} else {
console.log(e);
}
}, { capture: true, passive: false });
window.addEventListener('touchmove', e => {
if (e.target === window.g_app.canvasElt || e.target === window.document.body || e.target === window.document.documentElement) {
const width = window.innerWidth;
const height = window.innerWidth;
const events = [...e.touches];//e.getCoalescedEvents();
events.forEach(ee => {
const new_point = getPoint(ee);
if (point) {
let start_x = point.x * window.devicePixelRatio; //(point.x / width) * 2 - 1;
let start_y = point.y * window.devicePixelRatio; //(point.y / height) * 2 - 1;
let end_x = new_point.x * window.devicePixelRatio; //(new_point.x / width) * 2 - 1;
let end_y = new_point.y * window.devicePixelRatio; //(new_point.y / height) * 2 - 1;
const dx = end_x - start_x;
const dy = end_y - start_y;
app.panX += dx;
app.panY += dy;
}
point = new_point;
});
/*
if (point) {
const gl = window.g_app.gl;
const width = window.innerWidth;
const height = window.innerWidth;
//console.log(e);
const events = [e.touches[0]];// e.getCoalescedEvents();
for (let nn in events) {
const e = events[nn];
//events.forEach((e) => {
const new_point = getPoint(e);
const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
let start_x = (point.x / width) * 2 - 1;
let start_y = (point.y / height) * 2 - 1;
let end_x = (new_point.x / width) * 2 - 1;;
let end_y = (new_point.y / height) * 2 - 1;;
//const dist = Math.sqrt((start_x - end_x) * (start_x - end_x) +
// (start_y - end_y) * (start_y - end_y));
const dx = end_x - start_x;
const dy = end_y - start_y;
end_x += dx * 8;
end_y += dy * 8;
start_x += dx * 5;
start_y += dy * 5;
const vertices = [
start_x, start_y, 0.0,
start_x + .01, start_y + .01, 0.0,
end_x, end_y, 0.0,
end_x + .01, end_y + .01, 0.0,
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices) , gl.DYNAMIC_DRAW);
//const pos_attr = gl.getAttribLocation(shader, "a_Position");
//gl.enableVertexAttribArray(pos_attr);
gl.vertexAttribPointer(window.g_app.pos_attr, 3, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
gl.deleteBuffer(buffer);
// gl.flush();
point = new_point;
}//);
}
*/
e.stopPropagation();
e.preventDefault();
} else {
console.log(e);
}
}, { capture: true, passive: false });
window.addEventListener('mouseup', e => {
// window.g_app.gpuCompute();
window.g_app.createAnotherRandomLattice();
});
window.addEventListener('touchend', e => {
if (e.target === window.g_app.canvasElt || e.target === window.document.body || e.target === window.document.documentElement) {
e.stopPropagation();
e.preventDefault();
// Note this must happen in this microtask,
// otherwise the keyboard won't appear
if (e.target === window.g_app.canvasElt) {
// editText();
// window.g_app.gpuCompute();
}
} else {
console.log(e);
}
}, { capture: true, passive: false });
const updateVisibleSizeInfo = (w, h) => {
window.document.documentElement.style.setProperty('--visible-width', w + 'px');
window.document.documentElement.style.setProperty('--visible-height', h + 'px');
};
app.clearGl = (visibleWidth) => {
return;
if (window.g_app.gl) {
const gl = window.g_app.gl;
gl.clearColor(0.9, 0.9, 0.9, 0.5);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.enable(gl.SCISSOR_TEST);
gl.scissor(0, 0, visibleWidth, 1);
gl.clearColor(1, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.disable(gl.SCISSOR_TEST);
gl.flush();
}
};
app.fitTextareaInVisibleViewport = (visibleHeight, visibleWidth = window.innerWidth) => {
window.g_app.canvasElt.setAttribute('height', window.devicePixelRatio * visibleHeight + 'px');
window.g_app.canvasElt.setAttribute('width', window.devicePixelRatio * visibleWidth + 'px');
window.g_app.canvasElt.style.height = visibleHeight + 'px';
window.g_app.canvasElt.style.width = visibleWidth + 'px';
updateVisibleSizeInfo(visibleWidth, visibleHeight);
window.g_app.clearGl(visibleWidth);
// The GLSL GPU layout engine will return the extents for the textarea
// depending on the size of the visible area (including even font sizes!)
if (window.g_app.textboxElt) {
textboxElt.style.height = visibleHeight + 'px';
textboxElt.style.minHeight = visibleHeight + 'px';
}
// These are only when the textarea is active!
// On blur these must return to their empty size values.
window.document.documentElement.className = 'with-virtual-keyboard';
if (window.g_app.textboxElt) {
textboxElt.style.width = visibleWidth + 'px';
}
};
// On iOS, it doing setup, so the promise will be resolved when it completes.
window.addEventListener('scroll', e => {
if (e.target !== window.document) {
return;
}
if (window.g_trackFocusHappens) {
window.g_trackFocusHappens = false;
// To keep everything visible inside of the viewport when typing:
window.g_app.canvasElt.style.transform = 'translate3d(0px, ' + window.document.scrollingElement.scrollTop + 'px, 0px)';
textboxElt.style.transform = 'translate3d(0px, 0px, 1px)';
let visibleHeight = (window.g_trackFocusHappensScreenBase || window.innerHeight) - window.document.scrollingElement.scrollTop;
if (window.innerHeight < visibleHeight) {
visibleHeight = window.innerHeight;
}
console.log('fitting in...', visibleHeight, window.document.scrollingElement.scrollTop, window.g_trackFocusHappensScreenBase);
window.g_trackFocusHappensScreenBase = 0;
window.g_app.fitTextareaInVisibleViewport(visibleHeight);
}
if (window.document.scrollingElement.scrollTop) {
console.log('restoring scroll pos...');
setTimeout(() => {
window.scrollTo(0, 0);
}, 300);
} else {
// To keep everything visible inside of the viewport when typing:
window.g_app.canvasElt.style.transform = 'translate3d(0px, 0px, 0px)';
textboxElt.style.transform = 'translate3d(0px, 0px, 1px)';
}
}, true);
// On Android, we can get actual height only after 'resize' event if keyboard was appeared on the page reload!
window.addEventListener('resize', () => {
setTimeout(() => {
window.g_app.fitTextareaInVisibleViewport(window.innerHeight);
}, 100);
//window.console.log(window.performance.now(), 'resize', window.innerHeight, window.document.scrollingElement.scrollHeight,
// window.innerWidth, window.document.scrollingElement.scrollWidth, window.orientation);
if (window.navigator.platform === 'iPhone' || window.navigator.platform === 'iPad') {
// Dismiss the virtual keyboard if any resize happens, otherwise it'll break the layout
if (window.g_app.textboxElt && !textboxElt.hidden) {
textboxElt.blur();
}
}
}, true);
window.addEventListener('orientationchange', () => {
//console.log('orientationchange', window.innerHeight, window.document.scrollingElement.scrollHeight,
// window.innerWidth, window.document.scrollingElement.scrollWidth, window.orientation);
if ((window.orientation === 0 || window.orientation === 180) && window.navigator.appVersion.indexOf('Android') !== -1) {
// On Android, when rotating back to portrait from landscape, it's necessary to put the width to the low size,
// otherwise Android will scale the viewport to the smaller size
window.g_app.fitTextareaInVisibleViewport(window.innerHeight, window.innerHeight);
} else {
window.g_app.fitTextareaInVisibleViewport(window.innerHeight);
}
}, true);
// MAIN APP CODE
// setTimeout() is necessary because on iOS window.innerHeight is bigger than visible area until the animation frame finishes
if (window.orientation && (window.orientation === -90 || window.orientation === 90)) {
// Only in landscape mode on iOS Safari,
// after the first requestAnimationFrame() and plus 10 milliseconds, Safari seems to report real
// visible area's height as window.innerHeight, and so we're ready to render the page!
window.setTimeout(() => updateVisibleSizeInfo(window.innerWidth, window.innerHeight), 10);
} else {
updateVisibleSizeInfo(window.innerWidth, window.innerHeight);
}
console.log(gl.getSupportedExtensions());
// Slow init!
//const glExtDer = (function f1 () { return gl.getExtension('OES_standard_derivatives'); // 99% on tablets
// })();
const glExtVao = (function f2 () { return gl.getExtension('OES_vertex_array_object'); // 95% on desktops
})();
const glExtBlendMinmax = (function f3 () { return gl.getExtension('EXT_blend_minmax'); // 95% on desktops, 98% on tablets, 99% on phones
})();
const glExtDebug = (function f4 () { return gl.getExtension('WEBGL_debug_renderer_info'); // 99% desktop and tablet
})();
// gl.hint(glExtDer.FRAGMENT_SHADER_DERIVATIVE_HINT_OES, gl.NICEST);
// Often there
const isUintIndex = (function f5 () { return gl.getExtension('OES_element_index_uint'); // 95% tablet, 97% phone, 99% desktop
})();
const glExtInstancedArrays = (function f6 () { return gl.getExtension('ANGLE_instanced_arrays'); // 93% tablet, 97% phone, 99% desktop
})();
// Not always there:
const glExtSrgb = (function f7 () { return gl.getExtension('EXT_sRGB'); // 71% desktop, 4% consoles, 89% tablets, 94% phones.
})();
// Exists on the most platforms (but not on low-end)
// NOTE: slow init!
//const glExtFloatIn = (function f8 () { return gl.getExtension('OES_texture_float'); // TRUE always on WebGL2
// })();
// console.log(glExtFloatIn);
/*
// Mining mode - only with
const glExtFloatOut = gl.getExtension('WEBGL_color_buffer_float'); //
const glExtDrawBuffers = gl.getExtension('WEBGL_draw_buffers'); // 86% Desktop & 100% Console, 2% phones
// Must be at least 8 for super-performant mode. (on popular WebGL2 systems, it can be 4).
// Might support the 8K or 16K texture and render buffer size. But mostly 4K. Sometimes the texture size is bigger than the rendersize (4K textures with 8K or 16K renderbuffer)
// Can have 32 texture image units instead of just 8 (or just 16 on WebGL2 with 4K texture sizes and 8K renderbuffer)
// Can have 4K uniform vectors
// Can have 32 varyings instead of 8
// Typically has WebGL2 support
console.log(glExtDrawBuffers.MAX_COLOR_ATTACHMENTS_WEBGL, glExtDrawBuffers.MAX_DRAW_BUFFERS_WEBGL, glExtFloatIn, glExtFloatOut);
const pixelss = new Uint8Array([
0, 10, 0, 255,
0, 10, 0, 255,
0, 10, 0, 255,
0, 10, 0, 255,
]);
const tx = [gl.createTexture(), gl.createTexture(), gl.createTexture(), gl.createTexture()];
for (let ii = 0; ii < 4; ++ii) {
gl.bindTexture(gl.TEXTURE_2D, tx[ii]);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 2, 2, 0, gl.RGBA, gl.UNSIGNED_BYTE, pixelss);
}
const fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, glExtDrawBuffers.COLOR_ATTACHMENT0_WEBGL, gl.TEXTURE_2D, tx[0], 0);
gl.framebufferTexture2D(gl.FRAMEBUFFER, glExtDrawBuffers.COLOR_ATTACHMENT1_WEBGL, gl.TEXTURE_2D, tx[1], 0);
gl.framebufferTexture2D(gl.FRAMEBUFFER, glExtDrawBuffers.COLOR_ATTACHMENT2_WEBGL, gl.TEXTURE_2D, tx[2], 0);
gl.framebufferTexture2D(gl.FRAMEBUFFER, glExtDrawBuffers.COLOR_ATTACHMENT3_WEBGL, gl.TEXTURE_2D, tx[3], 0);
glExtDrawBuffers.drawBuffersWEBGL([
glExtDrawBuffers.COLOR_ATTACHMENT0_WEBGL, // gl_FragData[0]
glExtDrawBuffers.COLOR_ATTACHMENT1_WEBGL, // gl_FragData[1]
glExtDrawBuffers.COLOR_ATTACHMENT2_WEBGL, // gl_FragData[2]
glExtDrawBuffers.COLOR_ATTACHMENT3_WEBGL // gl_FragData[3]
]);
*/
// Super-slow operation. Offload after a microtask processing. Attempt to pre-init.
// Only set on real changes.
// app.canvasElt.setAttribute('width', window.innerWidth + 'px');
// app.canvasElt.setAttribute('height', window.innerHeight + 'px');
// Excess area in bottom of the scrollable view (will require to scroll the page back to 0):
// const excessWindowHeightInTheBottom = window.document.scrollingElement.scrollHeight - window.innerHeight;
// To make canvas visible
window.document.documentElement.hidden = false;
window.document.body.hidden = false;
if (window.scrollY) {
window.scrollTo(0, 0);
}
app.clearGl(window.innerWidth);
const VERTEX_SHADER = `#version 100
precision highp float;
attribute vec2 aPos;
// varying vec4 vcolor;
void main() {
// vcolor = vec4(0.0, 1.0, 0.0, 1.0);
gl_Position = vec4(aPos.x, aPos.y, 0.0, 1.0);
}
`;
const nodeModelLoader = `
uniform sampler2D texture0;
uniform vec2 dataWidthAndHeight;
// A number from 1 to 6
uniform float uniformPhase;
struct SignalPart {
// Defines position of green arrow, Q1, and Q2 over remained 5 ports
// Assuming that red arrow is at the bottom
// 1 out of remained 5 by 1 of out of 6 arrangements of Q1 and Q2
// (they are not discriminated in the permutation)
// Number from 1 to 30
lowp float greenArrowPermutedWithQ1andQ2;
// Defines internal routing
lowp float takeQ1fromBifTrueElseFromA; // 1 out 2 (a bit)
lowp float takeQ2fromBifTrueElseFromA; // 1 out 2 (a bit)
};
struct NodeStatePacked {
// Orientation from 1 to 6
lowp float redArrow;
// The same number stored as 3 bits (optimization of access for packing)
lowp float redArrow0;
lowp float redArrow1;
lowp float redArrow2;
SignalPart signalPart;
SignalPart signalInsideOfGreenArrow;
// Doesn't switch instantly (0 or 1)
lowp float greenArrowSignalAge;
// One of these two might be empty
SignalPart signalGoingToQ1;
SignalPart signalGoingToQ2;
};
struct Bitset4_of_5_1_1_1 {
lowp vec4 bits0to4;
lowp vec4 bit5;
lowp vec4 bit6;
lowp vec4 bit7;
};
vec4 whenGt (vec4 l, vec4 r) {
return max(sign(l - r), 0.0);
}
vec3 whenLt (vec3 l, vec3 r) {
return max(sign(r - l), 0.0);
}
float whenGt (float l, float r) {
return max(sign(l - r), 0.0);
}
float whenLt (float l, float r) {
return max(sign(r - l), 0.0);
}
float whenGtOrEq (float l, float r) {
return 1.0 - whenLt(l, r);
}
float whenLtOrEq(float l, float r) {
return 1.0 - whenGt(l, r);
}
float allVec4 (vec4 c) {
return c.x * c.y * c.z * c.w;
}
float allVec3 (vec3 c) {
return c.x * c.y * c.z;
}
float gpuOr(float x, float y) {
return min(x + y, 1.0);
}
Bitset4_of_5_1_1_1 unpack4Bytes (vec4 byte) {
Bitset4_of_5_1_1_1 result;
result.bit7 = whenGt(byte, vec4(127.5));
vec4 bits0to6 = byte - 128.0 * result.bit7;
result.bit6 = whenGt(bits0to6, vec4(63.5));
vec4 bits0to5 = bits0to6 - 64.0 * result.bit6;
result.bit5 = whenGt(bits0to5, vec4(31.5));
result.bits0to4 = bits0to5 - 32.0 * result.bit5;
return result;
}
// Each vector component is a number from 0 to 255
NodeStatePacked extractNodeStateFromVector (vec4 data) {
Bitset4_of_5_1_1_1 bytes = unpack4Bytes(data);
NodeStatePacked state;
// Minimum maximally packed number of states =
// = 6 * 30 * 2 * 2 * 30 * 2 * 2 * 30 * 2 * 2 * 30 * 2 * 2
// = 0..0x4A285FFF (1.2 billion combinations)
// The remainder single bit is used to store green arrow age information
// 3 bits of orientation information 1..6
state.redArrow0 = bytes.bit7.x;
state.redArrow1 = bytes.bit7.y;
state.redArrow2 = bytes.bit7.z;
state.redArrow = bytes.bit7.x + bytes.bit7.y * 2.0 + bytes.bit7.z * 4.0;
// 5 bits 1..30
state.signalPart.greenArrowPermutedWithQ1andQ2 = bytes.bits0to4.x;
// 1 bit
state.signalPart.takeQ1fromBifTrueElseFromA = bytes.bit5.x;
// 1 bit
state.signalPart.takeQ2fromBifTrueElseFromA = bytes.bit6.x;
// 3 input signals:
// 5 bits 1..30
state.signalInsideOfGreenArrow.greenArrowPermutedWithQ1andQ2 = bytes.bits0to4.y;
// 1 bit
state.signalInsideOfGreenArrow.takeQ1fromBifTrueElseFromA = bytes.bit5.y;
// 1 bit
state.signalInsideOfGreenArrow.takeQ2fromBifTrueElseFromA = bytes.bit6.y;
// 5 bits 1..30
state.signalGoingToQ1.greenArrowPermutedWithQ1andQ2 = bytes.bits0to4.z;
state.signalGoingToQ1.takeQ1fromBifTrueElseFromA = bytes.bit5.z;
state.signalGoingToQ1.takeQ2fromBifTrueElseFromA = bytes.bit6.z;
// 5 bits 1..30
state.signalGoingToQ2.greenArrowPermutedWithQ1andQ2 = bytes.bits0to4.w;
state.signalGoingToQ2.takeQ1fromBifTrueElseFromA = bytes.bit5.w;
state.signalGoingToQ2.takeQ2fromBifTrueElseFromA = bytes.bit6.w;
// 1 bit
state.greenArrowSignalAge = bytes.bit7.w;
return state;
}
vec2 texCoord (vec2 dataCoord) {
float width = dataWidthAndHeight.x;
float height = dataWidthAndHeight.y;
return vec2((dataCoord.x + 0.5) / width, (dataCoord.y + 0.5) / height);
}
vec4 fetch2d (vec2 coords) {
vec4 fetchedAnyway = texture2D(texture0, texCoord(coords)) * 255.0;
float isValidCoordinate = allVec4(whenGt(vec4(coords, dataWidthAndHeight), vec4(-0.1, -0.1, coords)));
return isValidCoordinate * fetchedAnyway;
}
// green arrow is 1..5 of remained ports, Q1andQ2 is 1..6
// perm is number from 1 to 30.
/*
1 1 1
2 2 1
3 3 1
4 4 1
5 5 1
6 1 2
7 2 2
8 3 2
9 4 2
10 5 2
11 1 3
12 2 3
13 3 3
14 4 3
15 5 3
16 1 4
17 2 4
18 3 4
19 4 4
20 5 4
21 1 5
22 2 5
23 3 5
24 4 5
25 5 5
26 1 6
27 2 6
28 3 6
29 4 6 *
30 5 6
*/
vec2 untangleGreenArrowFromQ1andQ2 (float perm) {
// perm = 5.0 * (6.0 - 1.0) + 4.0;
float q1q2perm = floor((perm - 1.0) / 5.0);
float greenArrow = floor(perm - q1q2perm * 5.0);
// q1q2perm = 5.0;
// greenArrow = 4.0;
return vec2(greenArrow, q1q2perm + 1.0);
}
float getGreenArrowPointsTo (float redArrow, float greenArrow) {
return whenGt(redArrow, 0.5) * (mod(redArrow + greenArrow - 1.0, 6.0) + 1.0);
}
// Switched inputs and outputs calculated from permutation, take bits, red and green arrow locations
struct Switching {
lowp float q1;
lowp float q2;
lowp float takeQ1from;
lowp float takeQ2from;
};
// Note that Q1andQ2perm describes the exact position of the two pass-thru outputs (number from 1 to 6)
// greenArrowPointsTo and redArrowPointsTo do exclude options, so we left only with the choice from 4).
Switching getSwitching (float redArrowPointsTo, float greenArrowPosRelativeToRedArrowCcw,
float Q1andQ2perm, float takeQ1fromBifTrueElseFromA, float takeQ2fromBifTrueElseFromA) {
Switching result;
float q1rel;
float q2rel;
float aRel;
float bRel;
if (whenGt(Q1andQ2perm, 0.5) * whenGt(1.5, Q1andQ2perm) > 0.0) {
q1rel = 1.0;
q2rel = 2.0;
aRel = 3.0;
bRel = 4.0;
} else if (whenGt(Q1andQ2perm, 1.5) * whenGt(2.5, Q1andQ2perm) > 0.0) {
q1rel = 1.0;
q2rel = 3.0;
aRel = 2.0;
bRel = 4.0;
} else if (whenGt(Q1andQ2perm, 2.5) * whenGt(3.5, Q1andQ2perm) > 0.0) {
q1rel = 1.0;
q2rel = 4.0;
aRel = 2.0;
bRel = 3.0;
} else if (whenGt(Q1andQ2perm, 3.5) * whenGt(4.5, Q1andQ2perm) > 0.0) {
q1rel = 2.0;
q2rel = 3.0;
aRel = 1.0;
bRel = 4.0;
} else if (whenGt(Q1andQ2perm, 4.5) * whenGt(5.5, Q1andQ2perm) > 0.0) {
q1rel = 2.0;
q2rel = 4.0;
aRel = 1.0;
bRel = 3.0;
} else if (whenGt(Q1andQ2perm, 5.5) * whenGt(6.5, Q1andQ2perm) > 0.0) {
q1rel = 3.0;
q2rel = 4.0;
aRel = 1.0;
bRel = 2.0;
}
result.q1 = mod(redArrowPointsTo + q1rel - whenGt(greenArrowPosRelativeToRedArrowCcw, q1rel), 6.0) + 1.0;
result.q2 = mod(redArrowPointsTo + q2rel - whenGt(greenArrowPosRelativeToRedArrowCcw, q2rel), 6.0) + 1.0;
float aIn = mod(redArrowPointsTo + aRel - whenGt(greenArrowPosRelativeToRedArrowCcw, aRel), 6.0) + 1.0;
float bIn = mod(redArrowPointsTo + bRel - whenGt(greenArrowPosRelativeToRedArrowCcw, bRel), 6.0) + 1.0;
result.takeQ1from = takeQ1fromBifTrueElseFromA > 0.0 ? bIn : aIn;
result.takeQ2from = takeQ2fromBifTrueElseFromA > 0.0 ? bIn : aIn;
return result;
}
`;
// 1. We can have up to 8 samplers simultaneously
// 2. texture2D(uSampler0, vec2(0, 0)) reads a single vec4.
// 3. Enabling the OES_texture_float extension, vec4 is 4 32-bit floats
// 3a. Otherwise, vec4 is 4 bytes.
// 4. Typical maximum texture size is 4096x4096. It addresses 16M locations.
// With typical format of UNSIGNED_BYTE vec4, it's 64 megabytes.
// With FLOAT format, it's 256 megabytes per texture.
// 5. There maximum typical 8 active textures attached,
// giving us minimum addressable RAM of 512 megabytes,
// extendable to 2GB on the machines supporting OES_texture_float.
// Some machines do support 32 texture units, which gives us maximum 8 gigabytes on those systems.
// 6. We don't want to abuse the system resources of client machines.
// We might choose to limit the maximum RAM we want to use to the minimum addressable,
// and distribute any excess memory in other machines. For fast data access on the machines
// supporting OES_texture_float, 2 textures units might be used for the entirety of the data input.
const FRAGMENT_SHADER = `#version 100
// Slow init!
// #extension GL_OES_standard_derivatives : require
// Only when WEBGL_draw_buffers is there (mostly on laptops only)
// #extension GL_EXT_draw_buffers : require
// #pragma debug(on)
// #pragma optimize(off)
# ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp float;
precision highp int;
precision highp sampler2D;
# else
precision mediump float;
precision lowp int;
precision lowp sampler2D;
# endif
// varying vec4 vcolor;
// uniform sampler2D uSampler1;