-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
library_browser.js
1538 lines (1374 loc) · 59.7 KB
/
library_browser.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2011 The Emscripten Authors. All rights reserved.
// Emscripten is available under two separate licenses, the MIT license and the
// University of Illinois/NCSA Open Source License. Both these licenses can be
// found in the LICENSE file.
//"use strict";
// Utilities for browser environments
var LibraryBrowser = {
$Browser__deps: ['emscripten_set_main_loop', 'emscripten_set_main_loop_timing'],
$Browser__postset: 'Module["requestFullScreen"] = function Module_requestFullScreen(lockPointer, resizeCanvas, vrDevice) { err("Module.requestFullScreen is deprecated. Please call Module.requestFullscreen instead."); Module["requestFullScreen"] = Module["requestFullscreen"]; Browser.requestFullScreen(lockPointer, resizeCanvas, vrDevice) };\n' + // exports
'Module["requestFullscreen"] = function Module_requestFullscreen(lockPointer, resizeCanvas, vrDevice) { Browser.requestFullscreen(lockPointer, resizeCanvas, vrDevice) };\n' + // exports
'Module["requestAnimationFrame"] = function Module_requestAnimationFrame(func) { Browser.requestAnimationFrame(func) };\n' +
'Module["setCanvasSize"] = function Module_setCanvasSize(width, height, noUpdates) { Browser.setCanvasSize(width, height, noUpdates) };\n' +
'Module["pauseMainLoop"] = function Module_pauseMainLoop() { Browser.mainLoop.pause() };\n' +
'Module["resumeMainLoop"] = function Module_resumeMainLoop() { Browser.mainLoop.resume() };\n' +
'Module["getUserMedia"] = function Module_getUserMedia() { Browser.getUserMedia() }\n' +
'Module["createContext"] = function Module_createContext(canvas, useWebGL, setInModule, webGLContextAttributes) { return Browser.createContext(canvas, useWebGL, setInModule, webGLContextAttributes) }',
$Browser: {
mainLoop: {
scheduler: null,
method: '',
// Each main loop is numbered with a ID in sequence order. Only one main loop can run at a time. This variable stores the ordinal number of the main loop that is currently
// allowed to run. All previous main loops will quit themselves. This is incremented whenever a new main loop is created.
currentlyRunningMainloop: 0,
func: null, // The main loop tick function that will be called at each iteration.
arg: 0, // The argument that will be passed to the main loop. (of type void*)
timingMode: 0,
timingValue: 0,
currentFrameNumber: 0,
queue: [],
pause: function() {
Browser.mainLoop.scheduler = null;
Browser.mainLoop.currentlyRunningMainloop++; // Incrementing this signals the previous main loop that it's now become old, and it must return.
},
resume: function() {
Browser.mainLoop.currentlyRunningMainloop++;
var timingMode = Browser.mainLoop.timingMode;
var timingValue = Browser.mainLoop.timingValue;
var func = Browser.mainLoop.func;
Browser.mainLoop.func = null;
_emscripten_set_main_loop(func, 0, false, Browser.mainLoop.arg, true /* do not set timing and call scheduler, we will do it on the next lines */);
_emscripten_set_main_loop_timing(timingMode, timingValue);
Browser.mainLoop.scheduler();
},
updateStatus: function() {
if (Module['setStatus']) {
var message = Module['statusMessage'] || 'Please wait...';
var remaining = Browser.mainLoop.remainingBlockers;
var expected = Browser.mainLoop.expectedBlockers;
if (remaining) {
if (remaining < expected) {
Module['setStatus'](message + ' (' + (expected - remaining) + '/' + expected + ')');
} else {
Module['setStatus'](message);
}
} else {
Module['setStatus']('');
}
}
},
runIter: function(func) {
if (ABORT) return;
if (Module['preMainLoop']) {
var preRet = Module['preMainLoop']();
if (preRet === false) {
return; // |return false| skips a frame
}
}
try {
func();
} catch (e) {
if (e instanceof ExitStatus) {
return;
} else {
if (e && typeof e === 'object' && e.stack) err('exception thrown: ' + [e, e.stack]);
throw e;
}
}
if (Module['postMainLoop']) Module['postMainLoop']();
}
},
isFullscreen: false,
pointerLock: false,
moduleContextCreatedCallbacks: [],
workers: [],
init: function() {
if (!Module["preloadPlugins"]) Module["preloadPlugins"] = []; // needs to exist even in workers
if (Browser.initted) return;
Browser.initted = true;
try {
new Blob();
Browser.hasBlobConstructor = true;
} catch(e) {
Browser.hasBlobConstructor = false;
console.log("warning: no blob constructor, cannot create blobs with mimetypes");
}
Browser.BlobBuilder = typeof MozBlobBuilder != "undefined" ? MozBlobBuilder : (typeof WebKitBlobBuilder != "undefined" ? WebKitBlobBuilder : (!Browser.hasBlobConstructor ? console.log("warning: no BlobBuilder") : null));
Browser.URLObject = typeof window != "undefined" ? (window.URL ? window.URL : window.webkitURL) : undefined;
if (!Module.noImageDecoding && typeof Browser.URLObject === 'undefined') {
console.log("warning: Browser does not support creating object URLs. Built-in browser image decoding will not be available.");
Module.noImageDecoding = true;
}
// Support for plugins that can process preloaded files. You can add more of these to
// your app by creating and appending to Module.preloadPlugins.
//
// Each plugin is asked if it can handle a file based on the file's name. If it can,
// it is given the file's raw data. When it is done, it calls a callback with the file's
// (possibly modified) data. For example, a plugin might decompress a file, or it
// might create some side data structure for use later (like an Image element, etc.).
var imagePlugin = {};
imagePlugin['canHandle'] = function imagePlugin_canHandle(name) {
return !Module.noImageDecoding && /\.(jpg|jpeg|png|bmp)$/i.test(name);
};
imagePlugin['handle'] = function imagePlugin_handle(byteArray, name, onload, onerror) {
var b = null;
if (Browser.hasBlobConstructor) {
try {
b = new Blob([byteArray], { type: Browser.getMimetype(name) });
if (b.size !== byteArray.length) { // Safari bug #118630
// Safari's Blob can only take an ArrayBuffer
b = new Blob([(new Uint8Array(byteArray)).buffer], { type: Browser.getMimetype(name) });
}
} catch(e) {
warnOnce('Blob constructor present but fails: ' + e + '; falling back to blob builder');
}
}
if (!b) {
var bb = new Browser.BlobBuilder();
bb.append((new Uint8Array(byteArray)).buffer); // we need to pass a buffer, and must copy the array to get the right data range
b = bb.getBlob();
}
var url = Browser.URLObject.createObjectURL(b);
#if ASSERTIONS
assert(typeof url == 'string', 'createObjectURL must return a url as a string');
#endif
var img = new Image();
img.onload = function img_onload() {
assert(img.complete, 'Image ' + name + ' could not be decoded');
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
Module["preloadedImages"][name] = canvas;
Browser.URLObject.revokeObjectURL(url);
if (onload) onload(byteArray);
};
img.onerror = function img_onerror(event) {
console.log('Image ' + url + ' could not be decoded');
if (onerror) onerror();
};
img.src = url;
};
Module['preloadPlugins'].push(imagePlugin);
var audioPlugin = {};
audioPlugin['canHandle'] = function audioPlugin_canHandle(name) {
return !Module.noAudioDecoding && name.substr(-4) in { '.ogg': 1, '.wav': 1, '.mp3': 1 };
};
audioPlugin['handle'] = function audioPlugin_handle(byteArray, name, onload, onerror) {
var done = false;
function finish(audio) {
if (done) return;
done = true;
Module["preloadedAudios"][name] = audio;
if (onload) onload(byteArray);
}
function fail() {
if (done) return;
done = true;
Module["preloadedAudios"][name] = new Audio(); // empty shim
if (onerror) onerror();
}
if (Browser.hasBlobConstructor) {
try {
var b = new Blob([byteArray], { type: Browser.getMimetype(name) });
} catch(e) {
return fail();
}
var url = Browser.URLObject.createObjectURL(b); // XXX we never revoke this!
#if ASSERTIONS
assert(typeof url == 'string', 'createObjectURL must return a url as a string');
#endif
var audio = new Audio();
audio.addEventListener('canplaythrough', function() { finish(audio) }, false); // use addEventListener due to chromium bug 124926
audio.onerror = function audio_onerror(event) {
if (done) return;
console.log('warning: browser could not fully decode audio ' + name + ', trying slower base64 approach');
function encode64(data) {
var BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var PAD = '=';
var ret = '';
var leftchar = 0;
var leftbits = 0;
for (var i = 0; i < data.length; i++) {
leftchar = (leftchar << 8) | data[i];
leftbits += 8;
while (leftbits >= 6) {
var curr = (leftchar >> (leftbits-6)) & 0x3f;
leftbits -= 6;
ret += BASE[curr];
}
}
if (leftbits == 2) {
ret += BASE[(leftchar&3) << 4];
ret += PAD + PAD;
} else if (leftbits == 4) {
ret += BASE[(leftchar&0xf) << 2];
ret += PAD;
}
return ret;
}
audio.src = 'data:audio/x-' + name.substr(-3) + ';base64,' + encode64(byteArray);
finish(audio); // we don't wait for confirmation this worked - but it's worth trying
};
audio.src = url;
// workaround for chrome bug 124926 - we do not always get oncanplaythrough or onerror
Browser.safeSetTimeout(function() {
finish(audio); // try to use it even though it is not necessarily ready to play
}, 10000);
} else {
return fail();
}
};
Module['preloadPlugins'].push(audioPlugin);
#if WASM
#if MAIN_MODULE
var wasmPlugin = {};
wasmPlugin['asyncWasmLoadPromise'] = new Promise(
function(resolve, reject) { return resolve(); });
wasmPlugin['canHandle'] = function(name) {
return !Module.noWasmDecoding && name.endsWith('.so');
};
wasmPlugin['handle'] = function(byteArray, name, onload, onerror) {
// loadWebAssemblyModule can not load modules out-of-order, so rather
// than just running the promises in parallel, this makes a chain of
// promises to run in series.
this['asyncWasmLoadPromise'] = this['asyncWasmLoadPromise'].then(
function() {
return loadWebAssemblyModule(byteArray, true);
}).then(
function(module) {
Module['preloadedWasm'][name] = module;
onload();
},
function(err) {
console.warn("Couldn't instantiate wasm: " + name + " '" + err + "'");
onerror();
});
};
Module['preloadPlugins'].push(wasmPlugin);
#endif // MAIN_MODULE
#endif // WASM
// Canvas event setup
function pointerLockChange() {
Browser.pointerLock = document['pointerLockElement'] === Module['canvas'] ||
document['mozPointerLockElement'] === Module['canvas'] ||
document['webkitPointerLockElement'] === Module['canvas'] ||
document['msPointerLockElement'] === Module['canvas'];
}
var canvas = Module['canvas'];
if (canvas) {
// forced aspect ratio can be enabled by defining 'forcedAspectRatio' on Module
// Module['forcedAspectRatio'] = 4 / 3;
canvas.requestPointerLock = canvas['requestPointerLock'] ||
canvas['mozRequestPointerLock'] ||
canvas['webkitRequestPointerLock'] ||
canvas['msRequestPointerLock'] ||
function(){};
canvas.exitPointerLock = document['exitPointerLock'] ||
document['mozExitPointerLock'] ||
document['webkitExitPointerLock'] ||
document['msExitPointerLock'] ||
function(){}; // no-op if function does not exist
canvas.exitPointerLock = canvas.exitPointerLock.bind(document);
document.addEventListener('pointerlockchange', pointerLockChange, false);
document.addEventListener('mozpointerlockchange', pointerLockChange, false);
document.addEventListener('webkitpointerlockchange', pointerLockChange, false);
document.addEventListener('mspointerlockchange', pointerLockChange, false);
if (Module['elementPointerLock']) {
canvas.addEventListener("click", function(ev) {
if (!Browser.pointerLock && Module['canvas'].requestPointerLock) {
Module['canvas'].requestPointerLock();
ev.preventDefault();
}
}, false);
}
}
},
createContext: function(canvas, useWebGL, setInModule, webGLContextAttributes) {
if (useWebGL && Module.ctx && canvas == Module.canvas) return Module.ctx; // no need to recreate GL context if it's already been created for this canvas.
var ctx;
var contextHandle;
if (useWebGL) {
// For GLES2/desktop GL compatibility, adjust a few defaults to be different to WebGL defaults, so that they align better with the desktop defaults.
var contextAttributes = {
antialias: false,
alpha: false
};
if (webGLContextAttributes) {
for (var attribute in webGLContextAttributes) {
contextAttributes[attribute] = webGLContextAttributes[attribute];
}
}
contextHandle = GL.createContext(canvas, contextAttributes);
if (contextHandle) {
ctx = GL.getContext(contextHandle).GLctx;
}
} else {
ctx = canvas.getContext('2d');
}
if (!ctx) return null;
if (setInModule) {
if (!useWebGL) assert(typeof GLctx === 'undefined', 'cannot set in module if GLctx is used, but we are a non-GL context that would replace it');
Module.ctx = ctx;
if (useWebGL) GL.makeContextCurrent(contextHandle);
Module.useWebGL = useWebGL;
Browser.moduleContextCreatedCallbacks.forEach(function(callback) { callback() });
Browser.init();
}
return ctx;
},
destroyContext: function(canvas, useWebGL, setInModule) {},
fullscreenHandlersInstalled: false,
lockPointer: undefined,
resizeCanvas: undefined,
requestFullscreen: function(lockPointer, resizeCanvas, vrDevice) {
Browser.lockPointer = lockPointer;
Browser.resizeCanvas = resizeCanvas;
Browser.vrDevice = vrDevice;
if (typeof Browser.lockPointer === 'undefined') Browser.lockPointer = true;
if (typeof Browser.resizeCanvas === 'undefined') Browser.resizeCanvas = false;
if (typeof Browser.vrDevice === 'undefined') Browser.vrDevice = null;
var canvas = Module['canvas'];
function fullscreenChange() {
Browser.isFullscreen = false;
var canvasContainer = canvas.parentNode;
if ((document['fullscreenElement'] || document['mozFullScreenElement'] ||
document['msFullscreenElement'] || document['webkitFullscreenElement'] ||
document['webkitCurrentFullScreenElement']) === canvasContainer) {
canvas.exitFullscreen = document['exitFullscreen'] ||
document['cancelFullScreen'] ||
document['mozCancelFullScreen'] ||
document['msExitFullscreen'] ||
document['webkitCancelFullScreen'] ||
function() {};
canvas.exitFullscreen = canvas.exitFullscreen.bind(document);
if (Browser.lockPointer) canvas.requestPointerLock();
Browser.isFullscreen = true;
if (Browser.resizeCanvas) {
Browser.setFullscreenCanvasSize();
} else {
Browser.updateCanvasDimensions(canvas);
}
} else {
// remove the full screen specific parent of the canvas again to restore the HTML structure from before going full screen
canvasContainer.parentNode.insertBefore(canvas, canvasContainer);
canvasContainer.parentNode.removeChild(canvasContainer);
if (Browser.resizeCanvas) {
Browser.setWindowedCanvasSize();
} else {
Browser.updateCanvasDimensions(canvas);
}
}
if (Module['onFullScreen']) Module['onFullScreen'](Browser.isFullscreen);
if (Module['onFullscreen']) Module['onFullscreen'](Browser.isFullscreen);
}
if (!Browser.fullscreenHandlersInstalled) {
Browser.fullscreenHandlersInstalled = true;
document.addEventListener('fullscreenchange', fullscreenChange, false);
document.addEventListener('mozfullscreenchange', fullscreenChange, false);
document.addEventListener('webkitfullscreenchange', fullscreenChange, false);
document.addEventListener('MSFullscreenChange', fullscreenChange, false);
}
// create a new parent to ensure the canvas has no siblings. this allows browsers to optimize full screen performance when its parent is the full screen root
var canvasContainer = document.createElement("div");
canvas.parentNode.insertBefore(canvasContainer, canvas);
canvasContainer.appendChild(canvas);
// use parent of canvas as full screen root to allow aspect ratio correction (Firefox stretches the root to screen size)
canvasContainer.requestFullscreen = canvasContainer['requestFullscreen'] ||
canvasContainer['mozRequestFullScreen'] ||
canvasContainer['msRequestFullscreen'] ||
(canvasContainer['webkitRequestFullscreen'] ? function() { canvasContainer['webkitRequestFullscreen'](Element['ALLOW_KEYBOARD_INPUT']) } : null) ||
(canvasContainer['webkitRequestFullScreen'] ? function() { canvasContainer['webkitRequestFullScreen'](Element['ALLOW_KEYBOARD_INPUT']) } : null);
if (vrDevice) {
canvasContainer.requestFullscreen({ vrDisplay: vrDevice });
} else {
canvasContainer.requestFullscreen();
}
},
requestFullScreen: function(lockPointer, resizeCanvas, vrDevice) {
err('Browser.requestFullScreen() is deprecated. Please call Browser.requestFullscreen instead.');
Browser.requestFullScreen = function(lockPointer, resizeCanvas, vrDevice) {
return Browser.requestFullscreen(lockPointer, resizeCanvas, vrDevice);
}
return Browser.requestFullscreen(lockPointer, resizeCanvas, vrDevice);
},
nextRAF: 0,
fakeRequestAnimationFrame: function(func) {
// try to keep 60fps between calls to here
var now = Date.now();
if (Browser.nextRAF === 0) {
Browser.nextRAF = now + 1000/60;
} else {
while (now + 2 >= Browser.nextRAF) { // fudge a little, to avoid timer jitter causing us to do lots of delay:0
Browser.nextRAF += 1000/60;
}
}
var delay = Math.max(Browser.nextRAF - now, 0);
setTimeout(func, delay);
},
requestAnimationFrame: function requestAnimationFrame(func) {
if (typeof window === 'undefined') { // Provide fallback to setTimeout if window is undefined (e.g. in Node.js)
Browser.fakeRequestAnimationFrame(func);
} else {
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = window['requestAnimationFrame'] ||
window['mozRequestAnimationFrame'] ||
window['webkitRequestAnimationFrame'] ||
window['msRequestAnimationFrame'] ||
window['oRequestAnimationFrame'] ||
Browser.fakeRequestAnimationFrame;
}
window.requestAnimationFrame(func);
}
},
// generic abort-aware wrapper for an async callback
safeCallback: function(func) {
return function() {
if (!ABORT) return func.apply(null, arguments);
};
},
// abort and pause-aware versions TODO: build main loop on top of this?
allowAsyncCallbacks: true,
queuedAsyncCallbacks: [],
pauseAsyncCallbacks: function() {
Browser.allowAsyncCallbacks = false;
},
resumeAsyncCallbacks: function() { // marks future callbacks as ok to execute, and synchronously runs any remaining ones right now
Browser.allowAsyncCallbacks = true;
if (Browser.queuedAsyncCallbacks.length > 0) {
var callbacks = Browser.queuedAsyncCallbacks;
Browser.queuedAsyncCallbacks = [];
callbacks.forEach(function(func) {
func();
});
}
},
safeRequestAnimationFrame: function(func) {
return Browser.requestAnimationFrame(function() {
if (ABORT) return;
if (Browser.allowAsyncCallbacks) {
func();
} else {
Browser.queuedAsyncCallbacks.push(func);
}
});
},
safeSetTimeout: function(func, timeout) {
Module['noExitRuntime'] = true;
return setTimeout(function() {
if (ABORT) return;
if (Browser.allowAsyncCallbacks) {
func();
} else {
Browser.queuedAsyncCallbacks.push(func);
}
}, timeout);
},
safeSetInterval: function(func, timeout) {
Module['noExitRuntime'] = true;
return setInterval(function() {
if (ABORT) return;
if (Browser.allowAsyncCallbacks) {
func();
} // drop it on the floor otherwise, next interval will kick in
}, timeout);
},
getMimetype: function(name) {
return {
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'png': 'image/png',
'bmp': 'image/bmp',
'ogg': 'audio/ogg',
'wav': 'audio/wav',
'mp3': 'audio/mpeg'
}[name.substr(name.lastIndexOf('.')+1)];
},
getUserMedia: function(func) {
if(!window.getUserMedia) {
window.getUserMedia = navigator['getUserMedia'] ||
navigator['mozGetUserMedia'];
}
window.getUserMedia(func);
},
getMovementX: function(event) {
return event['movementX'] ||
event['mozMovementX'] ||
event['webkitMovementX'] ||
0;
},
getMovementY: function(event) {
return event['movementY'] ||
event['mozMovementY'] ||
event['webkitMovementY'] ||
0;
},
// Browsers specify wheel direction according to the page CSS pixel Y direction:
// Scrolling mouse wheel down (==towards user/away from screen) on Windows/Linux (and OSX without 'natural scroll' enabled)
// is the positive wheel direction. Scrolling mouse wheel up (towards the screen) is the negative wheel direction.
// This function returns the wheel direction in the browser page coordinate system (+: down, -: up). Note that this is often the
// opposite of native code: In native APIs the positive scroll direction is to scroll up (away from the user).
// NOTE: The mouse wheel delta is a decimal number, and can be a fractional value within -1 and 1. If you need to represent
// this as an integer, don't simply cast to int, or you may receive scroll events for wheel delta == 0.
getMouseWheelDelta: function(event) {
var delta = 0;
switch (event.type) {
case 'DOMMouseScroll':
delta = event.detail;
break;
case 'mousewheel':
delta = event.wheelDelta;
break;
case 'wheel':
delta = event['deltaY'];
break;
default:
throw 'unrecognized mouse wheel event: ' + event.type;
}
return delta;
},
mouseX: 0,
mouseY: 0,
mouseMovementX: 0,
mouseMovementY: 0,
touches: {},
lastTouches: {},
calculateMouseEvent: function(event) { // event should be mousemove, mousedown or mouseup
if (Browser.pointerLock) {
// When the pointer is locked, calculate the coordinates
// based on the movement of the mouse.
// Workaround for Firefox bug 764498
if (event.type != 'mousemove' &&
('mozMovementX' in event)) {
Browser.mouseMovementX = Browser.mouseMovementY = 0;
} else {
Browser.mouseMovementX = Browser.getMovementX(event);
Browser.mouseMovementY = Browser.getMovementY(event);
}
// check if SDL is available
if (typeof SDL != "undefined") {
Browser.mouseX = SDL.mouseX + Browser.mouseMovementX;
Browser.mouseY = SDL.mouseY + Browser.mouseMovementY;
} else {
// just add the mouse delta to the current absolut mouse position
// FIXME: ideally this should be clamped against the canvas size and zero
Browser.mouseX += Browser.mouseMovementX;
Browser.mouseY += Browser.mouseMovementY;
}
} else {
// Otherwise, calculate the movement based on the changes
// in the coordinates.
var rect = Module["canvas"].getBoundingClientRect();
var cw = Module["canvas"].width;
var ch = Module["canvas"].height;
// Neither .scrollX or .pageXOffset are defined in a spec, but
// we prefer .scrollX because it is currently in a spec draft.
// (see: http://www.w3.org/TR/2013/WD-cssom-view-20131217/)
var scrollX = ((typeof window.scrollX !== 'undefined') ? window.scrollX : window.pageXOffset);
var scrollY = ((typeof window.scrollY !== 'undefined') ? window.scrollY : window.pageYOffset);
#if ASSERTIONS
// If this assert lands, it's likely because the browser doesn't support scrollX or pageXOffset
// and we have no viable fallback.
assert((typeof scrollX !== 'undefined') && (typeof scrollY !== 'undefined'), 'Unable to retrieve scroll position, mouse positions likely broken.');
#endif
if (event.type === 'touchstart' || event.type === 'touchend' || event.type === 'touchmove') {
var touch = event.touch;
if (touch === undefined) {
return; // the "touch" property is only defined in SDL
}
var adjustedX = touch.pageX - (scrollX + rect.left);
var adjustedY = touch.pageY - (scrollY + rect.top);
adjustedX = adjustedX * (cw / rect.width);
adjustedY = adjustedY * (ch / rect.height);
var coords = { x: adjustedX, y: adjustedY };
if (event.type === 'touchstart') {
Browser.lastTouches[touch.identifier] = coords;
Browser.touches[touch.identifier] = coords;
} else if (event.type === 'touchend' || event.type === 'touchmove') {
var last = Browser.touches[touch.identifier];
if (!last) last = coords;
Browser.lastTouches[touch.identifier] = last;
Browser.touches[touch.identifier] = coords;
}
return;
}
var x = event.pageX - (scrollX + rect.left);
var y = event.pageY - (scrollY + rect.top);
// the canvas might be CSS-scaled compared to its backbuffer;
// SDL-using content will want mouse coordinates in terms
// of backbuffer units.
x = x * (cw / rect.width);
y = y * (ch / rect.height);
Browser.mouseMovementX = x - Browser.mouseX;
Browser.mouseMovementY = y - Browser.mouseY;
Browser.mouseX = x;
Browser.mouseY = y;
}
},
asyncLoad: function(url, onload, onerror, noRunDep) {
var dep = !noRunDep ? getUniqueRunDependency('al ' + url) : '';
Module['readAsync'](url, function(arrayBuffer) {
assert(arrayBuffer, 'Loading data file "' + url + '" failed (no arrayBuffer).');
onload(new Uint8Array(arrayBuffer));
if (dep) removeRunDependency(dep);
}, function(event) {
if (onerror) {
onerror();
} else {
throw 'Loading data file "' + url + '" failed.';
}
});
if (dep) addRunDependency(dep);
},
resizeListeners: [],
updateResizeListeners: function() {
var canvas = Module['canvas'];
Browser.resizeListeners.forEach(function(listener) {
listener(canvas.width, canvas.height);
});
},
setCanvasSize: function(width, height, noUpdates) {
var canvas = Module['canvas'];
Browser.updateCanvasDimensions(canvas, width, height);
if (!noUpdates) Browser.updateResizeListeners();
},
windowedWidth: 0,
windowedHeight: 0,
setFullscreenCanvasSize: function() {
// check if SDL is available
if (typeof SDL != "undefined") {
var flags = {{{ makeGetValue('SDL.screen', '0', 'i32', 0, 1) }}};
flags = flags | 0x00800000; // set SDL_FULLSCREEN flag
{{{ makeSetValue('SDL.screen', '0', 'flags', 'i32') }}}
}
Browser.updateCanvasDimensions(Module['canvas']);
Browser.updateResizeListeners();
},
setWindowedCanvasSize: function() {
// check if SDL is available
if (typeof SDL != "undefined") {
var flags = {{{ makeGetValue('SDL.screen', '0', 'i32', 0, 1) }}};
flags = flags & ~0x00800000; // clear SDL_FULLSCREEN flag
{{{ makeSetValue('SDL.screen', '0', 'flags', 'i32') }}}
}
Browser.updateCanvasDimensions(Module['canvas']);
Browser.updateResizeListeners();
},
updateCanvasDimensions : function(canvas, wNative, hNative) {
if (wNative && hNative) {
canvas.widthNative = wNative;
canvas.heightNative = hNative;
} else {
wNative = canvas.widthNative;
hNative = canvas.heightNative;
}
var w = wNative;
var h = hNative;
if (Module['forcedAspectRatio'] && Module['forcedAspectRatio'] > 0) {
if (w/h < Module['forcedAspectRatio']) {
w = Math.round(h * Module['forcedAspectRatio']);
} else {
h = Math.round(w / Module['forcedAspectRatio']);
}
}
if (((document['fullscreenElement'] || document['mozFullScreenElement'] ||
document['msFullscreenElement'] || document['webkitFullscreenElement'] ||
document['webkitCurrentFullScreenElement']) === canvas.parentNode) && (typeof screen != 'undefined')) {
var factor = Math.min(screen.width / w, screen.height / h);
w = Math.round(w * factor);
h = Math.round(h * factor);
}
if (Browser.resizeCanvas) {
if (canvas.width != w) canvas.width = w;
if (canvas.height != h) canvas.height = h;
if (typeof canvas.style != 'undefined') {
canvas.style.removeProperty( "width");
canvas.style.removeProperty("height");
}
} else {
if (canvas.width != wNative) canvas.width = wNative;
if (canvas.height != hNative) canvas.height = hNative;
if (typeof canvas.style != 'undefined') {
if (w != wNative || h != hNative) {
canvas.style.setProperty( "width", w + "px", "important");
canvas.style.setProperty("height", h + "px", "important");
} else {
canvas.style.removeProperty( "width");
canvas.style.removeProperty("height");
}
}
}
},
wgetRequests: {},
nextWgetRequestHandle: 0,
getNextWgetRequestHandle: function() {
var handle = Browser.nextWgetRequestHandle;
Browser.nextWgetRequestHandle++;
return handle;
}
},
emscripten_async_wget__deps: ['$PATH'],
emscripten_async_wget__proxy: 'sync',
emscripten_async_wget__sig: 'viiii',
emscripten_async_wget: function(url, file, onload, onerror) {
Module['noExitRuntime'] = true;
var _url = Pointer_stringify(url);
var _file = Pointer_stringify(file);
_file = PATH.resolve(FS.cwd(), _file);
function doCallback(callback) {
if (callback) {
var stack = stackSave();
Module['dynCall_vi'](callback, allocate(intArrayFromString(_file), 'i8', ALLOC_STACK));
stackRestore(stack);
}
}
var destinationDirectory = PATH.dirname(_file);
FS.createPreloadedFile(
destinationDirectory,
PATH.basename(_file),
_url, true, true,
function() {
doCallback(onload);
},
function() {
doCallback(onerror);
},
false, // dontCreateFile
false, // canOwn
function() { // preFinish
// if a file exists there, we overwrite it
try {
FS.unlink(_file);
} catch (e) {}
// if the destination directory does not yet exist, create it
FS.mkdirTree(destinationDirectory);
}
);
},
emscripten_async_wget_data__proxy: 'sync',
emscripten_async_wget_data__sig: 'viiii',
emscripten_async_wget_data: function(url, arg, onload, onerror) {
Browser.asyncLoad(Pointer_stringify(url), function(byteArray) {
var buffer = _malloc(byteArray.length);
HEAPU8.set(byteArray, buffer);
Module['dynCall_viii'](onload, arg, buffer, byteArray.length);
_free(buffer);
}, function() {
if (onerror) Module['dynCall_vi'](onerror, arg);
}, true /* no need for run dependency, this is async but will not do any prepare etc. step */ );
},
emscripten_async_wget2__proxy: 'sync',
emscripten_async_wget2__sig: 'iiiiiiiii',
emscripten_async_wget2: function(url, file, request, param, arg, onload, onerror, onprogress) {
Module['noExitRuntime'] = true;
var _url = Pointer_stringify(url);
var _file = Pointer_stringify(file);
_file = PATH.resolve(FS.cwd(), _file);
var _request = Pointer_stringify(request);
var _param = Pointer_stringify(param);
var index = _file.lastIndexOf('/');
var http = new XMLHttpRequest();
http.open(_request, _url, true);
http.responseType = 'arraybuffer';
var handle = Browser.getNextWgetRequestHandle();
var destinationDirectory = PATH.dirname(_file);
// LOAD
http.onload = function http_onload(e) {
if (http.status == 200) {
// if a file exists there, we overwrite it
try {
FS.unlink(_file);
} catch (e) {}
// if the destination directory does not yet exist, create it
FS.mkdirTree(destinationDirectory);
FS.createDataFile( _file.substr(0, index), _file.substr(index + 1), new Uint8Array(http.response), true, true, false);
if (onload) {
var stack = stackSave();
Module['dynCall_viii'](onload, handle, arg, allocate(intArrayFromString(_file), 'i8', ALLOC_STACK));
stackRestore(stack);
}
} else {
if (onerror) Module['dynCall_viii'](onerror, handle, arg, http.status);
}
delete Browser.wgetRequests[handle];
};
// ERROR
http.onerror = function http_onerror(e) {
if (onerror) Module['dynCall_viii'](onerror, handle, arg, http.status);
delete Browser.wgetRequests[handle];
};
// PROGRESS
http.onprogress = function http_onprogress(e) {
if (e.lengthComputable || (e.lengthComputable === undefined && e.total != 0)) {
var percentComplete = (e.loaded / e.total)*100;
if (onprogress) Module['dynCall_viii'](onprogress, handle, arg, percentComplete);
}
};
// ABORT
http.onabort = function http_onabort(e) {
delete Browser.wgetRequests[handle];
};
if (_request == "POST") {
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(_param);
} else {
http.send(null);
}
Browser.wgetRequests[handle] = http;
return handle;
},
emscripten_async_wget2_data__proxy: 'sync',
emscripten_async_wget2_data__sig: 'iiiiiiiii',
emscripten_async_wget2_data: function(url, request, param, arg, free, onload, onerror, onprogress) {
var _url = Pointer_stringify(url);
var _request = Pointer_stringify(request);
var _param = Pointer_stringify(param);
var http = new XMLHttpRequest();
http.open(_request, _url, true);
http.responseType = 'arraybuffer';
var handle = Browser.getNextWgetRequestHandle();
// LOAD
http.onload = function http_onload(e) {
if (http.status == 200 || _url.substr(0,4).toLowerCase() != "http") {
var byteArray = new Uint8Array(http.response);
var buffer = _malloc(byteArray.length);
HEAPU8.set(byteArray, buffer);
if (onload) Module['dynCall_viiii'](onload, handle, arg, buffer, byteArray.length);
if (free) _free(buffer);
} else {
if (onerror) Module['dynCall_viiii'](onerror, handle, arg, http.status, http.statusText);
}
delete Browser.wgetRequests[handle];
};
// ERROR
http.onerror = function http_onerror(e) {
if (onerror) {
Module['dynCall_viiii'](onerror, handle, arg, http.status, http.statusText);
}
delete Browser.wgetRequests[handle];
};
// PROGRESS
http.onprogress = function http_onprogress(e) {
if (onprogress) Module['dynCall_viiii'](onprogress, handle, arg, e.loaded, e.lengthComputable || e.lengthComputable === undefined ? e.total : 0);
};
// ABORT
http.onabort = function http_onabort(e) {
delete Browser.wgetRequests[handle];
};
if (_request == "POST") {
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(_param);
} else {
http.send(null);
}
Browser.wgetRequests[handle] = http;
return handle;
},
emscripten_async_wget2_abort__proxy: 'sync',
emscripten_async_wget2_abort__sig: 'vi',
emscripten_async_wget2_abort: function(handle) {
var http = Browser.wgetRequests[handle];
if (http) {
http.abort();
}
},
emscripten_run_preload_plugins__deps: ['$PATH'],
emscripten_run_preload_plugins__proxy: 'sync',
emscripten_run_preload_plugins__sig: 'iiii',
emscripten_run_preload_plugins: function(file, onload, onerror) {
Module['noExitRuntime'] = true;
var _file = Pointer_stringify(file);
var data = FS.analyzePath(_file);
if (!data.exists) return -1;
FS.createPreloadedFile(
PATH.dirname(_file),
PATH.basename(_file),
new Uint8Array(data.object.contents), true, true,
function() {
if (onload) Module['dynCall_vi'](onload, file);
},
function() {
if (onerror) Module['dynCall_vi'](onerror, file);
},
true // don'tCreateFile - it's already there
);
return 0;
},
emscripten_run_preload_plugins_data__proxy: 'sync',
emscripten_run_preload_plugins_data__sig: 'viiiiii',
emscripten_run_preload_plugins_data: function(data, size, suffix, arg, onload, onerror) {
Module['noExitRuntime'] = true;