-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
renderer.js
1291 lines (1048 loc) · 47.1 KB
/
renderer.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
import { Debug, DebugHelper } from '../../core/debug.js';
import { now } from '../../core/time.js';
import { Vec3 } from '../../core/math/vec3.js';
import { Mat3 } from '../../core/math/mat3.js';
import { Mat4 } from '../../core/math/mat4.js';
import { BoundingSphere } from '../../core/shape/bounding-sphere.js';
import {
SORTKEY_DEPTH, SORTKEY_FORWARD,
VIEW_CENTER, PROJECTION_ORTHOGRAPHIC,
LIGHTTYPE_DIRECTIONAL, MASK_AFFECT_DYNAMIC, MASK_AFFECT_LIGHTMAPPED, MASK_BAKE,
SHADOWUPDATE_NONE, SHADOWUPDATE_THISFRAME
} from '../constants.js';
import { LightTextureAtlas } from '../lighting/light-texture-atlas.js';
import { Material } from '../materials/material.js';
import { LightCube } from '../graphics/light-cube.js';
import {
CLEARFLAG_COLOR, CLEARFLAG_DEPTH, CLEARFLAG_STENCIL,
BINDGROUP_MESH, BINDGROUP_VIEW, UNIFORM_BUFFER_DEFAULT_SLOT_NAME,
UNIFORMTYPE_MAT4, UNIFORMTYPE_MAT3, UNIFORMTYPE_VEC3, UNIFORMTYPE_VEC2, UNIFORMTYPE_FLOAT, UNIFORMTYPE_INT,
SHADERSTAGE_VERTEX, SHADERSTAGE_FRAGMENT,
SEMANTIC_ATTR,
CULLFACE_BACK, CULLFACE_FRONT, CULLFACE_NONE,
TEXTUREDIMENSION_2D, SAMPLETYPE_UNFILTERABLE_FLOAT, SAMPLETYPE_FLOAT, SAMPLETYPE_DEPTH
} from '../../platform/graphics/constants.js';
import { DebugGraphics } from '../../platform/graphics/debug-graphics.js';
import { UniformBuffer } from '../../platform/graphics/uniform-buffer.js';
import { BindGroup } from '../../platform/graphics/bind-group.js';
import { UniformFormat, UniformBufferFormat } from '../../platform/graphics/uniform-buffer-format.js';
import { BindGroupFormat, BindBufferFormat, BindTextureFormat } from '../../platform/graphics/bind-group-format.js';
import { ShadowMapCache } from './shadow-map-cache.js';
import { ShadowRendererLocal } from './shadow-renderer-local.js';
import { ShadowRendererDirectional } from './shadow-renderer-directional.js';
import { ShadowRenderer } from './shadow-renderer.js';
import { WorldClustersAllocator } from './world-clusters-allocator.js';
import { RenderPassUpdateClustered } from './render-pass-update-clustered.js';
let _skinUpdateIndex = 0;
const boneTextureSize = [0, 0, 0, 0];
const viewProjMat = new Mat4();
const viewInvMat = new Mat4();
const viewMat = new Mat4();
const viewMat3 = new Mat3();
const tempSphere = new BoundingSphere();
const _flipYMat = new Mat4().setScale(1, -1, 1);
const _tempLightSet = new Set();
const _tempLayerSet = new Set();
// Converts a projection matrix in OpenGL style (depth range of -1..1) to a DirectX style (depth range of 0..1).
const _fixProjRangeMat = new Mat4().set([
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 0.5, 0,
0, 0, 0.5, 1
]);
const _tempProjMat0 = new Mat4();
const _tempProjMat1 = new Mat4();
const _tempProjMat2 = new Mat4();
const _tempProjMat3 = new Mat4();
const _tempSet = new Set();
const _tempMeshInstances = [];
const _tempMeshInstancesSkinned = [];
/**
* The base renderer functionality to allow implementation of specialized renderers.
*
* @ignore
*/
class Renderer {
/** @type {boolean} */
clustersDebugRendered = false;
/**
* A set of visible mesh instances which need further processing before being rendered, e.g.
* skinning or morphing. Extracted during culling.
*
* @type {Set<import('../mesh-instance.js').MeshInstance>}
* @private
*/
processingMeshInstances = new Set();
/**
* @type {WorldClustersAllocator}
* @ignore
*/
worldClustersAllocator;
/**
* A list of all unique lights in the layer composition.
*
* @type {import('../light.js').Light[]}
*/
lights = [];
/**
* A list of all unique local lights (spot & omni) in the layer composition.
*
* @type {import('../light.js').Light[]}
*/
localLights = [];
/**
* A list of unique directional shadow casting lights for each enabled camera. This is generated
* each frame during light culling.
*
* @type {Map<import('../camera.js').Camera, Array<import('../light.js').Light>>}
*/
cameraDirShadowLights = new Map();
/**
* A mapping of a directional light to a camera, for which the shadow is currently valid. This
* is cleared each frame, and updated each time a directional light shadow is rendered for a
* camera, and allows us to manually schedule shadow passes when a new camera needs a shadow.
*
* @type {Map<import('../light.js').Light, import('../camera.js').Camera>}
*/
dirLightShadows = new Map();
/**
* Create a new instance.
*
* @param {import('../../platform/graphics/graphics-device.js').GraphicsDevice} graphicsDevice - The
* graphics device used by the renderer.
*/
constructor(graphicsDevice) {
this.device = graphicsDevice;
/** @type {import('../scene.js').Scene|null} */
this.scene = null;
// TODO: allocate only when the scene has clustered lighting enabled
this.worldClustersAllocator = new WorldClustersAllocator(graphicsDevice);
// texture atlas managing shadow map / cookie texture atlassing for omni and spot lights
this.lightTextureAtlas = new LightTextureAtlas(graphicsDevice);
// shadows
this.shadowMapCache = new ShadowMapCache();
this.shadowRenderer = new ShadowRenderer(this, this.lightTextureAtlas);
this._shadowRendererLocal = new ShadowRendererLocal(this, this.shadowRenderer);
this._shadowRendererDirectional = new ShadowRendererDirectional(this, this.shadowRenderer);
// clustered passes
this._renderPassUpdateClustered = new RenderPassUpdateClustered(this.device, this, this.shadowRenderer,
this._shadowRendererLocal, this.lightTextureAtlas);
// view bind group format with its uniform buffer format
this.viewUniformFormat = null;
this.viewBindGroupFormat = null;
// timing
this._skinTime = 0;
this._morphTime = 0;
this._cullTime = 0;
this._shadowMapTime = 0;
this._lightClustersTime = 0;
this._layerCompositionUpdateTime = 0;
// stats
this._shadowDrawCalls = 0;
this._skinDrawCalls = 0;
this._instancedDrawCalls = 0;
this._shadowMapUpdates = 0;
this._numDrawCallsCulled = 0;
this._camerasRendered = 0;
this._lightClusters = 0;
// Uniforms
const scope = graphicsDevice.scope;
this.boneTextureId = scope.resolve('texture_poseMap');
this.boneTextureSizeId = scope.resolve('texture_poseMapSize');
this.poseMatrixId = scope.resolve('matrix_pose[0]');
this.modelMatrixId = scope.resolve('matrix_model');
this.normalMatrixId = scope.resolve('matrix_normal');
this.viewInvId = scope.resolve('matrix_viewInverse');
this.viewPos = new Float32Array(3);
this.viewPosId = scope.resolve('view_position');
this.projId = scope.resolve('matrix_projection');
this.projSkyboxId = scope.resolve('matrix_projectionSkybox');
this.viewId = scope.resolve('matrix_view');
this.viewId3 = scope.resolve('matrix_view3');
this.viewProjId = scope.resolve('matrix_viewProjection');
this.flipYId = scope.resolve('projectionFlipY');
this.tbnBasis = scope.resolve('tbnBasis');
this.nearClipId = scope.resolve('camera_near');
this.farClipId = scope.resolve('camera_far');
this.cameraParams = new Float32Array(4);
this.cameraParamsId = scope.resolve('camera_params');
this.alphaTestId = scope.resolve('alpha_ref');
this.opacityMapId = scope.resolve('texture_opacityMap');
this.exposureId = scope.resolve('exposure');
this.twoSidedLightingNegScaleFactorId = scope.resolve('twoSidedLightingNegScaleFactor');
this.twoSidedLightingNegScaleFactorId.setValue(0);
this.morphWeightsA = scope.resolve('morph_weights_a');
this.morphWeightsB = scope.resolve('morph_weights_b');
this.morphPositionTex = scope.resolve('morphPositionTex');
this.morphNormalTex = scope.resolve('morphNormalTex');
this.morphTexParams = scope.resolve('morph_tex_params');
// a single instance of light cube
this.lightCube = new LightCube();
this.constantLightCube = scope.resolve('lightCube[0]');
}
destroy() {
this.shadowRenderer = null;
this._shadowRendererLocal = null;
this._shadowRendererDirectional = null;
this.shadowMapCache.destroy();
this.shadowMapCache = null;
this._renderPassUpdateClustered.destroy();
this._renderPassUpdateClustered = null;
this.lightTextureAtlas.destroy();
this.lightTextureAtlas = null;
}
sortCompare(drawCallA, drawCallB) {
if (drawCallA.layer === drawCallB.layer) {
if (drawCallA.drawOrder && drawCallB.drawOrder) {
return drawCallA.drawOrder - drawCallB.drawOrder;
} else if (drawCallA.zdist && drawCallB.zdist) {
return drawCallB.zdist - drawCallA.zdist; // back to front
} else if (drawCallA.zdist2 && drawCallB.zdist2) {
return drawCallA.zdist2 - drawCallB.zdist2; // front to back
}
}
return drawCallB._key[SORTKEY_FORWARD] - drawCallA._key[SORTKEY_FORWARD];
}
sortCompareMesh(drawCallA, drawCallB) {
if (drawCallA.layer === drawCallB.layer) {
if (drawCallA.drawOrder && drawCallB.drawOrder) {
return drawCallA.drawOrder - drawCallB.drawOrder;
} else if (drawCallA.zdist && drawCallB.zdist) {
return drawCallB.zdist - drawCallA.zdist; // back to front
}
}
const keyA = drawCallA._key[SORTKEY_FORWARD];
const keyB = drawCallB._key[SORTKEY_FORWARD];
if (keyA === keyB && drawCallA.mesh && drawCallB.mesh) {
return drawCallB.mesh.id - drawCallA.mesh.id;
}
return keyB - keyA;
}
sortCompareDepth(drawCallA, drawCallB) {
const keyA = drawCallA._key[SORTKEY_DEPTH];
const keyB = drawCallB._key[SORTKEY_DEPTH];
if (keyA === keyB && drawCallA.mesh && drawCallB.mesh) {
return drawCallB.mesh.id - drawCallA.mesh.id;
}
return keyB - keyA;
}
/**
* Set up the viewport and the scissor for camera rendering.
*
* @param {import('../camera.js').Camera} camera - The camera containing the viewport
* information.
* @param {import('../../platform/graphics/render-target.js').RenderTarget} [renderTarget] - The
* render target. NULL for the default one.
*/
setupViewport(camera, renderTarget) {
const device = this.device;
DebugGraphics.pushGpuMarker(device, 'SETUP-VIEWPORT');
const pixelWidth = renderTarget ? renderTarget.width : device.width;
const pixelHeight = renderTarget ? renderTarget.height : device.height;
const rect = camera.rect;
let x = Math.floor(rect.x * pixelWidth);
let y = Math.floor(rect.y * pixelHeight);
let w = Math.floor(rect.z * pixelWidth);
let h = Math.floor(rect.w * pixelHeight);
device.setViewport(x, y, w, h);
// use viewport rectangle by default. Use scissor rectangle when required.
if (camera._scissorRectClear) {
const scissorRect = camera.scissorRect;
x = Math.floor(scissorRect.x * pixelWidth);
y = Math.floor(scissorRect.y * pixelHeight);
w = Math.floor(scissorRect.z * pixelWidth);
h = Math.floor(scissorRect.w * pixelHeight);
}
device.setScissor(x, y, w, h);
DebugGraphics.popGpuMarker(device);
}
setCameraUniforms(camera, target) {
// flipping proj matrix
const flipY = target?.flipY;
let viewCount = 1;
if (camera.xr && camera.xr.session) {
const transform = camera._node?.parent?.getWorldTransform() || null;
const views = camera.xr.views;
viewCount = views.list.length;
for (let v = 0; v < viewCount; v++) {
const view = views.list[v];
view.updateTransforms(transform);
camera.frustum.setFromMat4(view.projViewOffMat);
}
} else {
// Projection Matrix
let projMat = camera.projectionMatrix;
if (camera.calculateProjection) {
camera.calculateProjection(projMat, VIEW_CENTER);
}
let projMatSkybox = camera.getProjectionMatrixSkybox();
// flip projection matrices
if (flipY) {
projMat = _tempProjMat0.mul2(_flipYMat, projMat);
projMatSkybox = _tempProjMat1.mul2(_flipYMat, projMatSkybox);
}
// update depth range of projection matrices (-1..1 to 0..1)
if (this.device.isWebGPU) {
projMat = _tempProjMat2.mul2(_fixProjRangeMat, projMat);
projMatSkybox = _tempProjMat3.mul2(_fixProjRangeMat, projMatSkybox);
}
this.projId.setValue(projMat.data);
this.projSkyboxId.setValue(projMatSkybox.data);
// ViewInverse Matrix
if (camera.calculateTransform) {
camera.calculateTransform(viewInvMat, VIEW_CENTER);
} else {
const pos = camera._node.getPosition();
const rot = camera._node.getRotation();
viewInvMat.setTRS(pos, rot, Vec3.ONE);
}
this.viewInvId.setValue(viewInvMat.data);
// View Matrix
viewMat.copy(viewInvMat).invert();
this.viewId.setValue(viewMat.data);
// View 3x3
viewMat3.setFromMat4(viewMat);
this.viewId3.setValue(viewMat3.data);
// ViewProjection Matrix
viewProjMat.mul2(projMat, viewMat);
this.viewProjId.setValue(viewProjMat.data);
this.flipYId.setValue(flipY ? -1 : 1);
// View Position (world space)
this.dispatchViewPos(camera._node.getPosition());
camera.frustum.setFromMat4(viewProjMat);
}
this.tbnBasis.setValue(flipY ? -1 : 1);
// Near and far clip values
const n = camera._nearClip;
const f = camera._farClip;
this.nearClipId.setValue(n);
this.farClipId.setValue(f);
// camera params
this.cameraParams[0] = 1 / f;
this.cameraParams[1] = f;
this.cameraParams[2] = n;
this.cameraParams[3] = camera.projection === PROJECTION_ORTHOGRAPHIC ? 1 : 0;
this.cameraParamsId.setValue(this.cameraParams);
// exposure
this.exposureId.setValue(this.scene.physicalUnits ? camera.getExposure() : this.scene.exposure);
return viewCount;
}
/**
* Clears the active render target. If the viewport is already set up, only its area is cleared.
*
* @param {import('../camera.js').Camera} camera - The camera supplying the value to clear to.
* @param {boolean} [clearColor] - True if the color buffer should be cleared. Uses the value
* from the camera if not supplied.
* @param {boolean} [clearDepth] - True if the depth buffer should be cleared. Uses the value
* from the camera if not supplied.
* @param {boolean} [clearStencil] - True if the stencil buffer should be cleared. Uses the
* value from the camera if not supplied.
*/
clear(camera, clearColor, clearDepth, clearStencil) {
const flags = ((clearColor ?? camera._clearColorBuffer) ? CLEARFLAG_COLOR : 0) |
((clearDepth ?? camera._clearDepthBuffer) ? CLEARFLAG_DEPTH : 0) |
((clearStencil ?? camera._clearStencilBuffer) ? CLEARFLAG_STENCIL : 0);
if (flags) {
const device = this.device;
DebugGraphics.pushGpuMarker(device, 'CLEAR');
device.clear({
color: [camera._clearColor.r, camera._clearColor.g, camera._clearColor.b, camera._clearColor.a],
depth: camera._clearDepth,
stencil: camera._clearStencil,
flags: flags
});
DebugGraphics.popGpuMarker(device);
}
}
// make sure colorWrite is set to true to all channels, if you want to fully clear the target
// TODO: this function is only used from outside of forward renderer, and should be deprecated
// when the functionality moves to the render passes. Note that Editor uses it as well.
setCamera(camera, target, clear, renderAction = null) {
this.setCameraUniforms(camera, target);
this.clearView(camera, target, clear, false);
}
// TODO: this is currently used by the lightmapper and the Editor,
// and will be removed when those call are removed.
clearView(camera, target, clear, forceWrite) {
const device = this.device;
DebugGraphics.pushGpuMarker(device, 'CLEAR-VIEW');
device.setRenderTarget(target);
device.updateBegin();
if (forceWrite) {
device.setColorWrite(true, true, true, true);
device.setDepthWrite(true);
}
this.setupViewport(camera, target);
if (clear) {
// use camera clear options if any
const options = camera._clearOptions;
device.clear(options ? options : {
color: [camera._clearColor.r, camera._clearColor.g, camera._clearColor.b, camera._clearColor.a],
depth: camera._clearDepth,
flags: (camera._clearColorBuffer ? CLEARFLAG_COLOR : 0) |
(camera._clearDepthBuffer ? CLEARFLAG_DEPTH : 0) |
(camera._clearStencilBuffer ? CLEARFLAG_STENCIL : 0),
stencil: camera._clearStencil
});
}
DebugGraphics.popGpuMarker(device);
}
setupCullMode(cullFaces, flipFactor, drawCall) {
const material = drawCall.material;
let mode = CULLFACE_NONE;
if (cullFaces) {
let flipFaces = 1;
if (material.cull === CULLFACE_FRONT || material.cull === CULLFACE_BACK) {
flipFaces = flipFactor * drawCall.flipFacesFactor * drawCall.node.worldScaleSign;
}
if (flipFaces < 0) {
mode = material.cull === CULLFACE_FRONT ? CULLFACE_BACK : CULLFACE_FRONT;
} else {
mode = material.cull;
}
}
this.device.setCullMode(mode);
if (mode === CULLFACE_NONE && material.cull === CULLFACE_NONE) {
this.twoSidedLightingNegScaleFactorId.setValue(drawCall.node.worldScaleSign);
}
}
updateCameraFrustum(camera) {
if (camera.xr && camera.xr.views.list.length) {
// calculate frustum based on XR view
const view = camera.xr.views.list[0];
viewProjMat.mul2(view.projMat, view.viewOffMat);
camera.frustum.setFromMat4(viewProjMat);
return;
}
const projMat = camera.projectionMatrix;
if (camera.calculateProjection) {
camera.calculateProjection(projMat, VIEW_CENTER);
}
if (camera.calculateTransform) {
camera.calculateTransform(viewInvMat, VIEW_CENTER);
} else {
const pos = camera._node.getPosition();
const rot = camera._node.getRotation();
viewInvMat.setTRS(pos, rot, Vec3.ONE);
this.viewInvId.setValue(viewInvMat.data);
}
viewMat.copy(viewInvMat).invert();
viewProjMat.mul2(projMat, viewMat);
camera.frustum.setFromMat4(viewProjMat);
}
setBaseConstants(device, material) {
// Cull mode
device.setCullMode(material.cull);
// Alpha test
if (material.opacityMap) {
this.opacityMapId.setValue(material.opacityMap);
}
if (material.opacityMap || material.alphaTest > 0) {
this.alphaTestId.setValue(material.alphaTest);
}
}
updateCpuSkinMatrices(drawCalls) {
_skinUpdateIndex++;
const drawCallsCount = drawCalls.length;
if (drawCallsCount === 0) return;
// #if _PROFILER
const skinTime = now();
// #endif
for (let i = 0; i < drawCallsCount; i++) {
const si = drawCalls[i].skinInstance;
if (si) {
si.updateMatrices(drawCalls[i].node, _skinUpdateIndex);
si._dirty = true;
}
}
// #if _PROFILER
this._skinTime += now() - skinTime;
// #endif
}
/**
* Update skin matrices ahead of rendering.
*
* @param {import('../mesh-instance.js').MeshInstance[]|Set<import('../mesh-instance.js').MeshInstance>} drawCalls - MeshInstances
* containing skinInstance.
* @ignore
*/
updateGpuSkinMatrices(drawCalls) {
// #if _PROFILER
const skinTime = now();
// #endif
for (const drawCall of drawCalls) {
const skin = drawCall.skinInstance;
if (skin && skin._dirty) {
skin.updateMatrixPalette(drawCall.node, _skinUpdateIndex);
skin._dirty = false;
}
}
// #if _PROFILER
this._skinTime += now() - skinTime;
// #endif
}
/**
* Update morphing ahead of rendering.
*
* @param {import('../mesh-instance.js').MeshInstance[]|Set<import('../mesh-instance.js').MeshInstance>} drawCalls - MeshInstances
* containing morphInstance.
* @ignore
*/
updateMorphing(drawCalls) {
// #if _PROFILER
const morphTime = now();
// #endif
for (const drawCall of drawCalls) {
const morphInst = drawCall.morphInstance;
if (morphInst && morphInst._dirty) {
morphInst.update();
}
}
// #if _PROFILER
this._morphTime += now() - morphTime;
// #endif
}
/**
* Update draw calls ahead of rendering.
*
* @param {import('../mesh-instance.js').MeshInstance[]|Set<import('../mesh-instance.js').MeshInstance>} drawCalls - MeshInstances
* requiring updates.
* @ignore
*/
gpuUpdate(drawCalls) {
// Note that drawCalls can be either a Set or an Array and contains mesh instances
// that are visible in this frame
this.updateGpuSkinMatrices(drawCalls);
this.updateMorphing(drawCalls);
}
setVertexBuffers(device, mesh) {
// main vertex buffer
device.setVertexBuffer(mesh.vertexBuffer);
}
setMorphing(device, morphInstance) {
if (morphInstance) {
if (morphInstance.morph.useTextureMorph) {
// vertex buffer with vertex ids
device.setVertexBuffer(morphInstance.morph.vertexBufferIds);
// textures
this.morphPositionTex.setValue(morphInstance.texturePositions);
this.morphNormalTex.setValue(morphInstance.textureNormals);
// texture params
this.morphTexParams.setValue(morphInstance._textureParams);
} else { // vertex attributes based morphing
for (let t = 0; t < morphInstance._activeVertexBuffers.length; t++) {
const vb = morphInstance._activeVertexBuffers[t];
if (vb) {
// patch semantic for the buffer to current ATTR slot (using ATTR8 - ATTR15 range)
const semantic = SEMANTIC_ATTR + (t + 8);
vb.format.elements[0].name = semantic;
vb.format.elements[0].scopeId = device.scope.resolve(semantic);
vb.format.update();
device.setVertexBuffer(vb);
}
}
// set all 8 weights
this.morphWeightsA.setValue(morphInstance._shaderMorphWeightsA);
this.morphWeightsB.setValue(morphInstance._shaderMorphWeightsB);
}
}
}
setSkinning(device, meshInstance) {
if (meshInstance.skinInstance) {
this._skinDrawCalls++;
if (device.supportsBoneTextures) {
const boneTexture = meshInstance.skinInstance.boneTexture;
this.boneTextureId.setValue(boneTexture);
boneTextureSize[0] = boneTexture.width;
boneTextureSize[1] = boneTexture.height;
boneTextureSize[2] = 1.0 / boneTexture.width;
boneTextureSize[3] = 1.0 / boneTexture.height;
this.boneTextureSizeId.setValue(boneTextureSize);
} else {
this.poseMatrixId.setValue(meshInstance.skinInstance.matrixPalette);
}
}
}
// sets Vec3 camera position uniform
dispatchViewPos(position) {
const vp = this.viewPos; // note that this reuses an array
vp[0] = position.x;
vp[1] = position.y;
vp[2] = position.z;
this.viewPosId.setValue(vp);
}
initViewBindGroupFormat(isClustered) {
if (this.device.supportsUniformBuffers && !this.viewUniformFormat) {
// format of the view uniform buffer
const uniforms = [
new UniformFormat("matrix_viewProjection", UNIFORMTYPE_MAT4),
new UniformFormat("cubeMapRotationMatrix", UNIFORMTYPE_MAT3),
new UniformFormat("view_position", UNIFORMTYPE_VEC3),
new UniformFormat("skyboxIntensity", UNIFORMTYPE_FLOAT),
new UniformFormat("exposure", UNIFORMTYPE_FLOAT),
new UniformFormat("textureBias", UNIFORMTYPE_FLOAT)
];
if (isClustered) {
uniforms.push(...[
new UniformFormat("clusterCellsCountByBoundsSize", UNIFORMTYPE_VEC3),
new UniformFormat("clusterTextureSize", UNIFORMTYPE_VEC3),
new UniformFormat("clusterBoundsMin", UNIFORMTYPE_VEC3),
new UniformFormat("clusterBoundsDelta", UNIFORMTYPE_VEC3),
new UniformFormat("clusterCellsDot", UNIFORMTYPE_VEC3),
new UniformFormat("clusterCellsMax", UNIFORMTYPE_VEC3),
new UniformFormat("clusterCompressionLimit0", UNIFORMTYPE_VEC2),
new UniformFormat("shadowAtlasParams", UNIFORMTYPE_VEC2),
new UniformFormat("clusterMaxCells", UNIFORMTYPE_INT),
new UniformFormat("clusterSkip", UNIFORMTYPE_FLOAT)
]);
}
this.viewUniformFormat = new UniformBufferFormat(this.device, uniforms);
// format of the view bind group - contains single uniform buffer, and some textures
const buffers = [
new BindBufferFormat(UNIFORM_BUFFER_DEFAULT_SLOT_NAME, SHADERSTAGE_VERTEX | SHADERSTAGE_FRAGMENT)
];
const textures = [
new BindTextureFormat('lightsTextureFloat', SHADERSTAGE_FRAGMENT, TEXTUREDIMENSION_2D, SAMPLETYPE_UNFILTERABLE_FLOAT),
new BindTextureFormat('lightsTexture8', SHADERSTAGE_FRAGMENT, TEXTUREDIMENSION_2D, SAMPLETYPE_UNFILTERABLE_FLOAT),
new BindTextureFormat('shadowAtlasTexture', SHADERSTAGE_FRAGMENT, TEXTUREDIMENSION_2D, SAMPLETYPE_DEPTH),
new BindTextureFormat('cookieAtlasTexture', SHADERSTAGE_FRAGMENT, TEXTUREDIMENSION_2D, SAMPLETYPE_FLOAT),
new BindTextureFormat('areaLightsLutTex1', SHADERSTAGE_FRAGMENT, TEXTUREDIMENSION_2D, SAMPLETYPE_FLOAT),
new BindTextureFormat('areaLightsLutTex2', SHADERSTAGE_FRAGMENT, TEXTUREDIMENSION_2D, SAMPLETYPE_FLOAT)
];
if (isClustered) {
textures.push(...[
new BindTextureFormat('clusterWorldTexture', SHADERSTAGE_FRAGMENT, TEXTUREDIMENSION_2D, SAMPLETYPE_UNFILTERABLE_FLOAT)
]);
}
this.viewBindGroupFormat = new BindGroupFormat(this.device, buffers, textures);
}
}
setupViewUniformBuffers(viewBindGroups, viewUniformFormat, viewBindGroupFormat, viewCount) {
Debug.assert(Array.isArray(viewBindGroups), "viewBindGroups must be an array");
const device = this.device;
Debug.assert(viewCount === 1, "This code does not handle the viewCount yet");
while (viewBindGroups.length < viewCount) {
const ub = new UniformBuffer(device, viewUniformFormat, false);
const bg = new BindGroup(device, viewBindGroupFormat, ub);
DebugHelper.setName(bg, `ViewBindGroup_${bg.id}`);
viewBindGroups.push(bg);
}
// update view bind group / uniforms
const viewBindGroup = viewBindGroups[0];
viewBindGroup.defaultUniformBuffer.update();
viewBindGroup.update();
// TODO; this needs to be moved to drawInstance functions to handle XR
device.setBindGroup(BINDGROUP_VIEW, viewBindGroup);
}
setupMeshUniformBuffers(shaderInstance, meshInstance) {
const device = this.device;
if (device.supportsUniformBuffers) {
// TODO: model matrix setup is part of the drawInstance call, but with uniform buffer it's needed
// earlier here. This needs to be refactored for multi-view anyways.
this.modelMatrixId.setValue(meshInstance.node.worldTransform.data);
this.normalMatrixId.setValue(meshInstance.node.normalMatrix.data);
// update mesh bind group / uniform buffer
const meshBindGroup = shaderInstance.getBindGroup(device);
meshBindGroup.defaultUniformBuffer.update();
meshBindGroup.update();
device.setBindGroup(BINDGROUP_MESH, meshBindGroup);
}
}
drawInstance(device, meshInstance, mesh, style, normal) {
DebugGraphics.pushGpuMarker(device, meshInstance.node.name);
const modelMatrix = meshInstance.node.worldTransform;
this.modelMatrixId.setValue(modelMatrix.data);
if (normal) {
this.normalMatrixId.setValue(meshInstance.node.normalMatrix.data);
}
const instancingData = meshInstance.instancingData;
if (instancingData) {
if (instancingData.count > 0) {
this._instancedDrawCalls++;
device.setVertexBuffer(instancingData.vertexBuffer);
device.draw(mesh.primitive[style], instancingData.count);
}
} else {
device.draw(mesh.primitive[style]);
}
DebugGraphics.popGpuMarker(device);
}
// used for stereo
drawInstance2(device, meshInstance, mesh, style) {
DebugGraphics.pushGpuMarker(device, meshInstance.node.name);
const instancingData = meshInstance.instancingData;
if (instancingData) {
if (instancingData.count > 0) {
this._instancedDrawCalls++;
device.draw(mesh.primitive[style], instancingData.count, true);
}
} else {
// matrices are already set
device.draw(mesh.primitive[style], undefined, true);
}
DebugGraphics.popGpuMarker(device);
}
/**
* @param {import('../camera.js').Camera} camera - The camera used for culling.
* @param {import('../mesh-instance.js').MeshInstance[]} drawCalls - Draw calls to cull.
* @param {import('../layer.js').CulledInstances} culledInstances - Stores culled instances.
*/
cull(camera, drawCalls, culledInstances) {
// #if _PROFILER
const cullTime = now();
// #endif
const opaque = culledInstances.opaque;
opaque.length = 0;
const transparent = culledInstances.transparent;
transparent.length = 0;
const doCull = camera.frustumCulling;
const count = drawCalls.length;
for (let i = 0; i < count; i++) {
const drawCall = drawCalls[i];
if (drawCall.visible) {
const visible = !doCull || !drawCall.cull || drawCall._isVisible(camera);
if (visible) {
drawCall.visibleThisFrame = true;
// sort mesh instance into the right bucket based on its transparency
const bucket = drawCall.transparent ? transparent : opaque;
bucket.push(drawCall);
if (drawCall.skinInstance || drawCall.morphInstance)
this.processingMeshInstances.add(drawCall);
}
}
}
// #if _PROFILER
this._cullTime += now() - cullTime;
this._numDrawCallsCulled += doCull ? count : 0;
// #endif
}
collectLights(comp) {
// build a list and of all unique lights from all layers
this.lights.length = 0;
this.localLights.length = 0;
// stats
const stats = this.scene._stats;
// #if _PROFILER
stats.dynamicLights = 0;
stats.bakedLights = 0;
// #endif
const count = comp.layerList.length;
for (let i = 0; i < count; i++) {
const layer = comp.layerList[i];
// layer can be in the list two times (opaque, transp), process it only one time
if (!_tempLayerSet.has(layer)) {
_tempLayerSet.add(layer);
const lights = layer._lights;
for (let j = 0; j < lights.length; j++) {
const light = lights[j];
// add new light
if (!_tempLightSet.has(light)) {
_tempLightSet.add(light);
this.lights.push(light);
if (light._type !== LIGHTTYPE_DIRECTIONAL) {
this.localLights.push(light);
}
// #if _PROFILER
// if affects dynamic or baked objects in real-time
if ((light.mask & MASK_AFFECT_DYNAMIC) || (light.mask & MASK_AFFECT_LIGHTMAPPED)) {
stats.dynamicLights++;
}
// bake lights
if (light.mask & MASK_BAKE) {
stats.bakedLights++;
}
// #endif
}
}
}
}
stats.lights = this.lights.length;
_tempLightSet.clear();
_tempLayerSet.clear();
}
cullLights(camera, lights) {
const clusteredLightingEnabled = this.scene.clusteredLightingEnabled;
const physicalUnits = this.scene.physicalUnits;
for (let i = 0; i < lights.length; i++) {
const light = lights[i];
if (light.enabled) {
// directional lights are marked visible at the start of the frame
if (light._type !== LIGHTTYPE_DIRECTIONAL) {
light.getBoundingSphere(tempSphere);
if (camera.frustum.containsSphere(tempSphere)) {
light.visibleThisFrame = true;
light.usePhysicalUnits = physicalUnits;
// maximum screen area taken by the light
const screenSize = camera.getScreenSize(tempSphere);
light.maxScreenSize = Math.max(light.maxScreenSize, screenSize);
} else {
// if shadow casting light does not have shadow map allocated, mark it visible to allocate shadow map
// Note: This won't be needed when clustered shadows are used, but at the moment even culled out lights
// are used for rendering, and need shadow map to be allocated
// TODO: delete this code when clusteredLightingEnabled is being removed and is on by default.
if (!clusteredLightingEnabled) {
if (light.castShadows && !light.shadowMap) {
light.visibleThisFrame = true;
}
}
}
} else {
light.usePhysicalUnits = this.scene.physicalUnits;
}
}
}
}
/**
* Shadow map culling for directional and visible local lights
* visible meshInstances are collected into light._renderData, and are marked as visible
* for directional lights also shadow camera matrix is set up
*
* @param {import('../composition/layer-composition.js').LayerComposition} comp - The layer
* composition.
*/
cullShadowmaps(comp) {
const isClustered = this.scene.clusteredLightingEnabled;
// shadow casters culling for local (point and spot) lights
for (let i = 0; i < this.localLights.length; i++) {
const light = this.localLights[i];
if (light._type !== LIGHTTYPE_DIRECTIONAL) {
if (isClustered) {
// if atlas slot is reassigned, make sure to update the shadow map, including the culling
if (light.atlasSlotUpdated && light.shadowUpdateMode === SHADOWUPDATE_NONE) {
light.shadowUpdateMode = SHADOWUPDATE_THISFRAME;