-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
1623 lines (1475 loc) · 51.4 KB
/
index.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
const path = require('path')
const vec3 = require('pex-math/vec3')
const vec4 = require('pex-math/vec4')
const mat3 = require('pex-math/mat3')
const mat4 = require('pex-math/mat4')
const aabb = require('pex-geom/aabb')
const createProfiler = require('./profiler')
const isBrowser = require('is-browser')
const createEntity = require('./entity')
const createTransform = require('./transform')
const createSkin = require('./skin')
const createMorph = require('./morph')
const createAnimation = require('./animation')
const createGeometry = require('./geometry')
const createMaterial = require('./material')
const createCamera = require('./camera')
const createPostProcessing = require('./post-processing')
const createOrbiter = require('./orbiter')
const createAmbientLight = require('./ambient-light')
const createDirectionalLight = require('./directional-light')
const createPointLight = require('./point-light')
const createSpotLight = require('./spot-light')
const createAreaLight = require('./area-light')
const createReflectionProbe = require('./reflection-probe')
const createSkybox = require('./skybox')
const createOverlay = require('./overlay')
const createBoundingBoxHelper = require('./helpers/bounding-box-helper')
const createLightHelper = require('./helpers/light-helper')
const createCameraHelper = require('./helpers/camera-helper')
const createAxisHelper = require('./helpers/axis-helper')
const createGridHelper = require('./helpers/grid-helper')
const loadGltf = require('./loaders/glTF')
const createGeomBuilder = require('geom-builder')
const PBR_VERT = require('./shaders/pipeline/material.vert.js')
const PBR_FRAG = require('./shaders/pipeline/material.frag.js')
const DEPTH_PASS_VERT = require('./shaders/pipeline/depth-pass.vert.js')
const DEPTH_PASS_FRAG = require('./shaders/pipeline/depth-pass.frag.js')
const DEPTH_PRE_PASS_FRAG = require('./shaders/pipeline/depth-pre-pass.frag.js')
const OVERLAY_VERT = require('./shaders/pipeline/overlay.vert.js')
const OVERLAY_FRAG = require('./shaders/pipeline/overlay.frag.js')
const HELPER_VERT = require('./shaders/pipeline/helper.vert.js')
const HELPER_FRAG = require('./shaders/pipeline/helper.frag.js')
const ERROR_VERT = require('./shaders/error/error.vert.js')
const ERROR_FRAG = require('./shaders/error/error.frag.js')
const SHADERS_CHUNKS = require('./shaders/chunks')
const LOADERS = new Map().set(['.gltf', '.glb'], loadGltf)
const LOADERS_ENTRIES = Array.from(LOADERS.entries())
var State = {
frame: 0,
shadowQuality: 2,
debug: false,
profile: false,
profiler: null,
paused: false,
rgbm: false
}
function isNil(x) {
return x == null
}
// TODO remove, should be in AABB
function aabbToPoints(bbox) {
if (aabb.isEmpty(bbox)) return []
return [
[bbox[0][0], bbox[0][1], bbox[0][2], 1],
[bbox[1][0], bbox[0][1], bbox[0][2], 1],
[bbox[1][0], bbox[0][1], bbox[1][2], 1],
[bbox[0][0], bbox[0][1], bbox[1][2], 1],
[bbox[0][0], bbox[1][1], bbox[0][2], 1],
[bbox[1][0], bbox[1][1], bbox[0][2], 1],
[bbox[1][0], bbox[1][1], bbox[1][2], 1],
[bbox[0][0], bbox[1][1], bbox[1][2], 1]
]
}
// opts = Context
// opts = { ctx: Context, width: Number, height: Number, profile: Boolean }
function Renderer(opts) {
this.entities = []
this.root = this.entity()
// check if we passed gl context or options object
opts = opts.texture2D ? { ctx: opts } : opts
const ctx = (this._ctx = opts.ctx)
const gl = opts.ctx.gl
gl.getExtension('OES_standard_derivatives')
this._dummyTexture2D = ctx.texture2D({ width: 4, height: 4 })
this._dummyTextureCube = ctx.textureCube({ width: 4, height: 4 })
this._defaultMaterial = createMaterial({
ctx: ctx,
unlit: true,
baseColor: [1, 0, 0, 1]
})
this._debug = false
this._programCacheMap = {
values: [],
getValue: function(flags, vert, frag) {
for (var i = 0; i < this.values.length; i++) {
var v = this.values[i]
if (v.frag === frag && v.vert === vert) {
if (v.flags.length === flags.length) {
var found = true
for (var j = 0; j < flags.length; j++) {
if (v.flags[j] !== flags[j]) {
found = false
break
}
}
if (found) {
return v.program
}
}
}
}
return false
},
setValue: function(flags, vert, frag, program) {
this.values.push({ flags, vert, frag, program })
}
}
if (opts.profile) {
State.profiler = createProfiler(opts.ctx, this)
State.profiler.flush = opts.profileFlush
}
if (opts.pauseOnBlur && isBrowser) {
window.addEventListener('focus', () => {
State.paused = false
})
window.addEventListener('blur', () => {
State.paused = true
})
}
// TODO: move from State object to internal probs and renderer({ opts }) setter?
Object.assign(State, opts)
this._state = State
this.shaders = {
chunks: SHADERS_CHUNKS,
pipeline: {
depthPrePass: {
vert: DEPTH_PASS_VERT,
frag: DEPTH_PRE_PASS_FRAG
},
depthPass: {
vert: DEPTH_PASS_VERT,
frag: DEPTH_PASS_FRAG
},
material: {
vert: PBR_VERT,
frag: PBR_FRAG
}
}
}
this.helperPositionVBuffer = ctx.vertexBuffer({ data: [0, 0, 0] })
this.helperColorVBuffer = ctx.vertexBuffer({ data: [0, 0, 0, 0] })
this.drawHelperLinesCmd = {
pipeline: ctx.pipeline({
vert: `
${HELPER_VERT}
`,
frag: `
${HELPER_FRAG}
`,
depthTest: true,
primitive: ctx.Primitive.Lines
}),
attributes: {
aPosition: this.helperPositionVBuffer,
aVertexColor: this.helperColorVBuffer
},
count: 1
}
this.drawHelperLinesPostProcCmd = {
pipeline: ctx.pipeline({
vert: `
${HELPER_VERT}
`,
frag: `
${ctx.capabilities.maxColorAttachments > 1 ? '#define USE_DRAW_BUFFERS' : '' }
${HELPER_FRAG}
`,
depthTest: true,
primitive: ctx.Primitive.Lines
}),
attributes: {
aPosition: this.helperPositionVBuffer,
aVertexColor: this.helperColorVBuffer
},
count: 1
}
}
Renderer.prototype.updateDirectionalLightShadowMap = function(
light,
geometries
) {
const ctx = this._ctx
const position = light.entity.transform.worldPosition
const target = [0, 0, 1, 0]
const up = [0, 1, 0, 0]
vec4.multMat4(target, light.entity.transform.modelMatrix)
vec3.add(target, position)
vec4.multMat4(up, light.entity.transform.modelMatrix)
mat4.lookAt(light._viewMatrix, position, target, up)
const shadowBboxPoints = geometries.reduce((points, geometry) => {
return points.concat(aabbToPoints(geometry.entity.transform.worldBounds))
}, [])
// TODO: gc vec3.copy, all the bounding box creation
const bboxPointsInLightSpace = shadowBboxPoints.map((p) =>
vec3.multMat4(vec3.copy(p), light._viewMatrix)
)
const sceneBboxInLightSpace = aabb.fromPoints(bboxPointsInLightSpace)
const lightNear = -sceneBboxInLightSpace[1][2]
const lightFar = -sceneBboxInLightSpace[0][2]
light.set({
_near: lightNear,
_far: lightFar
})
mat4.ortho(
light._projectionMatrix,
sceneBboxInLightSpace[0][0],
sceneBboxInLightSpace[1][0],
sceneBboxInLightSpace[0][1],
sceneBboxInLightSpace[1][1],
lightNear,
lightFar
)
ctx.submit(light._shadowMapDrawCommand, () => {
this.drawMeshes(null, true, light, geometries)
})
}
Renderer.prototype.updateSpotLightShadowMap = function(light, geometries) {
const position = light.entity.transform.worldPosition
const target = [0, 0, 1, 0]
const up = [0, 1, 0, 0]
vec4.multMat4(target, light.entity.transform.modelMatrix)
// vec3.add(target, position)
vec4.multMat4(up, light.entity.transform.modelMatrix)
mat4.lookAt(light._viewMatrix, position, target, up)
const shadowBboxPoints = geometries.reduce((points, geometry) => {
return points.concat(aabbToPoints(geometry.entity.transform.worldBounds))
}, [])
// TODO: gc vec3.copy, all the bounding box creation
const bboxPointsInLightSpace = shadowBboxPoints.map((p) =>
vec3.multMat4(vec3.copy(p), light._viewMatrix)
)
const sceneBboxInLightSpace = aabb.fromPoints(bboxPointsInLightSpace)
const lightNear = -sceneBboxInLightSpace[1][2]
const lightFar = -sceneBboxInLightSpace[0][2]
light.set({
_near: lightNear,
_far: lightFar
})
mat4.perspective(
light._projectionMatrix,
2 * light.angle,
light._shadowMap.width / light._shadowMap.height,
lightNear,
lightFar
)
const ctx = this._ctx
ctx.submit(light._shadowMapDrawCommand, () => {
this.drawMeshes(null, true, light, geometries)
})
}
Renderer.prototype.updatePointLightShadowMap = function(light, geometries) {
const ctx = this._ctx
light._sides.forEach((side) => {
var target = [0, 0, 0]
ctx.submit(side.drawPassCmd, () => {
const position = light.entity.transform.worldPosition
vec3.set(target, position)
vec3.add(target, side.target)
mat4.lookAt(side.viewMatrix, position, target, side.up)
var sideLight = {
_projectionMatrix: side.projectionMatrix,
_viewMatrix: side.viewMatrix
}
this.drawMeshes(null, true, sideLight, geometries)
})
})
}
Renderer.prototype.parseShader = function(string, options) {
// Unroll loop
const unrollLoopPattern = /#pragma unroll_loop[\s]+?for \(int i = (\d+); i < (\d+|\D+); i\+\+\) \{([\s\S]+?)(?=\})\}/g
string = string.replace(unrollLoopPattern, function(
match,
start,
end,
snippet
) {
let unroll = ''
// Replace lights number
end = end
.replace(/NUM_AMBIENT_LIGHTS/g, options.numAmbientLights || 0)
.replace(/NUM_DIRECTIONAL_LIGHTS/g, options.numDirectionalLights || 0)
.replace(/NUM_POINT_LIGHTS/g, options.numPointLights || 0)
.replace(/NUM_SPOT_LIGHTS/g, options.numSpotLights || 0)
.replace(/NUM_AREA_LIGHTS/g, options.numAreaLights || 0)
for (let i = Number.parseInt(start); i < Number.parseInt(end); i++) {
unroll += snippet.replace(/\[i\]/g, `[${i}]`)
}
return unroll
})
return string
}
Renderer.prototype.getMaterialProgramAndFlags = function(
geometry,
material,
skin,
options
) {
var ctx = this._ctx
var flags = []
if (!geometry._attributes.aNormal) {
flags.push('#define USE_UNLIT_WORKFLOW')
} else {
flags.push('#define USE_NORMALS')
}
if (geometry._attributes.aTangent) {
flags.push('#define USE_TANGENTS')
}
if (geometry._attributes.aTexCoord0) {
flags.push('#define USE_TEXCOORD_0')
}
if (geometry._attributes.aTexCoord1) {
flags.push('#define USE_TEXCOORD_1')
}
if (geometry._attributes.aOffset) {
flags.push('#define USE_INSTANCED_OFFSET')
}
if (geometry._attributes.aScale) {
flags.push('#define USE_INSTANCED_SCALE')
}
if (geometry._attributes.aRotation) {
flags.push('#define USE_INSTANCED_ROTATION')
}
if (geometry._attributes.aColor) {
flags.push('#define USE_INSTANCED_COLOR')
}
if (geometry._attributes.aVertexColor) {
flags.push('#define USE_VERTEX_COLORS')
}
if (options.useSSAO) {
flags.push('#define USE_AO')
}
if (material.displacementMap) {
flags.push('#define USE_DISPLACEMENT_MAP')
}
if (skin) {
flags.push('#define USE_SKIN')
flags.push('#define NUM_JOINTS ' + skin.joints.length)
}
if (ctx.capabilities.maxColorAttachments > 1) {
flags.push('#define USE_DRAW_BUFFERS')
}
if (material.baseColorMap) {
flags.push('#define USE_BASE_COLOR_MAP')
if (!material.baseColor) {
material.baseColor = [1, 1, 1, 1]
}
flags.push(
`#define BASE_COLOR_MAP_TEX_COORD_INDEX ${material.baseColorMap
.texCoord || 0}`
)
if (material.baseColorMap.texCoordTransformMatrix) {
flags.push('#define USE_BASE_COLOR_MAP_TEX_COORD_TRANSFORM')
}
}
if (material.alphaMap) {
flags.push('#define USE_ALPHA_MAP')
flags.push(
`#define ALPHA_MAP_TEX_COORD_INDEX ${material.alphaMap.texCoord || 0}`
)
if (material.alphaMap.texCoordTransformMatrix) {
flags.push('#define USE_ALPHA_MAP_TEX_COORD_TRANSFORM')
}
}
if (material.alphaTest) {
flags.push('#define USE_ALPHA_TEST')
}
if (options.depthPrePassOnly) {
flags.push('#define DEPTH_PRE_PASS_ONLY')
flags.push('#define SHADOW_QUALITY ' + 0)
flags.push('#define NUM_AMBIENT_LIGHTS ' + 0)
flags.push('#define NUM_DIRECTIONAL_LIGHTS ' + 0)
flags.push('#define NUM_POINT_LIGHTS ' + 0)
flags.push('#define NUM_SPOT_LIGHTS ' + 0)
flags.push('#define NUM_AREA_LIGHTS ' + 0)
return {
flags: flags,
vert: material.vert || DEPTH_PASS_VERT,
frag: material.frag || DEPTH_PRE_PASS_FRAG
}
}
if (options.depthPassOnly) {
flags.push('#define DEPTH_PASS_ONLY')
flags.push('#define SHADOW_QUALITY ' + 0)
flags.push('#define NUM_AMBIENT_LIGHTS ' + 0)
flags.push('#define NUM_DIRECTIONAL_LIGHTS ' + 0)
flags.push('#define NUM_POINT_LIGHTS ' + 0)
flags.push('#define NUM_SPOT_LIGHTS ' + 0)
flags.push('#define NUM_AREA_LIGHTS ' + 0)
return {
flags: flags,
vert: material.vert || DEPTH_PASS_VERT,
frag: material.frag || DEPTH_PASS_FRAG
}
}
flags.push(
'#define SHADOW_QUALITY ' +
(material.receiveShadows ? State.shadowQuality : 0)
)
if (material.unlit) {
if (flags.indexOf('#define USE_UNLIT_WORKFLOW') === -1) {
flags.push('#define USE_UNLIT_WORKFLOW')
}
} else if (material.useSpecularGlossinessWorkflow) {
flags.push('#define USE_SPECULAR_GLOSSINESS_WORKFLOW')
if (material.diffuseMap) {
flags.push('#define USE_DIFFUSE_MAP')
flags.push(
`#define DIFFUSE_MAP_TEX_COORD_INDEX ${material.diffuseMap.texCoord ||
0}`
)
if (material.diffuseMap.texCoordTransformMatrix) {
flags.push('#define USE_DIFFUSE_MAP_TEX_COORD_TRANSFORM')
}
}
if (material.specularGlossinessMap) {
flags.push('#define USE_SPECULAR_GLOSSINESS_MAP')
flags.push(
`#define SPECULAR_GLOSSINESS_MAP_TEX_COORD_INDEX ${material
.specularGlossinessMap.texCoord || 0}`
)
if (material.specularGlossinessMap.texCoordTransformMatrix) {
flags.push('#define USE_SPECULAR_GLOSSINESS_MAP_TEX_COORD_TRANSFORM')
}
}
} else {
flags.push('#define USE_METALLIC_ROUGHNESS_WORKFLOW')
if (material.metallicMap) {
flags.push('#define USE_METALLIC_MAP')
flags.push(
`#define METALLIC_MAP_TEX_COORD_INDEX ${material.metallicMap.texCoord ||
0}`
)
if (material.metallicMap.texCoordTransformMatrix) {
flags.push('#define USE_METALLIC_MAP_TEX_COORD_TRANSFORM')
}
}
if (material.roughnessMap) {
flags.push('#define USE_ROUGHNESS_MAP')
flags.push(
`#define ROUGHNESS_MAP_TEX_COORD_INDEX ${material.roughnessMap
.texCoord || 0}`
)
if (material.roughnessMap.texCoordTransformMatrix) {
flags.push('#define USE_ROUGHNESS_MAP_TEX_COORD_TRANSFORM')
}
}
if (material.metallicRoughnessMap) {
flags.push('#define USE_METALLIC_ROUGHNESS_MAP')
flags.push(
`#define METALLIC_ROUGHNESS_MAP_TEX_COORD_INDEX ${material
.metallicRoughnessMap.texCoord || 0}`
)
if (material.metallicRoughnessMap.texCoordTransformMatrix) {
flags.push('#define USE_METALLIC_ROUGHNESS_MAP_TEX_COORD_TRANSFORM')
}
}
}
if (material.occlusionMap) {
flags.push('#define USE_OCCLUSION_MAP')
flags.push(
`#define OCCLUSION_MAP_TEX_COORD_INDEX ${material.occlusionMap.texCoord ||
0}`
)
if (material.occlusionMap.texCoordTransformMatrix) {
flags.push('#define USE_OCCLUSION_MAP_TEX_COORD_TRANSFORM')
}
}
if (material.normalMap) {
flags.push('#define USE_NORMAL_MAP')
flags.push(
`#define NORMAL_MAP_TEX_COORD_INDEX ${material.normalMap.texCoord || 0}`
)
if (material.normalMap.texCoordTransformMatrix) {
flags.push('#define USE_NORMAL_MAP_TEX_COORD_TRANSFORM')
}
}
if (material.emissiveColorMap) {
flags.push('#define USE_EMISSIVE_COLOR_MAP')
flags.push(
`#define EMISSIVE_COLOR_MAP_TEX_COORD_INDEX ${material.emissiveColorMap
.texCoord || 0}`
)
if (material.emissiveColorMap.texCoordTransformMatrix) {
flags.push('#define USE_EMISSIVE_COLOR_MAP_TEX_COORD_TRANSFORM')
}
}
if (!isNil(material.emissiveColor)) {
flags.push('#define USE_EMISSIVE_COLOR')
}
if (!isNil(material.clearCoat)) {
flags.push('#define USE_CLEAR_COAT')
}
if (material.clearCoatNormalMap) {
flags.push('#define USE_CLEAR_COAT_NORMAL_MAP')
flags.push(
`#define CLEAR_COAT_NORMAL_MAP_TEX_COORD_INDEX ${material
.clearCoatNormalMap.texCoord || 0}`
)
if (material.clearCoatNormalMap.texCoordTransformMatrix) {
flags.push('#define USE_CLEAR_COAT_NORMAL_MAP_TEX_COORD_TRANSFORM')
}
}
if (material.blend) {
flags.push('#define USE_BLEND')
}
flags.push('#define NUM_AMBIENT_LIGHTS ' + (options.numAmbientLights || 0))
flags.push(
'#define NUM_DIRECTIONAL_LIGHTS ' + (options.numDirectionalLights || 0)
)
flags.push('#define NUM_POINT_LIGHTS ' + (options.numPointLights || 0))
flags.push('#define NUM_SPOT_LIGHTS ' + (options.numSpotLights || 0))
flags.push('#define NUM_AREA_LIGHTS ' + (options.numAreaLights || 0))
if (options.useReflectionProbes) {
flags.push('#define USE_REFLECTION_PROBES')
}
if (options.useTonemapping) {
flags.push('#define USE_TONEMAPPING')
}
return {
flags: flags,
vert: material.vert || PBR_VERT,
frag: material.frag || PBR_FRAG
}
}
Renderer.prototype.buildProgram = function(vertSrc, fragSrc) {
var ctx = this._ctx
let program = null
try {
program = ctx.program({ vert: vertSrc, frag: fragSrc })
} catch (e) {
console.error('pex-renderer glsl error', e)
program = ctx.program({ vert: ERROR_VERT, frag: ERROR_FRAG })
throw e
}
return program
}
Renderer.prototype.getMaterialProgram = function(
geometry,
material,
skin,
options
) {
var { flags, vert, frag } = this.getMaterialProgramAndFlags(
geometry,
material,
skin,
options
)
var flagsStr = flags.join('\n') + '\n'
var vertSrc = flagsStr + vert
var fragSrc = flagsStr + frag
var program = this._programCacheMap.getValue(flags, vert, frag)
if (!program) {
program = this.buildProgram(
this.parseShader(vertSrc, options),
this.parseShader(fragSrc, options)
)
this._programCacheMap.setValue(flags, vert, frag, program)
}
return program
}
Renderer.prototype.traverseTransformTree = function(
transform,
beforeCallback,
afterCallback
) {
if (!transform.enabled) return
beforeCallback(transform)
transform.children.forEach((child) => {
this.traverseTransformTree(child, beforeCallback, afterCallback)
})
if (afterCallback) afterCallback(transform)
}
Renderer.prototype.update = function() {
this.entities = []
this.traverseTransformTree(
this.root.transform,
(transform) => {
this.entities.push(transform.entity)
transform.entity.components.forEach((component) => {
if (component.update) component.update()
})
},
(transform) => {
transform.entity.components.forEach((component) => {
if (component.afterUpdate) component.afterUpdate()
})
}
)
}
Renderer.prototype.getGeometryPipeline = function(
geometry,
material,
skin,
opts
) {
const ctx = this._ctx
const program = this.getMaterialProgram(geometry, material, skin, opts)
if (!this._pipelineCache) {
this._pipelineCache = {}
}
// TODO: better pipeline caching
const hash = material.id + '_' + program.id + '_' + geometry.primitive
let pipeline = this._pipelineCache[hash]
if (!pipeline || material.needsPipelineUpdate) {
material.needsPipelineUpdate = false
pipeline = ctx.pipeline({
program: program,
depthTest: material.depthTest,
depthWrite: material.depthWrite,
depthFunc: material.depthFunc,
blend: material.blend,
blendSrcRGBFactor: material.blendSrcRGBFactor,
blendSrcAlphaFactor: material.blendSrcAlphaFactor,
blendDstRGBFactor: material.blendDstRGBFactor,
blendDstAlphaFactor: material.blendDstAlphaFactor,
cullFace: material.cullFace,
cullFaceMode: material.cullFaceMode,
primitive: geometry.primitive
})
this._pipelineCache[hash] = pipeline
}
return pipeline
}
Renderer.prototype.getOverlayCommand = function() {
const ctx = this._ctx
if (!this._drawOverlayCmd) {
const program = ctx.program({
vert: OVERLAY_VERT,
frag: OVERLAY_FRAG
})
this._drawOverlayCmd = {
name: 'DrawOverlayCmd',
attributes: {
aPosition: ctx.vertexBuffer([[-1, -1], [1, -1], [1, 1], [-1, 1]]),
aTexCoord0: ctx.vertexBuffer([[0, 0], [1, 0], [1, 1], [0, 1]])
},
indices: ctx.indexBuffer([[0, 1, 2], [0, 2, 3]]),
pipeline: ctx.pipeline({
program: program,
depthTest: false,
depthWrite: false,
blend: true,
blendSrcRGBFactor: ctx.BlendFactor.One,
blendDstRGBFactor: ctx.BlendFactor.OneMinusSrcAlpha,
blendSrcAlphaFactor: ctx.BlendFactor.One,
blendDstAlphaFactor: ctx.BlendFactor.OneMinusSrcAlpha,
cullFace: true,
cullFaceMode: ctx.Face.Back,
primitive: ctx.Primitive.Triangles
})
}
}
return this._drawOverlayCmd
}
Renderer.prototype.getComponents = function(type) {
const result = []
for (let i = 0; i < this.entities.length; i++) {
const entity = this.entities[i]
const component = entity.getComponent(type)
if (component) {
result.push(component)
}
}
return result
}
// sort meshes by material
// do material search by props not string concat
// set global uniforms like lights once
// set update transforms once per frame
// draw + shadowmap @ 1000 objects x 30 uniforms = 60'000 setters / frame!!
// transform feedback?
Renderer.prototype.drawMeshes = function(
camera,
shadowMapping,
shadowMappingLight,
geometries,
skybox,
forward
) {
const ctx = this._ctx
function byEnabledAndCameraTags(component) {
if (!component.enabled) return false
if (!camera || !camera.entity) return true
if (!camera.entity.tags.length) return true
if (!component.entity.tags.length) return true
return component.entity.tags[0] === camera.entity.tags[0]
}
geometries =
geometries || this.getComponents('Geometry').filter(byEnabledAndCameraTags)
const ambientLights = this.getComponents('AmbientLight').filter(
byEnabledAndCameraTags
)
const directionalLights = this.getComponents('DirectionalLight').filter(
byEnabledAndCameraTags
)
const pointLights = this.getComponents('PointLight').filter(
byEnabledAndCameraTags
)
const spotLights = this.getComponents('SpotLight').filter(
byEnabledAndCameraTags
)
const areaLights = this.getComponents('AreaLight').filter(
byEnabledAndCameraTags
)
const reflectionProbes = this.getComponents('ReflectionProbe').filter(
byEnabledAndCameraTags
)
if (!shadowMapping && !shadowMappingLight) {
directionalLights.forEach((light) => {
if (light.castShadows) {
const shadowCasters = geometries.filter((geometry) => {
const material = geometry.entity.getComponent('Material')
return material && material.castShadows
})
this.updateDirectionalLightShadowMap(light, shadowCasters)
}
})
pointLights.forEach((light) => {
if (light.castShadows) {
const shadowCasters = geometries.filter((geometry) => {
const material = geometry.entity.getComponent('Material')
return material && material.castShadows
})
this.updatePointLightShadowMap(light, shadowCasters)
}
})
spotLights.forEach((light) => {
if (light.castShadows) {
const shadowCasters = geometries.filter((geometry) => {
const material = geometry.entity.getComponent('Material')
return material && material.castShadows
})
this.updateSpotLightShadowMap(light, shadowCasters)
}
})
}
var sharedUniforms = (this._sharedUniforms = this._sharedUniforms || {})
sharedUniforms.uOutputEncoding = State.rgbm
? ctx.Encoding.RGBM
: ctx.Encoding.Linear // TODO: State.postprocess
if (forward) {
sharedUniforms.uOutputEncoding = ctx.Encoding.Gamma
}
// TODO: find nearest reflection probe
if (reflectionProbes.length > 0) {
sharedUniforms.uReflectionMap = reflectionProbes[0]._reflectionMap
sharedUniforms.uReflectionMapEncoding =
reflectionProbes[0]._reflectionMap.encoding
}
if (shadowMappingLight) {
sharedUniforms.uProjectionMatrix = shadowMappingLight._projectionMatrix
sharedUniforms.uViewMatrix = shadowMappingLight._viewMatrix
} else {
sharedUniforms.uCameraPosition = camera.entity.transform.worldPosition
sharedUniforms.uProjectionMatrix = camera.projectionMatrix
sharedUniforms.uViewMatrix = camera.viewMatrix
sharedUniforms.uInverseViewMatrix = camera.inverseViewMatrix
}
if (camera) {
const postProcessingCmp = camera.entity.getComponent('PostProcessing')
if (postProcessingCmp && postProcessingCmp.ssao) {
sharedUniforms.uAO = postProcessingCmp._frameAOTex
sharedUniforms.uScreenSize = [camera.viewport[2], camera.viewport[3]] // TODO: should this be camera viewport size?
}
if (!(postProcessingCmp && postProcessingCmp.enabled)) {
sharedUniforms.uExposure = camera.exposure
}
}
ambientLights.forEach((light, i) => {
sharedUniforms['uAmbientLights[' + i + '].color'] = light.color
})
directionalLights.forEach((light, i) => {
const dir4 = [0, 0, 1, 0] // TODO: GC
const dir = [0, 0, 0]
vec4.multMat4(dir4, light.entity.transform.modelMatrix)
vec3.set(dir, dir4)
sharedUniforms['uDirectionalLights[' + i + '].direction'] = dir
sharedUniforms['uDirectionalLights[' + i + '].color'] = light.color
sharedUniforms['uDirectionalLights[' + i + '].castShadows'] =
light.castShadows
sharedUniforms['uDirectionalLights[' + i + '].projectionMatrix'] =
light._projectionMatrix
sharedUniforms['uDirectionalLights[' + i + '].viewMatrix'] =
light._viewMatrix
sharedUniforms['uDirectionalLights[' + i + '].near'] = light._near
sharedUniforms['uDirectionalLights[' + i + '].far'] = light._far
sharedUniforms['uDirectionalLights[' + i + '].bias'] = light.bias
sharedUniforms[
'uDirectionalLights[' + i + '].shadowMapSize'
] = light.castShadows
? [light._shadowMap.width, light._shadowMap.height]
: [0, 0]
sharedUniforms['uDirectionalLightShadowMaps[' + i + ']'] = light.castShadows
? light._shadowMap
: this._dummyTexture2D
})
pointLights.forEach((light, i) => {
sharedUniforms['uPointLights[' + i + '].position'] =
light.entity.transform.worldPosition
sharedUniforms['uPointLights[' + i + '].color'] = light.color
sharedUniforms['uPointLights[' + i + '].range'] = light.range
sharedUniforms['uPointLights[' + i + '].castShadows'] = light.castShadows
sharedUniforms['uPointLightShadowMaps[' + i + ']'] = light.castShadows
? light._shadowCubemap
: this._dummyTextureCube
})
spotLights.forEach((light, i) => {
const dir4 = [0, 0, 1, 0] // TODO: GC
const dir = [0, 0, 0]
vec4.multMat4(dir4, light.entity.transform.modelMatrix)
vec3.set(dir, dir4)
sharedUniforms['uSpotLights[' + i + '].position'] =
light.entity.transform.position
sharedUniforms['uSpotLights[' + i + '].direction'] = dir
sharedUniforms['uSpotLights[' + i + '].color'] = light.color
sharedUniforms['uSpotLights[' + i + '].angle'] = light.angle
sharedUniforms['uSpotLights[' + i + '].innerAngle'] = light.innerAngle
sharedUniforms['uSpotLights[' + i + '].range'] = light.range
sharedUniforms['uSpotLights[' + i + '].castShadows'] = light.castShadows
sharedUniforms['uSpotLights[' + i + '].projectionMatrix'] =
light._projectionMatrix
sharedUniforms['uSpotLights[' + i + '].viewMatrix'] = light._viewMatrix
sharedUniforms['uSpotLights[' + i + '].near'] = light._near
sharedUniforms['uSpotLights[' + i + '].far'] = light._far
sharedUniforms['uSpotLights[' + i + '].bias'] = light.bias
sharedUniforms['uSpotLights[' + i + '].shadowMapSize'] = light.castShadows
? [light._shadowMap.width, light._shadowMap.height]
: [0, 0]
sharedUniforms['uSpotLightShadowMaps[' + i + ']'] = light.castShadows
? light._shadowMap
: this._dummyTexture2D
})
areaLights.forEach((light, i) => {
sharedUniforms.ltc_mat = light.ltc_mat_texture
sharedUniforms.ltc_mag = light.ltc_mag_texture
sharedUniforms['uAreaLights[' + i + '].position'] =
light.entity.transform.position
sharedUniforms['uAreaLights[' + i + '].color'] = light.color
sharedUniforms['uAreaLights[' + i + '].intensity'] = light.intensity // FIXME: why area light has intensity and other lights don't?
sharedUniforms['uAreaLights[' + i + '].rotation'] =
light.entity.transform.rotation
sharedUniforms['uAreaLights[' + i + '].size'] = [
light.entity.transform.scale[0] / 2,
light.entity.transform.scale[1] / 2
]
})
geometries.sort((a, b) => {
var matA = a.entity.getComponent('Material') || this._defaultMaterial
var matB = b.entity.getComponent('Material') || this._defaultMaterial
var transparentA = matA.blend ? 1 : 0
var transparentB = matB.blend ? 1 : 0
return transparentA - transparentB
})
var firstTransparent = geometries.findIndex(
(g) => (g.entity.getComponent('Material') || this._defaultMaterial).blend
)
for (let i = 0; i < geometries.length; i++) {
// also drawn below if transparent objects don't exist
if (firstTransparent === i && skybox && skybox.enabled) {
skybox.draw(camera, {
outputEncoding: sharedUniforms.uOutputEncoding,
backgroundMode: true
})
}
const geometry = geometries[i]
const transform = geometry.entity.transform
if (!transform.enabled) {
continue
}
// don't draw uninitialized geometries
if (!geometry._attributes.aPosition) {
continue
}
const material = geometry.entity.getComponent('Material') || this._defaultMaterial
if (!material.enabled || (material.blend && shadowMapping)) {
continue
}
const skin = geometry.entity.getComponent('Skin')
const cachedUniforms = material._uniforms
if (material.baseColorMap) {
cachedUniforms.uBaseColorMap =
material.baseColorMap.texture || material.baseColorMap
if (material.baseColorMap.texCoordTransformMatrix) {
cachedUniforms.uBaseColorMapTexCoordTransform =
material.baseColorMap.texCoordTransformMatrix
}
}
cachedUniforms.uBaseColor = material.baseColor
if (material.emissiveColorMap) {
cachedUniforms.uEmissiveColorMap =
material.emissiveColorMap.texture || material.emissiveColorMap
if (material.emissiveColorMap.texCoordTransformMatrix) {
cachedUniforms.uEmissiveColorMapTexCoordTransform =
material.emissiveColorMap.texCoordTransformMatrix
}
}
if (!isNil(material.emissiveColor)) {
cachedUniforms.uEmissiveColor = material.emissiveColor
cachedUniforms.uEmissiveIntensity = material.emissiveIntensity
}
if (material.useSpecularGlossinessWorkflow) {
if (material.diffuse) cachedUniforms.uDiffuse = material.diffuse
if (material.specular) cachedUniforms.uSpecular = material.specular
if (!isNil(material.glossiness))
cachedUniforms.uGlossiness = material.glossiness
if (material.diffuseMap) {