-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
Copy pathlibrary_sdl.js
3493 lines (3082 loc) · 130 KB
/
library_sdl.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//"use strict";
// See browser tests for examples (tests/runner.py, search for sdl_). Run with
// python tests/runner.py browser
// Notes:
// SDL_VIDEORESIZE: This is sent when the canvas is resized. Note that the user
// cannot manually do so, so this is only sent when the
// program manually resizes it (emscripten_set_canvas_size
// or otherwise).
var LibrarySDL = {
$SDL__deps: [
#if NO_FILESYSTEM == 0
'$FS',
#endif
'$PATH', '$Browser', 'SDL_GetTicks'
],
$SDL: {
defaults: {
width: 320,
height: 200,
// If true, SDL_LockSurface will copy the contents of each surface back to the Emscripten HEAP so that C code can access it. If false,
// the surface contents are captured only back to JS code.
copyOnLock: true,
// If true, SDL_LockSurface will discard the contents of each surface when SDL_LockSurface() is called. This greatly improves performance
// of SDL_LockSurface(). If discardOnLock is true, copyOnLock is ignored.
discardOnLock: false,
// If true, emulate compatibility with desktop SDL by ignoring alpha on the screen frontbuffer canvas. Setting this to false will improve
// performance considerably and enables alpha-blending on the frontbuffer, so be sure to properly write 0xFF alpha for opaque pixels
// if you set this to false!
opaqueFrontBuffer: true
},
version: null,
surfaces: {},
// A pool of freed canvas elements. Reusing them avoids GC pauses.
canvasPool: [],
events: [],
fonts: [null],
// The currently preloaded audio elements ready to be played
audios: [null],
rwops: [null],
// The currently playing audio element. There's only one music track.
music: {
audio: null,
volume: 1.0
},
mixerFrequency: 22050,
mixerFormat: {{{ cDefine('AUDIO_S16LSB') }}}, //0x8010, // AUDIO_S16LSB
mixerNumChannels: 2,
mixerChunkSize: 1024,
channelMinimumNumber: 0,
GL: false, // Set to true if we call SDL_SetVideoMode with SDL_OPENGL, and if so, we do not create 2D canvases&contexts for blitting
// Note that images loaded before SDL_SetVideoMode will not get this optimization
// all possible GL attributes, with their default value
glAttributes: {
0: 3, /* SDL_GL_RED_SIZE */
1: 3, /* SDL_GL_GREEN_SIZE */
2: 2, /* SDL_GL_BLUE_SIZE */
3: 0, /* SDL_GL_ALPHA_SIZE */
4: 0, /* SDL_GL_BUFFER_SIZE */
5: 1, /* SDL_GL_DOUBLEBUFFER */
6: 16, /* SDL_GL_DEPTH_SIZE */
7: 0, /* SDL_GL_STENCIL_SIZE */
8: 0, /* SDL_GL_ACCUM_RED_SIZE */
9: 0, /* SDL_GL_ACCUM_GREEN_SIZE */
10: 0, /* SDL_GL_ACCUM_BLUE_SIZE */
11: 0, /* SDL_GL_ACCUM_ALPHA_SIZE */
12: 0, /* SDL_GL_STEREO */
13: 0, /* SDL_GL_MULTISAMPLEBUFFERS */
14: 0, /* SDL_GL_MULTISAMPLESAMPLES */
15: 1, /* SDL_GL_ACCELERATED_VISUAL */
16: 0, /* SDL_GL_RETAINED_BACKING */
17: 0, /* SDL_GL_CONTEXT_MAJOR_VERSION */
18: 0 /* SDL_GL_CONTEXT_MINOR_VERSION */
},
keyboardState: null,
keyboardMap: {},
canRequestFullscreen: false,
isRequestingFullscreen: false,
textInput: false,
startTime: null,
initFlags: 0, // The flags passed to SDL_Init
buttonState: 0,
modState: 0,
DOMButtons: [0, 0, 0],
DOMEventToSDLEvent: {},
TOUCH_DEFAULT_ID: 0, // Our default deviceID for touch events (we get nothing from the browser)
eventHandler: null,
eventHandlerContext: null,
eventHandlerTemp: 0,
keyCodes: { // DOM code ==> SDL code. See https://developer.mozilla.org/en/Document_Object_Model_%28DOM%29/KeyboardEvent and SDL_keycode.h
// For keys that don't have unicode value, we map DOM codes with the corresponding scan codes + 1024 (using "| 1 << 10")
16: 225 | 1<<10, // shift
17: 224 | 1<<10, // control (right, or left)
18: 226 | 1<<10, // alt
20: 57 | 1<<10, // caps lock
33: 75 | 1<<10, // pagedup
34: 78 | 1<<10, // pagedown
35: 77 | 1<<10, // end
36: 74 | 1<<10, // home
37: 80 | 1<<10, // left arrow
38: 82 | 1<<10, // up arrow
39: 79 | 1<<10, // right arrow
40: 81 | 1<<10, // down arrow
44: 316, // print screen
45: 73 | 1<<10, // insert
46: 127, // SDLK_DEL == '\177'
91: 227 | 1<<10, // windows key or super key on linux (doesn't work on Mac)
93: 101 | 1<<10, // application
96: 98 | 1<<10, // keypad 0
97: 89 | 1<<10, // keypad 1
98: 90 | 1<<10, // keypad 2
99: 91 | 1<<10, // keypad 3
100: 92 | 1<<10, // keypad 4
101: 93 | 1<<10, // keypad 5
102: 94 | 1<<10, // keypad 6
103: 95 | 1<<10, // keypad 7
104: 96 | 1<<10, // keypad 8
105: 97 | 1<<10, // keypad 9
106: 85 | 1<<10, // keypad multiply
107: 87 | 1<<10, // keypad plus
109: 86 | 1<<10, // keypad minus
110: 99 | 1<<10, // keypad decimal point
111: 84 | 1<<10, // keypad divide
112: 58 | 1<<10, // F1
113: 59 | 1<<10, // F2
114: 60 | 1<<10, // F3
115: 61 | 1<<10, // F4
116: 62 | 1<<10, // F5
117: 63 | 1<<10, // F6
118: 64 | 1<<10, // F7
119: 65 | 1<<10, // F8
120: 66 | 1<<10, // F9
121: 67 | 1<<10, // F10
122: 68 | 1<<10, // F11
123: 69 | 1<<10, // F12
124: 104 | 1<<10, // F13
125: 105 | 1<<10, // F14
126: 106 | 1<<10, // F15
127: 107 | 1<<10, // F16
128: 108 | 1<<10, // F17
129: 109 | 1<<10, // F18
130: 110 | 1<<10, // F19
131: 111 | 1<<10, // F20
132: 112 | 1<<10, // F21
133: 113 | 1<<10, // F22
134: 114 | 1<<10, // F23
135: 115 | 1<<10, // F24
144: 83 | 1<<10, // keypad num lock
160: 94, // caret
161: 33, // exclaim
162: 34, // double quote
163: 35, // hash
164: 36, // dollar
165: 37, // percent
166: 38, // ampersand
167: 95, // underscore
168: 40, // open parenthesis
169: 41, // close parenthesis
170: 42, // asterix
171: 43, // plus
172: 124, // pipe
173: 45, // minus
174: 123, // open curly bracket
175: 125, // close curly bracket
176: 126, // tilde
181: 127, // audio mute
182: 129, // audio volume down
183: 128, // audio volume up
188: 44, // comma
190: 46, // period
191: 47, // slash (/)
192: 96, // backtick/backquote (`)
219: 91, // open square bracket
220: 92, // back slash
221: 93, // close square bracket
222: 39, // quote
224: 227 | 1<<10, // meta (command/windows)
},
scanCodes: { // SDL keycode ==> SDL scancode. See SDL_scancode.h
8: 42, // backspace
9: 43, // tab
13: 40, // return
27: 41, // escape
32: 44, // space
35: 204, // hash
39: 53, // grave
44: 54, // comma
46: 55, // period
47: 56, // slash
48: 39, // 0
49: 30, // 1
50: 31, // 2
51: 32, // 3
52: 33, // 4
53: 34, // 5
54: 35, // 6
55: 36, // 7
56: 37, // 8
57: 38, // 9
58: 203, // colon
59: 51, // semicolon
61: 46, // equals
91: 47, // left bracket
92: 49, // backslash
93: 48, // right bracket
96: 52, // apostrophe
97: 4, // A
98: 5, // B
99: 6, // C
100: 7, // D
101: 8, // E
102: 9, // F
103: 10, // G
104: 11, // H
105: 12, // I
106: 13, // J
107: 14, // K
108: 15, // L
109: 16, // M
110: 17, // N
111: 18, // O
112: 19, // P
113: 20, // Q
114: 21, // R
115: 22, // S
116: 23, // T
117: 24, // U
118: 25, // V
119: 26, // W
120: 27, // X
121: 28, // Y
122: 29, // Z
127: 76, // delete
305: 224, // ctrl
308: 226, // alt
316: 70, // print screen
},
loadRect: function(rect) {
return {
x: {{{ makeGetValue('rect + ' + C_STRUCTS.SDL_Rect.x, '0', 'i32') }}},
y: {{{ makeGetValue('rect + ' + C_STRUCTS.SDL_Rect.y, '0', 'i32') }}},
w: {{{ makeGetValue('rect + ' + C_STRUCTS.SDL_Rect.w, '0', 'i32') }}},
h: {{{ makeGetValue('rect + ' + C_STRUCTS.SDL_Rect.h, '0', 'i32') }}}
};
},
updateRect: function(rect, r) {
{{{ makeSetValue('rect', C_STRUCTS.SDL_Rect.x, 'r.x', 'i32') }}};
{{{ makeSetValue('rect', C_STRUCTS.SDL_Rect.y, 'r.y', 'i32') }}};
{{{ makeSetValue('rect', C_STRUCTS.SDL_Rect.w, 'r.w', 'i32') }}};
{{{ makeSetValue('rect', C_STRUCTS.SDL_Rect.h, 'r.h', 'i32') }}};
},
intersectionOfRects: function(first, second) {
var leftX = Math.max(first.x, second.x);
var leftY = Math.max(first.y, second.y);
var rightX = Math.min(first.x + first.w, second.x + second.w);
var rightY = Math.min(first.y + first.h, second.y + second.h);
return {
x: leftX,
y: leftY,
w: Math.max(leftX, rightX) - leftX,
h: Math.max(leftY, rightY) - leftY
}
},
checkPixelFormat: function(fmt) {
#if ASSERTIONS
// Canvas screens are always RGBA.
var format = {{{ makeGetValue('fmt', C_STRUCTS.SDL_PixelFormat.format, 'i32') }}};
if (format != {{{ cDefine('SDL_PIXELFORMAT_RGBA8888') }}}) {
Runtime.warnOnce('Unsupported pixel format!');
}
#endif
},
// Load SDL color into a CSS-style color specification
loadColorToCSSRGB: function(color) {
var rgba = {{{ makeGetValue('color', '0', 'i32') }}};
return 'rgb(' + (rgba&255) + ',' + ((rgba >> 8)&255) + ',' + ((rgba >> 16)&255) + ')';
},
loadColorToCSSRGBA: function(color) {
var rgba = {{{ makeGetValue('color', '0', 'i32') }}};
return 'rgba(' + (rgba&255) + ',' + ((rgba >> 8)&255) + ',' + ((rgba >> 16)&255) + ',' + (((rgba >> 24)&255)/255) + ')';
},
translateColorToCSSRGBA: function(rgba) {
return 'rgba(' + (rgba&0xff) + ',' + (rgba>>8 & 0xff) + ',' + (rgba>>16 & 0xff) + ',' + (rgba>>>24)/0xff + ')';
},
translateRGBAToCSSRGBA: function(r, g, b, a) {
return 'rgba(' + (r&0xff) + ',' + (g&0xff) + ',' + (b&0xff) + ',' + (a&0xff)/255 + ')';
},
translateRGBAToColor: function(r, g, b, a) {
return r | g << 8 | b << 16 | a << 24;
},
makeSurface: function(width, height, flags, usePageCanvas, source, rmask, gmask, bmask, amask) {
flags = flags || 0;
var is_SDL_HWSURFACE = flags & 0x00000001;
var is_SDL_HWPALETTE = flags & 0x00200000;
var is_SDL_OPENGL = flags & 0x04000000;
var surf = _malloc({{{ C_STRUCTS.SDL_Surface.__size__ }}});
var pixelFormat = _malloc({{{ C_STRUCTS.SDL_PixelFormat.__size__ }}});
//surface with SDL_HWPALETTE flag is 8bpp surface (1 byte)
var bpp = is_SDL_HWPALETTE ? 1 : 4;
var buffer = 0;
// preemptively initialize this for software surfaces,
// otherwise it will be lazily initialized inside of SDL_LockSurface
if (!is_SDL_HWSURFACE && !is_SDL_OPENGL) {
buffer = _malloc(width * height * 4);
}
{{{ makeSetValue('surf', C_STRUCTS.SDL_Surface.flags, 'flags', 'i32') }}};
{{{ makeSetValue('surf', C_STRUCTS.SDL_Surface.format, 'pixelFormat', 'void*') }}};
{{{ makeSetValue('surf', C_STRUCTS.SDL_Surface.w, 'width', 'i32') }}};
{{{ makeSetValue('surf', C_STRUCTS.SDL_Surface.h, 'height', 'i32') }}};
{{{ makeSetValue('surf', C_STRUCTS.SDL_Surface.pitch, 'width * bpp', 'i32') }}}; // assuming RGBA or indexed for now,
// since that is what ImageData gives us in browsers
{{{ makeSetValue('surf', C_STRUCTS.SDL_Surface.pixels, 'buffer', 'void*') }}};
{{{ makeSetValue('surf', C_STRUCTS.SDL_Surface.clip_rect+C_STRUCTS.SDL_Rect.x, '0', 'i32') }}};
{{{ makeSetValue('surf', C_STRUCTS.SDL_Surface.clip_rect+C_STRUCTS.SDL_Rect.y, '0', 'i32') }}};
{{{ makeSetValue('surf', C_STRUCTS.SDL_Surface.clip_rect+C_STRUCTS.SDL_Rect.w, 'Module["canvas"].width', 'i32') }}};
{{{ makeSetValue('surf', C_STRUCTS.SDL_Surface.clip_rect+C_STRUCTS.SDL_Rect.h, 'Module["canvas"].height', 'i32') }}};
{{{ makeSetValue('surf', C_STRUCTS.SDL_Surface.refcount, '1', 'i32') }}};
{{{ makeSetValue('pixelFormat', C_STRUCTS.SDL_PixelFormat.format, cDefine('SDL_PIXELFORMAT_RGBA8888'), 'i32') }}};
{{{ makeSetValue('pixelFormat', C_STRUCTS.SDL_PixelFormat.palette, '0', 'i32') }}};// TODO
{{{ makeSetValue('pixelFormat', C_STRUCTS.SDL_PixelFormat.BitsPerPixel, 'bpp * 8', 'i8') }}};
{{{ makeSetValue('pixelFormat', C_STRUCTS.SDL_PixelFormat.BytesPerPixel, 'bpp', 'i8') }}};
{{{ makeSetValue('pixelFormat', C_STRUCTS.SDL_PixelFormat.Rmask, 'rmask || 0x000000ff', 'i32') }}};
{{{ makeSetValue('pixelFormat', C_STRUCTS.SDL_PixelFormat.Gmask, 'gmask || 0x0000ff00', 'i32') }}};
{{{ makeSetValue('pixelFormat', C_STRUCTS.SDL_PixelFormat.Bmask, 'bmask || 0x00ff0000', 'i32') }}};
{{{ makeSetValue('pixelFormat', C_STRUCTS.SDL_PixelFormat.Amask, 'amask || 0xff000000', 'i32') }}};
// Decide if we want to use WebGL or not
SDL.GL = SDL.GL || is_SDL_OPENGL;
var canvas;
if (!usePageCanvas) {
if (SDL.canvasPool.length > 0) {
canvas = SDL.canvasPool.pop();
} else {
canvas = document.createElement('canvas');
}
canvas.width = width;
canvas.height = height;
} else {
canvas = Module['canvas'];
}
var webGLContextAttributes = {
antialias: ((SDL.glAttributes[13 /*SDL_GL_MULTISAMPLEBUFFERS*/] != 0) && (SDL.glAttributes[14 /*SDL_GL_MULTISAMPLESAMPLES*/] > 1)),
depth: (SDL.glAttributes[6 /*SDL_GL_DEPTH_SIZE*/] > 0),
stencil: (SDL.glAttributes[7 /*SDL_GL_STENCIL_SIZE*/] > 0),
alpha: (SDL.glAttributes[3 /*SDL_GL_ALPHA_SIZE*/] > 0)
};
var ctx = Browser.createContext(canvas, is_SDL_OPENGL, usePageCanvas, webGLContextAttributes);
SDL.surfaces[surf] = {
width: width,
height: height,
canvas: canvas,
ctx: ctx,
surf: surf,
buffer: buffer,
pixelFormat: pixelFormat,
alpha: 255,
flags: flags,
locked: 0,
usePageCanvas: usePageCanvas,
source: source,
isFlagSet: function(flag) {
return flags & flag;
}
};
return surf;
},
// Copy data from the C++-accessible storage to the canvas backing
// for surface with HWPALETTE flag(8bpp depth)
copyIndexedColorData: function(surfData, rX, rY, rW, rH) {
// HWPALETTE works with palette
// setted by SDL_SetColors
if (!surfData.colors) {
return;
}
var fullWidth = Module['canvas'].width;
var fullHeight = Module['canvas'].height;
var startX = rX || 0;
var startY = rY || 0;
var endX = (rW || (fullWidth - startX)) + startX;
var endY = (rH || (fullHeight - startY)) + startY;
var buffer = surfData.buffer;
if (!surfData.image.data32) {
surfData.image.data32 = new Uint32Array(surfData.image.data.buffer);
}
var data32 = surfData.image.data32;
var colors32 = surfData.colors32;
for (var y = startY; y < endY; ++y) {
var base = y * fullWidth;
for (var x = startX; x < endX; ++x) {
data32[base + x] = colors32[{{{ makeGetValue('buffer + base + x', '0', 'i8', null, true) }}}];
}
}
},
freeSurface: function(surf) {
var refcountPointer = surf + {{{ C_STRUCTS.SDL_Surface.refcount }}};
var refcount = {{{ makeGetValue('refcountPointer', '0', 'i32') }}};
if (refcount > 1) {
{{{ makeSetValue('refcountPointer', '0', 'refcount - 1', 'i32') }}};
return;
}
var info = SDL.surfaces[surf];
if (!info.usePageCanvas && info.canvas) SDL.canvasPool.push(info.canvas);
if (info.buffer) _free(info.buffer);
_free(info.pixelFormat);
_free(surf);
SDL.surfaces[surf] = null;
if (surf === SDL.screen) {
SDL.screen = null;
}
},
blitSurface__deps: ["SDL_LockSurface"],
blitSurface: function(src, srcrect, dst, dstrect, scale) {
var srcData = SDL.surfaces[src];
var dstData = SDL.surfaces[dst];
var sr, dr;
if (srcrect) {
sr = SDL.loadRect(srcrect);
} else {
sr = { x: 0, y: 0, w: srcData.width, h: srcData.height };
}
if (dstrect) {
dr = SDL.loadRect(dstrect);
} else {
dr = { x: 0, y: 0, w: srcData.width, h: srcData.height };
}
if (dstData.clipRect) {
var widthScale = (!scale || sr.w === 0) ? 1 : sr.w / dr.w;
var heightScale = (!scale || sr.h === 0) ? 1 : sr.h / dr.h;
dr = SDL.intersectionOfRects(dstData.clipRect, dr);
sr.w = dr.w * widthScale;
sr.h = dr.h * heightScale;
if (dstrect) {
SDL.updateRect(dstrect, dr);
}
}
var blitw, blith;
if (scale) {
blitw = dr.w; blith = dr.h;
} else {
blitw = sr.w; blith = sr.h;
}
if (sr.w === 0 || sr.h === 0 || blitw === 0 || blith === 0) {
return 0;
}
var oldAlpha = dstData.ctx.globalAlpha;
dstData.ctx.globalAlpha = srcData.alpha/255;
dstData.ctx.drawImage(srcData.canvas, sr.x, sr.y, sr.w, sr.h, dr.x, dr.y, blitw, blith);
dstData.ctx.globalAlpha = oldAlpha;
if (dst != SDL.screen) {
// XXX As in IMG_Load, for compatibility we write out |pixels|
Runtime.warnOnce('WARNING: copying canvas data to memory for compatibility');
_SDL_LockSurface(dst);
dstData.locked--; // The surface is not actually locked in this hack
}
return 0;
},
// the browser sends out touchstart events with the whole group of touches
// even if we received a previous touchstart for a specific touch identifier.
// You can test this by pressing one finger to the screen, then another. You'll
// receive two touchstart events, the first with a touches count of 1 the second
// with a touches count of two.
// SDL sends out a new touchstart event for only each newly started touch so to
// emulate this, we keep track of previously started touches.
downFingers: {},
savedKeydown: null,
receiveEvent: function(event) {
function unpressAllPressedKeys() {
// Un-press all pressed keys: TODO
for (var code in SDL.keyboardMap) {
SDL.events.push({
type: 'keyup',
keyCode: SDL.keyboardMap[code]
});
}
};
switch(event.type) {
case 'touchstart': case 'touchmove': {
event.preventDefault();
var touches = [];
// Clear out any touchstart events that we've already processed
if (event.type === 'touchstart') {
for (var i = 0; i < event.touches.length; i++) {
var touch = event.touches[i];
if (SDL.downFingers[touch.identifier] != true) {
SDL.downFingers[touch.identifier] = true;
touches.push(touch);
}
}
} else {
touches = event.touches;
}
var firstTouch = touches[0];
if (firstTouch) {
if (event.type == 'touchstart') {
SDL.DOMButtons[0] = 1;
}
var mouseEventType;
switch(event.type) {
case 'touchstart': mouseEventType = 'mousedown'; break;
case 'touchmove': mouseEventType = 'mousemove'; break;
}
var mouseEvent = {
type: mouseEventType,
button: 0,
pageX: firstTouch.clientX,
pageY: firstTouch.clientY
};
SDL.events.push(mouseEvent);
}
for (var i = 0; i < touches.length; i++) {
var touch = touches[i];
SDL.events.push({
type: event.type,
touch: touch
});
};
break;
}
case 'touchend': {
event.preventDefault();
// Remove the entry in the SDL.downFingers hash
// because the finger is no longer down.
for(var i = 0; i < event.changedTouches.length; i++) {
var touch = event.changedTouches[i];
if (SDL.downFingers[touch.identifier] === true) {
delete SDL.downFingers[touch.identifier];
}
}
var mouseEvent = {
type: 'mouseup',
button: 0,
pageX: event.changedTouches[0].clientX,
pageY: event.changedTouches[0].clientY
};
SDL.DOMButtons[0] = 0;
SDL.events.push(mouseEvent);
for (var i = 0; i < event.changedTouches.length; i++) {
var touch = event.changedTouches[i];
SDL.events.push({
type: 'touchend',
touch: touch
});
};
break;
}
case 'DOMMouseScroll': case 'mousewheel': case 'wheel':
var delta = -Browser.getMouseWheelDelta(event); // Flip the wheel direction to translate from browser wheel direction (+:down) to SDL direction (+:up)
delta = (delta == 0) ? 0 : (delta > 0 ? Math.max(delta, 1) : Math.min(delta, -1)); // Quantize to integer so that minimum scroll is at least +/- 1.
// Simulate old-style SDL events representing mouse wheel input as buttons
var button = delta > 0 ? 3 /*SDL_BUTTON_WHEELUP-1*/ : 4 /*SDL_BUTTON_WHEELDOWN-1*/; // Subtract one since JS->C marshalling is defined to add one back.
SDL.events.push({ type: 'mousedown', button: button, pageX: event.pageX, pageY: event.pageY });
SDL.events.push({ type: 'mouseup', button: button, pageX: event.pageX, pageY: event.pageY });
// Pass a delta motion event.
SDL.events.push({ type: 'wheel', deltaX: 0, deltaY: delta });
event.preventDefault(); // If we don't prevent this, then 'wheel' event will be sent again by the browser as 'DOMMouseScroll' and we will receive this same event the second time.
break;
case 'mousemove':
if (SDL.DOMButtons[0] === 1) {
SDL.events.push({
type: 'touchmove',
touch: {
identifier: 0,
deviceID: {{{ cDefine('SDL_TOUCH_MOUSEID') }}},
pageX: event.pageX,
pageY: event.pageY
}
});
}
if (Browser.pointerLock) {
// workaround for firefox bug 750111
if ('mozMovementX' in event) {
event['movementX'] = event['mozMovementX'];
event['movementY'] = event['mozMovementY'];
}
// workaround for Firefox bug 782777
if (event['movementX'] == 0 && event['movementY'] == 0) {
// ignore a mousemove event if it doesn't contain any movement info
// (without pointer lock, we infer movement from pageX/pageY, so this check is unnecessary)
event.preventDefault();
return;
}
}
// fall through
case 'keydown': case 'keyup': case 'keypress': case 'mousedown': case 'mouseup':
// If we preventDefault on keydown events, the subsequent keypress events
// won't fire. However, it's fine (and in some cases necessary) to
// preventDefault for keys that don't generate a character. Otherwise,
// preventDefault is the right thing to do in general.
if (event.type !== 'keydown' || (!SDL.unicode && !SDL.textInput) || (event.keyCode === 8 /* backspace */ || event.keyCode === 9 /* tab */)) {
event.preventDefault();
}
if (event.type == 'mousedown') {
SDL.DOMButtons[event.button] = 1;
SDL.events.push({
type: 'touchstart',
touch: {
identifier: 0,
deviceID: {{{ cDefine('SDL_TOUCH_MOUSEID') }}},
pageX: event.pageX,
pageY: event.pageY
}
});
} else if (event.type == 'mouseup') {
// ignore extra ups, can happen if we leave the canvas while pressing down, then return,
// since we add a mouseup in that case
if (!SDL.DOMButtons[event.button]) {
return;
}
SDL.events.push({
type: 'touchend',
touch: {
identifier: 0,
deviceID: {{{ cDefine('SDL_TOUCH_MOUSEID') }}},
pageX: event.pageX,
pageY: event.pageY
}
});
SDL.DOMButtons[event.button] = 0;
}
// We can only request fullscreen as the result of user input.
// Due to this limitation, we toggle a boolean on keydown which
// SDL_WM_ToggleFullScreen will check and subsequently set another
// flag indicating for us to request fullscreen on the following
// keyup. This isn't perfect, but it enables SDL_WM_ToggleFullScreen
// to work as the result of a keypress (which is an extremely
// common use case).
if (event.type === 'keydown' || event.type === 'mousedown') {
SDL.canRequestFullscreen = true;
} else if (event.type === 'keyup' || event.type === 'mouseup') {
if (SDL.isRequestingFullscreen) {
Module['requestFullscreen'](/*lockPointer=*/true, /*resizeCanvas=*/true);
SDL.isRequestingFullscreen = false;
}
SDL.canRequestFullscreen = false;
}
// SDL expects a unicode character to be passed to its keydown events.
// Unfortunately, the browser APIs only provide a charCode property on
// keypress events, so we must backfill in keydown events with their
// subsequent keypress event's charCode.
if (event.type === 'keypress' && SDL.savedKeydown) {
// charCode is read-only
SDL.savedKeydown.keypressCharCode = event.charCode;
SDL.savedKeydown = null;
} else if (event.type === 'keydown') {
SDL.savedKeydown = event;
}
// Don't push keypress events unless SDL_StartTextInput has been called.
if (event.type !== 'keypress' || SDL.textInput) {
SDL.events.push(event);
}
break;
case 'mouseout':
// Un-press all pressed mouse buttons, because we might miss the release outside of the canvas
for (var i = 0; i < 3; i++) {
if (SDL.DOMButtons[i]) {
SDL.events.push({
type: 'mouseup',
button: i,
pageX: event.pageX,
pageY: event.pageY
});
SDL.DOMButtons[i] = 0;
}
}
event.preventDefault();
break;
case 'focus':
SDL.events.push(event);
event.preventDefault();
break;
case 'blur':
SDL.events.push(event);
unpressAllPressedKeys();
event.preventDefault();
break;
case 'visibilitychange':
SDL.events.push({
type: 'visibilitychange',
visible: !document.hidden
});
unpressAllPressedKeys();
event.preventDefault();
break;
case 'unload':
if (Browser.mainLoop.runner) {
SDL.events.push(event);
// Force-run a main event loop, since otherwise this event will never be caught!
Browser.mainLoop.runner();
}
return;
case 'resize':
SDL.events.push(event);
// manually triggered resize event doesn't have a preventDefault member
if (event.preventDefault) {
event.preventDefault();
}
break;
}
if (SDL.events.length >= 10000) {
Module.printErr('SDL event queue full, dropping events');
SDL.events = SDL.events.slice(0, 10000);
}
// If we have a handler installed, this will push the events to the app
// instead of the app polling for them.
SDL.flushEventsToHandler();
return;
},
lookupKeyCodeForEvent: function(event) {
var code = event.keyCode;
if (code >= 65 && code <= 90) {
code += 32; // make lowercase for SDL
} else {
code = SDL.keyCodes[event.keyCode] || event.keyCode;
// If this is one of the modifier keys (224 | 1<<10 - 227 | 1<<10), and the event specifies that it is
// a right key, add 4 to get the right key SDL key code.
if (event.location === KeyboardEvent.DOM_KEY_LOCATION_RIGHT && code >= (224 | 1<<10) && code <= (227 | 1<<10)) {
code += 4;
}
}
return code;
},
handleEvent: function(event) {
if (event.handled) return;
event.handled = true;
switch (event.type) {
case 'touchstart': case 'touchend': case 'touchmove': {
Browser.calculateMouseEvent(event);
break;
}
case 'keydown': case 'keyup': {
var down = event.type === 'keydown';
var code = SDL.lookupKeyCodeForEvent(event);
{{{ makeSetValue('SDL.keyboardState', 'code', 'down', 'i8') }}};
// TODO: lmeta, rmeta, numlock, capslock, KMOD_MODE, KMOD_RESERVED
SDL.modState = ({{{ makeGetValue('SDL.keyboardState', '1248', 'i8') }}} ? 0x0040 : 0) | // KMOD_LCTRL
({{{ makeGetValue('SDL.keyboardState', '1249', 'i8') }}} ? 0x0001 : 0) | // KMOD_LSHIFT
({{{ makeGetValue('SDL.keyboardState', '1250', 'i8') }}} ? 0x0100 : 0) | // KMOD_LALT
({{{ makeGetValue('SDL.keyboardState', '1252', 'i8') }}} ? 0x0080 : 0) | // KMOD_RCTRL
({{{ makeGetValue('SDL.keyboardState', '1253', 'i8') }}} ? 0x0002 : 0) | // KMOD_RSHIFT
({{{ makeGetValue('SDL.keyboardState', '1254', 'i8') }}} ? 0x0200 : 0); // KMOD_RALT
if (down) {
SDL.keyboardMap[code] = event.keyCode; // save the DOM input, which we can use to unpress it during blur
} else {
delete SDL.keyboardMap[code];
}
break;
}
case 'mousedown': case 'mouseup':
if (event.type == 'mousedown') {
// SDL_BUTTON(x) is defined as (1 << ((x)-1)). SDL buttons are 1-3,
// and DOM buttons are 0-2, so this means that the below formula is
// correct.
SDL.buttonState |= 1 << event.button;
} else if (event.type == 'mouseup') {
SDL.buttonState &= ~(1 << event.button);
}
// fall through
case 'mousemove': {
Browser.calculateMouseEvent(event);
break;
}
}
},
flushEventsToHandler: function() {
if (!SDL.eventHandler) return;
while (SDL.pollEvent(SDL.eventHandlerTemp)) {
Module['dynCall_iii'](SDL.eventHandler, SDL.eventHandlerContext, SDL.eventHandlerTemp);
}
},
pollEvent: function(ptr) {
if (SDL.initFlags & 0x200 && SDL.joystickEventState) {
// If SDL_INIT_JOYSTICK was supplied AND the joystick system is configured
// to automatically query for events, query for joystick events.
SDL.queryJoysticks();
}
if (ptr) {
while (SDL.events.length > 0) {
if (SDL.makeCEvent(SDL.events.shift(), ptr) !== false) return 1;
}
return 0;
} else {
// XXX: somewhat risky in that we do not check if the event is real or not (makeCEvent returns false) if no pointer supplied
return SDL.events.length > 0;
}
},
// returns false if the event was determined to be irrelevant
makeCEvent: function(event, ptr) {
if (typeof event === 'number') {
// This is a pointer to a copy of a native C event that was SDL_PushEvent'ed
_memcpy(ptr, event, {{{ C_STRUCTS.SDL_KeyboardEvent.__size__ }}});
_free(event); // the copy is no longer needed
return;
}
SDL.handleEvent(event);
switch (event.type) {
case 'keydown': case 'keyup': {
var down = event.type === 'keydown';
//Module.print('Received key event: ' + event.keyCode);
var key = SDL.lookupKeyCodeForEvent(event);
var scan;
if (key >= 1024) {
scan = key - 1024;
} else {
scan = SDL.scanCodes[key] || key;
}
{{{ makeSetValue('ptr', C_STRUCTS.SDL_KeyboardEvent.type, 'SDL.DOMEventToSDLEvent[event.type]', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_KeyboardEvent.state, 'down ? 1 : 0', 'i8') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_KeyboardEvent.repeat, '0', 'i8') }}}; // TODO
{{{ makeSetValue('ptr', C_STRUCTS.SDL_KeyboardEvent.keysym + C_STRUCTS.SDL_Keysym.scancode, 'scan', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_KeyboardEvent.keysym + C_STRUCTS.SDL_Keysym.sym, 'key', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_KeyboardEvent.keysym + C_STRUCTS.SDL_Keysym.mod, 'SDL.modState', 'i16') }}};
// some non-character keys (e.g. backspace and tab) won't have keypressCharCode set, fill in with the keyCode.
{{{ makeSetValue('ptr', C_STRUCTS.SDL_KeyboardEvent.keysym + C_STRUCTS.SDL_Keysym.unicode, 'event.keypressCharCode || key', 'i32') }}};
break;
}
case 'keypress': {
{{{ makeSetValue('ptr', C_STRUCTS.SDL_TextInputEvent.type, 'SDL.DOMEventToSDLEvent[event.type]', 'i32') }}};
// Not filling in windowID for now
var cStr = intArrayFromString(String.fromCharCode(event.charCode));
for (var i = 0; i < cStr.length; ++i) {
{{{ makeSetValue('ptr', C_STRUCTS.SDL_TextInputEvent.text + ' + i', 'cStr[i]', 'i8') }}};
}
break;
}
case 'mousedown': case 'mouseup': case 'mousemove': {
if (event.type != 'mousemove') {
var down = event.type === 'mousedown';
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseButtonEvent.type, 'SDL.DOMEventToSDLEvent[event.type]', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseButtonEvent.timestamp, '0', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseButtonEvent.windowID, '0', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseButtonEvent.which, '0', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseButtonEvent.button, 'event.button+1', 'i8') }}}; // DOM buttons are 0-2, SDL 1-3
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseButtonEvent.state, 'down ? 1 : 0', 'i8') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseButtonEvent.x, 'Browser.mouseX', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseButtonEvent.y, 'Browser.mouseY', 'i32') }}};
} else {
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseMotionEvent.type, 'SDL.DOMEventToSDLEvent[event.type]', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseMotionEvent.timestamp, '0', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseMotionEvent.windowID, '0', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseMotionEvent.which, '0', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseMotionEvent.state, 'SDL.buttonState', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseMotionEvent.x, 'Browser.mouseX', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseMotionEvent.y, 'Browser.mouseY', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseMotionEvent.xrel, 'Browser.mouseMovementX', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseMotionEvent.yrel, 'Browser.mouseMovementY', 'i32') }}};
}
break;
}
case 'wheel': {
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseWheelEvent.type, 'SDL.DOMEventToSDLEvent[event.type]', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseWheelEvent.x, 'event.deltaX', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_MouseWheelEvent.y, 'event.deltaY', 'i32') }}};
break;
}
case 'touchstart': case 'touchend': case 'touchmove': {
var touch = event.touch;
if (!Browser.touches[touch.identifier]) break;
var w = Module['canvas'].width;
var h = Module['canvas'].height;
var x = Browser.touches[touch.identifier].x / w;
var y = Browser.touches[touch.identifier].y / h;
var lx = Browser.lastTouches[touch.identifier].x / w;
var ly = Browser.lastTouches[touch.identifier].y / h;
var dx = x - lx;
var dy = y - ly;
if (touch['deviceID'] === undefined) touch.deviceID = SDL.TOUCH_DEFAULT_ID;
if (dx === 0 && dy === 0 && event.type === 'touchmove') return false; // don't send these if nothing happened
{{{ makeSetValue('ptr', C_STRUCTS.SDL_TouchFingerEvent.type, 'SDL.DOMEventToSDLEvent[event.type]', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_TouchFingerEvent.timestamp, '_SDL_GetTicks()', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_TouchFingerEvent.touchId, 'touch.deviceID', 'i64') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_TouchFingerEvent.fingerId, 'touch.identifier', 'i64') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_TouchFingerEvent.x, 'x', 'float') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_TouchFingerEvent.y, 'y', 'float') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_TouchFingerEvent.dx, 'dx', 'float') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_TouchFingerEvent.dy, 'dy', 'float') }}};
if (touch.force !== undefined) {
{{{ makeSetValue('ptr', C_STRUCTS.SDL_TouchFingerEvent.pressure, 'touch.force', 'float') }}};
} else { // No pressure data, send a digital 0/1 pressure.
{{{ makeSetValue('ptr', C_STRUCTS.SDL_TouchFingerEvent.pressure, 'event.type == "touchend" ? 0 : 1', 'float') }}};
}
break;
}
case 'unload': {
{{{ makeSetValue('ptr', C_STRUCTS.SDL_KeyboardEvent.type, 'SDL.DOMEventToSDLEvent[event.type]', 'i32') }}};
break;
}
case 'resize': {
{{{ makeSetValue('ptr', C_STRUCTS.SDL_KeyboardEvent.type, 'SDL.DOMEventToSDLEvent[event.type]', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_ResizeEvent.w, 'event.w', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_ResizeEvent.h, 'event.h', 'i32') }}};
break;
}
case 'joystick_button_up': case 'joystick_button_down': {
var state = event.type === 'joystick_button_up' ? 0 : 1;
{{{ makeSetValue('ptr', C_STRUCTS.SDL_JoyButtonEvent.type, 'SDL.DOMEventToSDLEvent[event.type]', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_JoyButtonEvent.which, 'event.index', 'i8') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_JoyButtonEvent.button, 'event.button', 'i8') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_JoyButtonEvent.state, 'state', 'i8') }}};
break;
}
case 'joystick_axis_motion': {
{{{ makeSetValue('ptr', C_STRUCTS.SDL_JoyAxisEvent.type, 'SDL.DOMEventToSDLEvent[event.type]', 'i32') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_JoyAxisEvent.which, 'event.index', 'i8') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_JoyAxisEvent.axis, 'event.axis', 'i8') }}};
{{{ makeSetValue('ptr', C_STRUCTS.SDL_JoyAxisEvent.value, 'SDL.joystickAxisValueConversion(event.value)', 'i32') }}};
break;