forked from emscripten-core/emscripten
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibrary_gl.js
7251 lines (6601 loc) · 283 KB
/
library_gl.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
/*
* GL support. See http://kripken.github.io/emscripten-site/docs/porting/multimedia_and_graphics/OpenGL-support.html
* for current status.
*/
var LibraryGL = {
$GL__postset: 'var GLctx; GL.init()',
$GL: {
#if GL_DEBUG
debug: true,
#endif
counter: 1, // 0 is reserved as 'null' in gl
lastError: 0,
buffers: [],
mappedBuffers: {},
programs: [],
framebuffers: [],
renderbuffers: [],
textures: [],
uniforms: [],
shaders: [],
vaos: [],
contexts: [],
currentContext: null,
#if USE_WEBGL2
queries: [],
samplers: [],
transformFeedbacks: [],
syncs: [],
#endif
#if USES_GL_EMULATION
currArrayBuffer: 0,
currElementArrayBuffer: 0,
#endif
byteSizeByTypeRoot: 0x1400, // GL_BYTE
byteSizeByType: [
1, // GL_BYTE
1, // GL_UNSIGNED_BYTE
2, // GL_SHORT
2, // GL_UNSIGNED_SHORT
4, // GL_INT
4, // GL_UNSIGNED_INT
4, // GL_FLOAT
2, // GL_2_BYTES
3, // GL_3_BYTES
4, // GL_4_BYTES
8 // GL_DOUBLE
],
programInfos: {}, // Stores additional information needed for each shader program. Each entry is of form:
/* { uniforms: {}, // Maps ints back to the opaque WebGLUniformLocation objects.
maxUniformLength: int, // Cached in order to implement glGetProgramiv(GL_ACTIVE_UNIFORM_MAX_LENGTH)
maxAttributeLength: int // Cached in order to implement glGetProgramiv(GL_ACTIVE_ATTRIBUTE_MAX_LENGTH)
} */
stringCache: {},
#if USE_WEBGL2
stringiCache: {},
#endif
packAlignment: 4, // default alignment is 4 bytes
unpackAlignment: 4, // default alignment is 4 bytes
init: function() {
#if USES_GL_EMULATION
GL.createLog2ceilLookup(GL.MAX_TEMP_BUFFER_SIZE);
#endif
GL.miniTempBuffer = new Float32Array(GL.MINI_TEMP_BUFFER_SIZE);
for (var i = 0; i < GL.MINI_TEMP_BUFFER_SIZE; i++) {
GL.miniTempBufferViews[i] = GL.miniTempBuffer.subarray(0, i+1);
}
},
// Records a GL error condition that occurred, stored until user calls glGetError() to fetch it. As per GLES2 spec, only the first error
// is remembered, and subsequent errors are discarded until the user has cleared the stored error by a call to glGetError().
recordError: function recordError(errorCode) {
if (!GL.lastError) {
GL.lastError = errorCode;
}
},
// Get a new ID for a texture/buffer/etc., while keeping the table dense and fast. Creation is fairly rare so it is worth optimizing lookups later.
getNewId: function(table) {
var ret = GL.counter++;
for (var i = table.length; i < ret; i++) {
table[i] = null;
}
return ret;
},
// Mini temp buffer
MINI_TEMP_BUFFER_SIZE: 16,
miniTempBuffer: null,
miniTempBufferViews: [0], // index i has the view of size i+1
#if USES_GL_EMULATION
// When user GL code wants to render from client-side memory, we need to upload the vertex data to a temp VBO
// for rendering. Maintain a set of temp VBOs that are created-on-demand to appropriate sizes, and never destroyed.
// Also, for best performance the VBOs are double-buffered, i.e. every second frame we switch the set of VBOs we
// upload to, so that rendering from the previous frame is not disturbed by uploading from new data to it, which
// could cause a GPU-CPU pipeline stall.
// Note that index buffers are not double-buffered (at the moment) in this manner.
MAX_TEMP_BUFFER_SIZE: {{{ GL_MAX_TEMP_BUFFER_SIZE }}},
// Maximum number of temp VBOs of one size to maintain, after that we start reusing old ones, which is safe but can give
// a performance impact. If CPU-GPU stalls are a problem, increasing this might help.
numTempVertexBuffersPerSize: 64, // (const)
// Precompute a lookup table for the function ceil(log2(x)), i.e. how many bits are needed to represent x, or,
// if x was rounded up to next pow2, which index is the single '1' bit at?
// Then log2ceilLookup[x] returns ceil(log2(x)).
log2ceilLookup: null,
createLog2ceilLookup: function(maxValue) {
GL.log2ceilLookup = new Uint8Array(maxValue+1);
var log2 = 0;
var pow2 = 1;
GL.log2ceilLookup[0] = 0;
for(var i = 1; i <= maxValue; ++i) {
if (i > pow2) {
pow2 <<= 1;
++log2;
}
GL.log2ceilLookup[i] = log2;
}
},
generateTempBuffers: function(quads, context) {
var largestIndex = GL.log2ceilLookup[GL.MAX_TEMP_BUFFER_SIZE];
context.tempVertexBufferCounters1 = [];
context.tempVertexBufferCounters2 = [];
context.tempVertexBufferCounters1.length = context.tempVertexBufferCounters2.length = largestIndex+1;
context.tempVertexBuffers1 = [];
context.tempVertexBuffers2 = [];
context.tempVertexBuffers1.length = context.tempVertexBuffers2.length = largestIndex+1;
context.tempIndexBuffers = [];
context.tempIndexBuffers.length = largestIndex+1;
for(var i = 0; i <= largestIndex; ++i) {
context.tempIndexBuffers[i] = null; // Created on-demand
context.tempVertexBufferCounters1[i] = context.tempVertexBufferCounters2[i] = 0;
var ringbufferLength = GL.numTempVertexBuffersPerSize;
context.tempVertexBuffers1[i] = [];
context.tempVertexBuffers2[i] = [];
var ringbuffer1 = context.tempVertexBuffers1[i];
var ringbuffer2 = context.tempVertexBuffers2[i];
ringbuffer1.length = ringbuffer2.length = ringbufferLength;
for(var j = 0; j < ringbufferLength; ++j) {
ringbuffer1[j] = ringbuffer2[j] = null; // Created on-demand
}
}
if (quads) {
// GL_QUAD indexes can be precalculated
context.tempQuadIndexBuffer = GLctx.createBuffer();
context.GLctx.bindBuffer(context.GLctx.ELEMENT_ARRAY_BUFFER, context.tempQuadIndexBuffer);
var numIndexes = GL.MAX_TEMP_BUFFER_SIZE >> 1;
var quadIndexes = new Uint16Array(numIndexes);
var i = 0, v = 0;
while (1) {
quadIndexes[i++] = v;
if (i >= numIndexes) break;
quadIndexes[i++] = v+1;
if (i >= numIndexes) break;
quadIndexes[i++] = v+2;
if (i >= numIndexes) break;
quadIndexes[i++] = v;
if (i >= numIndexes) break;
quadIndexes[i++] = v+2;
if (i >= numIndexes) break;
quadIndexes[i++] = v+3;
if (i >= numIndexes) break;
v += 4;
}
context.GLctx.bufferData(context.GLctx.ELEMENT_ARRAY_BUFFER, quadIndexes, context.GLctx.STATIC_DRAW);
context.GLctx.bindBuffer(context.GLctx.ELEMENT_ARRAY_BUFFER, null);
}
},
getTempVertexBuffer: function getTempVertexBuffer(sizeBytes) {
var idx = GL.log2ceilLookup[sizeBytes];
var ringbuffer = GL.currentContext.tempVertexBuffers1[idx];
var nextFreeBufferIndex = GL.currentContext.tempVertexBufferCounters1[idx];
GL.currentContext.tempVertexBufferCounters1[idx] = (GL.currentContext.tempVertexBufferCounters1[idx]+1) & (GL.numTempVertexBuffersPerSize-1);
var vbo = ringbuffer[nextFreeBufferIndex];
if (vbo) {
return vbo;
}
var prevVBO = GLctx.getParameter(GLctx.ARRAY_BUFFER_BINDING);
ringbuffer[nextFreeBufferIndex] = GLctx.createBuffer();
GLctx.bindBuffer(GLctx.ARRAY_BUFFER, ringbuffer[nextFreeBufferIndex]);
GLctx.bufferData(GLctx.ARRAY_BUFFER, 1 << idx, GLctx.DYNAMIC_DRAW);
GLctx.bindBuffer(GLctx.ARRAY_BUFFER, prevVBO);
return ringbuffer[nextFreeBufferIndex];
},
getTempIndexBuffer: function getTempIndexBuffer(sizeBytes) {
var idx = GL.log2ceilLookup[sizeBytes];
var ibo = GL.currentContext.tempIndexBuffers[idx];
if (ibo) {
return ibo;
}
var prevIBO = GLctx.getParameter(GLctx.ELEMENT_ARRAY_BUFFER_BINDING);
GL.currentContext.tempIndexBuffers[idx] = GLctx.createBuffer();
GLctx.bindBuffer(GLctx.ELEMENT_ARRAY_BUFFER, GL.currentContext.tempIndexBuffers[idx]);
GLctx.bufferData(GLctx.ELEMENT_ARRAY_BUFFER, 1 << idx, GLctx.DYNAMIC_DRAW);
GLctx.bindBuffer(GLctx.ELEMENT_ARRAY_BUFFER, prevIBO);
return GL.currentContext.tempIndexBuffers[idx];
},
// Called at start of each new WebGL rendering frame. This swaps the doublebuffered temp VB memory pointers,
// so that every second frame utilizes different set of temp buffers. The aim is to keep the set of buffers
// being rendered, and the set of buffers being updated disjoint.
newRenderingFrameStarted: function newRenderingFrameStarted() {
if (!GL.currentContext) {
return;
}
var vb = GL.currentContext.tempVertexBuffers1;
GL.currentContext.tempVertexBuffers1 = GL.currentContext.tempVertexBuffers2;
GL.currentContext.tempVertexBuffers2 = vb;
vb = GL.currentContext.tempVertexBufferCounters1;
GL.currentContext.tempVertexBufferCounters1 = GL.currentContext.tempVertexBufferCounters2;
GL.currentContext.tempVertexBufferCounters2 = vb;
var largestIndex = GL.log2ceilLookup[GL.MAX_TEMP_BUFFER_SIZE];
for(var i = 0; i <= largestIndex; ++i) {
GL.currentContext.tempVertexBufferCounters1[i] = 0;
}
},
#endif
#if LEGACY_GL_EMULATION
// Find a token in a shader source string
findToken: function(source, token) {
function isIdentChar(ch) {
if (ch >= 48 && ch <= 57) // 0-9
return true;
if (ch >= 65 && ch <= 90) // A-Z
return true;
if (ch >= 97 && ch <= 122) // a-z
return true;
return false;
}
var i = -1;
do {
i = source.indexOf(token, i + 1);
if (i < 0) {
break;
}
if (i > 0 && isIdentChar(source[i - 1])) {
continue;
}
i += token.length;
if (i < source.length - 1 && isIdentChar(source[i + 1])) {
continue;
}
return true;
} while (true);
return false;
},
#endif
getSource: function(shader, count, string, length) {
var source = '';
for (var i = 0; i < count; ++i) {
var frag;
if (length) {
var len = {{{ makeGetValue('length', 'i*4', 'i32') }}};
if (len < 0) {
frag = Pointer_stringify({{{ makeGetValue('string', 'i*4', 'i32') }}});
} else {
frag = Pointer_stringify({{{ makeGetValue('string', 'i*4', 'i32') }}}, len);
}
} else {
frag = Pointer_stringify({{{ makeGetValue('string', 'i*4', 'i32') }}});
}
source += frag;
}
#if LEGACY_GL_EMULATION
// Let's see if we need to enable the standard derivatives extension
type = GLctx.getShaderParameter(GL.shaders[shader], 0x8B4F /* GL_SHADER_TYPE */);
if (type == 0x8B30 /* GL_FRAGMENT_SHADER */) {
if (GL.findToken(source, "dFdx") ||
GL.findToken(source, "dFdy") ||
GL.findToken(source, "fwidth")) {
source = "#extension GL_OES_standard_derivatives : enable\n" + source;
var extension = GLctx.getExtension("OES_standard_derivatives");
#if GL_DEBUG
if (!extension) {
Module.printErr("Shader attempts to use the standard derivatives extension which is not available.");
}
#endif
}
}
#endif
return source;
},
#if GL_FFP_ONLY
enabledClientAttribIndices: [],
enableVertexAttribArray: function enableVertexAttribArray(index) {
if (!GL.enabledClientAttribIndices[index]) {
GL.enabledClientAttribIndices[index] = true;
GLctx.enableVertexAttribArray(index);
}
},
disableVertexAttribArray: function disableVertexAttribArray(index) {
if (GL.enabledClientAttribIndices[index]) {
GL.enabledClientAttribIndices[index] = false;
GLctx.disableVertexAttribArray(index);
}
},
#endif
#if FULL_ES2
calcBufLength: function calcBufLength(size, type, stride, count) {
if (stride > 0) {
return count * stride; // XXXvlad this is not exactly correct I don't think
}
var typeSize = GL.byteSizeByType[type - GL.byteSizeByTypeRoot];
return size * typeSize * count;
},
usedTempBuffers: [],
preDrawHandleClientVertexAttribBindings: function preDrawHandleClientVertexAttribBindings(count) {
GL.resetBufferBinding = false;
// TODO: initial pass to detect ranges we need to upload, might not need an upload per attrib
for (var i = 0; i < GL.currentContext.maxVertexAttribs; ++i) {
var cb = GL.currentContext.clientBuffers[i];
if (!cb.clientside || !cb.enabled) continue;
GL.resetBufferBinding = true;
var size = GL.calcBufLength(cb.size, cb.type, cb.stride, count);
var buf = GL.getTempVertexBuffer(size);
GLctx.bindBuffer(GLctx.ARRAY_BUFFER, buf);
GLctx.bufferSubData(GLctx.ARRAY_BUFFER,
0,
HEAPU8.subarray(cb.ptr, cb.ptr + size));
#if GL_ASSERTIONS
GL.validateVertexAttribPointer(cb.size, cb.type, cb.stride, 0);
#endif
GLctx.vertexAttribPointer(i, cb.size, cb.type, cb.normalized, cb.stride, 0);
}
},
postDrawHandleClientVertexAttribBindings: function postDrawHandleClientVertexAttribBindings() {
if (GL.resetBufferBinding) {
GLctx.bindBuffer(GLctx.ARRAY_BUFFER, GL.buffers[GL.currArrayBuffer]);
}
},
#endif
#if GL_ASSERTIONS
validateGLObjectID: function(objectHandleArray, objectID, callerFunctionName, objectReadableType) {
if (objectID != 0) {
if (objectHandleArray[objectID] === null) {
console.error(callerFunctionName + ' called with an already deleted ' + objectReadableType + ' ID ' + objectID + '!');
} else if (!objectHandleArray[objectID]) {
console.error(callerFunctionName + ' called with an invalid ' + objectReadableType + ' ID ' + objectID + '!');
}
}
},
// Validates that user obeys GL spec #6.4: http://www.khronos.org/registry/webgl/specs/latest/1.0/#6.4
validateVertexAttribPointer: function(dimension, dataType, stride, offset) {
var sizeBytes = 1;
switch(dataType) {
case 0x1400 /* GL_BYTE */:
case 0x1401 /* GL_UNSIGNED_BYTE */:
sizeBytes = 1;
break;
case 0x1402 /* GL_SHORT */:
case 0x1403 /* GL_UNSIGNED_SHORT */:
sizeBytes = 2;
break;
case 0x1404 /* GL_INT */:
case 0x1405 /* GL_UNSIGNED_INT */:
case 0x1406 /* GL_FLOAT */:
sizeBytes = 4;
break;
case 0x140A /* GL_DOUBLE */:
sizeBytes = 8;
break;
default:
console.error('Invalid vertex attribute data type GLenum ' + dataType + ' passed to GL function!');
}
if (dimension == 0x80E1 /* GL_BGRA */) {
console.error('WebGL does not support size=GL_BGRA in a call to glVertexAttribPointer! Please use size=4 and type=GL_UNSIGNED_BYTE instead!');
} else if (dimension < 1 || dimension > 4) {
console.error('Invalid dimension='+dimension+' in call to glVertexAttribPointer, must be 1,2,3 or 4.');
}
if (stride < 0 || stride > 255) {
console.error('Invalid stride='+stride+' in call to glVertexAttribPointer. Note that maximum supported stride in WebGL is 255!');
}
if (offset % sizeBytes != 0) {
console.error('GL spec section 6.4 error: vertex attribute data offset of ' + offset + ' bytes should have been a multiple of the data type size that was used: GLenum ' + dataType + ' has size of ' + sizeBytes + ' bytes!');
}
if (stride % sizeBytes != 0) {
console.error('GL spec section 6.4 error: vertex attribute data stride of ' + stride + ' bytes should have been a multiple of the data type size that was used: GLenum ' + dataType + ' has size of ' + sizeBytes + ' bytes!');
}
},
#endif
// Returns the context handle to the new context.
createContext: function(canvas, webGLContextAttributes) {
if (typeof webGLContextAttributes.majorVersion === 'undefined' && typeof webGLContextAttributes.minorVersion === 'undefined') {
#if USE_WEBGL2
webGLContextAttributes.majorVersion = 2;
#else
webGLContextAttributes.majorVersion = 1;
#endif
webGLContextAttributes.minorVersion = 0;
}
var ctx;
var errorInfo = '?';
function onContextCreationError(event) {
errorInfo = event.statusMessage || errorInfo;
}
try {
canvas.addEventListener('webglcontextcreationerror', onContextCreationError, false);
try {
if (webGLContextAttributes.majorVersion == 1 && webGLContextAttributes.minorVersion == 0) {
ctx = canvas.getContext("webgl", webGLContextAttributes) || canvas.getContext("experimental-webgl", webGLContextAttributes);
} else if (webGLContextAttributes.majorVersion == 2 && webGLContextAttributes.minorVersion == 0) {
ctx = canvas.getContext("webgl2", webGLContextAttributes) || canvas.getContext("experimental-webgl2", webGLContextAttributes);
} else {
throw 'Unsupported WebGL context version ' + majorVersion + '.' + minorVersion + '!'
}
} finally {
canvas.removeEventListener('webglcontextcreationerror', onContextCreationError, false);
}
if (!ctx) throw ':(';
} catch (e) {
Module.print('Could not create canvas: ' + [errorInfo, e, JSON.stringify(webGLContextAttributes)]);
return 0;
}
#if GL_DEBUG
function wrapDebugGL(ctx) {
var printObjectList = [];
function prettyPrint(arg) {
if (typeof arg == 'undefined') return '!UNDEFINED!';
if (typeof arg == 'boolean') arg = arg + 0;
if (!arg) return arg;
var index = printObjectList.indexOf(arg);
if (index >= 0) return '<' + arg + '|'; // + index + '>';
if (arg.toString() == '[object HTMLImageElement]') {
return arg + '\n\n';
}
if (arg.byteLength) {
return '{' + Array.prototype.slice.call(arg, 0, Math.min(arg.length, 400)) + '}'; // Useful for correct arrays, less so for compiled arrays, see the code below for that
var buf = new ArrayBuffer(32);
var i8buf = new Int8Array(buf);
var i16buf = new Int16Array(buf);
var f32buf = new Float32Array(buf);
switch(arg.toString()) {
case '[object Uint8Array]':
i8buf.set(arg.subarray(0, 32));
break;
case '[object Float32Array]':
f32buf.set(arg.subarray(0, 5));
break;
case '[object Uint16Array]':
i16buf.set(arg.subarray(0, 16));
break;
default:
alert('unknown array for debugging: ' + arg);
throw 'see alert';
}
var ret = '{' + arg.byteLength + ':\n';
var arr = Array.prototype.slice.call(i8buf);
ret += 'i8:' + arr.toString().replace(/,/g, ',') + '\n';
arr = Array.prototype.slice.call(f32buf, 0, 8);
ret += 'f32:' + arr.toString().replace(/,/g, ',') + '}';
return ret;
}
if (typeof arg == 'object') {
printObjectList.push(arg);
return '<' + arg + '|'; // + (printObjectList.length-1) + '>';
}
if (typeof arg == 'number') {
if (arg > 0) return '0x' + arg.toString(16) + ' (' + arg + ')';
}
return arg;
}
var wrapper = {};
for (var prop in ctx) {
(function(prop) {
switch (typeof ctx[prop]) {
case 'function': {
wrapper[prop] = function gl_wrapper() {
var printArgs = Array.prototype.slice.call(arguments).map(prettyPrint);
dump('[gl_f:' + prop + ':' + printArgs + ']\n');
var ret = ctx[prop].apply(ctx, arguments);
if (typeof ret != 'undefined') {
dump('[ gl:' + prop + ':return:' + prettyPrint(ret) + ']\n');
}
return ret;
}
break;
}
case 'number': case 'string': {
wrapper.__defineGetter__(prop, function() {
//dump('[gl_g:' + prop + ':' + ctx[prop] + ']\n');
return ctx[prop];
});
wrapper.__defineSetter__(prop, function(value) {
dump('[gl_s:' + prop + ':' + value + ']\n');
ctx[prop] = value;
});
break;
}
}
})(prop);
}
return wrapper;
}
#endif
// possible GL_DEBUG entry point: ctx = wrapDebugGL(ctx);
if (!ctx) return 0;
return GL.registerContext(ctx, webGLContextAttributes);
},
registerContext: function(ctx, webGLContextAttributes) {
var handle = GL.getNewId(GL.contexts);
var context = {
handle: handle,
version: webGLContextAttributes.majorVersion,
GLctx: ctx
};
// Store the created context object so that we can access the context given a canvas without having to pass the parameters again.
if (ctx.canvas) ctx.canvas.GLctxObject = context;
GL.contexts[handle] = context;
if (typeof webGLContextAttributes['enableExtensionsByDefault'] === 'undefined' || webGLContextAttributes.enableExtensionsByDefault) {
GL.initExtensions(context);
}
return handle;
},
makeContextCurrent: function(contextHandle) {
var context = GL.contexts[contextHandle];
if (!context) return false;
GLctx = Module.ctx = context.GLctx; // Active WebGL context object.
GL.currentContext = context; // Active Emscripten GL layer context object.
return true;
},
getContext: function(contextHandle) {
return GL.contexts[contextHandle];
},
deleteContext: function(contextHandle) {
if (GL.currentContext === GL.contexts[contextHandle]) GL.currentContext = null;
if (typeof JSEvents === 'object') JSEvents.removeAllHandlersOnTarget(GL.contexts[contextHandle].GLctx.canvas); // Release all JS event handlers on the DOM element that the GL context is associated with since the context is now deleted.
if (GL.contexts[contextHandle] && GL.contexts[contextHandle].GLctx.canvas) GL.contexts[contextHandle].GLctx.canvas.GLctxObject = undefined; // Make sure the canvas object no longer refers to the context object so there are no GC surprises.
GL.contexts[contextHandle] = null;
},
// In WebGL, extensions must be explicitly enabled to be active, see http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.14
// In GLES2, all extensions are enabled by default without additional operations. Init all extensions we need to give to GLES2 user
// code here, so that GLES2 code can operate without changing behavior.
initExtensions: function(context) {
// If this function is called without a specific context object, init the extensions of the currently active context.
if (!context) context = GL.currentContext;
if (context.initExtensionsDone) return;
context.initExtensionsDone = true;
var GLctx = context.GLctx;
context.maxVertexAttribs = GLctx.getParameter(GLctx.MAX_VERTEX_ATTRIBS);
#if FULL_ES2
context.clientBuffers = [];
for (var i = 0; i < context.maxVertexAttribs; i++) {
context.clientBuffers[i] = { enabled: false, clientside: false, size: 0, type: 0, normalized: 0, stride: 0, ptr: 0 };
}
GL.generateTempBuffers(false, context);
#endif
// Detect the presence of a few extensions manually, this GL interop layer itself will need to know if they exist.
#if LEGACY_GL_EMULATION
context.compressionExt = GLctx.getExtension('WEBGL_compressed_texture_s3tc');
context.anisotropicExt = GLctx.getExtension('EXT_texture_filter_anisotropic');
#endif
if (context.version < 2) {
// Extension available from Firefox 26 and Google Chrome 30
var instancedArraysExt = GLctx.getExtension('ANGLE_instanced_arrays');
if (instancedArraysExt) {
GLctx['vertexAttribDivisor'] = function(index, divisor) { instancedArraysExt['vertexAttribDivisorANGLE'](index, divisor); };
GLctx['drawArraysInstanced'] = function(mode, first, count, primcount) { instancedArraysExt['drawArraysInstancedANGLE'](mode, first, count, primcount); };
GLctx['drawElementsInstanced'] = function(mode, count, type, indices, primcount) { instancedArraysExt['drawElementsInstancedANGLE'](mode, count, type, indices, primcount); };
}
// Extension available from Firefox 25 and WebKit
var vaoExt = GLctx.getExtension('OES_vertex_array_object');
if (vaoExt) {
GLctx['createVertexArray'] = function() { return vaoExt['createVertexArrayOES'](); };
GLctx['deleteVertexArray'] = function(vao) { vaoExt['deleteVertexArrayOES'](vao); };
GLctx['bindVertexArray'] = function(vao) { vaoExt['bindVertexArrayOES'](vao); };
GLctx['isVertexArray'] = function(vao) { return vaoExt['isVertexArrayOES'](vao); };
}
var drawBuffersExt = GLctx.getExtension('WEBGL_draw_buffers');
if (drawBuffersExt) {
GLctx['drawBuffers'] = function(n, bufs) { drawBuffersExt['drawBuffersWEBGL'](n, bufs); };
}
}
// These are the 'safe' feature-enabling extensions that don't add any performance impact related to e.g. debugging, and
// should be enabled by default so that client GLES2/GL code will not need to go through extra hoops to get its stuff working.
// As new extensions are ratified at http://www.khronos.org/registry/webgl/extensions/ , feel free to add your new extensions
// here, as long as they don't produce a performance impact for users that might not be using those extensions.
// E.g. debugging-related extensions should probably be off by default.
var automaticallyEnabledExtensions = [ "OES_texture_float", "OES_texture_half_float", "OES_standard_derivatives",
"OES_vertex_array_object", "WEBGL_compressed_texture_s3tc", "WEBGL_depth_texture",
"OES_element_index_uint", "EXT_texture_filter_anisotropic", "ANGLE_instanced_arrays",
"OES_texture_float_linear", "OES_texture_half_float_linear", "WEBGL_compressed_texture_atc",
"WEBGL_compressed_texture_pvrtc", "EXT_color_buffer_half_float", "WEBGL_color_buffer_float",
"EXT_frag_depth", "EXT_sRGB", "WEBGL_draw_buffers", "WEBGL_shared_resources",
"EXT_shader_texture_lod" ];
function shouldEnableAutomatically(extension) {
var ret = false;
automaticallyEnabledExtensions.forEach(function(include) {
if (ext.indexOf(include) != -1) {
ret = true;
}
});
return ret;
}
var exts = GLctx.getSupportedExtensions();
if (exts && exts.length > 0) {
GLctx.getSupportedExtensions().forEach(function(ext) {
if (automaticallyEnabledExtensions.indexOf(ext) != -1) {
GLctx.getExtension(ext); // Calling .getExtension enables that extension permanently, no need to store the return value to be enabled.
}
});
}
},
// In WebGL, uniforms in a shader program are accessed through an opaque object type 'WebGLUniformLocation'.
// In GLES2, uniforms are accessed via indices. Therefore we must generate a mapping of indices -> WebGLUniformLocations
// to provide the client code the API that uses indices.
// This function takes a linked GL program and generates a mapping table for the program.
// NOTE: Populating the uniform table is performed eagerly at glLinkProgram time, so glLinkProgram should be considered
// to be a slow/costly function call. Calling glGetUniformLocation is relatively fast, since it is always a read-only
// lookup to the table populated in this function call.
populateUniformTable: function(program) {
#if GL_ASSERTIONS
GL.validateGLObjectID(GL.programs, program, 'populateUniformTable', 'program');
#endif
var p = GL.programs[program];
GL.programInfos[program] = {
uniforms: {},
maxUniformLength: 0, // This is eagerly computed below, since we already enumerate all uniforms anyway.
maxAttributeLength: -1 // This is lazily computed and cached, computed when/if first asked, "-1" meaning not computed yet.
};
var ptable = GL.programInfos[program];
var utable = ptable.uniforms;
// A program's uniform table maps the string name of an uniform to an integer location of that uniform.
// The global GL.uniforms map maps integer locations to WebGLUniformLocations.
var numUniforms = GLctx.getProgramParameter(p, GLctx.ACTIVE_UNIFORMS);
for (var i = 0; i < numUniforms; ++i) {
var u = GLctx.getActiveUniform(p, i);
var name = u.name;
ptable.maxUniformLength = Math.max(ptable.maxUniformLength, name.length+1);
// Strip off any trailing array specifier we might have got, e.g. "[0]".
if (name.indexOf(']', name.length-1) !== -1) {
var ls = name.lastIndexOf('[');
name = name.slice(0, ls);
}
// Optimize memory usage slightly: If we have an array of uniforms, e.g. 'vec3 colors[3];', then
// only store the string 'colors' in utable, and 'colors[0]', 'colors[1]' and 'colors[2]' will be parsed as 'colors'+i.
// Note that for the GL.uniforms table, we still need to fetch the all WebGLUniformLocations for all the indices.
var loc = GLctx.getUniformLocation(p, name);
var id = GL.getNewId(GL.uniforms);
utable[name] = [u.size, id];
GL.uniforms[id] = loc;
for (var j = 1; j < u.size; ++j) {
var n = name + '['+j+']';
loc = GLctx.getUniformLocation(p, n);
id = GL.getNewId(GL.uniforms);
GL.uniforms[id] = loc;
}
}
}
},
glPixelStorei__sig: 'vii',
glPixelStorei: function(pname, param) {
if (pname == 0x0D05 /* GL_PACK_ALIGNMENT */) {
GL.packAlignment = param;
} else if (pname == 0x0cf5 /* GL_UNPACK_ALIGNMENT */) {
GL.unpackAlignment = param;
}
GLctx.pixelStorei(pname, param);
},
glGetString__sig: 'ii',
glGetString: function(name_) {
if (GL.stringCache[name_]) return GL.stringCache[name_];
var ret;
switch(name_) {
case 0x1F00 /* GL_VENDOR */:
case 0x1F01 /* GL_RENDERER */:
case 0x1F02 /* GL_VERSION */:
ret = allocate(intArrayFromString(GLctx.getParameter(name_)), 'i8', ALLOC_NORMAL);
break;
case 0x1F03 /* GL_EXTENSIONS */:
var exts = GLctx.getSupportedExtensions();
var gl_exts = [];
for (var i in exts) {
gl_exts.push(exts[i]);
gl_exts.push("GL_" + exts[i]);
}
ret = allocate(intArrayFromString(gl_exts.join(' ')), 'i8', ALLOC_NORMAL);
break;
case 0x8B8C /* GL_SHADING_LANGUAGE_VERSION */:
ret = allocate(intArrayFromString('OpenGL ES GLSL 1.00 (WebGL)'), 'i8', ALLOC_NORMAL);
break;
default:
GL.recordError(0x0500/*GL_INVALID_ENUM*/);
#if GL_ASSERTIONS
Module.printErr('GL_INVALID_ENUM in glGetString: Unknown parameter ' + name_ + '!');
#endif
return 0;
}
GL.stringCache[name_] = ret;
return ret;
},
$emscriptenWebGLGet: function(name_, p, type) {
// Guard against user passing a null pointer.
// Note that GLES2 spec does not say anything about how passing a null pointer should be treated.
// Testing on desktop core GL 3, the application crashes on glGetIntegerv to a null pointer, but
// better to report an error instead of doing anything random.
if (!p) {
#if GL_ASSERTIONS
Module.printErr('GL_INVALID_VALUE in glGet' + type + 'v(name=' + name_ + ': Function called with null out pointer!');
#endif
GL.recordError(0x0501 /* GL_INVALID_VALUE */);
return;
}
var ret = undefined;
switch(name_) { // Handle a few trivial GLES values
case 0x8DFA: // GL_SHADER_COMPILER
ret = 1;
break;
case 0x8DF8: // GL_SHADER_BINARY_FORMATS
if (type !== 'Integer' && type !== 'Integer64') {
GL.recordError(0x0500); // GL_INVALID_ENUM
#if GL_ASSERTIONS
Module.printErr('GL_INVALID_ENUM in glGet' + type + 'v(GL_SHADER_BINARY_FORMATS): Invalid parameter type!');
#endif
}
return; // Do not write anything to the out pointer, since no binary formats are supported.
#if USE_WEBGL2
case 0x87FE: // GL_NUM_PROGRAM_BINARY_FORMATS
#endif
case 0x8DF9: // GL_NUM_SHADER_BINARY_FORMATS
ret = 0;
break;
case 0x86A2: // GL_NUM_COMPRESSED_TEXTURE_FORMATS
// WebGL doesn't have GL_NUM_COMPRESSED_TEXTURE_FORMATS (it's obsolete since GL_COMPRESSED_TEXTURE_FORMATS returns a JS array that can be queried for length),
// so implement it ourselves to allow C++ GLES2 code get the length.
var formats = GLctx.getParameter(0x86A3 /*GL_COMPRESSED_TEXTURE_FORMATS*/);
ret = formats.length;
break;
case 0x8B9A: // GL_IMPLEMENTATION_COLOR_READ_TYPE
ret = 0x1401; // GL_UNSIGNED_BYTE
break;
case 0x8B9B: // GL_IMPLEMENTATION_COLOR_READ_FORMAT
ret = 0x1908; // GL_RGBA
break;
#if USE_WEBGL2
case 0x821D: // GL_NUM_EXTENSIONS
if (GLctx.canvas.GLctxObject.version < 2) {
GL.recordError(0x0502 /* GL_INVALID_OPERATION */); // Calling GLES3/WebGL2 function with a GLES2/WebGL1 context
return;
}
var exts = GLctx.getSupportedExtensions();
ret = 2*exts.length; // each extension is duplicated, first in unprefixed WebGL form, and then a second time with "GL_" prefix.
break;
#endif
}
if (ret === undefined) {
var result = GLctx.getParameter(name_);
switch (typeof(result)) {
case "number":
ret = result;
break;
case "boolean":
ret = result ? 1 : 0;
break;
case "string":
GL.recordError(0x0500); // GL_INVALID_ENUM
#if GL_ASSERTIONS
Module.printErr('GL_INVALID_ENUM in glGet' + type + 'v(' + name_ + ') on a name which returns a string!');
#endif
return;
case "object":
if (result === null) {
// null is a valid result for some (e.g., which buffer is bound - perhaps nothing is bound), but otherwise
// can mean an invalid name_, which we need to report as an error
switch(name_) {
case 0x8894: // ARRAY_BUFFER_BINDING
case 0x8B8D: // CURRENT_PROGRAM
case 0x8895: // ELEMENT_ARRAY_BUFFER_BINDING
case 0x8CA6: // FRAMEBUFFER_BINDING
case 0x8CA7: // RENDERBUFFER_BINDING
case 0x8069: // TEXTURE_BINDING_2D
case 0x8514: { // TEXTURE_BINDING_CUBE_MAP
ret = 0;
break;
}
default: {
GL.recordError(0x0500); // GL_INVALID_ENUM
#if GL_ASSERTIONS
Module.printErr('GL_INVALID_ENUM in glGet' + type + 'v(' + name_ + ') and it returns null!');
#endif
return;
}
}
} else if (result instanceof Float32Array ||
result instanceof Uint32Array ||
result instanceof Int32Array ||
result instanceof Array) {
for (var i = 0; i < result.length; ++i) {
switch (type) {
case 'Integer': {{{ makeSetValue('p', 'i*4', 'result[i]', 'i32') }}}; break;
case 'Float': {{{ makeSetValue('p', 'i*4', 'result[i]', 'float') }}}; break;
case 'Boolean': {{{ makeSetValue('p', 'i', 'result[i] ? 1 : 0', 'i8') }}}; break;
default: throw 'internal glGet error, bad type: ' + type;
}
}
return;
} else if (result instanceof WebGLBuffer ||
result instanceof WebGLProgram ||
result instanceof WebGLFramebuffer ||
result instanceof WebGLRenderbuffer ||
result instanceof WebGLTexture) {
ret = result.name | 0;
} else {
GL.recordError(0x0500); // GL_INVALID_ENUM
#if GL_ASSERTIONS
Module.printErr('GL_INVALID_ENUM in glGet' + type + 'v: Unknown object returned from WebGL getParameter(' + name_ + ')!');
#endif
return;
}
break;
default:
GL.recordError(0x0500); // GL_INVALID_ENUM
#if GL_ASSERTIONS
Module.printErr('GL_INVALID_ENUM in glGetIntegerv: Native code calling glGet' + type + 'v(' + name_ + ') and it returns ' + result + ' of type ' + typeof(result) + '!');
#endif
return;
}
}
switch (type) {
case 'Integer64': {{{ makeSetValue('p', '0', 'ret', 'i64') }}}; break;
case 'Integer': {{{ makeSetValue('p', '0', 'ret', 'i32') }}}; break;
case 'Float': {{{ makeSetValue('p', '0', 'ret', 'float') }}}; break;
case 'Boolean': {{{ makeSetValue('p', '0', 'ret ? 1 : 0', 'i8') }}}; break;
default: throw 'internal glGet error, bad type: ' + type;
}
},
#if USE_WEBGL2
glGetStringi: function(name, index) {
if (GLctx.canvas.GLctxObject.version < 2) {
GL.recordError(0x0502 /* GL_INVALID_OPERATION */); // Calling GLES3/WebGL2 function with a GLES2/WebGL1 context
return 0;
}
var stringiCache = GL.stringiCache[name];
if (stringiCache) {
if (index < 0 || index >= stringiCache.length) {
GL.recordError(0x0501/*GL_INVALID_VALUE*/);
#if GL_ASSERTIONS
Module.printErr('GL_INVALID_VALUE in glGetStringi: index out of range (' + index + ')!');
#endif
return 0;
}
return stringiCache[index];
}
switch(name) {
case 0x1F03 /* GL_EXTENSIONS */:
var exts = GLctx.getSupportedExtensions();
var gl_exts = [];
// each extension is duplicated, first in unprefixed WebGL form, and then a second time with "GL_" prefix.
for (var i in exts) {
gl_exts.push(allocate(intArrayFromString(exts[i]), 'i8', ALLOC_NORMAL));
gl_exts.push(allocate(intArrayFromString("GL_" + exts[i]), 'i8', ALLOC_NORMAL));
}
stringiCache = GL.stringiCache[name] = gl_exts;
if (index < 0 || index >= stringiCache.length) {
GL.recordError(0x0501/*GL_INVALID_VALUE*/);
#if GL_ASSERTIONS
Module.printErr('GL_INVALID_VALUE in glGetStringi: index out of range (' + index + ') in a call to GL_EXTENSIONS!');
#endif
return 0;
}
return stringiCache[index];
default:
GL.recordError(0x0500/*GL_INVALID_ENUM*/);
#if GL_ASSERTIONS
Module.printErr('GL_INVALID_ENUM in glGetStringi: Unknown parameter ' + name + '!');
#endif
return 0;
}
},
glGetInteger64v__sig: 'vii',
glGetInteger64v__deps: ['$emscriptenWebGLGet'],
glGetInteger64v: function(name_, p) {
emscriptenWebGLGet(name_, p, 'Integer64');
},
#endif
glGetIntegerv__sig: 'vii',
glGetIntegerv__deps: ['$emscriptenWebGLGet'],
glGetIntegerv: function(name_, p) {
emscriptenWebGLGet(name_, p, 'Integer');
},
glGetFloatv__sig: 'vii',
glGetFloatv__deps: ['$emscriptenWebGLGet'],
glGetFloatv: function(name_, p) {
emscriptenWebGLGet(name_, p, 'Float');
},
glGetBooleanv__sig: 'vii',
glGetBooleanv__deps: ['$emscriptenWebGLGet'],
glGetBooleanv: function(name_, p) {
emscriptenWebGLGet(name_, p, 'Boolean');
},
glGenTextures__sig: 'vii',
glGenTextures: function(n, textures) {
for (var i = 0; i < n; i++) {
var texture = GLctx.createTexture();
if (!texture) {
GL.recordError(0x0502 /* GL_INVALID_OPERATION */); // GLES + EGL specs don't specify what should happen here, so best to issue an error and create IDs with 0.
#if GL_ASSERTIONS
Module.printErr('GL_INVALID_OPERATION in glGenTextures: GLctx.createTexture returned null - most likely GL context is lost!');
#endif
while(i < n) {{{ makeSetValue('textures', 'i++*4', 0, 'i32') }}};
return;
}
var id = GL.getNewId(GL.textures);
texture.name = id;
GL.textures[id] = texture;
{{{ makeSetValue('textures', 'i*4', 'id', 'i32') }}};
}
},
glDeleteTextures__sig: 'vii',
glDeleteTextures: function(n, textures) {
for (var i = 0; i < n; i++) {
var id = {{{ makeGetValue('textures', 'i*4', 'i32') }}};
var texture = GL.textures[id];
if (!texture) continue; // GL spec: "glDeleteTextures silently ignores 0s and names that do not correspond to existing textures".
GLctx.deleteTexture(texture);
texture.name = 0;
GL.textures[id] = null;
}
},
glCompressedTexImage2D__sig: 'viiiiiiii',
glCompressedTexImage2D: function(target, level, internalFormat, width, height, border, imageSize, data) {
var heapView;
if (data) {
heapView = {{{ makeHEAPView('U8', 'data', 'data+imageSize') }}};
} else {
heapView = null;
}
GLctx['compressedTexImage2D'](target, level, internalFormat, width, height, border, heapView);
},
#if USE_WEBGL2
glCompressedTexImage3D__sig: 'viiiiiiiii',
glCompressedTexImage3D: function(target, level, internalFormat, width, height, depth, border, imageSize, data) {
var heapView;
if (data) {
heapView = {{{ makeHEAPView('U8', 'data', 'data+imageSize') }}};
} else {
heapView = null;