@luma.gl/engine 10.0.0-alpha.10 → 10.0.0-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/dist/animation/node-animation-binding.cjs +10 -0
  2. package/dist/animation/node-animation-binding.d.ts +1 -1
  3. package/dist/animation/node-animation-binding.d.ts.map +1 -1
  4. package/dist/animation/node-animation-binding.js +10 -0
  5. package/dist/animation/node-animation-binding.js.map +1 -1
  6. package/dist/dist.dev.js +457 -206
  7. package/dist/dist.min.js +58 -58
  8. package/dist/gltf/gltf/animations/animations.d.ts +1 -1
  9. package/dist/gltf/gltf/animations/animations.d.ts.map +1 -1
  10. package/dist/gltf/gltf/create-scenegraph-from-gltf.cjs +80 -12
  11. package/dist/gltf/gltf/create-scenegraph-from-gltf.d.ts +8 -1
  12. package/dist/gltf/gltf/create-scenegraph-from-gltf.d.ts.map +1 -1
  13. package/dist/gltf/gltf/create-scenegraph-from-gltf.js +82 -14
  14. package/dist/gltf/gltf/create-scenegraph-from-gltf.js.map +1 -1
  15. package/dist/gltf/gltf/gltf-billboard.cjs +6 -1
  16. package/dist/gltf/gltf/gltf-billboard.d.ts.map +1 -1
  17. package/dist/gltf/gltf/gltf-billboard.js +6 -1
  18. package/dist/gltf/gltf/gltf-billboard.js.map +1 -1
  19. package/dist/gltf/gltf/gltf-extension-support.cjs +2 -2
  20. package/dist/gltf/gltf/gltf-extension-support.js +2 -2
  21. package/dist/gltf/gltf/gltf-extension-support.js.map +1 -1
  22. package/dist/gltf/index.cjs +2 -0
  23. package/dist/gltf/index.cjs.map +3 -3
  24. package/dist/gltf/index.d.ts +1 -1
  25. package/dist/gltf/index.d.ts.map +1 -1
  26. package/dist/gltf/index.js +1 -1
  27. package/dist/gltf/index.js.map +1 -1
  28. package/dist/gltf/parsers/parse-gltf-animations.cjs +8 -5
  29. package/dist/gltf/parsers/parse-gltf-animations.js +20 -5
  30. package/dist/gltf/parsers/parse-gltf-animations.js.map +1 -1
  31. package/dist/gltf/parsers/parse-gltf-lights.cjs +36 -72
  32. package/dist/gltf/parsers/parse-gltf-lights.d.ts +6 -2
  33. package/dist/gltf/parsers/parse-gltf-lights.d.ts.map +1 -1
  34. package/dist/gltf/parsers/parse-gltf-lights.js +34 -91
  35. package/dist/gltf/parsers/parse-gltf-lights.js.map +1 -1
  36. package/dist/gltf/parsers/parse-gltf-metadata.cjs +60 -0
  37. package/dist/gltf/parsers/parse-gltf-metadata.d.ts +5 -0
  38. package/dist/gltf/parsers/parse-gltf-metadata.d.ts.map +1 -0
  39. package/dist/gltf/parsers/parse-gltf-metadata.js +39 -0
  40. package/dist/gltf/parsers/parse-gltf-metadata.js.map +1 -0
  41. package/dist/gltf/parsers/parse-gltf.cjs +4 -1
  42. package/dist/gltf/parsers/parse-gltf.d.ts +4 -0
  43. package/dist/gltf/parsers/parse-gltf.d.ts.map +1 -1
  44. package/dist/gltf/parsers/parse-gltf.js +3 -0
  45. package/dist/gltf/parsers/parse-gltf.js.map +1 -1
  46. package/dist/gltf/pbr/pbr-environment.cjs +21 -3
  47. package/dist/gltf/pbr/pbr-environment.d.ts +3 -0
  48. package/dist/gltf/pbr/pbr-environment.d.ts.map +1 -1
  49. package/dist/gltf/pbr/pbr-environment.js +19 -1
  50. package/dist/gltf/pbr/pbr-environment.js.map +1 -1
  51. package/dist/graph/models/index.cjs.map +1 -1
  52. package/dist/graph/models/path/path-attribute-model.cjs +1 -1
  53. package/dist/graph/models/path/path-attribute-model.js +1 -1
  54. package/dist/graph/models/path/path-attribute-model.js.map +1 -1
  55. package/dist/graph/models/path/path-storage-model.cjs +1 -1
  56. package/dist/graph/models/path/path-storage-model.js +1 -1
  57. package/dist/graph/models/path/path-storage-model.js.map +1 -1
  58. package/dist/graph/physics/index.cjs.map +1 -1
  59. package/dist/graph/tables/index.cjs.map +1 -1
  60. package/dist/index.cjs +13 -0
  61. package/dist/index.cjs.map +3 -3
  62. package/dist/index.d.ts +4 -0
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +3 -0
  65. package/dist/index.js.map +1 -1
  66. package/dist/lighting/ambient-occlusion-pass.cjs +126 -0
  67. package/dist/lighting/ambient-occlusion-pass.d.ts +31 -0
  68. package/dist/lighting/ambient-occlusion-pass.d.ts.map +1 -0
  69. package/dist/lighting/ambient-occlusion-pass.js +108 -0
  70. package/dist/lighting/ambient-occlusion-pass.js.map +1 -0
  71. package/dist/lighting/clustered-light-grid.cjs +378 -0
  72. package/dist/lighting/clustered-light-grid.d.ts +94 -0
  73. package/dist/lighting/clustered-light-grid.d.ts.map +1 -0
  74. package/dist/lighting/clustered-light-grid.js +370 -0
  75. package/dist/lighting/clustered-light-grid.js.map +1 -0
  76. package/dist/lighting/contact-shadow-composite.cjs +80 -0
  77. package/dist/lighting/contact-shadow-composite.d.ts +6 -0
  78. package/dist/lighting/contact-shadow-composite.d.ts.map +1 -0
  79. package/dist/lighting/contact-shadow-composite.js +59 -0
  80. package/dist/lighting/contact-shadow-composite.js.map +1 -0
  81. package/dist/lighting/contact-shadow-pass.cjs +102 -0
  82. package/dist/lighting/contact-shadow-pass.d.ts +23 -0
  83. package/dist/lighting/contact-shadow-pass.d.ts.map +1 -0
  84. package/dist/lighting/contact-shadow-pass.js +85 -0
  85. package/dist/lighting/contact-shadow-pass.js.map +1 -0
  86. package/dist/lighting/index.cjs +118 -0
  87. package/dist/lighting/index.cjs.map +6 -0
  88. package/dist/lighting/index.d.ts +31 -0
  89. package/dist/lighting/index.d.ts.map +1 -0
  90. package/dist/lighting/index.js +20 -0
  91. package/dist/lighting/index.js.map +1 -0
  92. package/dist/lighting/lightmap-baker.cjs +238 -0
  93. package/dist/lighting/lightmap-baker.d.ts +62 -0
  94. package/dist/lighting/lightmap-baker.d.ts.map +1 -0
  95. package/dist/lighting/lightmap-baker.js +236 -0
  96. package/dist/lighting/lightmap-baker.js.map +1 -0
  97. package/dist/lighting/lightmap-data.cjs +117 -0
  98. package/dist/lighting/lightmap-data.d.ts +20 -0
  99. package/dist/lighting/lightmap-data.d.ts.map +1 -0
  100. package/dist/lighting/lightmap-data.js +110 -0
  101. package/dist/lighting/lightmap-data.js.map +1 -0
  102. package/dist/lighting/lightmap-environment.cjs +61 -0
  103. package/dist/lighting/lightmap-environment.d.ts +18 -0
  104. package/dist/lighting/lightmap-environment.d.ts.map +1 -0
  105. package/dist/lighting/lightmap-environment.js +46 -0
  106. package/dist/lighting/lightmap-environment.js.map +1 -0
  107. package/dist/lighting/pbr-environment.cjs +45 -0
  108. package/dist/lighting/pbr-environment.d.ts +25 -0
  109. package/dist/lighting/pbr-environment.d.ts.map +1 -0
  110. package/dist/lighting/pbr-environment.js +30 -0
  111. package/dist/lighting/pbr-environment.js.map +1 -0
  112. package/dist/lighting/pbr-material.cjs +75 -0
  113. package/dist/lighting/pbr-material.d.ts +33 -0
  114. package/dist/lighting/pbr-material.d.ts.map +1 -0
  115. package/dist/lighting/pbr-material.js +52 -0
  116. package/dist/lighting/pbr-material.js.map +1 -0
  117. package/dist/lighting/pbr-model.cjs +579 -0
  118. package/dist/lighting/pbr-model.d.ts +45 -0
  119. package/dist/lighting/pbr-model.d.ts.map +1 -0
  120. package/dist/lighting/pbr-model.js +545 -0
  121. package/dist/lighting/pbr-model.js.map +1 -0
  122. package/dist/lighting/pbr-surface-pass.cjs +116 -0
  123. package/dist/lighting/pbr-surface-pass.d.ts +35 -0
  124. package/dist/lighting/pbr-surface-pass.d.ts.map +1 -0
  125. package/dist/lighting/pbr-surface-pass.js +98 -0
  126. package/dist/lighting/pbr-surface-pass.js.map +1 -0
  127. package/dist/lighting/prefiltered-environment.cjs +275 -0
  128. package/dist/lighting/prefiltered-environment.d.ts +56 -0
  129. package/dist/lighting/prefiltered-environment.d.ts.map +1 -0
  130. package/dist/lighting/prefiltered-environment.js +264 -0
  131. package/dist/lighting/prefiltered-environment.js.map +1 -0
  132. package/dist/lighting/shadow-map-renderer.cjs +631 -0
  133. package/dist/lighting/shadow-map-renderer.d.ts +92 -0
  134. package/dist/lighting/shadow-map-renderer.d.ts.map +1 -0
  135. package/dist/lighting/shadow-map-renderer.js +622 -0
  136. package/dist/lighting/shadow-map-renderer.js.map +1 -0
  137. package/dist/lighting/shadow-quality.cjs +58 -0
  138. package/dist/lighting/shadow-quality.d.ts +13 -0
  139. package/dist/lighting/shadow-quality.d.ts.map +1 -0
  140. package/dist/lighting/shadow-quality.js +37 -0
  141. package/dist/lighting/shadow-quality.js.map +1 -0
  142. package/dist/material/material.cjs +3 -0
  143. package/dist/material/material.d.ts +2 -0
  144. package/dist/material/material.d.ts.map +1 -1
  145. package/dist/material/material.js +3 -0
  146. package/dist/material/material.js.map +1 -1
  147. package/dist/model/gpu-vector-model.cjs +11 -1
  148. package/dist/model/gpu-vector-model.d.ts +4 -2
  149. package/dist/model/gpu-vector-model.d.ts.map +1 -1
  150. package/dist/model/gpu-vector-model.js +12 -1
  151. package/dist/model/gpu-vector-model.js.map +1 -1
  152. package/dist/scenegraph/controllers/punctual-light-controller.cjs +121 -0
  153. package/dist/scenegraph/controllers/punctual-light-controller.d.ts +31 -0
  154. package/dist/scenegraph/controllers/punctual-light-controller.d.ts.map +1 -0
  155. package/dist/scenegraph/controllers/punctual-light-controller.js +117 -0
  156. package/dist/scenegraph/controllers/punctual-light-controller.js.map +1 -0
  157. package/dist/scenegraph/scene-metadata.cjs +43 -0
  158. package/dist/scenegraph/scene-metadata.d.ts +9 -0
  159. package/dist/scenegraph/scene-metadata.d.ts.map +1 -0
  160. package/dist/scenegraph/scene-metadata.js +21 -0
  161. package/dist/scenegraph/scene-metadata.js.map +1 -0
  162. package/dist/scenegraph/scenegraph-interaction.cjs +99 -0
  163. package/dist/scenegraph/scenegraph-interaction.d.ts +47 -0
  164. package/dist/scenegraph/scenegraph-interaction.d.ts.map +1 -0
  165. package/dist/scenegraph/scenegraph-interaction.js +79 -0
  166. package/dist/scenegraph/scenegraph-interaction.js.map +1 -0
  167. package/dist/scenegraph/scenegraph-node.cjs +10 -0
  168. package/dist/scenegraph/scenegraph-node.d.ts +10 -0
  169. package/dist/scenegraph/scenegraph-node.d.ts.map +1 -1
  170. package/dist/scenegraph/scenegraph-node.js +10 -0
  171. package/dist/scenegraph/scenegraph-node.js.map +1 -1
  172. package/dist/text/experimental.cjs.map +1 -1
  173. package/dist/text/fonts/atlas/text-utils.cjs +1 -1
  174. package/dist/text/fonts/atlas/text-utils.js +1 -1
  175. package/dist/text/fonts/atlas/text-utils.js.map +1 -1
  176. package/dist/text/fonts/index.cjs.map +1 -1
  177. package/dist/text/index.cjs.map +1 -1
  178. package/dist/text/text-2d/models/text-attribute-model.cjs +1 -1
  179. package/dist/text/text-2d/models/text-attribute-model.js +1 -1
  180. package/dist/text/text-2d/models/text-attribute-model.js.map +1 -1
  181. package/dist/text/text-2d/models/text-dictionary-model.cjs +1 -1
  182. package/dist/text/text-2d/models/text-dictionary-model.js +1 -1
  183. package/dist/text/text-2d/models/text-dictionary-model.js.map +1 -1
  184. package/dist/text/text-2d/models/text-storage-model.cjs +1 -1
  185. package/dist/text/text-2d/models/text-storage-model.js +1 -1
  186. package/dist/text/text-2d/models/text-storage-model.js.map +1 -1
  187. package/package.json +13 -8
  188. package/src/animation/node-animation-binding.ts +18 -1
  189. package/src/gltf/gltf/animations/animations.ts +8 -1
  190. package/src/gltf/gltf/create-scenegraph-from-gltf.ts +98 -17
  191. package/src/gltf/gltf/gltf-billboard.ts +6 -1
  192. package/src/gltf/gltf/gltf-extension-support.ts +2 -2
  193. package/src/gltf/index.ts +1 -0
  194. package/src/gltf/parsers/parse-gltf-animations.ts +22 -8
  195. package/src/gltf/parsers/parse-gltf-lights.ts +42 -130
  196. package/src/gltf/parsers/parse-gltf-metadata.ts +40 -0
  197. package/src/gltf/parsers/parse-gltf.ts +5 -0
  198. package/src/gltf/pbr/pbr-environment.ts +27 -1
  199. package/src/graph/models/path/path-attribute-model.ts +1 -1
  200. package/src/graph/models/path/path-storage-model.ts +1 -1
  201. package/src/index.ts +16 -0
  202. package/src/lighting/ambient-occlusion-pass.ts +130 -0
  203. package/src/lighting/clustered-light-grid.ts +481 -0
  204. package/src/lighting/contact-shadow-composite.ts +67 -0
  205. package/src/lighting/contact-shadow-pass.ts +107 -0
  206. package/src/lighting/index.ts +107 -0
  207. package/src/lighting/lightmap-baker.ts +306 -0
  208. package/src/lighting/lightmap-data.ts +138 -0
  209. package/src/lighting/lightmap-environment.ts +70 -0
  210. package/src/lighting/pbr-environment.ts +55 -0
  211. package/src/lighting/pbr-material.ts +85 -0
  212. package/src/lighting/pbr-model.ts +608 -0
  213. package/src/lighting/pbr-surface-pass.ts +122 -0
  214. package/src/lighting/prefiltered-environment.ts +354 -0
  215. package/src/lighting/shadow-map-renderer.ts +918 -0
  216. package/src/lighting/shadow-quality.ts +50 -0
  217. package/src/material/material.ts +3 -0
  218. package/src/model/gpu-vector-model.ts +18 -3
  219. package/src/scenegraph/controllers/punctual-light-controller.ts +172 -0
  220. package/src/scenegraph/scene-metadata.ts +23 -0
  221. package/src/scenegraph/scenegraph-interaction.ts +131 -0
  222. package/src/scenegraph/scenegraph-node.ts +12 -0
  223. package/src/text/fonts/atlas/text-utils.ts +1 -1
  224. package/src/text/text-2d/models/text-attribute-model.ts +1 -1
  225. package/src/text/text-2d/models/text-dictionary-model.ts +1 -1
  226. package/src/text/text-2d/models/text-storage-model.ts +1 -1
@@ -0,0 +1,918 @@
1
+ // luma.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import type {
6
+ Framebuffer,
7
+ RenderPass,
8
+ RenderPipelineParameters,
9
+ Sampler,
10
+ Texture,
11
+ TextureView
12
+ } from '@luma.gl/core';
13
+ import {Device, Texture as TextureResource} from '@luma.gl/core';
14
+ import {Matrix4, radians} from '@math.gl/core';
15
+ import type {NumberArray3, NumberArray16} from '@math.gl/core';
16
+ import {SHADOW_QUALITY_SETTINGS} from './shadow-quality';
17
+ import type {
18
+ DirectionalShadowLight,
19
+ SpotShadowLight,
20
+ PointShadowLight,
21
+ ShadowProps,
22
+ ShadowBiasProps
23
+ } from '@luma.gl/shaders';
24
+ export type {DirectionalShadowLight, SpotShadowLight, PointShadowLight} from '@luma.gl/shaders';
25
+
26
+ const MAX_DIRECTIONAL_LIGHTS = 1;
27
+ const MAX_SPOT_LIGHTS = 4;
28
+ const MAX_POINT_LIGHTS = 4;
29
+ const MAX_CASCADES = 4;
30
+ const POINT_FACE_COUNT = 6;
31
+ const DEFAULT_NEAR_PLANE = 0.1;
32
+ // math.gl projection builders use OpenGL [-1, 1] depth; shadow maps require WebGPU [0, 1].
33
+ const OPENGL_TO_WEBGPU_MATRIX: NumberArray16 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 1];
34
+ const IDENTITY_MATRIX: NumberArray16 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1];
35
+
36
+ export type PointShadowFace = '+X' | '-X' | '+Y' | '-Y' | '+Z' | '-Z';
37
+
38
+ /** Camera matrices and clip distances used to fit directional cascades. */
39
+ export type ShadowCamera = {
40
+ viewMatrix: Readonly<Matrix4 | NumberArray16>;
41
+ projectionMatrix: Readonly<Matrix4 | NumberArray16>;
42
+ near: number;
43
+ far: number;
44
+ /** Input projection depth convention. Defaults to math.gl's OpenGL convention. */
45
+ clipDepth?: 'negative-one-to-one' | 'zero-to-one';
46
+ };
47
+
48
+ /** Resource capacities and quality defaults owned by {@link ShadowMapRenderer}. */
49
+ export type ShadowMapRendererProps = {
50
+ quality?: 'low' | 'balanced' | 'cinematic';
51
+ directionalLightCapacity?: number;
52
+ spotLightCapacity?: number;
53
+ pointLightCapacity?: number;
54
+ directionalMapSize?: number;
55
+ spotMapSize?: number;
56
+ pointMapSize?: number;
57
+ };
58
+
59
+ /** One depth-only light view passed to the application caster callback. */
60
+ export type ShadowRenderView = {
61
+ renderPass: RenderPass;
62
+ framebuffer: Framebuffer;
63
+ type: 'directional' | 'spot' | 'point';
64
+ lightIndex: number;
65
+ cascadeIndex?: number;
66
+ pointFace?: PointShadowFace;
67
+ camera: ShadowCamera;
68
+ viewProjectionMatrix: Readonly<Matrix4>;
69
+ mapSize: number;
70
+ rasterParameters: Readonly<RenderPipelineParameters>;
71
+ };
72
+
73
+ /** Per-frame lights and caster callback accepted by {@link ShadowMapRenderer.render}. */
74
+ export type ShadowRenderOptions = {
75
+ camera: ShadowCamera;
76
+ directionalLights?: readonly DirectionalShadowLight[];
77
+ spotLights?: readonly SpotShadowLight[];
78
+ pointLights?: readonly PointShadowLight[];
79
+ drawShadowCasters: (view: ShadowRenderView) => void;
80
+ /** Upload resources before opening the depth render pass. */
81
+ prepareShadowCasters?: (view: Omit<ShadowRenderView, 'renderPass'>) => void;
82
+ };
83
+
84
+ /** GPU resource props returned by the renderer for the shadow sampling module. */
85
+ export type ShadowShaderProps = ShadowProps<Texture, Sampler>;
86
+
87
+ type ResolvedShadowMapRendererProps = Required<ShadowMapRendererProps> & {
88
+ cascadeCount: number;
89
+ blockerSampleCount: number;
90
+ filterSampleCount: number;
91
+ };
92
+
93
+ type ShadowMapResources = {
94
+ directionalTexture: Texture;
95
+ spotTexture: Texture;
96
+ pointTexture: Texture;
97
+ comparisonSampler: Sampler;
98
+ nonFilteringSampler: Sampler;
99
+ directionalFramebuffers: Framebuffer[];
100
+ spotFramebuffers: Framebuffer[];
101
+ pointFramebuffers: Framebuffer[];
102
+ attachmentViews: TextureView[];
103
+ };
104
+
105
+ type ComputedShadowView = {
106
+ camera: ShadowCamera;
107
+ viewProjectionMatrix: Matrix4;
108
+ };
109
+
110
+ const POINT_FACE_ORIENTATIONS: ReadonlyArray<{
111
+ face: PointShadowFace;
112
+ direction: NumberArray3;
113
+ up: NumberArray3;
114
+ }> = [
115
+ {face: '+X', direction: [1, 0, 0], up: [0, -1, 0]},
116
+ {face: '-X', direction: [-1, 0, 0], up: [0, -1, 0]},
117
+ {face: '+Y', direction: [0, 1, 0], up: [0, 0, 1]},
118
+ {face: '-Y', direction: [0, -1, 0], up: [0, 0, -1]},
119
+ {face: '+Z', direction: [0, 0, 1], up: [0, -1, 0]},
120
+ {face: '-Z', direction: [0, 0, -1], up: [0, -1, 0]}
121
+ ];
122
+
123
+ let nextShadowResourceId = 0;
124
+
125
+ /**
126
+ * Owns backend-selected depth-array resources and records application-supplied shadow caster draws.
127
+ *
128
+ * The renderer never submits the device command encoder. Applications should pre-create any
129
+ * per-view uniform storage needed by `drawShadowCasters`; one shared mutable uniform buffer cannot
130
+ * retain different matrices for several passes recorded into the same command buffer.
131
+ */
132
+ export class ShadowMapRenderer {
133
+ readonly device: Device;
134
+ props: ResolvedShadowMapRendererProps;
135
+
136
+ private inputProps: ShadowMapRendererProps;
137
+ private resources: ShadowMapResources;
138
+ private destroyed = false;
139
+
140
+ constructor(device: Device, props: ShadowMapRendererProps = {}) {
141
+ if (device.type !== 'webgpu' && device.type !== 'webgl') {
142
+ throw new Error('ShadowMapRenderer requires a WebGPU or WebGL2 device.');
143
+ }
144
+ this.device = device;
145
+ this.inputProps = {...props};
146
+ this.props = resolveShadowMapRendererProps(device, this.inputProps);
147
+ this.resources = createShadowMapResources(device, this.props);
148
+ }
149
+
150
+ /** Reconfigures capacities or quality, rebuilding GPU resources only when their shape changes. */
151
+ setProps(props: ShadowMapRendererProps): void {
152
+ this.assertNotDestroyed();
153
+ const nextInputProps = {...this.inputProps, ...props};
154
+ const nextProps = resolveShadowMapRendererProps(this.device, nextInputProps);
155
+ const needsResourceRebuild = !resourcePropsEqual(this.props, nextProps);
156
+ this.inputProps = nextInputProps;
157
+ this.props = nextProps;
158
+ if (!needsResourceRebuild) {
159
+ return;
160
+ }
161
+ const previousResources = this.resources;
162
+ this.resources = createShadowMapResources(this.device, nextProps);
163
+ destroyShadowMapResources(previousResources);
164
+ }
165
+
166
+ /** Records all active shadow-map views and returns props ready for `ShaderInputs.setProps`. */
167
+ render(options: ShadowRenderOptions): ShadowShaderProps {
168
+ this.assertNotDestroyed();
169
+ validateShadowCamera(options.camera);
170
+ const directionalLights = options.directionalLights || [];
171
+ const spotLights = options.spotLights || [];
172
+ const pointLights = options.pointLights || [];
173
+ validateLightCount(
174
+ 'directional',
175
+ directionalLights.length,
176
+ this.props.directionalLightCapacity
177
+ );
178
+ validateLightCount('spot', spotLights.length, this.props.spotLightCapacity);
179
+ validateLightCount('point', pointLights.length, this.props.pointLightCapacity);
180
+
181
+ const directionalViews: ComputedShadowView[] = [];
182
+ let cascadeSplits = padCascadeSplits([], options.camera.far);
183
+ if (directionalLights[0]) {
184
+ const light = resolveDirectionalLight(directionalLights[0], options.camera);
185
+ cascadeSplits = padCascadeSplits(
186
+ getPracticalCascadeSplits(
187
+ options.camera.near,
188
+ light.shadowDistance,
189
+ this.props.cascadeCount,
190
+ light.cascadeSplitLambda
191
+ ),
192
+ light.shadowDistance
193
+ );
194
+ directionalViews.push(
195
+ ...getDirectionalCascadeViews(
196
+ options.camera,
197
+ light,
198
+ cascadeSplits,
199
+ this.props.cascadeCount,
200
+ this.props.directionalMapSize
201
+ )
202
+ );
203
+ directionalViews.forEach((view, cascadeIndex) => {
204
+ this.renderView({
205
+ framebuffer: this.resources.directionalFramebuffers[cascadeIndex],
206
+ view,
207
+ type: 'directional',
208
+ lightIndex: 0,
209
+ cascadeIndex,
210
+ mapSize: this.props.directionalMapSize,
211
+ light,
212
+ drawShadowCasters: options.drawShadowCasters,
213
+ prepareShadowCasters: options.prepareShadowCasters
214
+ });
215
+ });
216
+ }
217
+
218
+ const spotViews = spotLights.map(light => getSpotShadowView(resolveSpotLight(light)));
219
+ spotViews.forEach((view, lightIndex) => {
220
+ this.renderView({
221
+ framebuffer: this.resources.spotFramebuffers[lightIndex],
222
+ view,
223
+ type: 'spot',
224
+ lightIndex,
225
+ mapSize: this.props.spotMapSize,
226
+ light: resolveSpotLight(spotLights[lightIndex]),
227
+ drawShadowCasters: options.drawShadowCasters,
228
+ prepareShadowCasters: options.prepareShadowCasters
229
+ });
230
+ });
231
+
232
+ const pointViews = pointLights.flatMap(light =>
233
+ getPointShadowViews(resolvePointLight(light), this.device.type === 'webgpu')
234
+ );
235
+ pointLights.forEach((inputLight, lightIndex) => {
236
+ const light = resolvePointLight(inputLight);
237
+ for (let faceIndex = 0; faceIndex < POINT_FACE_COUNT; faceIndex++) {
238
+ const viewIndex = lightIndex * POINT_FACE_COUNT + faceIndex;
239
+ this.renderView({
240
+ framebuffer: this.resources.pointFramebuffers[viewIndex],
241
+ view: pointViews[viewIndex],
242
+ type: 'point',
243
+ lightIndex,
244
+ pointFace: POINT_FACE_ORIENTATIONS[faceIndex].face,
245
+ mapSize: this.props.pointMapSize,
246
+ light,
247
+ drawShadowCasters: options.drawShadowCasters,
248
+ prepareShadowCasters: options.prepareShadowCasters
249
+ });
250
+ }
251
+ });
252
+
253
+ return {
254
+ quality: this.props.quality,
255
+ cascadeCount: this.props.cascadeCount,
256
+ cascadeSplits,
257
+ blockerSampleCount: this.props.blockerSampleCount,
258
+ filterSampleCount: this.props.filterSampleCount,
259
+ directionalLights: directionalLights.map(light =>
260
+ resolveDirectionalLight(light, options.camera)
261
+ ),
262
+ spotLights: spotLights.map(resolveSpotLight),
263
+ pointLights: pointLights.map(resolvePointLight),
264
+ directionalViewProjectionMatrices: padMatrices(
265
+ directionalViews.map(view => view.viewProjectionMatrix),
266
+ MAX_CASCADES
267
+ ),
268
+ spotViewProjectionMatrices: padMatrices(
269
+ spotViews.map(view => view.viewProjectionMatrix),
270
+ MAX_SPOT_LIGHTS
271
+ ),
272
+ pointViewProjectionMatrices: padMatrices(
273
+ pointViews.map(view => view.viewProjectionMatrix),
274
+ MAX_POINT_LIGHTS * POINT_FACE_COUNT
275
+ ),
276
+ directionalShadowTexture: this.resources.directionalTexture,
277
+ spotShadowTexture: this.resources.spotTexture,
278
+ pointShadowTexture: this.resources.pointTexture,
279
+ comparisonSampler: this.resources.comparisonSampler,
280
+ nonFilteringSampler: this.resources.nonFilteringSampler
281
+ };
282
+ }
283
+
284
+ /** Destroys all owned depth textures, views, framebuffers and samplers. */
285
+ destroy(): void {
286
+ if (this.destroyed) {
287
+ return;
288
+ }
289
+ this.destroyed = true;
290
+ destroyShadowMapResources(this.resources);
291
+ }
292
+
293
+ private renderView(options: {
294
+ framebuffer: Framebuffer;
295
+ view: ComputedShadowView;
296
+ type: ShadowRenderView['type'];
297
+ lightIndex: number;
298
+ cascadeIndex?: number;
299
+ pointFace?: PointShadowFace;
300
+ mapSize: number;
301
+ light: ShadowBiasProps;
302
+ drawShadowCasters: ShadowRenderOptions['drawShadowCasters'];
303
+ prepareShadowCasters?: ShadowRenderOptions['prepareShadowCasters'];
304
+ }): void {
305
+ const rasterParameters = Object.freeze({
306
+ depthWriteEnabled: true,
307
+ depthCompare: 'less-equal',
308
+ depthBias: options.light.depthBias,
309
+ depthBiasSlopeScale: options.light.depthBiasSlopeScale,
310
+ cullMode: 'back',
311
+ // Cube sampling uses top-left texel coordinates on WebGPU; its face projection flips Y.
312
+ frontFace: options.type === 'point' && this.device.type === 'webgpu' ? 'cw' : 'ccw'
313
+ } satisfies RenderPipelineParameters);
314
+ const context = {
315
+ framebuffer: options.framebuffer,
316
+ type: options.type,
317
+ lightIndex: options.lightIndex,
318
+ cascadeIndex: options.cascadeIndex,
319
+ pointFace: options.pointFace,
320
+ camera: options.view.camera,
321
+ viewProjectionMatrix: options.view.viewProjectionMatrix,
322
+ mapSize: options.mapSize,
323
+ rasterParameters
324
+ };
325
+ options.prepareShadowCasters?.(context);
326
+ const renderPass = this.device.beginRenderPass({
327
+ id: makeShadowResourceId(`${options.type}-shadow-pass`),
328
+ framebuffer: options.framebuffer,
329
+ clearDepth: 1
330
+ });
331
+ try {
332
+ options.drawShadowCasters({
333
+ renderPass,
334
+ framebuffer: options.framebuffer,
335
+ type: options.type,
336
+ lightIndex: options.lightIndex,
337
+ cascadeIndex: options.cascadeIndex,
338
+ pointFace: options.pointFace,
339
+ camera: options.view.camera,
340
+ viewProjectionMatrix: options.view.viewProjectionMatrix,
341
+ mapSize: options.mapSize,
342
+ rasterParameters
343
+ });
344
+ } finally {
345
+ renderPass.end();
346
+ }
347
+ }
348
+
349
+ private assertNotDestroyed(): void {
350
+ if (this.destroyed) {
351
+ throw new Error('ShadowMapRenderer has been destroyed.');
352
+ }
353
+ }
354
+ }
355
+
356
+ /** Returns logarithmic/uniform blended cascade far distances. */
357
+ export function getPracticalCascadeSplits(
358
+ near: number,
359
+ far: number,
360
+ cascadeCount: number,
361
+ lambda = 0.5
362
+ ): number[] {
363
+ if (!(near > 0 && far > near)) {
364
+ throw new Error('Cascade split range requires 0 < near < far.');
365
+ }
366
+ if (!Number.isInteger(cascadeCount) || cascadeCount < 1 || cascadeCount > MAX_CASCADES) {
367
+ throw new Error(`Cascade count must be an integer from 1 to ${MAX_CASCADES}.`);
368
+ }
369
+ const clampedLambda = clamp(lambda, 0, 1);
370
+ const splits: number[] = [];
371
+ for (let splitIndex = 1; splitIndex <= cascadeCount; splitIndex++) {
372
+ const fraction = splitIndex / cascadeCount;
373
+ const logarithmic = near * Math.pow(far / near, fraction);
374
+ const uniform = near + (far - near) * fraction;
375
+ splits.push(uniform * (1 - clampedLambda) + logarithmic * clampedLambda);
376
+ }
377
+ return splits;
378
+ }
379
+
380
+ /** Computes texel-snapped orthographic cascade cameras for a directional light. */
381
+ export function getDirectionalCascadeViews(
382
+ camera: ShadowCamera,
383
+ light: Required<DirectionalShadowLight>,
384
+ cascadeSplits: readonly number[],
385
+ cascadeCount: number,
386
+ mapSize: number
387
+ ): ComputedShadowView[] {
388
+ const inverseViewProjection = new Matrix4(camera.projectionMatrix)
389
+ .multiplyRight(camera.viewMatrix)
390
+ .invert();
391
+ const nearCorners = getNdcPlaneCorners(
392
+ inverseViewProjection,
393
+ camera.clipDepth === 'zero-to-one' ? 0 : -1
394
+ );
395
+ const farCorners = getNdcPlaneCorners(inverseViewProjection, 1);
396
+ const lightDirection = normalize3(light.direction);
397
+ const views: ComputedShadowView[] = [];
398
+ let cascadeNear = camera.near;
399
+
400
+ for (let cascadeIndex = 0; cascadeIndex < cascadeCount; cascadeIndex++) {
401
+ const cascadeFar = cascadeSplits[cascadeIndex];
402
+ const nearFraction = (cascadeNear - camera.near) / (camera.far - camera.near);
403
+ const farFraction = (cascadeFar - camera.near) / (camera.far - camera.near);
404
+ const corners: NumberArray3[] = [];
405
+ for (let cornerIndex = 0; cornerIndex < 4; cornerIndex++) {
406
+ corners.push(lerp3(nearCorners[cornerIndex], farCorners[cornerIndex], nearFraction));
407
+ corners.push(lerp3(nearCorners[cornerIndex], farCorners[cornerIndex], farFraction));
408
+ }
409
+ const center = average3(corners);
410
+ let radius = 0;
411
+ for (const corner of corners) {
412
+ radius = Math.max(radius, distance3(center, corner));
413
+ }
414
+ radius = Math.ceil(radius * 16) / 16;
415
+ const texelWorldSize = (radius * 2) / mapSize;
416
+ const lightForward = scale3(lightDirection, -1);
417
+ const referenceUp: NumberArray3 = Math.abs(lightForward[1]) > 0.99 ? [0, 0, 1] : [0, 1, 0];
418
+ const lightRight = normalize3(cross3(lightForward, referenceUp));
419
+ const lightUp = normalize3(cross3(lightRight, lightForward));
420
+ const centerRight = dot3(center, lightRight);
421
+ const centerUp = dot3(center, lightUp);
422
+ const snappedCenter = add3(
423
+ center,
424
+ add3(
425
+ scale3(lightRight, Math.round(centerRight / texelWorldSize) * texelWorldSize - centerRight),
426
+ scale3(lightUp, Math.round(centerUp / texelWorldSize) * texelWorldSize - centerUp)
427
+ )
428
+ );
429
+ const eye = add3(snappedCenter, scale3(lightDirection, radius + light.casterDistance));
430
+ const viewMatrix = new Matrix4().lookAt({eye, center: snappedCenter, up: lightUp});
431
+ const projectionMatrix = new Matrix4(OPENGL_TO_WEBGPU_MATRIX).multiplyRight(
432
+ new Matrix4().ortho({
433
+ left: -radius,
434
+ right: radius,
435
+ bottom: -radius,
436
+ top: radius,
437
+ near: 0.01,
438
+ far: radius * 2 + light.casterDistance
439
+ })
440
+ );
441
+ views.push({
442
+ camera: {
443
+ viewMatrix,
444
+ projectionMatrix,
445
+ near: 0.01,
446
+ far: radius * 2 + light.casterDistance,
447
+ clipDepth: 'zero-to-one'
448
+ },
449
+ viewProjectionMatrix: new Matrix4(projectionMatrix).multiplyRight(viewMatrix)
450
+ });
451
+ cascadeNear = cascadeFar;
452
+ }
453
+ return views;
454
+ }
455
+
456
+ /** Computes a perspective camera for one spot shadow map. */
457
+ export function getSpotShadowView(light: Required<SpotShadowLight>): ComputedShadowView {
458
+ const direction = normalize3(light.direction);
459
+ const up: NumberArray3 = Math.abs(direction[1]) > 0.99 ? [0, 0, 1] : [0, 1, 0];
460
+ const viewMatrix = new Matrix4().lookAt({
461
+ eye: light.position,
462
+ center: add3(light.position, direction),
463
+ up
464
+ });
465
+ const projectionMatrix = new Matrix4(OPENGL_TO_WEBGPU_MATRIX).multiplyRight(
466
+ new Matrix4().perspective({
467
+ fovy: light.outerConeAngle * 2,
468
+ aspect: 1,
469
+ near: light.nearPlane,
470
+ far: light.range
471
+ })
472
+ );
473
+ return {
474
+ camera: {
475
+ viewMatrix,
476
+ projectionMatrix,
477
+ near: light.nearPlane,
478
+ far: light.range,
479
+ clipDepth: 'zero-to-one'
480
+ },
481
+ viewProjectionMatrix: new Matrix4(projectionMatrix).multiplyRight(viewMatrix)
482
+ };
483
+ }
484
+
485
+ /** Computes the six canonical cameras used by one cube-array point shadow. */
486
+ export function getPointShadowViews(
487
+ light: Required<PointShadowLight>,
488
+ invertY = false
489
+ ): ComputedShadowView[] {
490
+ const projectionMatrix = new Matrix4(OPENGL_TO_WEBGPU_MATRIX).multiplyRight(
491
+ new Matrix4().perspective({
492
+ fovy: radians(90),
493
+ aspect: 1,
494
+ near: light.nearPlane,
495
+ far: light.range
496
+ })
497
+ );
498
+ // WebGPU cube lookups use the same face axes as GL but a top-left texture origin.
499
+ if (invertY) projectionMatrix.multiplyLeft(new Matrix4().scale([1, -1, 1]));
500
+ return POINT_FACE_ORIENTATIONS.map((orientation): ComputedShadowView => {
501
+ const viewMatrix = new Matrix4().lookAt({
502
+ eye: light.position,
503
+ center: add3(light.position, orientation.direction),
504
+ up: orientation.up
505
+ });
506
+ return {
507
+ camera: {
508
+ viewMatrix,
509
+ projectionMatrix,
510
+ near: light.nearPlane,
511
+ far: light.range,
512
+ clipDepth: 'zero-to-one'
513
+ },
514
+ viewProjectionMatrix: new Matrix4(projectionMatrix).multiplyRight(viewMatrix)
515
+ };
516
+ });
517
+ }
518
+
519
+ function resolveShadowMapRendererProps(
520
+ device: Device,
521
+ props: ShadowMapRendererProps
522
+ ): ResolvedShadowMapRendererProps {
523
+ const quality = props.quality || 'balanced';
524
+ const qualitySettings = SHADOW_QUALITY_SETTINGS[quality];
525
+ if (!qualitySettings) {
526
+ throw new Error(`Unknown shadow quality: ${String(quality)}.`);
527
+ }
528
+ const resolved = {
529
+ quality,
530
+ directionalLightCapacity: props.directionalLightCapacity ?? 1,
531
+ spotLightCapacity: props.spotLightCapacity ?? 1,
532
+ pointLightCapacity: props.pointLightCapacity ?? 1,
533
+ directionalMapSize: props.directionalMapSize ?? qualitySettings.directionalMapSize,
534
+ spotMapSize: props.spotMapSize ?? qualitySettings.spotMapSize,
535
+ pointMapSize: props.pointMapSize ?? qualitySettings.pointMapSize,
536
+ cascadeCount: qualitySettings.cascadeCount,
537
+ blockerSampleCount: qualitySettings.blockerSampleCount,
538
+ filterSampleCount: qualitySettings.filterSampleCount
539
+ };
540
+ validateCapacity(
541
+ 'directionalLightCapacity',
542
+ resolved.directionalLightCapacity,
543
+ MAX_DIRECTIONAL_LIGHTS
544
+ );
545
+ validateCapacity('spotLightCapacity', resolved.spotLightCapacity, MAX_SPOT_LIGHTS);
546
+ validateCapacity('pointLightCapacity', resolved.pointLightCapacity, MAX_POINT_LIGHTS);
547
+ validateMapSize(device, 'directionalMapSize', resolved.directionalMapSize);
548
+ validateMapSize(device, 'spotMapSize', resolved.spotMapSize);
549
+ validateMapSize(device, 'pointMapSize', resolved.pointMapSize);
550
+ const pointLayers = Math.max(POINT_FACE_COUNT, resolved.pointLightCapacity * POINT_FACE_COUNT);
551
+ if (pointLayers > device.limits.maxTextureArrayLayers) {
552
+ throw new Error(
553
+ `pointLightCapacity requires ${pointLayers} array layers, exceeding the device limit ${device.limits.maxTextureArrayLayers}.`
554
+ );
555
+ }
556
+ return resolved;
557
+ }
558
+
559
+ function createShadowMapResources(
560
+ device: Device,
561
+ props: ResolvedShadowMapRendererProps
562
+ ): ShadowMapResources {
563
+ const directionalLayers = Math.max(1, props.directionalLightCapacity * props.cascadeCount);
564
+ const spotLayers = Math.max(1, props.spotLightCapacity);
565
+ const pointLayers = Math.max(POINT_FACE_COUNT, props.pointLightCapacity * POINT_FACE_COUNT);
566
+ const comparisonSampler = device.createSampler({
567
+ id: makeShadowResourceId('shadow-comparison-sampler'),
568
+ type: 'comparison-sampler',
569
+ compare: 'less-equal',
570
+ minFilter: 'linear',
571
+ magFilter: 'linear',
572
+ addressModeU: 'clamp-to-edge',
573
+ addressModeV: 'clamp-to-edge',
574
+ addressModeW: 'clamp-to-edge'
575
+ });
576
+ const nonFilteringSampler = device.createSampler({
577
+ id: makeShadowResourceId('shadow-depth-sampler'),
578
+ minFilter: 'nearest',
579
+ magFilter: 'nearest',
580
+ addressModeU: 'clamp-to-edge',
581
+ addressModeV: 'clamp-to-edge',
582
+ addressModeW: 'clamp-to-edge'
583
+ });
584
+ const directionalTexture = createDepthArrayTexture(
585
+ device,
586
+ 'directional-shadow-map',
587
+ '2d-array',
588
+ props.directionalMapSize,
589
+ directionalLayers,
590
+ nonFilteringSampler
591
+ );
592
+ const spotTexture = createDepthArrayTexture(
593
+ device,
594
+ 'spot-shadow-map',
595
+ '2d-array',
596
+ props.spotMapSize,
597
+ spotLayers,
598
+ nonFilteringSampler
599
+ );
600
+ const pointTexture = createDepthArrayTexture(
601
+ device,
602
+ 'point-shadow-map',
603
+ device.type === 'webgpu' ? 'cube-array' : '2d-array',
604
+ props.pointMapSize,
605
+ pointLayers,
606
+ nonFilteringSampler
607
+ );
608
+ const attachmentViews: TextureView[] = [];
609
+ const directionalFramebuffers = createLayerFramebuffers(
610
+ device,
611
+ directionalTexture,
612
+ props.directionalMapSize,
613
+ directionalLayers,
614
+ attachmentViews
615
+ );
616
+ const spotFramebuffers = createLayerFramebuffers(
617
+ device,
618
+ spotTexture,
619
+ props.spotMapSize,
620
+ spotLayers,
621
+ attachmentViews
622
+ );
623
+ const pointFramebuffers = createLayerFramebuffers(
624
+ device,
625
+ pointTexture,
626
+ props.pointMapSize,
627
+ pointLayers,
628
+ attachmentViews
629
+ );
630
+ return {
631
+ directionalTexture,
632
+ spotTexture,
633
+ pointTexture,
634
+ comparisonSampler,
635
+ nonFilteringSampler,
636
+ directionalFramebuffers,
637
+ spotFramebuffers,
638
+ pointFramebuffers,
639
+ attachmentViews
640
+ };
641
+ }
642
+
643
+ function createDepthArrayTexture(
644
+ device: Device,
645
+ id: string,
646
+ dimension: '2d-array' | 'cube-array',
647
+ size: number,
648
+ depth: number,
649
+ sampler: Sampler
650
+ ): Texture {
651
+ return device.createTexture({
652
+ id: makeShadowResourceId(id),
653
+ dimension,
654
+ format: 'depth32float',
655
+ width: size,
656
+ height: size,
657
+ depth,
658
+ sampler,
659
+ usage: TextureResource.SAMPLE | TextureResource.RENDER
660
+ });
661
+ }
662
+
663
+ function createLayerFramebuffers(
664
+ device: Device,
665
+ texture: Texture,
666
+ size: number,
667
+ layerCount: number,
668
+ views: TextureView[]
669
+ ): Framebuffer[] {
670
+ return Array.from({length: layerCount}, (_, layerIndex) => {
671
+ const view = texture.createView({
672
+ id: makeShadowResourceId('shadow-layer-view'),
673
+ format: texture.format,
674
+ dimension: '2d',
675
+ baseMipLevel: 0,
676
+ mipLevelCount: 1,
677
+ baseArrayLayer: layerIndex,
678
+ arrayLayerCount: 1
679
+ });
680
+ views.push(view);
681
+ return device.createFramebuffer({
682
+ id: makeShadowResourceId('shadow-layer-framebuffer'),
683
+ width: size,
684
+ height: size,
685
+ colorAttachments: [],
686
+ depthStencilAttachment: view
687
+ });
688
+ });
689
+ }
690
+
691
+ function destroyShadowMapResources(resources: ShadowMapResources): void {
692
+ for (const framebuffer of [
693
+ ...resources.directionalFramebuffers,
694
+ ...resources.spotFramebuffers,
695
+ ...resources.pointFramebuffers
696
+ ]) {
697
+ framebuffer.destroy();
698
+ }
699
+ for (const view of resources.attachmentViews) {
700
+ view.destroy();
701
+ }
702
+ resources.directionalTexture.destroy();
703
+ resources.spotTexture.destroy();
704
+ resources.pointTexture.destroy();
705
+ resources.comparisonSampler.destroy();
706
+ resources.nonFilteringSampler.destroy();
707
+ }
708
+
709
+ function resourcePropsEqual(
710
+ first: ResolvedShadowMapRendererProps,
711
+ second: ResolvedShadowMapRendererProps
712
+ ): boolean {
713
+ return (
714
+ first.cascadeCount === second.cascadeCount &&
715
+ first.directionalLightCapacity === second.directionalLightCapacity &&
716
+ first.spotLightCapacity === second.spotLightCapacity &&
717
+ first.pointLightCapacity === second.pointLightCapacity &&
718
+ first.directionalMapSize === second.directionalMapSize &&
719
+ first.spotMapSize === second.spotMapSize &&
720
+ first.pointMapSize === second.pointMapSize
721
+ );
722
+ }
723
+
724
+ function resolveDirectionalLight(
725
+ light: DirectionalShadowLight,
726
+ camera: ShadowCamera
727
+ ): Required<DirectionalShadowLight> {
728
+ const shadowDistance = clamp(light.shadowDistance ?? camera.far, camera.near, camera.far);
729
+ return {
730
+ direction: normalize3(light.direction),
731
+ shadowDistance,
732
+ casterDistance: light.casterDistance ?? shadowDistance,
733
+ sourceAngularRadius: light.sourceAngularRadius ?? 0.00465,
734
+ cascadeSplitLambda: light.cascadeSplitLambda ?? 0.5,
735
+ cascadeBlendFraction: light.cascadeBlendFraction ?? 0.1,
736
+ farFadeFraction: light.farFadeFraction ?? 0.1,
737
+ normalBias: light.normalBias ?? 0.04,
738
+ depthBias: light.depthBias ?? 2,
739
+ depthBiasSlopeScale: light.depthBiasSlopeScale ?? 2,
740
+ strength: clamp(light.strength ?? 1, 0, 1)
741
+ };
742
+ }
743
+
744
+ function resolveSpotLight(light: SpotShadowLight): Required<SpotShadowLight> {
745
+ validateRange('Spot shadow', light.range);
746
+ if (!(light.outerConeAngle > 0 && light.outerConeAngle < Math.PI / 2)) {
747
+ throw new Error('Spot shadow outerConeAngle must be between 0 and PI / 2 radians.');
748
+ }
749
+ return {
750
+ position: [...light.position] as NumberArray3,
751
+ direction: normalize3(light.direction),
752
+ range: light.range,
753
+ outerConeAngle: light.outerConeAngle,
754
+ nearPlane: resolveNearPlane(light.nearPlane, light.range),
755
+ sourceRadius: light.sourceRadius ?? 0.2,
756
+ normalBias: light.normalBias ?? 0.025,
757
+ depthBias: light.depthBias ?? 2,
758
+ depthBiasSlopeScale: light.depthBiasSlopeScale ?? 2,
759
+ strength: clamp(light.strength ?? 1, 0, 1)
760
+ };
761
+ }
762
+
763
+ function resolvePointLight(light: PointShadowLight): Required<PointShadowLight> {
764
+ validateRange('Point shadow', light.range);
765
+ return {
766
+ position: [...light.position] as NumberArray3,
767
+ range: light.range,
768
+ nearPlane: resolveNearPlane(light.nearPlane, light.range),
769
+ sourceRadius: light.sourceRadius ?? 0.2,
770
+ normalBias: light.normalBias ?? 0.025,
771
+ depthBias: light.depthBias ?? 2,
772
+ depthBiasSlopeScale: light.depthBiasSlopeScale ?? 2,
773
+ strength: clamp(light.strength ?? 1, 0, 1)
774
+ };
775
+ }
776
+
777
+ function resolveNearPlane(nearPlane: number | undefined, range: number): number {
778
+ const resolvedNearPlane = nearPlane ?? Math.max(DEFAULT_NEAR_PLANE, range / 1000);
779
+ if (!(resolvedNearPlane > 0 && resolvedNearPlane < range)) {
780
+ throw new Error('Shadow nearPlane must be greater than zero and less than range.');
781
+ }
782
+ return resolvedNearPlane;
783
+ }
784
+
785
+ function validateShadowCamera(camera: ShadowCamera): void {
786
+ if (!(camera.near > 0 && camera.far > camera.near)) {
787
+ throw new Error('ShadowCamera requires 0 < near < far.');
788
+ }
789
+ }
790
+
791
+ function validateCapacity(name: string, value: number, maximum: number): void {
792
+ if (!Number.isInteger(value) || value < 0 || value > maximum) {
793
+ throw new Error(`${name} must be an integer from 0 to ${maximum}.`);
794
+ }
795
+ }
796
+
797
+ function validateMapSize(device: Device, name: string, value: number): void {
798
+ if (!Number.isInteger(value) || value < 1 || value > device.limits.maxTextureDimension2D) {
799
+ throw new Error(
800
+ `${name} must be a positive integer no greater than ${device.limits.maxTextureDimension2D}.`
801
+ );
802
+ }
803
+ }
804
+
805
+ function validateLightCount(type: string, count: number, capacity: number): void {
806
+ if (count > capacity) {
807
+ throw new Error(`${type} shadow light count ${count} exceeds configured capacity ${capacity}.`);
808
+ }
809
+ }
810
+
811
+ function validateRange(label: string, range: number): void {
812
+ if (!(range > 0 && Number.isFinite(range))) {
813
+ throw new Error(`${label} range must be a finite positive number.`);
814
+ }
815
+ }
816
+
817
+ function padCascadeSplits(splits: readonly number[], fallback: number): number[] {
818
+ const result = splits.slice(0, MAX_CASCADES);
819
+ while (result.length < MAX_CASCADES) {
820
+ result.push(result[result.length - 1] ?? fallback);
821
+ }
822
+ return result;
823
+ }
824
+
825
+ function padMatrices(
826
+ matrices: readonly Readonly<Matrix4 | NumberArray16>[],
827
+ count: number
828
+ ): Readonly<Matrix4 | NumberArray16>[] {
829
+ const result = matrices.slice(0, count);
830
+ while (result.length < count) {
831
+ result.push(IDENTITY_MATRIX);
832
+ }
833
+ return result;
834
+ }
835
+
836
+ function getNdcPlaneCorners(matrix: Matrix4, z: number): NumberArray3[] {
837
+ return [
838
+ transformHomogeneous(matrix, [-1, -1, z]),
839
+ transformHomogeneous(matrix, [1, -1, z]),
840
+ transformHomogeneous(matrix, [1, 1, z]),
841
+ transformHomogeneous(matrix, [-1, 1, z])
842
+ ];
843
+ }
844
+
845
+ function transformHomogeneous(matrix: Matrix4, point: NumberArray3): NumberArray3 {
846
+ const x = point[0];
847
+ const y = point[1];
848
+ const z = point[2];
849
+ const w = matrix[3] * x + matrix[7] * y + matrix[11] * z + matrix[15];
850
+ return [
851
+ (matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12]) / w,
852
+ (matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13]) / w,
853
+ (matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14]) / w
854
+ ];
855
+ }
856
+
857
+ function normalize3(vector: Readonly<NumberArray3>): NumberArray3 {
858
+ const length = Math.hypot(vector[0], vector[1], vector[2]);
859
+ if (!(length > 0)) {
860
+ throw new Error('Shadow light direction must be non-zero.');
861
+ }
862
+ return [vector[0] / length, vector[1] / length, vector[2] / length];
863
+ }
864
+
865
+ function add3(first: Readonly<NumberArray3>, second: Readonly<NumberArray3>): NumberArray3 {
866
+ return [first[0] + second[0], first[1] + second[1], first[2] + second[2]];
867
+ }
868
+
869
+ function scale3(vector: Readonly<NumberArray3>, scale: number): NumberArray3 {
870
+ return [vector[0] * scale, vector[1] * scale, vector[2] * scale];
871
+ }
872
+
873
+ function dot3(first: Readonly<NumberArray3>, second: Readonly<NumberArray3>): number {
874
+ return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];
875
+ }
876
+
877
+ function cross3(first: Readonly<NumberArray3>, second: Readonly<NumberArray3>): NumberArray3 {
878
+ return [
879
+ first[1] * second[2] - first[2] * second[1],
880
+ first[2] * second[0] - first[0] * second[2],
881
+ first[0] * second[1] - first[1] * second[0]
882
+ ];
883
+ }
884
+
885
+ function lerp3(
886
+ first: Readonly<NumberArray3>,
887
+ second: Readonly<NumberArray3>,
888
+ t: number
889
+ ): NumberArray3 {
890
+ return [
891
+ first[0] + (second[0] - first[0]) * t,
892
+ first[1] + (second[1] - first[1]) * t,
893
+ first[2] + (second[2] - first[2]) * t
894
+ ];
895
+ }
896
+
897
+ function average3(vectors: readonly Readonly<NumberArray3>[]): NumberArray3 {
898
+ const sum: NumberArray3 = [0, 0, 0];
899
+ for (const vector of vectors) {
900
+ sum[0] += vector[0];
901
+ sum[1] += vector[1];
902
+ sum[2] += vector[2];
903
+ }
904
+ return scale3(sum, 1 / vectors.length);
905
+ }
906
+
907
+ function distance3(first: Readonly<NumberArray3>, second: Readonly<NumberArray3>): number {
908
+ return Math.hypot(first[0] - second[0], first[1] - second[1], first[2] - second[2]);
909
+ }
910
+
911
+ function clamp(value: number, minimum: number, maximum: number): number {
912
+ return Math.max(minimum, Math.min(maximum, value));
913
+ }
914
+
915
+ function makeShadowResourceId(prefix: string): string {
916
+ nextShadowResourceId += 1;
917
+ return `${prefix}-${nextShadowResourceId}`;
918
+ }