forked from makepad/makepad.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcx_webgl.js
More file actions
2067 lines (1875 loc) · 79.3 KB
/
cx_webgl.js
File metadata and controls
2067 lines (1875 loc) · 79.3 KB
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
(function(root) {
var user_agent = window.navigator.userAgent;
var is_mobile_safari = window.navigator.platform.match(/iPhone|iPad/i);
var is_android = user_agent.match(/Android/i);
var is_add_to_homescreen_safari = is_mobile_safari && navigator.standalone;
var is_touch_device = ('ontouchstart' in window || navigator.maxTouchPoints);
var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
// message we can send to wasm
class ToWasm {
constructor(wasm_app) {
this.wasm_app = wasm_app;
this.exports = wasm_app.exports;
this.slots = 512;
this.used = 2; // skip 8 byte header
// lets write
this.pointer = this.exports.alloc_wasm_message(this.slots * 4);
this.update_refs();
}
update_refs() {
this.mf32 = new Float32Array(this.exports.memory.buffer, this.pointer, this.slots);
this.mu32 = new Uint32Array(this.exports.memory.buffer, this.pointer, this.slots);
this.mf64 = new Float64Array(this.exports.memory.buffer, this.pointer, this.slots >> 1);
}
fit(slots) {
this.update_refs(); // its possible our mf32/mu32 refs are dead because of realloccing of wasm heap inbetween calls
if (this.used + slots > this.slots) {
let new_slots = Math.max(this.used + slots, this.slots * 2) // exp alloc algo
if (new_slots & 1)new_slots ++; // float64 align it
let new_bytes = new_slots * 4;
this.pointer = this.exports.realloc_wasm_message(this.pointer, new_bytes); // by
this.slots = new_slots
this.update_refs()
}
let pos = this.used;
this.used += slots;
return pos;
}
fetch_deps() {
let pos = this.fit(1);
this.mu32[pos ++] = 1;
}
send_string(str) {
let pos = this.fit(str.length + 1)
this.mu32[pos ++] = str.length
for (let i = 0; i < str.length; i ++) {
this.mu32[pos ++] = str.charCodeAt(i)
}
}
send_f64(value) {
if (this.used & 1) { // float64 align, need to fit another
var pos = this.fit(3);
pos ++;
this.mf64[pos >> 1] = value;
}
else {
var pos = this.fit(2);
this.mf64[pos >> 1] = value;
}
}
deps_loaded(deps) {
let pos = this.fit(2);
this.mu32[pos ++] = 2
this.mu32[pos ++] = deps.length
for (let i = 0; i < deps.length; i ++) {
let dep = deps[i];
this.send_string(dep.name);
pos = this.fit(2);
this.mu32[pos ++] = dep.vec_ptr
this.mu32[pos ++] = dep.vec_len
}
}
init(info) {
let pos = this.fit(5);
this.mu32[pos ++] = 3;
this.mf32[pos ++] = info.width;
this.mf32[pos ++] = info.height;
this.mf32[pos ++] = info.dpi_factor;
this.mu32[pos ++] = info.vr_can_present? 1: 0;
}
resize(info) {
let pos = this.fit(6);
this.mu32[pos ++] = 4;
this.mf32[pos ++] = info.width;
this.mf32[pos ++] = info.height;
this.mf32[pos ++] = info.dpi_factor;
this.mu32[pos ++] = info.vr_is_presenting? 1: 0;
this.mu32[pos ++] = info.vr_can_present? 1: 0;
}
animation_frame(time) {
let pos = this.fit(1); // float64 uses 2 slots
this.mu32[pos ++] = 5;
this.send_f64(time);
}
finger_down(finger) {
let pos = this.fit(6);
this.mu32[pos ++] = 6;
this.mf32[pos ++] = finger.x
this.mf32[pos ++] = finger.y
this.mu32[pos ++] = finger.digit
this.mu32[pos ++] = finger.touch? 1: 0
this.mu32[pos ++] = finger.modifiers
this.send_f64(finger.time);
}
finger_up(finger) {
let pos = this.fit(6);
this.mu32[pos ++] = 7;
this.mf32[pos ++] = finger.x
this.mf32[pos ++] = finger.y
this.mu32[pos ++] = finger.digit
this.mu32[pos ++] = finger.touch? 1: 0
this.mu32[pos ++] = finger.modifiers
this.send_f64(finger.time);
}
finger_move(finger) {
let pos = this.fit(6);
this.mu32[pos ++] = 8;
this.mf32[pos ++] = finger.x
this.mf32[pos ++] = finger.y
this.mu32[pos ++] = finger.digit
this.mu32[pos ++] = finger.touch? 1: 0
this.mu32[pos ++] = finger.modifiers
this.send_f64(finger.time);
}
finger_hover(finger) {
let pos = this.fit(4);
this.mu32[pos ++] = 9;
this.mf32[pos ++] = finger.x
this.mf32[pos ++] = finger.y
this.mu32[pos ++] = finger.modifiers
this.send_f64(finger.time);
}
finger_scroll(finger) {
let pos = this.fit(7);
this.mu32[pos ++] = 10;
this.mf32[pos ++] = finger.x
this.mf32[pos ++] = finger.y
this.mf32[pos ++] = finger.scroll_x
this.mf32[pos ++] = finger.scroll_y
this.mu32[pos ++] = finger.is_wheel? 1: 0
this.mu32[pos ++] = finger.modifiers
this.send_f64(finger.time);
}
finger_out(finger) {
let pos = this.fit(4);
this.mu32[pos ++] = 11;
this.mf32[pos ++] = finger.x
this.mf32[pos ++] = finger.y
this.mu32[pos ++] = finger.modifiers
this.send_f64(finger.time);
}
key_down(key) {
let pos = this.fit(4);
this.mu32[pos ++] = 12;
this.mu32[pos ++] = key.key_code;
this.mu32[pos ++] = key.is_repeat? 1: 0;
this.mu32[pos ++] = key.modifiers;
this.send_f64(key.time);
}
key_up(key) {
let pos = this.fit(4);
this.mu32[pos ++] = 13;
this.mu32[pos ++] = key.key_code;
this.mu32[pos ++] = key.is_repeat? 1: 0;
this.mu32[pos ++] = key.modifiers;
this.send_f64(key.time);
}
text_input(data) {
let pos = this.fit(3);
this.mu32[pos ++] = 14;
this.mu32[pos ++] = data.was_paste? 1: 0,
this.mu32[pos ++] = data.replace_last? 1: 0,
this.send_string(data.input);
}
read_file_data(id, buf_ptr, buf_len) {
let pos = this.fit(4);
this.mu32[pos ++] = 15;
this.mu32[pos ++] = id;
this.mu32[pos ++] = buf_ptr;
this.mu32[pos ++] = buf_len;
}
read_file_error(id) {
let pos = this.fit(2);
this.mu32[pos ++] = 16;
this.mu32[pos ++] = id;
}
text_copy() {
let pos = this.fit(1);
this.mu32[pos ++] = 17;
}
timer(id) {
let pos = this.fit(1);
this.mu32[pos ++] = 18;
this.send_f64(id);
}
window_focus(is_focus) { // TODO CALL THIS
let pos = this.fit(2);
this.mu32[pos ++] = 19;
this.mu32[pos ++] = is_focus? 1: 0;
}
vr_frame(time, frame_data) {
let pos = this.fit(1);
this.mu32[pos ++] = 20;
this.send_f64(time);
}
paint_dirty(time, frame_data) {
let pos = this.fit(1);
this.mu32[pos ++] = 21;
}
http_send_response(signal_id, success) {
let pos = this.fit(3);
this.mu32[pos ++] = 22;
this.mu32[pos ++] = signal_id;
this.mu32[pos ++] = success?1:2;
}
end() {
let pos = this.fit(1);
this.mu32[pos] = 0;
}
}
class WasmApp {
constructor(canvas, webasm) {
this.canvas = canvas;
this.webasm = webasm;
this.exports = webasm.instance.exports;
this.memory = webasm.instance.exports.memory
// local webgl resources
this.shaders = [];
this.vr_mode = false;
this.index_buffers = [];
this.array_buffers = [];
this.timers = [];
this.vaos = [];
this.textures = [];
this.framebuffers = [];
this.resources = [];
this.req_anim_frame_id = 0;
this.text_copy_response = "";
this.init_webgl_context();
this.init_webvr_bindings();
this.bind_mouse_and_touch();
this.bind_keyboard();
window.addEventListener('focus', _ => {
this.to_wasm.window_focus(true);
this.do_wasm_io();
})
window.addEventListener('blur', _ => {
this.to_wasm.window_focus(false);
this.do_wasm_io();
})
// lets create the wasm app and cx
this.app = this.exports.create_wasm_app();
// create initial to_wasm
this.to_wasm = new ToWasm(this);
// fetch dependencies
this.to_wasm.fetch_deps();
this.do_wasm_io();
this.do_wasm_block = true;
// ok now, we wait for our resources to load.
Promise.all(this.resources).then(results => {
let deps = []
// copy our reslts into wasm pointers
for (let i = 0; i < results.length; i ++) {
var result = results[i]
// allocate pointer, do +8 because of the u64 length at the head of the buffer
let vec_len = result.buffer.byteLength;
let vec_ptr = this.exports.alloc_wasm_vec(vec_len);
this.copy_to_wasm(result.buffer, vec_ptr);
deps.push({
name: result.name,
vec_ptr: vec_ptr,
vec_len: vec_len
});
}
// pass wasm the deps
this.to_wasm.deps_loaded(deps);
// initialize the application
this.to_wasm.init({
width: this.width,
height: this.height,
dpi_factor: this.dpi_factor,
vr_can_present: this.vr_can_present,
vr_is_presenting: false
})
this.do_wasm_block = false;
this.do_wasm_io();
var loaders = document.getElementsByClassName('cx_webgl_loader');
for (var i = 0; i < loaders.length; i ++) {
loaders[i].parentNode.removeChild(loaders[i])
}
})
}
do_wasm_io() {
if (this.do_wasm_block) {
return
}
//if(this.dpi_factor != window.devicePixelRatio){
// this.on_screen_resize();
//}
this.to_wasm.end();
let from_wasm_ptr = this.exports.process_to_wasm(this.app, this.to_wasm.pointer)
// get a clean to_wasm set up immediately
this.to_wasm = new ToWasm(this);
// set up local shortcuts to the from_wasm memory chunk for faster parsing
this.parse = 2; // skip the 8 byte header
this.mf32 = new Float32Array(this.memory.buffer, from_wasm_ptr);
this.mu32 = new Uint32Array(this.memory.buffer, from_wasm_ptr);
this.mf64 = new Float64Array(this.memory.buffer, from_wasm_ptr);
this.basef32 = new Float32Array(this.memory.buffer);
this.baseu32 = new Uint32Array(this.memory.buffer);
this.basef64 = new Float64Array(this.memory.buffer);
// process all messages
var send_fn_table = this.send_fn_table;
while (1) {
let msg_type = this.mu32[this.parse ++];
if (send_fn_table[msg_type](this)) {
break;
}
}
// destroy from_wasm_ptr object
this.exports.dealloc_wasm_message(from_wasm_ptr);
}
request_animation_frame() {
if (this.vr_is_presenting || this.req_anim_frame_id) {
return;
}
this.req_anim_frame_id = window.requestAnimationFrame(time => {
this.req_anim_frame_id = 0;
if (this.vr_is_presenting) {
return
}
this.to_wasm.animation_frame(time / 1000.0);
this.in_animation_frame = true;
this.do_wasm_io();
this.in_animation_frame = false;
})
}
// i forgot how to do memcpy with typed arrays. so, we'll do this.
copy_to_wasm(input_buffer, output_ptr) {
let u8len = input_buffer.byteLength;
if ((u8len & 3) != 0 || (output_ptr & 3) != 0) { // not u32 aligned, do a byte copy
var u8out = new Uint8Array(this.memory.buffer, output_ptr, u8len)
var u8in = new Uint8Array(input_buffer)
for (let i = 0; i < u8len; i ++) {
u8out[i] = u8in[i];
}
}
else { // not f64 aligned, do a u32 copy
let u32len = u8len >> 2; //4 bytes at a time.
var u32out = new Uint32Array(this.memory.buffer, output_ptr, u32len)
var u32in = new Uint32Array(input_buffer)
for (let i = 0; i < u32len; i ++) {
u32out[i] = u32in[i];
}
}
}
on_screen_resize() {
var dpi_factor = window.devicePixelRatio;
var w,
h;
var canvas = this.canvas;
if (this.vr_is_presenting) {
let vr_display = this.vr_display;
var left_eye = vr_display.getEyeParameters("left");
var right_eye = vr_display.getEyeParameters("right");
canvas.width = Math.max(left_eye.renderWidth, right_eye.renderWidth) * 2;
canvas.height = Math.max(left_eye.renderHeight, right_eye.renderHeight);
this.dpi_factor = 1.0;
this.width = canvas.width >> 1;
this.height = canvas.height;
}
else {
if (canvas.getAttribute("fullpage")) {
if (is_add_to_homescreen_safari) { // extremely ugly. but whatever.
if (window.orientation == 90 || window.orientation == -90) {
h = screen.width;
w = screen.height - 90;
}
else {
w = screen.width;
h = screen.height - 80;
}
}
else {
w = window.innerWidth;
h = window.innerHeight;
}
}
else {
w = canvas.offsetWidth;
h = canvas.offsetHeight;
}
var sw = canvas.width = w * dpi_factor;
var sh = canvas.height = h * dpi_factor;
this.gl.viewport(0, 0, sw, sh);
this.dpi_factor = dpi_factor;
this.width = canvas.offsetWidth;
this.height = canvas.offsetHeight;
// send the wasm a screenresize event
}
if (this.to_wasm) {
// initialize the application
this.to_wasm.resize({
width: this.width,
height: this.height,
dpi_factor: this.dpi_factor,
vr_can_present: this.vr_can_present,
vr_is_presenting: this.vr_is_presenting
})
this.request_animation_frame()
}
}
load_deps(deps) {
for (var i = 0; i < deps.length; i ++) {
let file_path = deps[i];
this.resources.push(fetch_path(file_path))
}
}
parse_string() {
var str = "";
var len = this.mu32[this.parse ++];
for (let i = 0; i < len; i ++) {
var c = this.mu32[this.parse ++];
if (c != 0) str += String.fromCharCode(c);
}
return str
}
parse_u8slice(){
var str = "";
var u8_len = this.mu32[this.parse ++];
let len = u8_len >> 2;
let data = new Uint8Array(u8_len);
let spare = u8_len & 3;
for(let i = 0; i < len; i++){
let u8_pos = i<<2;
let u32 = this.mu32[this.parse++];
data[u8_pos + 0] = u32&0xff;
data[u8_pos + 1] = (u32>>8)&0xff;
data[u8_pos + 2] = (u32>>16)&0xff;
data[u8_pos + 3] = (u32>>24)&0xff;
}
let u8_pos = len<<2;
if(spare == 1){
let u32 = this.mu32[this.parse++];
data[u8_pos + 0] = u32&0xff;
}
else if(spare == 2){
let u32 = this.mu32[this.parse++];
data[u8_pos + 0] = u32&0xff;
data[u8_pos + 1] = (u32>>8)&0xff;
}
else if(spare == 3){
let u32 = this.mu32[this.parse++];
data[u8_pos + 0] = u32&0xff;
data[u8_pos + 1] = (u32>>8)&0xff;
data[u8_pos + 2] = (u32>>16)&0xff;
}
console.log(data);
return data
}
parse_f64() {
if (this.parse & 1) {
this.parse ++;
}
var ret = this.mf64[this.parse >> 1];
this.parse += 2;
return ret
}
parse_shvarvec() {
var len = this.mu32[this.parse ++];
var vars = []
for (let i = 0; i < len; i ++) {
vars.push({ty: this.parse_string(), name: this.parse_string()})
}
return vars
}
// The UA may kick us out of VR present mode for any reason, so to
// ensure we always know when we begin/end presenting we need to
// listen for vrdisplaypresentchange events.
on_vr_display_present_change() {
this.vr_is_presenting = this.vr_display.isPresenting;
if (this.vr_is_presenting) { // we need to start the continuous repaintloop
let vr_on_request_animation_frame = time => {
if (!this.vr_is_presenting) {
return
}
this.vr_display.requestAnimationFrame(vr_on_request_animation_frame);
// compute the view matrices taking into account the persons movement
this.to_wasm.paint_dirty();
this.to_wasm.vr_frame(time / 1000.0, this.vr_frame_data);
this.in_animation_frame = true;
this.do_wasm_io();
this.in_animation_frame = false;
this.vr_display.submitFrame();
};
this.vr_display.requestAnimationFrame(vr_on_request_animation_frame);
}
else { // lets return to normal
this.to_wasm.paint_dirty();
this.request_animation_frame();
}
this.on_screen_resize();
}
on_vr_display_activate() {
var attributes = {depth: true, antialias: true, multiview: false};
this.vr_display.requestPresent([{source: this.canvas, attributes: attributes}]).then(_ => {
}, error => {
console.log("requestPresent failed", error)
});
}
on_vr_display_deactivate() {
if (!this.vr_display.isPresenting) {
return;
}
this.vr_display.exitPresent().then(_ => {
}, error => {
console.log("exitPresent failed", error)
});
}
init_webvr_bindings() {
this.vr_can_present = false;
this.vr_is_presenting = false;
// ok this changes a bunch in how the renderflow works.
// first thing we are going to do is get the vr displays.
if (navigator.getVRDisplays) {
this.vr_frame_data = new VRFrameData();
navigator.getVRDisplays().then(displays => {
if (displays.length > 0) {
this.vr_display = displays[0];
// It's heighly reccommended that you set the near and far planes to
// something appropriate for your scene so the projection matricies
// WebVR produces have a well scaled depth buffer.
this.vr_display.depthNear = 0.1;
this.vr_display.depthFar = 250.0;
// vrDisplay.resetPose();
// Generally, you want to wait until VR support is confirmed and
// you know the user has a VRDisplay capable of presenting connected
// before adding UI that advertises VR features.
if (this.vr_display.capabilities.canPresent) {
this.vr_can_present = true;
console.log("webVR available");
window.addEventListener("vrdisplaypresentchange", this.on_vr_display_present_change.bind(this), false);
window.addEventListener("vrdisplayactivate", this.on_vr_display_activate.bind(this), false);
window.addEventListener("vrdisplaydeactivate", this.on_vr_display_deactivate.bind(this), false);
}
}
else {
console.log("No VR displays found")
}
})
}
else {
console.log("No webVR support found")
}
}
vr_start_presenting() {
if (this.vr_can_present) {
console.log("Starting webVR")
this.on_vr_display_activate();
}
}
vr_stop_presenting() {
}
init_webgl_context() {
window.addEventListener('resize', _ => {
this.on_screen_resize()
})
window.addEventListener('orientationchange', _ => {
this.on_screen_resize()
})
let mqString = '(resolution: ' + window.devicePixelRatio + 'dppx)'
let mq = matchMedia(mqString);
if (mq && mq.addEventListener) {
mq.addEventListener("change", _ => {
this.on_screen_resize()
});
}
else { // poll for it. yes. its terrible
window.setInterval(_ => {
if (window.devicePixelRation != this.dpi_factor) {
this.on_screen_resize()
}
}, 1000);
}
var canvas = this.canvas
var options = {
alpha: canvas.getAttribute("noalpha")? false: true,
depth: canvas.getAttribute("nodepth")? false: true,
stencil: canvas.getAttribute("nostencil")? false: true,
antialias: canvas.getAttribute("noantialias")? false: true,
premultipliedAlpha: canvas.getAttribute("premultipliedAlpha")? true: false,
preserveDrawingBuffer: canvas.getAttribute("preserveDrawingBuffer")? true: false,
preferLowPowerToHighPerformance: true
}
var gl = this.gl = canvas.getContext('webgl', options)
|| canvas.getContext('webgl-experimental', options)
|| canvas.getContext('experimental-webgl', options)
if (!gl) {
var span = document.createElement('span')
span.style.color = 'white'
canvas.parentNode.replaceChild(span, canvas)
span.innerHTML = "Sorry, makepad needs browser support for WebGL to run<br/>Please update your browser to a more modern one<br/>Update to atleast iOS 10, Safari 10, latest Chrome, Edge or Firefox<br/>Go and update and come back, your browser will be better, faster and more secure!<br/>If you are using chrome on OSX on a 2011/2012 mac please enable your GPU at: Override software rendering list:Enable (the top item) in: <a href='about://flags'>about://flags</a>. Or switch to Firefox or Safari."
return
}
gl.OES_standard_derivatives = gl.getExtension('OES_standard_derivatives')
gl.OES_vertex_array_object = gl.getExtension('OES_vertex_array_object')
gl.OES_element_index_uint = gl.getExtension("OES_element_index_uint")
gl.ANGLE_instanced_arrays = gl.getExtension('ANGLE_instanced_arrays')
//gl.EXT_blend_minmax = gl.getExtension('EXT_blend_minmax')
//gl.OES_texture_half_float_linear = gl.getExtension('OES_texture_half_float_linear')
//gl.OES_texture_float_linear = gl.getExtension('OES_texture_float_linear')
//gl.OES_texture_half_float = gl.getExtension('OES_texture_half_float')
//gl.OES_texture_float = gl.getExtension('OES_texture_float')
//gl.WEBGL_depth_texture = gl.getExtension("WEBGL_depth_texture") || gl.getExtension("WEBKIT_WEBGL_depth_texture")
this.on_screen_resize()
}
// new shader helpers
get_attrib_locations(program, base, slots) {
var gl = this.gl;
let attrib_locs = [];
let attribs = slots >> 2;
let stride = slots * 4;
if ((slots & 3) != 0) attribs ++;
for (let i = 0; i < attribs; i ++) {
let size = (slots - i * 4);
if (size > 4) size = 4;
attrib_locs.push({
loc: gl.getAttribLocation(program, base + i),
offset: i * 16,
size: size,
stride: slots * 4
});
}
return attrib_locs
}
get_uniform_locations(program, uniforms) {
var gl = this.gl;
let uniform_locs = [];
let offset = 0;
for (let i = 0; i < uniforms.length; i ++) {
let uniform = uniforms[i];
// lets align the uniform
let slots = this.uniform_size_table[uniform.ty];
if ((offset & 3) != 0 && (offset & 3) + slots > 4) { // goes over the boundary
offset += 4 - (offset & 3); // make jump to new slot
}
uniform_locs.push({
name: uniform.name,
offset: offset << 2,
ty: uniform.ty,
loc: gl.getUniformLocation(program, uniform.name),
fn: this.uniform_fn_table[uniform.ty]
});
offset += slots
}
return uniform_locs;
}
compile_webgl_shader(ash) {
var gl = this.gl
var vsh = gl.createShader(gl.VERTEX_SHADER)
gl.shaderSource(vsh, ash.vertex)
gl.compileShader(vsh)
if (!gl.getShaderParameter(vsh, gl.COMPILE_STATUS)) {
return console.log(
gl.getShaderInfoLog(vsh),
add_line_numbers_to_string(ash.vertex)
)
}
// compile pixelshader
var fsh = gl.createShader(gl.FRAGMENT_SHADER)
gl.shaderSource(fsh, ash.fragment)
gl.compileShader(fsh)
if (!gl.getShaderParameter(fsh, gl.COMPILE_STATUS)) {
return console.log(
gl.getShaderInfoLog(fsh),
add_line_numbers_to_string(ash.fragment)
)
}
var program = gl.createProgram()
gl.attachShader(program, vsh)
gl.attachShader(program, fsh)
gl.linkProgram(program)
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
return console.log(
gl.getProgramInfoLog(program),
add_line_numbers_to_string(ash.vertex),
add_line_numbers_to_string(ash.fragment)
)
}
// fetch all attribs and uniforms
this.shaders[ash.shader_id] = {
geom_attribs: this.get_attrib_locations(program, "geomattr", ash.geometry_slots),
inst_attribs: this.get_attrib_locations(program, "instattr", ash.instance_slots),
pass_uniforms: this.get_uniform_locations(program, ash.pass_uniforms),
view_uniforms: this.get_uniform_locations(program, ash.view_uniforms),
draw_uniforms: this.get_uniform_locations(program, ash.draw_uniforms),
uniforms: this.get_uniform_locations(program, ash.uniforms),
texture_slots: this.get_uniform_locations(program, ash.texture_slots),
instance_slots: ash.instance_slots,
program: program,
ash: ash
};
}
set_document_title(title) {
document.title = title
}
bind_mouse_and_touch() {
this.cursor_map = [
"none", //Hidden=>0
"default", //Default=>1,
"crosshair", //CrossHair=>2,
"pointer", //Hand=>3,
"default", //Arrow=>4,
"move", //Move=>5,
"text", //Text=>6,
"wait", //Wait=>7,
"help", //Help=>8,
"not-allowed", //NotAllowed=>9,
"n-resize", // NResize=>10,
"ne-resize", // NeResize=>11,
"e-resize", // EResize=>12,
"se-resize", // SeResize=>13,
"s-resize", // SResize=>14,
"sw-resize", // SwResize=>15,
"w-resize", // WResize=>16,
"nw-resize", // NwResize=>17,
"ns-resize", //NsResize=>18,
"nesw-resize", //NeswResize=>19,
"ew-resize", //EwResize=>20,
"nwse-resize", //NwseResize=>21,
"col-resize", //ColResize=>22,
"row-resize", //RowResize=>23,
]
var canvas = this.canvas
function mouse_to_finger(e) {
return {
x: e.pageX,
y: e.pageY,
digit: e.button,
time: e.timeStamp / 1000.0,
modifiers: pack_key_modifier(e),
touch: false
}
}
var digit_map = {}
var digit_alloc = 0;
function touch_to_finger_alloc(e) {
var f = []
for (let i = 0; i < e.changedTouches.length; i ++) {
var t = e.changedTouches[i]
// find an unused digit
var digit = undefined;
for (digit in digit_map) {
if (!digit_map[digit]) break
}
// we need to alloc a new one
if (digit === undefined || digit_map[digit]) digit = digit_alloc ++;
// store it
digit_map[digit] = {identifier: t.identifier};
// return allocated digit
digit = parseInt(digit);
f.push({
x: t.pageX,
y: t.pageY,
digit: digit,
time: e.timeStamp / 1000.0,
modifiers: 0,
touch: true,
})
}
return f
}
function lookup_digit(identifier) {
for (let digit in digit_map) {
var digit_id = digit_map[digit]
if (!digit_id) continue
if (digit_id.identifier == identifier) {
return digit
}
}
}
function touch_to_finger_lookup(e) {
var f = []
for (let i = 0; i < e.changedTouches.length; i ++) {
var t = e.changedTouches[i]
f.push({
x: t.pageX,
y: t.pageY,
digit: lookup_digit(t.identifier),
time: e.timeStamp / 1000.0,
modifiers: {},
touch: true,
})
}
return f
}
function touch_to_finger_free(e) {
var f = []
for (let i = 0; i < e.changedTouches.length; i ++) {
var t = e.changedTouches[i]
var digit = lookup_digit(t.identifier)
if (!digit) {
console.log("Undefined state in free_digit");
digit = 0
}
else {
digit_map[digit] = undefined
}
f.push({
x: t.pageX,
y: t.pageY,
time: e.timeStamp / 1000.0,
digit: digit,
modifiers: 0,
touch: true,
})
}
return f
}
var mouse_buttons_down = [];
this.mouse_down_handler = e => {
e.preventDefault();
this.focus_keyboard_input();
mouse_buttons_down[e.button] = true;
this.to_wasm.finger_down(mouse_to_finger(e))
this.do_wasm_io();
}
canvas.addEventListener('mousedown', this.mouse_down_handler)
this.mouse_up_handler = e => {
e.preventDefault();
mouse_buttons_down[e.button] = false;
this.to_wasm.finger_up(mouse_to_finger(e))
this.do_wasm_io();
}
window.addEventListener('mouseup', this.mouse_up_handler)
let mouse_move = e => {
document.body.scrollTop = 0;
document.body.scrollLeft = 0;
for (var i = 0; i < mouse_buttons_down.length; i ++) {
if (mouse_buttons_down[i]) {
this.to_wasm.finger_move({
x: e.pageX,
y: e.pageY,
time: e.timeStamp / 1000.0,
modifiers: 0,
digit: i
})
}
}
this.to_wasm.finger_hover(mouse_to_finger(e));
var begin = performance.now();
this.do_wasm_io();
var end = performance.now();
//console.log("Redraw cycle "+(end-begin)+" ms");
}
window.addEventListener('mousemove', mouse_move);
window.addEventListener('mouseout', e => {
this.to_wasm.finger_out(mouse_to_finger(e)) //e.pageX, e.pageY, pa;
this.do_wasm_io();
});
canvas.addEventListener('contextmenu', e => {
e.preventDefault()
return false
})
canvas.addEventListener('touchstart', e => {
e.preventDefault()
let fingers = touch_to_finger_alloc(e);
for (let i = 0; i < fingers.length; i ++) {
this.to_wasm.finger_down(fingers[i])
}
this.do_wasm_io();
return false
})
canvas.addEventListener('touchmove', e => {
//e.preventDefault();
var fingers = touch_to_finger_lookup(e);
for (let i = 0; i < fingers.length; i ++) {
this.to_wasm.finger_move(fingers[i])
}
this.do_wasm_io();
return false
}, {passive: false})
var end_cancel_leave = e => {
e.preventDefault();
var fingers = touch_to_finger_free(e);
for (let i = 0; i < fingers.length; i ++) {
this.to_wasm.finger_up(fingers[i])
}
this.do_wasm_io();
return false
}
canvas.addEventListener('touchend', end_cancel_leave);
canvas.addEventListener('touchcancel', end_cancel_leave);
canvas.addEventListener('touchleave', end_cancel_leave);
var last_wheel_time;
var last_was_wheel;