-
Notifications
You must be signed in to change notification settings - Fork 3
/
gl.js
1936 lines (1666 loc) · 46.7 KB
/
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
/*
WebGL 2 wrapper.
Written by Cosmin Apreutesei. Public domain.
Canvas
gl.clear_all(r, g, b, [a=1], [depth=1])
Programs
gl.module(name, code)
gl.program(name, vs_code, fs_code) -> prog
prog.set_uni(name, f | v2 | v3 | v4 | x,[y,[z,[w]]])
prog.set_uni(name, tex, [texture_unit=0])
VBOs
gl.[dyn_][arr_]<type>_[instance_]buffer([data|capacity]) -> [d][a]b
type: f32|u8|u16|u32|i8|i16|i32|v2|v3|v4|mat3|mat4
gl.[dyn_][arr_][<type>_]index_buffer(data|capacity, [type|max_idx]) -> [d][a]b
type: u8|u16|u32
gl.dyn_arr_vertex_buffer({name->type}) -> davb
b.upload(in_arr, [offset=0], [len=1/0], [in_offset=0])
b.download(out_arr, [offset=0], [len=1/0], [out_offset=0]) -> out_arr
b.set(offset, in_b, [len=1/0], [in_offset=0])
b.arr([data|len]) -> a
b.len
db.setlen(len) db.len db.buffer
db.grow_type(arr|[...]|u8arr|u16arr|u32arr|max_idx, [preserve_contents=true])
db.grow(cap, [preserve_contents=true], [pow2=true])
dab.setlen(len) dab.len dab.buffer dab.array
dab.grow_type(type|max_idx, [preserve_contents=true])
dab.grow(cap, [preserve_contents=true], [pow2=true])
dab.set(offset, in_arr, [len=1/0], [in_offset=0])
dab.remove(offset, [len=1])
dab.invalidate([offset=0], [len=1/0])
dab.upload()
davb.setlen(len) davb.len
davb.grow(cap, [preserve_contents=true], [pow2=true])
davb.<name> -> dab
davb.to_vao(vao)
UBOs
gl.ubo(ub_name) -> ubo
ubo.set(field_name, val)
ubo.values = {name->val}
ubo.upload()
ubo.bind()
VAOs
prog.vao() -> vao
vao.use()
vao.set_attrs(davb)
vao.set_attr(name, b)
vao.set_index(b)
vao.unuse()
vao.dab(attr_name, [cap]) -> dab
Textures
gl.texture(['cubemap']) -> tex
tex.set_rgba(w, h, pixels, [side])
tex.set_u32(w, h, values, [side])
tex.set_depth(w, h, [f32])
tex.set_image(image, [pixel_scale], [side])
tex.load(url, [pixel_scale], [on_load])
RBOs
gl.rbo() -> rbo
rbo.set_rgba(w, h, [n_samples|multisampling])
rbo.set_depth(w, h, [f32], [n_samples|multisampling])
FBOs
gl.fbo() -> fbo
fbo.bind('read', 'none|back|color', [color_unit=0])
fbo.bind(['draw'], [ 'none'|'back'|'color'|['none'|'back'|'color',...] ])
fbo.attach(tex|rbo, 'color|depth|depth_stencil', [color_unit])
fbo.clear_color(color_unit, r, g, b, [a=1])
fbo.clear_depth_stencil([depth=1], [stencil=0])
gl.read_pixels(attachment, color_unit, [buf], [x, y, w, h])
gl.blit(
[src_fbo], 'back|color', [color_unit],
[dst_fbo], [ 'none'|'back'|'color'|['none'|'back'|'color',...] ],
['color depth stencil'], ['nearest|linear'],
[sx0], [sy0], [sx1], [sy1],
[dx0], [dy0], [dx1], [dy1])
Freeing
prog|b|db|dab|davb|ubo|vao|tex|rbo|fbo.free()
*/
(function() {
let gl = WebGL2RenderingContext.prototype
// debugging -----------------------------------------------------------------
let methods = {}
let C = {}
for (let name in gl) {
let d = Object.getOwnPropertyDescriptor(gl, name)
if (isfunc(d.value) && name != 'getError')
methods[name] = d.value
else if (isnum(d.value))
C[d.value] = name
}
gl.C = C
function count_call(name, args, t) {
if (name == 'useProgram' && args[0])
name = name + ' ' + args[0].name
if (name.starts('uniform'))
name = name + ' ' + args[0].name
t[name] = (t[name] || 0) + 1
t._n++
}
gl.wrap_calls = function() {
for (let name in methods) {
let f = methods[name]
this[name] = function(...args) {
if (this._trace)
count_call(name, args, this._trace)
let ret = f.call(this, ...args)
let err = this.getError()
assert(!err, '{0}: {1}', name, C[err])
return ret
}
}
this.wrap_calls = noop
return this
}
gl.start_trace = function() {
this.wrap_calls()
this._trace = {_n: 0, _t0: time()}
}
gl.stop_trace = function() {
let t = this._trace
this._trace = null
t._t1 = time()
t._dt_ms = (t._t1 - t._t0) * 1000
return t
}
// clearing ------------------------------------------------------------------
gl.clear_all = function(r, g, b, a, depth) {
let gl = this
if (gl.draw_fbo) {
// NOTE: not using gl.clear(gl.COLOR_BUFFER_BIT) on a FBO because that
// clears _all_ color buffers, which we don't want (we clear the
// secondary color buffers separately with a different value).
if (r != null)
gl.draw_fbo.clear_color(0, r, g, b, a)
gl.draw_fbo.clear_depth_stencil(depth)
} else {
if (r != null)
gl.clearColor(r, g, b, or(a, 1))
gl.clearDepth(or(depth, 1))
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
}
gl.enable(gl.DEPTH_TEST)
gl.depthFunc(gl.LEQUAL)
gl.enable(gl.POLYGON_OFFSET_FILL)
return this
}
// programs ------------------------------------------------------------------
let outdent = function(s) {
s = s
.replaceAll('\r', '')
// trim line ends.
.replaceAll(/[\t ]+\n/g, '\n')
.replace(/[\t ]+$/, '')
// trim text of empty lines.
.replace(/^\n+/, '')
.replace(/\n+$/, '')
let indent = s.match(/^[\t ]*/)[0]
return s.replace(indent, '').replaceAll('\n'+indent, '\n')
}
gl.module = function(name, s) {
let t = attr(this, 'includes')
assert(t[name] == null, 'module already exists: {0}', name)
t[name] = outdent(s)
}
let preprocess = function(gl, code, included) {
return ('\n' + outdent(code))
.replaceAll(/\n#include[ \t]+([^\n]+)/g, function(_, name) {
if (included[name])
return ''
included[name] = true
let inc_code = attr(gl, 'includes')[name]
assert(inc_code, 'include not found: {0}', name)
return '\n'+preprocess(gl, inc_code, included)+'\n'
}).replace(/^\n/, '')
}
let linenumbers = function(s, errors) {
let t = map()
for (let match of errors.matchAll(/ERROR\: 0\:(\d+)\: ([^\n]+)/g))
t.set(num(match[1]), match[2])
let i = 0
s = ('\n' + s).replaceAll(/\n/g, function() {
i++
return '\n' + (t.has(i) ? t.get(i) + '\n' + '!' : ' ') + (i+'').padStart(4, ' ') + ' '
}).slice(1)
return s
}
gl.shader = function(type, name, gl_type, code) {
let gl = this
let shader = gl.createShader(gl_type)
shader.code = code
shader.raw_code = preprocess(gl, code, {})
gl.shaderSource(shader, shader.raw_code)
gl.compileShader(shader)
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
let errors = gl.getShaderInfoLog(shader)
print(errors)
print(linenumbers(shader.raw_code, errors))
gl.deleteShader(shader)
assert(false, '{0} shader compilation failed for program {1}', type, name)
}
return shader
}
let prog = WebGLProgram.prototype
let bt_by_gl_type = {}
let bt_by_type = {}
let bt_by_arr_type = map()
for (let [gl_type, type, arr_type, nc, val_gl_type, nloc] of [
[gl.FLOAT , 'f32' , f32arr, 1, null , 1],
[gl.UNSIGNED_BYTE , 'u8' , u8arr , 1, null , 1],
[gl.UNSIGNED_SHORT, 'u16' , u16arr, 1, null , 1],
[gl.UNSIGNED_INT , 'u32' , u32arr, 1, null , 1],
[gl.BYTE , 'i8' , i8arr , 1, null , 1],
[gl.SHORT , 'i16' , i16arr, 1, null , 1],
[gl.INT , 'i32' , i32arr, 1, null , 1],
[gl.FLOAT_VEC2 , 'v2' , f32arr, 2, gl.FLOAT, 1],
[gl.FLOAT_VEC3 , 'v3' , f32arr, 3, gl.FLOAT, 1],
[gl.FLOAT_VEC4 , 'v4' , f32arr, 4, gl.FLOAT, 1],
[gl.FLOAT_MAT3 , 'mat3', f32arr, 9, gl.FLOAT, 3],
[gl.FLOAT_MAT4 , 'mat4', f32arr, 16, gl.FLOAT, 4],
]) {
let bt = {
gl_type: gl_type,
val_gl_type: or(val_gl_type, gl_type),
type: type,
arr_type: arr_type,
nc: nc,
nloc: nloc,
}
bt_by_gl_type[gl_type] = bt
bt_by_type[type] = bt
if (nc == 1)
bt_by_arr_type.set(arr_type, bt)
}
function tex_type(gl_type) {
return (
gl_type == gl.SAMPLER_2D && '2d'
|| gl_type == gl.SAMPLER_CUBE && 'cubemap'
)
}
gl.ub = function(name) {
return assert(this.ubs && this.ubs[name], 'unknown uniform block {0}', name)
}
// NOTE: Each UB gets assigned a static UB binding index (we call it slot).
// NOTE: UBs with the same name must have exactly the same layout, which
// is what makes it possible to use the same UBO with different programs.
// This scheme is wasteful of UB binding indices but the assumption is that
// you'll make just a few very reusable UBOs (one for globals, one for materials).
gl.register_ub = function(ub) {
let ub0 = attr(this, 'ubs')[ub.name]
if (ub0) {
// check that the layouts of ub and ub0 match.
assert(ub0.size == ub.size)
assert(ub0.field_count == ub.field_count)
for (let name in ub.fields) {
let u1 = ub.fields[name]
let u0 = ub0.fields[name]
assert(u1.type == u0.type)
assert(u1.size == u0.size)
assert(u1.ub_offset == u0.ub_offset)
}
return ub0
} else {
this.ubs[ub.name] = ub
this.ub_slot_count = this.ub_slot_count || 0
ub.slot = this.ub_slot_count++
return ub
}
}
gl.program = function(pr_name, vs_code, fs_code) {
let gl = this
assert(isstr(pr_name), 'program name required')
let pr = attr(gl, 'programs')[pr_name]
if (pr) {
assert(pr.vs.code == vs_code)
assert(pr.fs.code == fs_code)
return pr
}
let vs = gl.shader('vertex' , pr_name, gl.VERTEX_SHADER , vs_code)
let fs = gl.shader('fragment', pr_name, gl.FRAGMENT_SHADER, fs_code)
pr = gl.createProgram()
gl.attachShader(pr, vs)
gl.attachShader(pr, fs)
gl.linkProgram(pr)
gl.validateProgram(pr)
if (!gl.getProgramParameter(pr, gl.LINK_STATUS)) {
print(gl.getProgramInfoLog(pr))
print('VERTEX SHADER')
print(vs_code)
print('FRAGMENT SHADER')
print(fs_code)
gl.deleteProgram(pr)
gl.deleteShader(vs)
gl.deleteShader(fs)
assert(false, 'linking failed for program {0}', pr_name)
}
// uniforms RTTI.
pr.uniform_count = gl.getProgramParameter(pr, gl.ACTIVE_UNIFORMS)
pr.uniforms = {} // {name->u}, excluding UB fields.
let us = [] // [index->u], including UB fields.
let n_cubemap = 0
for (let i = 0, n = pr.uniform_count; i < n; i++) {
let u = gl.getActiveUniform(pr, i)
u.location = gl.getUniformLocation(pr, u.name)
us[i] = u
if (u.location) { // UBO fields are listed too but don't get a location.
pr.uniforms[u.name] = u
u.location.name = u.name
let tt = tex_type(u.type)
if (tt)
u.tex_type = tt
}
}
// UBs RTTI.
pr.uniform_block_count = gl.getProgramParameter(pr, gl.ACTIVE_UNIFORM_BLOCKS)
pr.uniform_blocks = {} // {name->ub}
for (let ubi = 0, ubn = pr.uniform_block_count; ubi < ubn; ubi++) {
let ub_name = gl.getActiveUniformBlockName(pr, ubi)
let ub = {
name: ub_name,
fields: {}, // {name->u}
}
ub.size = gl.getActiveUniformBlockParameter(pr, ubi, gl.UNIFORM_BLOCK_DATA_SIZE)
let uis = gl.getActiveUniformBlockParameter(pr, ubi, gl.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES)
let ubos = gl.getActiveUniforms(pr, uis, gl.UNIFORM_OFFSET)
for (let i = 0, n = uis.length; i < n; i++) {
let u = us[uis[i]]
u.ub_offset = ubos[i]
ub.fields[u.name] = u
}
ub.field_count = uis.length
ub = gl.register_ub(ub)
gl.uniformBlockBinding(pr, ubi, ub.slot)
pr.uniform_blocks[ub_name] = ub
}
// assign static texture units to sampler uniforms.
pr.tex_uniforms = [] // [u1,...]
let t = {}
for (let u of us) {
if (u.tex_type && u.location) {
t[u.tex_type] = t[u.tex_type] || 0
u.tex_unit = t[u.tex_type]++
pr.tex_uniforms.push(u)
}
}
// attributes RTTI.
pr.attrs = {} // {name->a}
pr.attr_count = gl.getProgramParameter(pr, gl.ACTIVE_ATTRIBUTES)
for (let i = 0, n = pr.attr_count; i < n; i++) {
let info = gl.getActiveAttrib(pr, i)
let location = gl.getAttribLocation(pr, info.name)
let a = assign({
name: info.name,
size: info.size,
location: location,
program: pr,
}, bt_by_gl_type[info.type])
pr.attrs[info.name] = a
pr.attrs[location] = a
}
pr.gl = gl
pr.vs = vs
pr.fs = fs
pr.name = pr_name
gl.programs[pr_name] = pr
return pr
}
prog.use = function() {
let gl = this.gl
if (gl.active_program == this)
return this
gl.useProgram(this)
gl.active_program = this
// set or clear texture units to previously set values.
for (let u of this.tex_uniforms)
gl.bind_texture(u.tex_type, u.value, u.tex_unit)
return this
}
prog.unuse = function() {
let gl = this.gl
assert(gl.active_program == this, 'program not in use: {0}', this.name)
gl.useProgram(null)
gl.active_program = null
}
prog.free = function() {
let pr = this
let gl = pr.gl
if (gl.active_vao && gl.active_vao.program == this)
gl.active_vao.unbind()
for (let vao of this.vaos)
gl.deleteVertexArray(vao)
if (gl.active_program == this)
this.unuse()
delete gl.programs[pr.name]
gl.deleteProgram(pr)
gl.deleteShader(pr.vs)
gl.deleteShader(pr.fs)
this.free = noop
}
// uniforms ------------------------------------------------------------------
prog.set_uni = function(name, x, y, z, w) {
let gl = this.gl
let u = this.uniforms[name]
if (!u)
return this
let loc = u.location
let t = u.type
if (t == gl.FLOAT || t == gl.INT || t == gl.BOOL) {
x = x || 0
if (u.value == null || x != u.value) {
if (t == gl.FLOAT)
gl.uniform1f(loc, x)
else
gl.uniform1i(loc, x)
u.value = x
}
} else if (t == gl.FLOAT_VEC2) {
if (x == null) {
x = 0
y = 0
} else if (x.is_v2 || x.is_v3 || x.is_v4) {
let p = x
x = p[0]
y = p[1]
}
let v = u.value
if (!v || x != v[0] || y != v[1]) {
gl.uniform2f(loc, x, y)
if (v)
v.set(x, y)
else
u.value = v2(x, y)
}
} else if (t == gl.FLOAT_VEC3) {
if (x == null) {
x = 0
y = 0
z = 0
} else if (x.is_v3 || x.is_v4) {
let p = x
x = p[0]
y = p[1]
z = p[2]
} else if (isnum(x) && y == null) { // 0xRRGGBB -> (r, g, b)
let c = x
x = (c >> 16 & 0xff) / 255
y = (c >> 8 & 0xff) / 255
z = (c & 0xff) / 255
}
let v = u.value
if (!v || x != v[0] || y != v[1] || z != v[2]) {
gl.uniform3f(loc, x, y, z)
if (v)
v.set(x, y, z)
else
u.value = v3(x, y, z)
}
} else if (t == gl.FLOAT_VEC4) {
if (x == null) {
x = 0
y = 0
z = 0
w = 1
} else if (x.is_v3 || x.is_v4) {
let p = x
x = p[0]
y = p[1]
z = p[2]
w = p[3]
} else if (isnum(x) && y == null) { // 0xRRGGBBAA -> (r, g, b, a)
let c = x
x = (c >> 24 ) / 255
y = (c >> 16 & 0xff) / 255
z = (c >> 8 & 0xff) / 255
w = (c & 0xff) / 255
}
w = or(w, 1)
let v = u.value
if (!v || x != v[0] || y != v[1] || z != v[2] || w != v[3]) {
gl.uniform4f(loc, x, y, z, w)
if (v)
v.set(x, y, z, w)
else
u.value = v4(x, y, z, w)
}
} else if (t == gl.FLOAT_MAT3) {
let changed = !u.value || !u.value.equals(x)
if (u.value)
u.value.set(x)
else
u.value = mat3f32(...x)
if (changed)
gl.uniformMatrix3fv(loc, false, u.value)
} else if (t == gl.FLOAT_MAT4) {
let changed = !u.value || !u.value.equals(x)
if (u.value)
u.value.set(x)
else
u.value = mat4f32(...x)
if (changed)
gl.uniformMatrix4fv(loc, false, u.value)
} else if (t == gl.SAMPLER_2D || t == gl.SAMPLER_CUBE) {
let tex = x
let tex0 = u.value
if (tex == tex0)
return this
if (tex)
assert(tex.type == u.tex_type,
'texture type mismatch {0}, expected {1}', tex.type, u.tex_type)
gl.bind_texture(u.tex_type, tex, u.tex_unit)
u.value = tex
gl.uniform1i(loc, u.tex_unit)
} else {
assert(false, 'NYI: {2} uniform (program {0}, uniform {1})',
this.name, name, C[t])
}
return this
}
// UBOs ----------------------------------------------------------------------
gl.ubo = function(ub_name) {
let gl = this
let ub = gl.ub(ub_name)
let b = gl.buffer(ub.size)
let arr = new ArrayBuffer(ub.size)
let arr_u8 = new u8arr(arr)
let arr_f32 = new f32arr(arr)
let arr_i32 = new i32arr(arr)
let ubo = {
name: ub_name,
buffer: b,
values: {}, // {name->val}
tex_values: [],
}
ubo.set = function(name, val) {
if (!ub.fields[name])
return this
this.values[name] = val
return this
}
ubo.upload = function() {
let set_one
for (let name in this.values) {
let val = this.values[name]
let u = ub.fields[name]
let gl_type = u.type
let offset = u.ub_offset >> 2
if (gl_type == gl.INT || gl_type == gl.BOOL) {
arr_i32[offset] = val
} else if (gl_type == gl.FLOAT) {
arr_f32[offset] = val
} else if (
gl_type == gl.FLOAT_VEC2
|| gl_type == gl.FLOAT_VEC3
|| gl_type == gl.FLOAT_VEC4
|| gl_type == gl.FLOAT_MAT3
|| gl_type == gl.FLOAT_MAT4
) {
assert(val.length == bt_by_gl_type[gl_type].nc)
arr_f32.set(val, offset)
} else {
assert(false, 'NYI: {3} field', C[gl_type])
}
delete this.values[name]
set_one = true
}
if (set_one)
b.upload(arr_u8)
return this
}
let slot = ub.slot
ubo.bind = function() {
let slots = attr(gl, 'ubo_slots', Array)
if (slots[slot] != this) {
gl.bindBufferBase(gl.UNIFORM_BUFFER, slot, b)
slots[slot] = this
}
return this
}
return ubo
}
// drawing -------------------------------------------------------------------
gl.draw = function(gl_mode, offset, count) {
let gl = this
let vao = gl.active_vao
let ib = vao.index_buffer
let n_inst = vao.instance_count
offset = offset || 0
if (ib) {
if (count == null)
count = ib.len
if (n_inst != null) {
// NOTE: don't look for an offset-in-the-instance-buffers arg,
// that's glDrawElementsInstancedBaseInstance() which is not exposed.
gl.drawElementsInstanced(gl_mode, count, ib.gl_type, offset, n_inst)
} else {
gl.drawElements(gl_mode, count, ib.gl_type, offset)
}
} else {
if (count == null)
count = vao.vertex_count
if (n_inst != null) {
gl.drawArraysInstanced(gl_mode, offset, count, n_inst)
} else {
gl.drawArrays(gl_mode, offset, count)
}
}
return this
}
gl.draw_triangles = function(o, n) { return this.draw(gl.TRIANGLES, o, n) }
gl.draw_points = function(o, n) { return this.draw(gl.POINTS , o, n) }
gl.draw_lines = function(o, n) { return this.draw(gl.LINES , o, n) }
gl.cull = function(which) {
if (which == this.cull_mode)
return this
if (!which) {
this.disable(gl.CULL_FACE)
} else {
this.enable(gl.CULL_FACE)
this.cullFace(which == 'back' ? gl.BACK : gl.FRONT)
}
this.cull_mode = which
return this
}
// VAOs ----------------------------------------------------------------------
let vao = WebGLVertexArrayObject.prototype
// shared VAO: works with multiple programs but requires hardcoded attr. locations.
gl.vao = function(programs) {
let gl = this
let vao = gl.createVertexArray()
vao.gl = gl
vao.programs = assert(programs, 'programs required')
vao.attrs = {}
for (let prog of programs) {
for (let name of prog.attrs) {
let a = prog.attrs[name]
let a0 = vao.attrs[name]
if (!a0) {
a.program = prog
vao.attrs[name] = a
} else {
assert(a0.type == a.type, 'type mismatch {0} from {1} vs {2} from {3}',
a.type, prog, a0.type, a0.program.name)
assert(a0.location == a.location, 'location mismatch {0} from {1} vs {2} from {3}',
a.location, prog, a0.location, a0.program.name)
}
}
}
return vao
}
// program-specific VAO: only with the program that created it.
prog.vao = function() {
let gl = this.gl
let vao = gl.createVertexArray()
vao.gl = gl
vao.program = this
vao.attrs = this.attrs
vao.buffers = [] // {loc->buffer}
if (!this.vaos)
this.vaos = []
this.vaos.push(vao)
return vao
}
vao.bind = function() {
let gl = this.gl
if (this != gl.active_vao) {
assert(!gl.active_program || !this.program || gl.active_program == this.program,
'different active program')
gl.bindVertexArray(this)
gl.active_vao = this
}
}
vao.unbind = function() {
let gl = this.gl
assert(gl.active_vao == this, 'vao not bound')
gl.bindVertexArray(null)
gl.active_vao = null
}
vao.use = function() {
let gl = this.gl
if (this.program) {
this.program.use()
} else {
assert(gl.active_program, 'no active program for shared VAO')
}
this.bind()
return this
}
vao.unuse = function() {
this.unbind()
this.program.unuse()
}
vao.set_attr = function(name, b) {
let gl = this.gl
let bound = gl.active_vao == this
assert(bound || !gl.active_vao)
let a = this.attrs[name]
if (a == null)
return this
let loc = a.location
let b0 = this.buffers[loc]
if (b0 == b)
return this
if (!bound)
this.bind()
gl.bindBuffer(gl.ARRAY_BUFFER, b)
let nc = a.nc
let nloc = a.nloc
if (!b != !b0) {
for (let i = 0; i < nloc; i++)
if (b)
gl.enableVertexAttribArray(loc+i)
else
gl.disableVertexAttribArray(loc+i)
}
if (b) {
assert(b.nc == nc && b.nloc == nloc,
'type mismatch {0}, expected {1} for {2}', b.type, a.type, name)
if (b.type == 'i32' || b.type == 'u32') {
gl.vertexAttribIPointer(loc, nc, b.val_gl_type, 0, 0)
} else if (nloc == 1) {
gl.vertexAttribPointer(loc, nc, b.val_gl_type, false, 0, 0)
} else {
let nc_per_loc = nc / nloc
let stride = nc * 4
for (let i = 0; i < nloc; i++) {
let offset = i * nc_per_loc * 4
gl.vertexAttribPointer(loc+i, nc_per_loc, b.val_gl_type, false, stride, offset)
}
}
}
if ((b && b.inst_div || 0) != (b0 && b0.inst_div || 0))
for (let i = 0; i < nloc; i++)
gl.vertexAttribDivisor(loc+i, b && b.inst_div || 0)
if (!bound)
this.unbind()
this.buffers[loc] = b
return this
}
vao.set_attrs = function(davb) {
assert(davb.is_dyn_arr_vertex_buffer)
davb.to_vao(this)
return this
}
property(vao, 'vertex_count', function() {
let min_len
if (this.buffers)
for (let b of this.buffers)
if (b && !b.inst_div)
min_len = min(or(min_len, 1/0), b.len)
return min_len || 0
})
property(vao, 'instance_count', function() {
let min_len
if (this.buffers)
for (let b of this.buffers)
if (b && b.inst_div)
min_len = min(or(min_len, 1/0), b.len)
return min_len || 0
})
vao.set_index = function(b) {
let gl = this.gl
let bound = gl.active_vao == this
assert(bound || !gl.active_vao)
if (!bound)
this.bind()
if (this.index_buffer != b) {
assert(!b || b.for_index, 'not an index buffer')
this.index_buffer = b
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, b)
}
if (!bound)
this.unbind()
return this
}
vao.free = function() {
this.gl.deleteVertexArray(this)
this.program.vaos.remove_value(this)
this.free = noop
}
gl.vao_set = function() {
let vaos = {}
let e = {}
e.vao = function(prog) {
let vao = vaos[prog.name]
if (!vao) {
vao = prog.vao()
vaos[prog.name] = vao
}
return vao
}
e.free = function() {
for (let prog_name in vaos)
vaos[prog_name].free()
vaos = null
}
return e
}
// VBOs ----------------------------------------------------------------------
function get_bt(type) {
assert(type, 'type required')
if (isobject(type)) // custom type
return type
return assert(bt_by_type[type], 'unknown type {1}', type)
}
function check_arr_type(arr, arr_type) {
if (!arr_type)
return arr.constructor
assert(arr instanceof arr_type,
'different arr_type {0}, expected {1}', arr.constructor.name, arr_type.name)
return arr_type
}
function check_arr_nc(arr, nc) {
let arr_nc = arr.nc
nc = or(or(nc, arr_nc), 1)
assert(or(arr_nc, nc) == nc, 'different number of components {0}, expected {1}', arr_nc, nc)
return nc
}
function check_arr_len(nc, arr, len, arr_offset) {
if (len == null && arr.len != null) // dyn_arr
len = arr.len - arr_offset
if (len == null) {
len = arr.length / nc - arr_offset
assert(len == floor(len), 'array length not multiple of {0}', nc)
}
return max(0, len)
}
gl.buffer = function(data_or_cap, type, inst_div, for_index) {
let gl = this
data_or_cap = data_or_cap || 0
inst_div = inst_div || 0
assert(inst_div == 0 || inst_div == 1, 'NYI: inst_div != 1')
let bt, cap, len
if (isnum(data_or_cap)) { // [capacity], [type], ...
bt = get_bt(type || 'u8')
cap = data_or_cap
len = 0
data_or_cap = cap * bt.nc * bt.arr_type.BYTES_PER_ELEMENT
} else if (isarray(data_or_cap)) { // [element1, ...], [type], ...
type = type || data_or_cap.type // take the hint from the array.
bt = get_bt(type)
cap = check_arr_len(bt.nc, data_or_cap, null, 0)
len = cap
data_or_cap = new bt.arr_type(data_or_cap)
} else { // arr, [type], ...
type = type || data_or_cap.type // take the hint from the array.
if (type) {
bt = get_bt(type)
check_arr_type(data_or_cap, bt.arr_type)
check_arr_nc(data_or_cap, bt.nc)
} else { // infer type
let arr_type = check_arr_type(data_or_cap)
// inferring type based on the array's `nc` would be more aking to
// speculation than inference, so we're not going to do that.
let nc = check_arr_nc(data_or_cap, 1)
bt = assign({}, bt_by_arr_type.get(arr_type))
}
cap = check_arr_len(bt.nc, data_or_cap, null, 0)
len = cap
}
let ib0 = for_index && gl.active_vao && gl.active_vao.index_buffer
let gl_target = for_index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER
let b = gl.createBuffer()
gl.bindBuffer(gl_target, b)
gl.bufferData(gl_target, data_or_cap, gl.STATIC_DRAW)
if (ib0) // TODO: decide if OpenGL was made by psychotic apes.
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ib0)
b.gl = gl
b.capacity = cap
b._len = len
assign(b, bt)
b.for_index = for_index
b.inst_div = inst_div