@needle-tools/three-mesh-effects 0.0.0-stage → 0.1.0-alpha

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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +88 -3
  3. package/build/deformation-runtime.js +2143 -0
  4. package/build/deformation-runtime.js.map +7 -0
  5. package/build/impostor-runtime-needle-engine.js +42 -0
  6. package/build/impostor-runtime-needle-engine.js.map +7 -0
  7. package/build/impostor-runtime.js +1333 -0
  8. package/build/impostor-runtime.js.map +7 -0
  9. package/build/internal/deformation/cloth-surface.js +288 -0
  10. package/build/internal/deformation/cloth-surface.js.map +7 -0
  11. package/build/internal/deformation/fur-surface.js +130 -0
  12. package/build/internal/deformation/fur-surface.js.map +7 -0
  13. package/build/internal/deformation/ik-constraints.js +44 -0
  14. package/build/internal/deformation/ik-constraints.js.map +7 -0
  15. package/build/internal/deformation/joints-json.js +197 -0
  16. package/build/internal/deformation/joints-json.js.map +7 -0
  17. package/build/internal/deformation/limits.js +16 -0
  18. package/build/internal/deformation/limits.js.map +7 -0
  19. package/build/internal/deformation/motion-settings.js +12 -0
  20. package/build/internal/deformation/motion-settings.js.map +7 -0
  21. package/build/internal/deformation/pin-cloth.js +196 -0
  22. package/build/internal/deformation/pin-cloth.js.map +7 -0
  23. package/build/internal/deformation/pin-ik.js +650 -0
  24. package/build/internal/deformation/pin-ik.js.map +7 -0
  25. package/build/internal/deformation/pin-types.js +12 -0
  26. package/build/internal/deformation/pin-types.js.map +7 -0
  27. package/build/internal/deformation/pin-wiggle.js +249 -0
  28. package/build/internal/deformation/pin-wiggle.js.map +7 -0
  29. package/build/internal/deformation/pose-slots.js +84 -0
  30. package/build/internal/deformation/pose-slots.js.map +7 -0
  31. package/build/internal/deformation/pose-timeline.js +210 -0
  32. package/build/internal/deformation/pose-timeline.js.map +7 -0
  33. package/build/internal/deformation/rig-drivers.js +48 -0
  34. package/build/internal/deformation/rig-drivers.js.map +7 -0
  35. package/build/internal/deformation/rig-extension.js +334 -0
  36. package/build/internal/deformation/rig-extension.js.map +7 -0
  37. package/build/internal/deformation/rig-runtime.js +2141 -0
  38. package/build/internal/deformation/rig-runtime.js.map +7 -0
  39. package/build/internal/deformation/wind.js +34 -0
  40. package/build/internal/deformation/wind.js.map +7 -0
  41. package/build/internal/impostor/impostor-metadata.js +77 -0
  42. package/build/internal/impostor/impostor-metadata.js.map +7 -0
  43. package/build/internal/impostor/impostor-node-material.js +1331 -0
  44. package/build/internal/impostor/impostor-node-material.js.map +7 -0
  45. package/build/internal/impostor/impostor-runtime-support.js +162 -0
  46. package/build/internal/impostor/impostor-runtime-support.js.map +7 -0
  47. package/build/internal/impostor/octahedral.js +232 -0
  48. package/build/internal/impostor/octahedral.js.map +7 -0
  49. package/build/internal/pixel-impostor/pixel-impostor-display.js +728 -0
  50. package/build/internal/pixel-impostor/pixel-impostor-display.js.map +7 -0
  51. package/build/internal/pixel-impostor/pixel-impostor-metadata.js +71 -0
  52. package/build/internal/pixel-impostor/pixel-impostor-metadata.js.map +7 -0
  53. package/build/internal/pixel-impostor/pixel-impostor-runtime.js +150 -0
  54. package/build/internal/pixel-impostor/pixel-impostor-runtime.js.map +7 -0
  55. package/build/internal/public/deformation-runtime.js +2143 -0
  56. package/build/internal/public/deformation-runtime.js.map +7 -0
  57. package/build/internal/public/impostor-runtime-needle-engine.js +42 -0
  58. package/build/internal/public/impostor-runtime-needle-engine.js.map +7 -0
  59. package/build/internal/public/impostor-runtime.js +1333 -0
  60. package/build/internal/public/impostor-runtime.js.map +7 -0
  61. package/build/internal/public/pixel-impostor-runtime.js +876 -0
  62. package/build/internal/public/pixel-impostor-runtime.js.map +7 -0
  63. package/build/internal/public/wrap-effects.js +5640 -0
  64. package/build/internal/public/wrap-effects.js.map +7 -0
  65. package/build/internal/rendering/skin-projection.js +4630 -0
  66. package/build/internal/rendering/skin-projection.js.map +7 -0
  67. package/build/internal/rendering/surface-query.js +4519 -0
  68. package/build/internal/rendering/surface-query.js.map +7 -0
  69. package/build/internal/rendering/wireframe.js +112 -0
  70. package/build/internal/rendering/wireframe.js.map +7 -0
  71. package/build/internal/rendering/wrap-preview-settings.js +126 -0
  72. package/build/internal/rendering/wrap-preview-settings.js.map +7 -0
  73. package/build/internal/rendering/wrap-preview.js +5610 -0
  74. package/build/internal/rendering/wrap-preview.js.map +7 -0
  75. package/build/internal/rendering/wrap-skin.js +4746 -0
  76. package/build/internal/rendering/wrap-skin.js.map +7 -0
  77. package/build/pixel-impostor-runtime.js +876 -0
  78. package/build/pixel-impostor-runtime.js.map +7 -0
  79. package/build/types/deformation/cloth-surface.d.ts +39 -0
  80. package/build/types/deformation/cloth-surface.js +1 -0
  81. package/build/types/deformation/fur-surface.d.ts +27 -0
  82. package/build/types/deformation/fur-surface.js +1 -0
  83. package/build/types/deformation/ik-constraints.d.ts +18 -0
  84. package/build/types/deformation/ik-constraints.js +1 -0
  85. package/build/types/deformation/joints-json.d.ts +17 -0
  86. package/build/types/deformation/joints-json.js +1 -0
  87. package/build/types/deformation/limits.d.ts +23 -0
  88. package/build/types/deformation/limits.js +1 -0
  89. package/build/types/deformation/motion-settings.d.ts +9 -0
  90. package/build/types/deformation/motion-settings.js +1 -0
  91. package/build/types/deformation/pin-cloth.d.ts +28 -0
  92. package/build/types/deformation/pin-cloth.js +1 -0
  93. package/build/types/deformation/pin-ik.d.ts +37 -0
  94. package/build/types/deformation/pin-ik.js +1 -0
  95. package/build/types/deformation/pin-types.d.ts +53 -0
  96. package/build/types/deformation/pin-types.js +1 -0
  97. package/build/types/deformation/pin-wiggle.d.ts +16 -0
  98. package/build/types/deformation/pin-wiggle.js +1 -0
  99. package/build/types/deformation/pose-slots.d.ts +41 -0
  100. package/build/types/deformation/pose-slots.js +1 -0
  101. package/build/types/deformation/pose-timeline.d.ts +65 -0
  102. package/build/types/deformation/pose-timeline.js +1 -0
  103. package/build/types/deformation/rig-drivers.d.ts +19 -0
  104. package/build/types/deformation/rig-drivers.js +1 -0
  105. package/build/types/deformation/rig-extension.d.ts +33 -0
  106. package/build/types/deformation/rig-extension.js +1 -0
  107. package/build/types/deformation/rig-runtime.d.ts +95 -0
  108. package/build/types/deformation/rig-runtime.js +1 -0
  109. package/build/types/deformation/wind.d.ts +16 -0
  110. package/build/types/deformation/wind.js +1 -0
  111. package/build/types/impostor/impostor-metadata.d.ts +61 -0
  112. package/build/types/impostor/impostor-metadata.js +1 -0
  113. package/build/types/impostor/impostor-node-material.d.ts +140 -0
  114. package/build/types/impostor/impostor-node-material.js +1 -0
  115. package/build/types/impostor/impostor-runtime-support.d.ts +52 -0
  116. package/build/types/impostor/impostor-runtime-support.js +1 -0
  117. package/build/types/impostor/octahedral.d.ts +84 -0
  118. package/build/types/impostor/octahedral.js +1 -0
  119. package/build/types/pixel-impostor/pixel-impostor-display.d.ts +48 -0
  120. package/build/types/pixel-impostor/pixel-impostor-display.js +1 -0
  121. package/build/types/pixel-impostor/pixel-impostor-metadata.d.ts +34 -0
  122. package/build/types/pixel-impostor/pixel-impostor-metadata.js +1 -0
  123. package/build/types/pixel-impostor/pixel-impostor-runtime.d.ts +18 -0
  124. package/build/types/pixel-impostor/pixel-impostor-runtime.js +1 -0
  125. package/build/types/public/deformation-runtime.d.ts +3 -0
  126. package/build/types/public/deformation-runtime.js +1 -0
  127. package/build/types/public/impostor-runtime-needle-engine.d.ts +31 -0
  128. package/build/types/public/impostor-runtime-needle-engine.js +1 -0
  129. package/build/types/public/impostor-runtime.d.ts +6 -0
  130. package/build/types/public/impostor-runtime.js +1 -0
  131. package/build/types/public/pixel-impostor-runtime.d.ts +3 -0
  132. package/build/types/public/pixel-impostor-runtime.js +1 -0
  133. package/build/types/public/wrap-effects.d.ts +4 -0
  134. package/build/types/public/wrap-effects.js +1 -0
  135. package/build/types/rendering/skin-projection.d.ts +44 -0
  136. package/build/types/rendering/skin-projection.js +1 -0
  137. package/build/types/rendering/surface-query.d.ts +66 -0
  138. package/build/types/rendering/surface-query.js +1 -0
  139. package/build/types/rendering/wireframe.d.ts +25 -0
  140. package/build/types/rendering/wireframe.js +1 -0
  141. package/build/types/rendering/wrap-preview-settings.d.ts +22 -0
  142. package/build/types/rendering/wrap-preview-settings.js +1 -0
  143. package/build/types/rendering/wrap-preview.d.ts +39 -0
  144. package/build/types/rendering/wrap-preview.js +1 -0
  145. package/build/types/rendering/wrap-skin.d.ts +14 -0
  146. package/build/types/rendering/wrap-skin.js +1 -0
  147. package/build/wrap-effects.js +5640 -0
  148. package/build/wrap-effects.js.map +7 -0
  149. package/package.json +94 -6
  150. package/src/deformation/cloth-surface.ts +223 -0
  151. package/src/deformation/fur-surface.ts +129 -0
  152. package/src/deformation/ik-constraints.ts +37 -0
  153. package/src/deformation/joints-json.ts +94 -0
  154. package/src/deformation/limits.ts +25 -0
  155. package/src/deformation/motion-settings.ts +9 -0
  156. package/src/deformation/pin-cloth.ts +149 -0
  157. package/src/deformation/pin-ik.ts +582 -0
  158. package/src/deformation/pin-types.ts +22 -0
  159. package/src/deformation/pin-wiggle.ts +119 -0
  160. package/src/deformation/pose-slots.ts +106 -0
  161. package/src/deformation/pose-timeline.ts +242 -0
  162. package/src/deformation/rig-drivers.ts +32 -0
  163. package/src/deformation/rig-extension.ts +87 -0
  164. package/src/deformation/rig-runtime.ts +416 -0
  165. package/src/deformation/wind.ts +36 -0
  166. package/src/impostor/impostor-metadata.js +137 -0
  167. package/src/impostor/impostor-node-material.js +1581 -0
  168. package/src/impostor/impostor-runtime-support.js +139 -0
  169. package/src/impostor/octahedral.js +280 -0
  170. package/src/pixel-impostor/pixel-impostor-display.js +794 -0
  171. package/src/pixel-impostor/pixel-impostor-metadata.js +74 -0
  172. package/src/pixel-impostor/pixel-impostor-runtime.js +78 -0
  173. package/src/public/deformation-runtime.ts +3 -0
  174. package/src/public/impostor-runtime-needle-engine.js +56 -0
  175. package/src/public/impostor-runtime.js +21 -0
  176. package/src/public/pixel-impostor-runtime.js +5 -0
  177. package/src/public/wrap-effects.js +21 -0
  178. package/src/rendering/skin-projection.js +113 -0
  179. package/src/rendering/surface-query.js +88 -0
  180. package/src/rendering/wireframe.js +115 -0
  181. package/src/rendering/wrap-preview-settings.js +123 -0
  182. package/src/rendering/wrap-preview.js +645 -0
  183. package/src/rendering/wrap-skin.js +109 -0
@@ -0,0 +1,1581 @@
1
+ // TSL's current declarations erase custom struct member types to `Node`, which
2
+ // makes a checked JS implementation impossible without casting every operator.
3
+ // Keep this backend module runtime-tested until Three's StructNode types retain
4
+ // their declared member layout.
5
+ // @ts-nocheck
6
+
7
+ import {
8
+ ClampToEdgeWrapping,
9
+ DoubleSide,
10
+ GLSL3,
11
+ LinearFilter,
12
+ LinearMipmapLinearFilter,
13
+ MeshStandardNodeMaterial,
14
+ NoColorSpace,
15
+ SRGBColorSpace,
16
+ ShaderMaterial,
17
+ Vector3,
18
+ Vector4,
19
+ } from 'three/webgpu';
20
+ import * as TSL from 'three/tsl';
21
+ import {
22
+ Fn,
23
+ If,
24
+ Loop,
25
+ abs,
26
+ any,
27
+ bool,
28
+ cameraFar,
29
+ cameraNear,
30
+ cameraPosition,
31
+ cameraWorldMatrix,
32
+ cross,
33
+ dot,
34
+ exp,
35
+ float,
36
+ floor,
37
+ fract,
38
+ fwidth,
39
+ int,
40
+ ivec2,
41
+ max,
42
+ min,
43
+ mix,
44
+ modelViewMatrix,
45
+ modelWorldMatrix,
46
+ modelWorldMatrixInverse,
47
+ positionGeometry,
48
+ smoothstep,
49
+ texture,
50
+ textureLoad,
51
+ transformNormalToView,
52
+ uniformArray,
53
+ vec2,
54
+ vec3,
55
+ vec4,
56
+ viewZToOrthographicDepth,
57
+ viewZToPerspectiveDepth,
58
+ } from 'three/tsl';
59
+ import { NEEDLE_MESH_IMPOSTOR } from './impostor-metadata.js';
60
+ import { PERSPECTIVE_RAY_PLANE_SIGN } from './octahedral.js';
61
+ import {
62
+ REPROJECTION_CONFIDENCE_INNER_TEXELS,
63
+ REPROJECTION_CONFIDENCE_OUTER_TEXELS,
64
+ createImpostorViewBoundsTexture,
65
+ impostorContourUnionSharpness,
66
+ parseImpostorDescriptor,
67
+ } from './impostor-runtime-support.js';
68
+
69
+ const NAMED_STRUCT_FACTORY = Reflect.get(TSL, 'struct');
70
+
71
+ /** @import { ImpostorDescriptor } from './impostor-metadata.js' */
72
+
73
+ /**
74
+ * @typedef {object} ImpostorRenderer
75
+ * @property {boolean=} isWebGPURenderer
76
+ * @property {boolean=} isWebGLRenderer
77
+ * @property {(object & {supportsNodeMaterials?: boolean})=} capabilities
78
+ */
79
+
80
+ /**
81
+ * @typedef {object} ImpostorRuntimeFeatures
82
+ * @property {boolean} interpolation
83
+ * @property {boolean} reprojection
84
+ * @property {boolean} depthWeights
85
+ * @property {boolean} perspectiveCorrection
86
+ * @property {boolean} cellCorrection
87
+ * @property {boolean} boundedReprojection
88
+ * @property {number} raySamples
89
+ * @property {number} depthSamples
90
+ * @property {number} blendZone
91
+ */
92
+
93
+ /**
94
+ * @typedef {object} ResolvedImpostorRuntimeFeatures
95
+ * @property {ImpostorRuntimeFeatures} requested
96
+ * @property {Pick<ImpostorRuntimeFeatures, 'interpolation' | 'reprojection' | 'depthWeights' | 'perspectiveCorrection' | 'cellCorrection' | 'boundedReprojection'>} effective
97
+ * @property {Pick<ImpostorRuntimeFeatures, 'interpolation' | 'reprojection' | 'depthWeights' | 'perspectiveCorrection' | 'cellCorrection' | 'boundedReprojection' | 'raySamples' | 'depthSamples'> & {frameSamples: number, blendZone: number}} profile
98
+ */
99
+
100
+ const RUNTIME_FEATURE_NAMES = /** @type {const} */ ([
101
+ 'interpolation',
102
+ 'reprojection',
103
+ 'depthWeights',
104
+ 'perspectiveCorrection',
105
+ 'cellCorrection',
106
+ 'boundedReprojection',
107
+ ]);
108
+
109
+ export const DEFAULT_IMPOSTOR_RUNTIME_FEATURES = Object.freeze({
110
+ interpolation: true,
111
+ reprojection: true,
112
+ depthWeights: true,
113
+ perspectiveCorrection: true,
114
+ cellCorrection: false,
115
+ boundedReprojection: true,
116
+ });
117
+
118
+ export const IMPOSTOR_RUNTIME_SAMPLE_LIMITS = Object.freeze({
119
+ raySamples: 32,
120
+ depthSamples: 8,
121
+ });
122
+
123
+ const IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS = 0.002;
124
+ const HEMISPHERE_HORIZON_TRANSITION_SINE = Math.sin(Math.PI / 180);
125
+
126
+ /**
127
+ * Reports whether a renderer can compile Baker's TSL impostor material.
128
+ * WebGPURenderer supports node materials directly. Classic WebGLRenderer
129
+ * integrations must advertise that they installed a compatible nodes handler.
130
+ *
131
+ * @param {ImpostorRenderer | undefined} renderer
132
+ */
133
+ export function rendererSupportsImpostorNodeMaterials(renderer) {
134
+ if (typeof NAMED_STRUCT_FACTORY !== 'function') return false;
135
+ return renderer?.isWebGPURenderer === true
136
+ || renderer?.capabilities?.supportsNodeMaterials === true;
137
+ }
138
+
139
+ /**
140
+ * @param {ImpostorDescriptor} descriptor
141
+ * @param {Partial<ImpostorRuntimeFeatures>=} input
142
+ * @returns {ResolvedImpostorRuntimeFeatures}
143
+ */
144
+ export function resolveImpostorRuntimeFeatures(descriptor, input = {}) {
145
+ const requested = {
146
+ ...DEFAULT_IMPOSTOR_RUNTIME_FEATURES,
147
+ raySamples: descriptor.parallaxSteps * 4,
148
+ depthSamples: descriptor.parallaxSteps,
149
+ blendZone: descriptor.blendZone,
150
+ ...input,
151
+ };
152
+ for (const name of RUNTIME_FEATURE_NAMES) requested[name] = requested[name] !== false;
153
+ requested.raySamples = clampRuntimeSamples(
154
+ requested.raySamples,
155
+ IMPOSTOR_RUNTIME_SAMPLE_LIMITS.raySamples,
156
+ );
157
+ requested.depthSamples = clampRuntimeSamples(
158
+ requested.depthSamples,
159
+ IMPOSTOR_RUNTIME_SAMPLE_LIMITS.depthSamples,
160
+ );
161
+ requested.blendZone = Math.min(1, Math.max(0.35, Number(requested.blendZone) || descriptor.blendZone));
162
+ const interpolation = requested.interpolation;
163
+ const reprojection = interpolation && requested.reprojection && requested.raySamples > 0;
164
+ const depthWeights = interpolation && requested.depthWeights && descriptor.depthDerivedWeights;
165
+ const perspectiveCorrection = requested.perspectiveCorrection;
166
+ const cellCorrection = interpolation && perspectiveCorrection && requested.cellCorrection;
167
+ const boundedReprojection = reprojection && requested.boundedReprojection;
168
+ return {
169
+ requested,
170
+ effective: {
171
+ interpolation,
172
+ reprojection,
173
+ depthWeights,
174
+ perspectiveCorrection,
175
+ cellCorrection,
176
+ boundedReprojection,
177
+ },
178
+ profile: {
179
+ interpolation,
180
+ reprojection,
181
+ depthWeights,
182
+ perspectiveCorrection,
183
+ cellCorrection,
184
+ boundedReprojection,
185
+ frameSamples: interpolation ? 3 : 1,
186
+ raySamples: reprojection ? requested.raySamples : 0,
187
+ depthSamples: reprojection ? requested.depthSamples : 0,
188
+ blendZone: requested.blendZone,
189
+ },
190
+ };
191
+ }
192
+
193
+ function clampRuntimeSamples(value, maximum) {
194
+ const numeric = Number(value);
195
+ if (!Number.isFinite(numeric)) return 0;
196
+ return Math.min(maximum, Math.max(0, Math.round(numeric)));
197
+ }
198
+
199
+ /**
200
+ * Installs a backend-neutral TSL material. WebGPURenderer compiles this graph
201
+ * to WGSL on WebGPU and GLSL on its WebGL2 compatibility backend.
202
+ *
203
+ * @param {import('three').Object3D} root
204
+ * @param {Map<import('three').Object3D, {descriptor: unknown, maps: {
205
+ * baseColor: import('three').Texture,
206
+ * normalDepth: import('three').Texture,
207
+ * material?: import('three').Texture | null,
208
+ * emissive?: import('three').Texture | null,
209
+ * geometry?: import('three').Texture | null,
210
+ * }}>} bindings
211
+ * @param {Partial<ImpostorRuntimeFeatures>=} inputFeatures
212
+ * @param {ImpostorRenderer=} renderer
213
+ */
214
+ export function upgradeImpostorScene(root, bindings = new Map(), inputFeatures = {}, renderer) {
215
+ let upgraded = 0;
216
+ root.traverse((object) => {
217
+ const binding = bindings.get(object);
218
+ const metadata = binding?.descriptor
219
+ ?? object.userData?.gltfExtensions?.[NEEDLE_MESH_IMPOSTOR];
220
+ if (metadata === undefined) return;
221
+ if (!('isMesh' in object) || object.isMesh !== true) {
222
+ throw new Error('Impostor metadata must belong to a mesh.');
223
+ }
224
+ const descriptor = parseImpostorDescriptor(metadata);
225
+ if (!descriptor) {
226
+ throw new Error('Unsupported impostor GLB descriptor; rebake this asset with the current baker.');
227
+ }
228
+ if (!binding) {
229
+ throw new Error('NEEDLE_mesh_impostor textures require the registered GLTFLoader plugin.');
230
+ }
231
+ const fallback = Array.isArray(object.material) ? object.material[0] : object.material;
232
+ if (!fallback) return;
233
+ const compactLayout = descriptor.compression?.layout === 'compact-atlas-v4';
234
+ if (!binding.maps.baseColor || !binding.maps.normalDepth) {
235
+ throw new Error('Impostor GLB is missing a required base-color or normal-depth atlas.');
236
+ }
237
+ const compressedGeometry = descriptor.compression?.depthEncoding === 'lossless-geometry10-rgba';
238
+ if (compressedGeometry && !binding.maps.geometry) {
239
+ throw new Error('Compressed impostor GLB is missing its geometry atlas.');
240
+ }
241
+ // Extension texture semantics are authoritative. Do not depend on a
242
+ // fallback PBR slot having happened to request the same glTF texture first:
243
+ // loader order and host integrations may otherwise leave a base-color atlas
244
+ // in linear space, which turns bright authored colors nearly white. Packed
245
+ // normals, depth, ORM, and coverage are data and must never be decoded.
246
+ binding.maps.baseColor.colorSpace = SRGBColorSpace;
247
+ binding.maps.normalDepth.colorSpace = NoColorSpace;
248
+ if (binding.maps.material) binding.maps.material.colorSpace = NoColorSpace;
249
+ if (binding.maps.geometry) binding.maps.geometry.colorSpace = NoColorSpace;
250
+ if (binding.maps.emissive) binding.maps.emissive.colorSpace = SRGBColorSpace;
251
+ for (const atlas of [
252
+ binding.maps.baseColor,
253
+ binding.maps.normalDepth,
254
+ binding.maps.material,
255
+ binding.maps.geometry,
256
+ binding.maps.emissive,
257
+ ]) {
258
+ if (!atlas) continue;
259
+ // glTF declares CLAMP_TO_EDGE for every impostor atlas. Reassert it on
260
+ // the runtime textures as well: these are packed view grids, never
261
+ // repeatable images, and one repeated edge texel can become a visible
262
+ // line around the billboard.
263
+ atlas.wrapS = ClampToEdgeWrapping;
264
+ atlas.wrapT = ClampToEdgeWrapping;
265
+ atlas.minFilter = LinearMipmapLinearFilter;
266
+ atlas.magFilter = LinearFilter;
267
+ atlas.generateMipmaps = !atlas.isCompressedTexture;
268
+ atlas.needsUpdate = true;
269
+ }
270
+ if (compressedGeometry && binding.maps.geometry) {
271
+ binding.maps.geometry.minFilter = LinearFilter;
272
+ binding.maps.geometry.generateMipmaps = false;
273
+ binding.maps.geometry.needsUpdate = true;
274
+ }
275
+ const viewBoundsTexture = createImpostorViewBoundsTexture(descriptor);
276
+ const maps = {
277
+ baseColor: binding.maps.baseColor,
278
+ normalDepth: binding.maps.normalDepth,
279
+ orm: compactLayout ? binding.maps.normalDepth : binding.maps.material,
280
+ emissive: compactLayout
281
+ ? descriptor.compression?.emissive ? binding.maps.baseColor : null
282
+ : binding.maps.emissive,
283
+ geometry: compressedGeometry ? binding.maps.geometry : null,
284
+ viewBounds: viewBoundsTexture,
285
+ };
286
+ const nodeMaterials = rendererSupportsImpostorNodeMaterials(renderer);
287
+ const runtime = {
288
+ backend: nodeMaterials ? 'three-tsl' : 'three-webgl-compat',
289
+ descriptor,
290
+ viewBoundsTexture,
291
+ atlases: {
292
+ baseColor: binding.maps.baseColor,
293
+ normalDepth: binding.maps.normalDepth,
294
+ orm: compactLayout ? binding.maps.normalDepth : binding.maps.material,
295
+ emissive: compactLayout
296
+ ? descriptor.compression?.emissive ? binding.maps.baseColor : null
297
+ : binding.maps.emissive,
298
+ geometry: compressedGeometry ? binding.maps.geometry : null,
299
+ },
300
+ };
301
+ const requestedFeatures = {
302
+ ...DEFAULT_IMPOSTOR_RUNTIME_FEATURES,
303
+ raySamples: descriptor.parallaxSteps * 4,
304
+ depthSamples: descriptor.parallaxSteps,
305
+ blendZone: descriptor.blendZone,
306
+ ...inputFeatures,
307
+ };
308
+ const debugControls = Object.fromEntries(RUNTIME_FEATURE_NAMES.map((name) => [
309
+ name,
310
+ { value: requestedFeatures[name] ? 1 : 0 },
311
+ ]));
312
+ debugControls.raySamples = { value: descriptor.parallaxSteps * 4 };
313
+ debugControls.depthSamples = { value: descriptor.parallaxSteps };
314
+ debugControls.blendZone = { value: descriptor.blendZone };
315
+ debugControls.setFeatures = (features) => {
316
+ const next = resolveImpostorRuntimeFeatures(descriptor, features);
317
+ if (JSON.stringify(next.requested) === JSON.stringify(requestedFeatures)) return false;
318
+ Object.assign(requestedFeatures, next.requested);
319
+ for (const name of RUNTIME_FEATURE_NAMES) {
320
+ debugControls[name].value = requestedFeatures[name] ? 1 : 0;
321
+ }
322
+ debugControls.raySamples.value = requestedFeatures.raySamples;
323
+ debugControls.depthSamples.value = requestedFeatures.depthSamples;
324
+ debugControls.blendZone.value = requestedFeatures.blendZone;
325
+ const previous = object.material;
326
+ const replacement = createPbrImpostorNodeMaterial(
327
+ descriptor,
328
+ maps,
329
+ requestedFeatures,
330
+ renderer,
331
+ );
332
+ replacement.userData.impostor = runtime;
333
+ replacement.userData.impostorDebug = debugControls;
334
+ debugControls.profile = replacement.userData.impostorShaderProfile;
335
+ object.material = replacement;
336
+ if (previous !== fallback) previous.dispose();
337
+ return true;
338
+ };
339
+ const material = createPbrImpostorNodeMaterial(descriptor, maps, requestedFeatures, renderer);
340
+ material.userData.impostor = runtime;
341
+ material.userData.impostorDebug = debugControls;
342
+ debugControls.profile = material.userData.impostorShaderProfile;
343
+ object.material = material;
344
+ object.castShadow = descriptor.castShadow;
345
+ object.receiveShadow = descriptor.receiveShadow;
346
+ object.frustumCulled = false;
347
+ fallback.dispose();
348
+ upgraded++;
349
+ });
350
+ return upgraded;
351
+ }
352
+
353
+ /**
354
+ * Three.js GLTFLoader plugin that upgrades Needle impostor nodes after their
355
+ * atlas textures have loaded. Register KTX2Loader on GLTFLoader as usual when
356
+ * loading compressed impostors; uncompressed GLBs need no extra texture setup.
357
+ */
358
+ export class NeedleImpostorLoaderPlugin {
359
+ /**
360
+ * @param {unknown} parser GLTFLoader parser supplied by `loader.register()`.
361
+ * @param {{
362
+ * onUpgrade?: (count: number, result: import('three/addons/loaders/GLTFLoader.js').GLTF) => void,
363
+ * features?: Partial<ImpostorRuntimeFeatures>,
364
+ * renderer?: ImpostorRenderer,
365
+ * }=} options
366
+ */
367
+ constructor(parser, options = {}) {
368
+ this.name = NEEDLE_MESH_IMPOSTOR;
369
+ this.parser = parser;
370
+ this.options = options;
371
+ }
372
+
373
+ /** @param {import('three/addons/loaders/GLTFLoader.js').GLTF} result */
374
+ async afterRoot(result) {
375
+ const parser = /** @type {{
376
+ * json: {meshes?: Array<{primitives: Array<{extensions?: Record<string, unknown>}>}>},
377
+ * associations: Map<import('three').Object3D, {meshes?: number, primitives?: number}>,
378
+ * getDependency(type: 'texture', index: number): Promise<import('three').Texture>,
379
+ * }} */ (this.parser);
380
+ const bindings = new Map();
381
+ const roots = result.scenes?.length ? result.scenes : [result.scene];
382
+ const visited = new Set();
383
+ let upgraded = 0;
384
+ for (const root of roots) {
385
+ if (!root || visited.has(root)) continue;
386
+ visited.add(root);
387
+ const pending = [];
388
+ root.traverse((object) => {
389
+ if (!('isMesh' in object) || object.isMesh !== true) return;
390
+ const association = parser.associations.get(object);
391
+ if (association?.meshes === undefined || association.primitives === undefined) return;
392
+ const raw = parser.json.meshes?.[association.meshes]
393
+ ?.primitives[association.primitives]?.extensions?.[NEEDLE_MESH_IMPOSTOR];
394
+ if (!raw || typeof raw !== 'object') return;
395
+ const definition = /** @type {Record<string, unknown>} */ (raw);
396
+ const descriptor = parseImpostorDescriptor(definition);
397
+ if (!descriptor) {
398
+ throw new Error('Unsupported NEEDLE_mesh_impostor descriptor; rebake this asset.');
399
+ }
400
+ const rawTextures = definition.textures;
401
+ if (!rawTextures || typeof rawTextures !== 'object') {
402
+ throw new Error('NEEDLE_mesh_impostor has no texture bindings.');
403
+ }
404
+ pending.push((async () => {
405
+ const maps = /** @type {Record<string, import('three').Texture>} */ ({});
406
+ for (const role of ['baseColor', 'normalDepth', 'material', 'emissive', 'geometry']) {
407
+ const info = Reflect.get(rawTextures, role);
408
+ const index = info && typeof info === 'object' ? Reflect.get(info, 'index') : undefined;
409
+ if (!Number.isInteger(index)) continue;
410
+ maps[role] = await parser.getDependency('texture', index);
411
+ }
412
+ if (!maps.baseColor || !maps.normalDepth) {
413
+ throw new Error('NEEDLE_mesh_impostor is missing a required atlas binding.');
414
+ }
415
+ bindings.set(object, {
416
+ descriptor,
417
+ maps: /** @type {any} */ (maps),
418
+ });
419
+ })());
420
+ });
421
+ await Promise.all(pending);
422
+ upgraded += upgradeImpostorScene(
423
+ root,
424
+ bindings,
425
+ this.options.features,
426
+ this.options.renderer,
427
+ );
428
+ }
429
+ this.options.onUpgrade?.(upgraded, result);
430
+ }
431
+ }
432
+
433
+ /**
434
+ * Registers the Needle impostor material plugin on a Three.js GLTFLoader.
435
+ *
436
+ * @template {import('three/addons/loaders/GLTFLoader.js').GLTFLoader} T
437
+ * @param {T} loader
438
+ * @param {ConstructorParameters<typeof NeedleImpostorLoaderPlugin>[1]=} options
439
+ * @returns {T}
440
+ */
441
+ export function registerNeedleImpostorLoader(loader, options = {}) {
442
+ loader.register((parser) => new NeedleImpostorLoaderPlugin(parser, options));
443
+ return loader;
444
+ }
445
+
446
+ /**
447
+ * Compact GLSL runtime for Three versions before named TSL structs. It uses
448
+ * the closest authored capture and reconstructs fragment depth without asking
449
+ * the older node compiler to expand the modern structured graph.
450
+ *
451
+ * @param {ImpostorDescriptor} descriptor
452
+ * @param {Parameters<typeof createPbrImpostorNodeMaterial>[1]} maps
453
+ */
454
+ function createCompatibleImpostorNodeMaterial(descriptor, maps) {
455
+ const compactLayout = descriptor.compression?.layout === 'compact-atlas-v4';
456
+ const compressedGeometry = descriptor.compression?.depthEncoding === 'lossless-geometry10-rgba';
457
+ const compactEmissive = descriptor.compression?.emissive === true;
458
+ const boundsCount = descriptor.frames * descriptor.frames;
459
+ const material = new ShaderMaterial({
460
+ name: 'Needle PBR impostor WebGL compatibility',
461
+ side: DoubleSide,
462
+ transparent: false,
463
+ depthTest: true,
464
+ depthWrite: true,
465
+ glslVersion: GLSL3,
466
+ uniforms: {
467
+ baseColorAtlas: { value: maps.baseColor },
468
+ geometryAtlas: { value: maps.geometry ?? maps.normalDepth },
469
+ viewBounds: {
470
+ value: Array.from({ length: boundsCount }, (_, index) => new Vector4(
471
+ descriptor.viewBounds[index * 4],
472
+ descriptor.viewBounds[index * 4 + 1],
473
+ descriptor.viewBounds[index * 4 + 2],
474
+ descriptor.viewBounds[index * 4 + 3],
475
+ )),
476
+ },
477
+ frames: { value: descriptor.frames },
478
+ frameResolution: { value: descriptor.frameResolution },
479
+ padding: { value: descriptor.padding },
480
+ radius: { value: descriptor.radius },
481
+ captureDirection: { value: new Vector3(...(descriptor.captureDirection ?? [0, 1, 0])) },
482
+ },
483
+ defines: {
484
+ VIEW_BOUNDS_COUNT: boundsCount,
485
+ FULL_SPHERE: descriptor.mapping === 'full' ? 1 : 0,
486
+ SINGLE_VIEW: descriptor.mapping === 'single' ? 1 : 0,
487
+ COMPACT_COLOR: compactLayout ? 1 : 0,
488
+ COMPACT_EMISSIVE: compactEmissive ? 1 : 0,
489
+ COMPRESSED_GEOMETRY: compressedGeometry ? 1 : 0,
490
+ },
491
+ vertexShader: /* glsl */ `
492
+ out vec3 vPlaneLocal;
493
+ void main() {
494
+ mat4 inverseModel = inverse(modelMatrix);
495
+ mat4 cameraWorld = inverse(viewMatrix);
496
+ vec3 rightLocal = normalize((inverseModel * vec4(cameraWorld[0].xyz, 0.0)).xyz);
497
+ vec3 upLocal = normalize((inverseModel * vec4(cameraWorld[1].xyz, 0.0)).xyz);
498
+ vPlaneLocal = rightLocal * position.x + upLocal * position.y;
499
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(vPlaneLocal, 1.0);
500
+ }
501
+ `,
502
+ fragmentShader: /* glsl */ `
503
+ uniform sampler2D baseColorAtlas;
504
+ uniform sampler2D geometryAtlas;
505
+ uniform vec4 viewBounds[VIEW_BOUNDS_COUNT];
506
+ uniform float frames;
507
+ uniform float frameResolution;
508
+ uniform float padding;
509
+ uniform float radius;
510
+ uniform vec3 captureDirection;
511
+ uniform mat4 modelMatrix;
512
+ uniform mat4 modelViewMatrix;
513
+ uniform mat4 projectionMatrix;
514
+ in vec3 vPlaneLocal;
515
+ out vec4 fragColor;
516
+
517
+ float nonZeroSign(float value) { return value < 0.0 ? -1.0 : 1.0; }
518
+ vec2 directionToGrid(vec3 direction) {
519
+ direction = normalize(direction);
520
+ #if !FULL_SPHERE
521
+ direction.y = max(direction.y, 0.000001);
522
+ #endif
523
+ direction /= abs(direction.x) + abs(direction.y) + abs(direction.z);
524
+ #if FULL_SPHERE
525
+ vec2 folded = vec2(
526
+ nonZeroSign(direction.x) * (1.0 - abs(direction.z)),
527
+ nonZeroSign(direction.z) * (1.0 - abs(direction.x))
528
+ );
529
+ return (direction.y < 0.0 ? folded : direction.xz) * 0.5 + 0.5;
530
+ #else
531
+ return vec2(direction.x + direction.z, direction.z - direction.x) * 0.5 + 0.5;
532
+ #endif
533
+ }
534
+ vec3 gridToDirection(vec2 coordinate) {
535
+ #if FULL_SPHERE
536
+ float x = coordinate.x * 2.0 - 1.0;
537
+ float z = coordinate.y * 2.0 - 1.0;
538
+ float y = 1.0 - abs(x) - abs(z);
539
+ if (y < 0.0) {
540
+ float foldedX = nonZeroSign(x) * (1.0 - abs(z));
541
+ float foldedZ = nonZeroSign(z) * (1.0 - abs(x));
542
+ x = foldedX;
543
+ z = foldedZ;
544
+ }
545
+ return normalize(vec3(x, y, z));
546
+ #else
547
+ return normalize(vec3(
548
+ coordinate.x - coordinate.y,
549
+ 1.0 - abs(coordinate.x - coordinate.y) - abs(-1.0 + coordinate.x + coordinate.y),
550
+ -1.0 + coordinate.x + coordinate.y
551
+ ));
552
+ #endif
553
+ }
554
+ vec2 atlasUv(vec2 frame, vec2 frameUv) {
555
+ float interiorPixels = max(frameResolution - padding * 2.0, 1.0);
556
+ float interiorScale = interiorPixels / frameResolution;
557
+ float gutterUv = padding / interiorPixels;
558
+ vec2 insideCell = padding / frameResolution
559
+ + clamp(frameUv, vec2(-gutterUv), vec2(1.0 + gutterUv)) * interiorScale;
560
+ float halfTexel = 0.5001 / frameResolution;
561
+ return (frame + clamp(insideCell, vec2(halfTexel), vec2(1.0 - halfTexel))) / frames;
562
+ }
563
+ void main() {
564
+ vec3 cameraLocal = (inverse(modelMatrix) * vec4(cameraPosition, 1.0)).xyz;
565
+ vec3 cameraDirection = normalize(cameraLocal);
566
+ #if SINGLE_VIEW
567
+ vec2 frame = vec2(0.0);
568
+ vec3 frameDirection = normalize(captureDirection);
569
+ #else
570
+ vec2 frame = clamp(
571
+ floor(directionToGrid(cameraDirection) * (frames - 1.0) + 0.5),
572
+ vec2(0.0),
573
+ vec2(frames - 1.0)
574
+ );
575
+ vec3 frameDirection = gridToDirection(frame / (frames - 1.0));
576
+ #endif
577
+ vec3 referenceUp = abs(frameDirection.y) > 0.999 ? vec3(0.0, 0.0, -1.0) : vec3(0.0, 1.0, 0.0);
578
+ vec3 right = normalize(cross(referenceUp, frameDirection));
579
+ vec3 up = normalize(cross(frameDirection, right));
580
+ int frameIndex = int(frame.y * frames + frame.x);
581
+ vec4 bounds = viewBounds[frameIndex];
582
+ float denominator = dot(cameraDirection, frameDirection);
583
+ float safeDenominator = nonZeroSign(denominator) * max(abs(denominator), 0.05);
584
+ vec3 framePlanePosition = vPlaneLocal - cameraDirection
585
+ * (dot(vPlaneLocal, frameDirection) / safeDenominator);
586
+ vec2 frameUv = (vec2(dot(framePlanePosition, right), dot(framePlanePosition, up))
587
+ - bounds.xy) / (bounds.zw - bounds.xy);
588
+ float interiorPixels = max(frameResolution - padding * 2.0, 1.0);
589
+ float gutterUv = padding / interiorPixels;
590
+ if (any(lessThan(frameUv, vec2(-gutterUv)))
591
+ || any(greaterThan(frameUv, vec2(1.0 + gutterUv)))) discard;
592
+ vec2 atlas = atlasUv(frame, frameUv);
593
+ vec2 colorUv = atlas;
594
+ #if COMPACT_COLOR
595
+ colorUv.x *= COMPACT_EMISSIVE == 1 ? 0.5 : 1.0;
596
+ #endif
597
+ vec4 base = texture(baseColorAtlas, colorUv);
598
+ vec4 geometry = texture(geometryAtlas, atlas);
599
+ float contour = base.a;
600
+ float depthValue;
601
+ #if COMPRESSED_GEOMETRY
602
+ vec2 packed = floor(geometry.rg * 255.0 + 0.5);
603
+ depthValue = (packed.x * 4.0 + floor(packed.y / 85.0 + 0.5)) / 1023.0;
604
+ contour = geometry.a;
605
+ #else
606
+ vec2 packed = floor(geometry.ba * 255.0 + 0.5);
607
+ depthValue = (packed.x * 256.0 + packed.y) / 65535.0;
608
+ #endif
609
+ float width = max(fwidth(contour), 1.0 / 255.0);
610
+ float coverage = smoothstep(0.5 - width, 0.5 + width, contour);
611
+ if (coverage < 0.25) discard;
612
+ vec2 plane = mix(bounds.xy, bounds.zw, frameUv);
613
+ vec3 reconstructedLocal = right * plane.x + up * plane.y
614
+ + frameDirection * (radius - depthValue * radius * 2.0);
615
+ vec4 clip = projectionMatrix * modelViewMatrix * vec4(reconstructedLocal, 1.0);
616
+ gl_FragDepth = clip.z / clip.w * 0.5 + 0.5;
617
+ fragColor = vec4(base.rgb, coverage);
618
+ #if defined(TONE_MAPPING)
619
+ fragColor.rgb = toneMapping(fragColor.rgb);
620
+ #endif
621
+ fragColor = linearToOutputTexel(fragColor);
622
+ }
623
+ `,
624
+ });
625
+ material.alphaToCoverage = true;
626
+ material.toneMapped = true;
627
+ material.userData.impostorShaderProfile = {
628
+ interpolation: false,
629
+ reprojection: false,
630
+ depthWeights: false,
631
+ perspectiveCorrection: false,
632
+ cellCorrection: false,
633
+ boundedReprojection: false,
634
+ frameSamples: 1,
635
+ raySamples: 0,
636
+ depthSamples: 0,
637
+ blendZone: descriptor.blendZone,
638
+ };
639
+ return material;
640
+ }
641
+
642
+ /**
643
+ * @param {ImpostorDescriptor} descriptor
644
+ * @param {{
645
+ * baseColor: import('three').Texture,
646
+ * normalDepth: import('three').Texture,
647
+ * orm?: import('three').Texture | null,
648
+ * emissive: import('three').Texture | null,
649
+ * geometry?: import('three').Texture | null,
650
+ * viewBounds: import('three').DataTexture,
651
+ * }} maps
652
+ * @param {Partial<ImpostorRuntimeFeatures>=} inputFeatures
653
+ * @param {ImpostorRenderer=} renderer
654
+ * @returns {MeshStandardNodeMaterial | ShaderMaterial}
655
+ */
656
+ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, renderer) {
657
+ if (!rendererSupportsImpostorNodeMaterials(renderer)) {
658
+ return createCompatibleImpostorNodeMaterial(descriptor, maps);
659
+ }
660
+ const { effective: features, profile } = resolveImpostorRuntimeFeatures(descriptor, inputFeatures);
661
+ const frames = float(descriptor.frames);
662
+ const frameResolution = float(descriptor.frameResolution);
663
+ const padding = float(descriptor.padding);
664
+ const radius = float(descriptor.radius);
665
+ const captureAlphaCutoff = float(descriptor.captureAlphaCutoff);
666
+ // Source MASK/OPAQUE alpha has already been resolved during capture. At
667
+ // multisampled silhouette edges, one covered sample is valid geometry even
668
+ // though its resolved alpha is below the authored 0.5 contour. Reprojection
669
+ // must retain that depth candidate; the SDF and final alpha-to-coverage pass
670
+ // still decide whether the pixel contributes to the visible silhouette.
671
+ const reprojectionSurfaceCutoff = descriptor.coverageEncoding === 'sdf-base-alpha'
672
+ ? float(0.5)
673
+ : min(captureAlphaCutoff, float(0.25));
674
+ const blendCutoff = float((1 - profile.blendZone) * 0.5);
675
+ const coarseSearchSteps = profile.raySamples;
676
+ const fullSphere = descriptor.mapping === 'full';
677
+ const singleView = descriptor.mapping === 'single';
678
+ const singleCaptureDirection = vec3(...(descriptor.captureDirection ?? [0, 1, 0])).normalize();
679
+ const baseColorAtlas = texture(maps.baseColor);
680
+ const normalDepthAtlas = texture(maps.normalDepth);
681
+ const geometryAtlas = texture(maps.geometry ?? maps.normalDepth);
682
+ const ormAtlas = maps.orm ? texture(maps.orm) : null;
683
+ const emissiveAtlas = maps.emissive ? texture(maps.emissive) : null;
684
+ const compressedGeometry = descriptor.compression?.depthEncoding === 'lossless-geometry10-rgba';
685
+ const compactLayout = descriptor.compression?.layout === 'compact-atlas-v4';
686
+ const compactEmissive = descriptor.compression?.emissive === true;
687
+ const colorAtlasUv = (uvNode, emissive = false) => compactLayout
688
+ ? vec2(
689
+ uvNode.x.mul(compactEmissive ? 0.5 : 1).add(emissive && compactEmissive ? 0.5 : 0),
690
+ uvNode.y,
691
+ )
692
+ : uvNode;
693
+ const sampleCapturedAlpha = (uvNode) => compressedGeometry
694
+ ? texture(baseColorAtlas, colorAtlasUv(uvNode)).level(0).a
695
+ : texture(baseColorAtlas, uvNode).level(0).a;
696
+ const sampleContour = (uvNode) => compressedGeometry
697
+ ? texture(geometryAtlas, uvNode).level(0).a
698
+ : descriptor.coverageEncoding === 'sdf-base-alpha'
699
+ ? texture(baseColorAtlas, uvNode).level(0).a
700
+ : texture(ormAtlas, uvNode).level(0).a;
701
+ const viewBounds = uniformArray(
702
+ Array.from({ length: descriptor.frames * descriptor.frames }, (_, index) => new Vector4(
703
+ descriptor.viewBounds[index * 4],
704
+ descriptor.viewBounds[index * 4 + 1],
705
+ descriptor.viewBounds[index * 4 + 2],
706
+ descriptor.viewBounds[index * 4 + 3],
707
+ )),
708
+ 'vec4',
709
+ );
710
+ const atlasResolution = float(descriptor.frames * descriptor.frameResolution);
711
+ const materialAtlasResolution = float(
712
+ descriptor.frames * (descriptor.compression?.materialFrameResolution ?? descriptor.frameResolution),
713
+ );
714
+ // Stop before the atlas gutter becomes sub-texel, otherwise adjacent views
715
+ // bleed into one another in the generated mip chain.
716
+ const maximumSafeAtlasLod = float(Math.max(0, Math.floor(Math.log2(Math.max(1, descriptor.padding)))));
717
+
718
+ const FrameBasis = NAMED_STRUCT_FACTORY(
719
+ { right: 'vec3', up: 'vec3' },
720
+ 'ImpostorFrameBasis',
721
+ );
722
+ const FrameSample = NAMED_STRUCT_FACTORY({
723
+ base: 'vec4',
724
+ surfaceAlpha: 'float',
725
+ normalLocal: 'vec3',
726
+ positionLocal: 'vec3',
727
+ orm: 'vec3',
728
+ emissive: 'vec3',
729
+ contour: 'float',
730
+ validity: 'float',
731
+ strictValidity: 'float',
732
+ rayError: 'float',
733
+ footprint: 'float',
734
+ }, 'ImpostorFrameSample');
735
+ const BlendedSample = NAMED_STRUCT_FACTORY({
736
+ base: 'vec4',
737
+ normalLocal: 'vec3',
738
+ positionLocal: 'vec3',
739
+ orm: 'vec3',
740
+ emissive: 'vec3',
741
+ capturedCoverage: 'float',
742
+ distanceCoverage: 'float',
743
+ cropSupport: 'float',
744
+ coverageWidth: 'float',
745
+ transition: 'float',
746
+ }, 'ImpostorBlendedSample');
747
+ const basisMember = (value, name) => value.get(name);
748
+ const frameMember = (value, name) => value.get(name);
749
+ const blendedMember = (value, name) => value.get(name);
750
+
751
+ const nonZeroSign = Fn(([value]) => value.lessThan(0).select(float(-1), float(1)), 'float');
752
+ const buildFrameBasis = ([direction]) => {
753
+ const referenceUp = abs(direction.y).greaterThan(0.999)
754
+ .select(vec3(0, 0, -1), vec3(0, 1, 0));
755
+ const right = referenceUp.cross(direction).normalize();
756
+ return FrameBasis(right, direction.cross(right).normalize());
757
+ };
758
+ const frameBasis = Fn(buildFrameBasis);
759
+ const gridToDirection = Fn(([coordinate]) => {
760
+ const hemisphere = vec3(
761
+ coordinate.x.sub(coordinate.y),
762
+ float(1).sub(abs(coordinate.x.sub(coordinate.y))).sub(abs(float(-1).add(coordinate.x).add(coordinate.y))),
763
+ float(-1).add(coordinate.x).add(coordinate.y),
764
+ ).normalize();
765
+ const fullX = coordinate.x.mul(2).sub(1).toVar();
766
+ const fullZ = coordinate.y.mul(2).sub(1).toVar();
767
+ const fullY = float(1).sub(abs(fullX)).sub(abs(fullZ)).toVar();
768
+ const foldedX = nonZeroSign(fullX).mul(float(1).sub(abs(fullZ)));
769
+ const foldedZ = nonZeroSign(fullZ).mul(float(1).sub(abs(fullX)));
770
+ const full = fullY.lessThan(0)
771
+ .select(vec3(foldedX, fullY, foldedZ), vec3(fullX, fullY, fullZ))
772
+ .normalize();
773
+ return fullSphere ? full : hemisphere;
774
+ }, 'vec3');
775
+ const directionToGrid = Fn(([inputDirection]) => {
776
+ const direction = inputDirection.normalize().toVar();
777
+ if (!fullSphere) {
778
+ direction.y.assign(max(direction.y, 0.000001));
779
+ }
780
+ direction.divAssign(abs(direction.x).add(abs(direction.y)).add(abs(direction.z)));
781
+ const hemisphere = vec2(direction.x.add(direction.z), direction.z.sub(direction.x));
782
+ const folded = vec2(
783
+ nonZeroSign(direction.x).mul(float(1).sub(abs(direction.z))),
784
+ nonZeroSign(direction.z).mul(float(1).sub(abs(direction.x))),
785
+ );
786
+ const full = direction.y.lessThan(0).select(folded, direction.xz);
787
+ return (fullSphere ? full : hemisphere).mul(0.5).add(0.5).clamp(0, 1);
788
+ }, 'vec2');
789
+ const atlasUv = Fn(([frame, frameUv]) => {
790
+ const interiorPixels = max(frameResolution.sub(padding.mul(2)), 1);
791
+ const interiorScale = interiorPixels.div(frameResolution);
792
+ const gutterUv = padding.div(interiorPixels);
793
+ const insideCell = padding.div(frameResolution).add(
794
+ frameUv.clamp(gutterUv.negate(), float(1).add(gutterUv)).mul(interiorScale),
795
+ );
796
+ // Clamp to texel centers, not the mathematical cell edge. Clamp-to-edge
797
+ // only protects the outside of the complete texture; it cannot protect
798
+ // internal atlas cells. Sampling exactly on an internal boundary linearly
799
+ // mixes two unrelated captured views and exposes the neighboring cell as
800
+ // a faint rectangular card outline.
801
+ const halfTexel = float(0.5001).div(frameResolution);
802
+ return frame.add(insideCell.clamp(halfTexel, float(1).sub(halfTexel))).div(frames);
803
+ }, 'vec2');
804
+ const atlasLod = Fn(([uvNode]) => {
805
+ const texelCoordinate = uvNode.mul(atlasResolution);
806
+ const footprint = max(
807
+ texelCoordinate.dFdx().length(),
808
+ texelCoordinate.dFdy().length(),
809
+ );
810
+ return max(footprint, 1).log2().clamp(0, maximumSafeAtlasLod);
811
+ }, 'float');
812
+ const materialAtlasLod = Fn(([uvNode]) => {
813
+ const texelCoordinate = uvNode.mul(materialAtlasResolution);
814
+ const footprint = max(
815
+ texelCoordinate.dFdx().length(),
816
+ texelCoordinate.dFdy().length(),
817
+ );
818
+ return max(footprint, 1).log2().clamp(0, maximumSafeAtlasLod);
819
+ }, 'float');
820
+ const decodeDepth16 = Fn(([packed]) => {
821
+ if (descriptor.compression?.depthEncoding === 'lossless-geometry10-rgba') {
822
+ const bytes = floor(packed.rg.mul(255).add(0.5));
823
+ return bytes.x.mul(4).add(floor(bytes.y.div(85).add(0.5))).div(1023);
824
+ }
825
+ const bytes = floor(packed.ba.mul(255).add(0.5));
826
+ return bytes.x.mul(256).add(bytes.y).div(65535);
827
+ }, 'float');
828
+ const loadDepth16 = Fn(([texel]) => decodeDepth16(textureLoad(
829
+ geometryAtlas,
830
+ ivec2(texel).clamp(ivec2(0), ivec2(atlasResolution.sub(1))),
831
+ )), 'float');
832
+ // Packed 16-bit depth cannot use hardware linear filtering: interpolating
833
+ // the high/low bytes independently produces carry artifacts. Decode four
834
+ // integer texels first and then bilinearly filter their scalar depths. The
835
+ // previous nearest-depth lookup made a sub-pixel UV crossing alter the
836
+ // reprojection root abruptly, which showed up as half-degree silhouette
837
+ // flicker even though view weights were continuous.
838
+ const sampleDepth16 = Fn(([uvNode]) => {
839
+ const pixel = uvNode.mul(atlasResolution).sub(0.5);
840
+ const base = floor(pixel);
841
+ const fraction = fract(pixel);
842
+ const lower = mix(
843
+ loadDepth16(base),
844
+ loadDepth16(base.add(vec2(1, 0))),
845
+ fraction.x,
846
+ );
847
+ const upper = mix(
848
+ loadDepth16(base.add(vec2(0, 1))),
849
+ loadDepth16(base.add(1)),
850
+ fraction.x,
851
+ );
852
+ return mix(lower, upper, fraction.y);
853
+ }, 'float');
854
+ const decodeOctahedral = Fn(([encoded]) => {
855
+ const f = encoded.mul(2).sub(1).toVar();
856
+ const value = vec3(f, float(1).sub(abs(f.x)).sub(abs(f.y))).toVar();
857
+ const folded = vec2(
858
+ float(1).sub(abs(value.y)).mul(nonZeroSign(value.x)),
859
+ float(1).sub(abs(value.x)).mul(nonZeroSign(value.y)),
860
+ );
861
+ If(value.z.lessThan(0), () => {
862
+ value.xy.assign(folded);
863
+ });
864
+ return value.normalize();
865
+ }, 'vec3');
866
+ const reconstructPosition = Fn(([frameUv, bounds, frameDirection, right, up, depthValue]) => {
867
+ const plane = mix(bounds.xy, bounds.zw, frameUv);
868
+ return right.mul(plane.x)
869
+ .add(up.mul(plane.y))
870
+ .add(frameDirection.mul(radius.sub(depthValue.mul(radius).mul(2))));
871
+ }, 'vec3');
872
+ const cameraLocal = modelWorldMatrixInverse.mul(vec4(cameraPosition, 1)).xyz;
873
+ // Match the physical card basis produced by Three's billboard helper. A
874
+ // direction-derived world-up frame is equivalent away from the poles, but
875
+ // becomes undefined at zenith/nadir and falls back to a fixed orientation.
876
+ // The camera still has a valid screen-space roll there, so using its actual
877
+ // right/up axes keeps sampling coordinates rotating with the source view.
878
+ const cameraRightLocal = modelWorldMatrixInverse
879
+ .mul(vec4(cameraWorldMatrix[0].xyz, 0)).xyz.normalize();
880
+ const cameraUpLocal = modelWorldMatrixInverse
881
+ .mul(vec4(cameraWorldMatrix[1].xyz, 0)).xyz.normalize();
882
+ const cameraOutLocal = modelWorldMatrixInverse
883
+ .mul(vec4(cameraWorldMatrix[2].xyz, 0)).xyz.normalize();
884
+ const projectionCameraDirection = Fn(([], builder) => (
885
+ builder.camera.isPerspectiveCamera ? cameraLocal.normalize() : cameraOutLocal
886
+ ), 'vec3')();
887
+ // An upper-hemisphere atlas has no authored camera below the horizon. Keep
888
+ // its sampling camera and sampling plane on that horizon. The display card
889
+ // remains camera-facing: below the authored range it therefore shows the
890
+ // last representable horizon view at a stable size instead of stretching
891
+ // reprojection rays into a solid rectangle. It only fades at exact nadir.
892
+ const horizontalCamera = vec3(
893
+ projectionCameraDirection.x,
894
+ 0,
895
+ projectionCameraDirection.z,
896
+ );
897
+ const horizontalUp = vec3(cameraUpLocal.x, 0, cameraUpLocal.z);
898
+ const horizonFromPosition = horizontalCamera.div(max(horizontalCamera.length(), 0.000001));
899
+ const horizonFromCameraUp = horizontalUp.div(max(horizontalUp.length(), 0.000001));
900
+ const horizonDirection = horizontalCamera.length().greaterThan(0.0001)
901
+ .select(horizonFromPosition, horizonFromCameraUp);
902
+ const cameraDirection = projectionCameraDirection;
903
+ // There is no well-defined horizon azimuth at exact nadir. Preserve the
904
+ // clamped horizon reconstruction through almost the entire lower hemisphere,
905
+ // then remove the card within the final ~1.8 degrees instead of exposing an
906
+ // arbitrary pole orientation as an opaque rectangle.
907
+ const mappingVisibility = (fullSphere || singleView)
908
+ ? float(1)
909
+ : smoothstep(-1, -0.9995, cameraDirection.y);
910
+ // Ease into the authored hemisphere over its first degree. Although the
911
+ // directions on either side of zero are mathematically close, switching the
912
+ // billboard basis exactly at zero moves rasterized edges by a pixel and
913
+ // exposes a visible horizon seam.
914
+ const horizonTransition = smoothstep(
915
+ 0,
916
+ HEMISPHERE_HORIZON_TRANSITION_SINE,
917
+ max(cameraDirection.y, 0),
918
+ );
919
+ const clampedCameraDirection = (fullSphere || singleView)
920
+ ? cameraDirection
921
+ : mix(horizonDirection, cameraDirection, horizonTransition).normalize();
922
+ const horizonBillboardUp = cross(horizonDirection, cameraRightLocal).normalize();
923
+ const billboardUpLocal = (fullSphere || singleView)
924
+ ? cameraUpLocal
925
+ : mix(horizonBillboardUp, cameraUpLocal, horizonTransition).normalize();
926
+ const samplingCamera = clampedCameraDirection.mul(cameraLocal.length());
927
+ const samplingBillboardPosition = cameraRightLocal.mul(positionGeometry.x)
928
+ .add(billboardUpLocal.mul(positionGeometry.y));
929
+ const displayBillboardPosition = cameraRightLocal.mul(positionGeometry.x)
930
+ .add(cameraUpLocal.mul(positionGeometry.y));
931
+ const planeLocal = samplingBillboardPosition.toVarying('vImpostorPlaneLocal');
932
+ const createFrameSampler = (withReprojection) => {
933
+ const buildFrameSample = ([frame, planePosition, rayDirection]) => {
934
+ const frameDirection = singleView
935
+ ? singleCaptureDirection
936
+ : gridToDirection(frame.div(frames.sub(1)));
937
+ const basis = frameBasis(frameDirection);
938
+ const right = basisMember(basis, 'right');
939
+ const up = basisMember(basis, 'up');
940
+ const bounds = viewBounds.element(int(frame.y.mul(frames).add(frame.x)));
941
+ // Every atlas frame is an orthographic capture whose image plane passes
942
+ // through the object center. Start from the intersection of the current
943
+ // perspective camera ray and that frame plane. Projecting `planePosition`
944
+ // directly only works when the selected capture matches the current view;
945
+ // with sparse view grids it starts neighboring frames on different source
946
+ // features and no finite depth iteration can put them back in register.
947
+ const rayPlaneDenominator = dot(rayDirection, frameDirection);
948
+ const safeRayPlaneDenominator = nonZeroSign(rayPlaneDenominator)
949
+ .mul(max(abs(rayPlaneDenominator), 0.05));
950
+ const framePlanePosition = planePosition.sub(rayDirection.mul(
951
+ dot(planePosition, frameDirection).div(safeRayPlaneDenominator),
952
+ ));
953
+ const projectedFrameUv = vec2(
954
+ dot(framePlanePosition, right),
955
+ dot(framePlanePosition, up),
956
+ ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
957
+ const interiorResolution = max(frameResolution.sub(padding.mul(2)), 1);
958
+ const gutterUv = padding.div(interiorResolution);
959
+ const minimumFrameUv = gutterUv.negate();
960
+ const maximumFrameUv = float(1).add(gutterUv);
961
+ const frameUv = projectedFrameUv.clamp(minimumFrameUv, maximumFrameUv).toVar();
962
+ const reconstructed = planePosition.toVar();
963
+ const rootSolved = bool(!withReprojection).toVar();
964
+ const strictRootSolved = bool(!withReprojection).toVar();
965
+ if (withReprojection) {
966
+ // A capture is a height field D(u). Parameterize the physical runtime
967
+ // ray by the same normalized capture depth `s`: at a surface root,
968
+ // `s == D(u(s))`. March from the capture camera toward the back, bracket
969
+ // the first sign change, then refine that scalar equation. This is
970
+ // standard relief mapping applied to an orthographic depth capture. The
971
+ // previous soft closest-point average could blend two unrelated roots
972
+ // and then jump between them as the camera moved.
973
+ const rootFound = bool(false).toVar();
974
+ const rootLower = float(0).toVar();
975
+ const rootUpper = float(1).toVar();
976
+ const previousHasSurface = bool(false).toVar();
977
+ const previousSearchDepth = float(0).toVar();
978
+ const previousSurfaceDepth = float(1).toVar();
979
+ const coarseStep = float(1).div(coarseSearchSteps);
980
+ Loop(coarseSearchSteps, ({ i }) => {
981
+ const searchDepth = float(i).add(1).mul(coarseStep);
982
+ const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));
983
+ const searchRayPosition = planePosition.add(rayDirection.mul(
984
+ searchPlaneDepth.sub(dot(planePosition, frameDirection))
985
+ .div(safeRayPlaneDenominator),
986
+ ));
987
+ const searchUv = vec2(
988
+ dot(searchRayPosition, right),
989
+ dot(searchRayPosition, up),
990
+ ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
991
+ const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv)))
992
+ .or(any(searchUv.greaterThan(vec2(maximumFrameUv))));
993
+ If(searchOutOfBounds, () => {
994
+ previousHasSurface.assign(false);
995
+ });
996
+ If(searchOutOfBounds.not(), () => {
997
+ const searchAtlasUv = atlasUv(frame, searchUv);
998
+ const searchCoverage = sampleCapturedAlpha(searchAtlasUv);
999
+ const searchSurfaceDepth = sampleDepth16(searchAtlasUv);
1000
+ // Only captured coverage represents geometry. The transition SDF
1001
+ // deliberately extends outside the silhouette; accepting it as a
1002
+ // ray hit turns that band into repeated depth shells and streaks.
1003
+ const hasSurface = searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff);
1004
+ const depthDelta = searchDepth.sub(searchSurfaceDepth);
1005
+ const crossesDepth = previousHasSurface
1006
+ .and(previousSearchDepth.lessThan(previousSurfaceDepth))
1007
+ .and(depthDelta.greaterThanEqual(0));
1008
+ const continuousDepthStep = abs(searchSurfaceDepth.sub(previousSurfaceDepth))
1009
+ .lessThanEqual(coarseStep.mul(2));
1010
+ const crossesCoveredSurface = crossesDepth.and(continuousDepthStep);
1011
+ // A thin captured feature can occupy less than one coarse ray step,
1012
+ // so its first covered sample may already lie just behind the stored
1013
+ // surface. Only accept that entry when the root is inside the
1014
+ // immediately preceding march interval. A late silhouette entry is
1015
+ // not a height-field crossing and must not become a second layer.
1016
+ const entersAtSurface = previousHasSurface.not()
1017
+ .and(depthDelta.greaterThanEqual(0))
1018
+ .and(depthDelta.lessThanEqual(coarseStep.mul(1.15)));
1019
+ const boundedRoot = crossesCoveredSurface.or(entersAtSurface);
1020
+ If(
1021
+ rootFound.not()
1022
+ .and(hasSurface)
1023
+ .and(features.boundedReprojection
1024
+ ? boundedRoot
1025
+ : depthDelta.greaterThanEqual(0)),
1026
+ () => {
1027
+ rootLower.assign(max(searchDepth.sub(coarseStep), 0));
1028
+ rootUpper.assign(searchDepth);
1029
+ rootFound.assign(true);
1030
+ rootSolved.assign(true);
1031
+ strictRootSolved.assign(true);
1032
+ },
1033
+ );
1034
+ If(rootFound.not().and(hasSurface), () => {
1035
+ previousHasSurface.assign(true);
1036
+ previousSearchDepth.assign(searchDepth);
1037
+ previousSurfaceDepth.assign(searchSurfaceDepth);
1038
+ });
1039
+ If(hasSurface.not(), () => {
1040
+ previousHasSurface.assign(false);
1041
+ });
1042
+ });
1043
+ });
1044
+ // The bounded march deliberately rejects height-field discontinuities.
1045
+ // Near a dense capture direction, a valid surface can still be too steep
1046
+ // to form a coarse bracket. Use the center-plane depth only as a seed for
1047
+ // a fixed-point solve, and accept it solely after the projected UV/depth
1048
+ // pair converges inside captured coverage. Unlike the removed planar
1049
+ // fallback, this path produces a point on the runtime camera ray and
1050
+ // never contributes an unconverged card layer.
1051
+ If(rootFound.not(), () => {
1052
+ const iterativeUv = frameUv.toVar();
1053
+ const iterativeDepth = sampleDepth16(atlasUv(frame, iterativeUv)).toVar();
1054
+ const iterationResidual = float(1).toVar();
1055
+ const iterationValid = bool(true).toVar();
1056
+ Loop(profile.depthSamples * 2, () => {
1057
+ If(iterationValid, () => {
1058
+ const iterativePlaneDepth = radius.sub(iterativeDepth.mul(radius).mul(2));
1059
+ const iterativeRayPosition = planePosition.add(rayDirection.mul(
1060
+ iterativePlaneDepth.sub(dot(planePosition, frameDirection))
1061
+ .div(safeRayPlaneDenominator),
1062
+ ));
1063
+ const nextUv = vec2(
1064
+ dot(iterativeRayPosition, right),
1065
+ dot(iterativeRayPosition, up),
1066
+ ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
1067
+ const nextOutOfBounds = any(nextUv.lessThan(vec2(minimumFrameUv)))
1068
+ .or(any(nextUv.greaterThan(vec2(maximumFrameUv))));
1069
+ If(nextOutOfBounds, () => {
1070
+ iterationValid.assign(false);
1071
+ });
1072
+ If(nextOutOfBounds.not(), () => {
1073
+ const nextAtlasUv = atlasUv(frame, nextUv);
1074
+ const nextCoverage = sampleCapturedAlpha(nextAtlasUv);
1075
+ const nextDepth = sampleDepth16(nextAtlasUv);
1076
+ iterationResidual.assign(abs(nextDepth.sub(iterativeDepth)));
1077
+ iterativeUv.assign(nextUv);
1078
+ iterativeDepth.assign(nextDepth);
1079
+ If(nextCoverage.lessThan(reprojectionSurfaceCutoff), () => {
1080
+ iterationValid.assign(false);
1081
+ });
1082
+ });
1083
+ });
1084
+ });
1085
+ If(
1086
+ iterationValid.and(iterationResidual.lessThanEqual(coarseStep)),
1087
+ () => {
1088
+ frameUv.assign(iterativeUv);
1089
+ rootSolved.assign(true);
1090
+ },
1091
+ );
1092
+ });
1093
+ If(rootFound, () => {
1094
+ Loop(profile.depthSamples, () => {
1095
+ const searchDepth = rootLower.add(rootUpper).mul(0.5);
1096
+ const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));
1097
+ const searchRayPosition = planePosition.add(rayDirection.mul(
1098
+ searchPlaneDepth.sub(dot(planePosition, frameDirection))
1099
+ .div(safeRayPlaneDenominator),
1100
+ ));
1101
+ const searchUv = vec2(
1102
+ dot(searchRayPosition, right),
1103
+ dot(searchRayPosition, up),
1104
+ ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
1105
+ const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv)))
1106
+ .or(any(searchUv.greaterThan(vec2(maximumFrameUv))));
1107
+ const midpointIsUpper = bool(false).toVar();
1108
+ If(searchOutOfBounds.not(), () => {
1109
+ const searchAtlasUv = atlasUv(frame, searchUv);
1110
+ const searchCoverage = sampleCapturedAlpha(searchAtlasUv);
1111
+ const searchSurfaceDepth = sampleDepth16(searchAtlasUv);
1112
+ midpointIsUpper.assign(
1113
+ searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff)
1114
+ .and(searchDepth.greaterThanEqual(searchSurfaceDepth)),
1115
+ );
1116
+ });
1117
+ If(midpointIsUpper, () => {
1118
+ rootUpper.assign(searchDepth);
1119
+ });
1120
+ If(midpointIsUpper.not(), () => {
1121
+ rootLower.assign(searchDepth);
1122
+ });
1123
+ });
1124
+ const rootDepth = rootLower.add(rootUpper).mul(0.5);
1125
+ const rootPlaneDepth = radius.sub(rootDepth.mul(radius).mul(2));
1126
+ const rootRayPosition = planePosition.add(rayDirection.mul(
1127
+ rootPlaneDepth.sub(dot(planePosition, frameDirection))
1128
+ .div(safeRayPlaneDenominator),
1129
+ ));
1130
+ frameUv.assign(vec2(
1131
+ dot(rootRayPosition, right),
1132
+ dot(rootRayPosition, up),
1133
+ ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy)).clamp(
1134
+ minimumFrameUv,
1135
+ maximumFrameUv,
1136
+ ));
1137
+ });
1138
+ }
1139
+ const uvNode = atlasUv(frame, frameUv);
1140
+ const lod = atlasLod(uvNode);
1141
+ const materialLod = compactLayout ? materialAtlasLod(uvNode) : lod;
1142
+ reconstructed.assign(reconstructPosition(
1143
+ frameUv,
1144
+ bounds,
1145
+ frameDirection,
1146
+ right,
1147
+ up,
1148
+ sampleDepth16(uvNode),
1149
+ ));
1150
+ const shadingSample = texture(normalDepthAtlas, uvNode).level(materialLod);
1151
+ const geometrySample = compressedGeometry
1152
+ ? texture(geometryAtlas, uvNode).level(0)
1153
+ : null;
1154
+ const viewNormal = decodeOctahedral(shadingSample.rg);
1155
+ const normal = right.mul(viewNormal.x)
1156
+ .add(up.mul(viewNormal.y))
1157
+ .add(frameDirection.mul(viewNormal.z))
1158
+ .normalize();
1159
+ // Captures face-forward double-sided source normals. Neighboring views of
1160
+ // a thin card can therefore encode opposite local directions; averaging
1161
+ // those vectors collapses toward zero and creates dark foliage splotches.
1162
+ // Reorient every contributing normal into the runtime view hemisphere
1163
+ // before interpolation. Exact capture views are unchanged.
1164
+ const faceForwardNormal = dot(normal, rayDirection).lessThan(0)
1165
+ .select(normal.negate(), normal);
1166
+ const closestRayPoint = planePosition.add(
1167
+ rayDirection.mul(dot(reconstructed.sub(planePosition), rayDirection)),
1168
+ );
1169
+ const footprint = max(
1170
+ bounds.z.sub(bounds.x),
1171
+ bounds.w.sub(bounds.y),
1172
+ ).div(interiorResolution);
1173
+ const rayError = reconstructed.sub(closestRayPoint).length();
1174
+ const finalFrameEdgeDistance = min(
1175
+ min(frameUv.x.sub(minimumFrameUv), frameUv.y.sub(minimumFrameUv)),
1176
+ min(maximumFrameUv.sub(frameUv.x), maximumFrameUv.sub(frameUv.y)),
1177
+ );
1178
+ // Validate the address that actually supplies the reconstructed surface.
1179
+ // Using the pre-reprojection center-plane address here erased precisely the
1180
+ // deep features that the ray solve had recovered near a tight crop edge.
1181
+ const boundsConfidence = smoothstep(
1182
+ 0,
1183
+ float(1).div(interiorResolution),
1184
+ finalFrameEdgeDistance,
1185
+ );
1186
+ // Reprojection confidence fades across a bounded texel interval instead
1187
+ // of switching at one residual. The outer bound still rejects a different
1188
+ // depth layer, while the continuous interval prevents thin features from
1189
+ // changing reconstruction paths after a sub-degree camera move.
1190
+ const alignedConfidence = float(1).sub(smoothstep(
1191
+ REPROJECTION_CONFIDENCE_INNER_TEXELS,
1192
+ REPROJECTION_CONFIDENCE_OUTER_TEXELS,
1193
+ rayError.div(max(footprint, 0.000001)),
1194
+ ));
1195
+ const validFloat = boundsConfidence.mul(
1196
+ withReprojection
1197
+ ? alignedConfidence.mul(rootSolved)
1198
+ : float(1),
1199
+ );
1200
+ const strictValidFloat = boundsConfidence.mul(
1201
+ withReprojection
1202
+ ? alignedConfidence.mul(strictRootSolved)
1203
+ : float(1),
1204
+ );
1205
+ const baseColor = texture(baseColorAtlas, colorAtlasUv(uvNode)).level(materialLod);
1206
+ const capturedAlpha = sampleCapturedAlpha(uvNode);
1207
+ const orm = compactLayout
1208
+ ? vec4(geometrySample.b, shadingSample.b, shadingSample.a, 1)
1209
+ : ormAtlas
1210
+ ? texture(ormAtlas, uvNode).level(lod)
1211
+ : vec4(
1212
+ descriptor.material.occlusion,
1213
+ descriptor.material.roughness,
1214
+ descriptor.material.metalness,
1215
+ 1,
1216
+ );
1217
+ // The signed-distance contour must not shift with minification. Only the
1218
+ // material channels use mip LOD; coverage keeps its authored level-zero
1219
+ // values and performs screen-space antialiasing after view interpolation.
1220
+ const coverage = sampleContour(uvNode);
1221
+ const resolvedValidity = validFloat;
1222
+ return FrameSample(
1223
+ // Validity is a blend weight, not an attribute. Premultiplying both the
1224
+ // sampled color/alpha here and the frame weight below applied crop
1225
+ // confidence twice; low-confidence crop-edge samples consequently
1226
+ // rendered as black outlines instead of fading away.
1227
+ vec4(baseColor.rgb, coverage),
1228
+ capturedAlpha,
1229
+ faceForwardNormal,
1230
+ reconstructed,
1231
+ orm.rgb,
1232
+ emissiveAtlas
1233
+ ? texture(emissiveAtlas, colorAtlasUv(uvNode, true)).level(materialLod).rgb
1234
+ : vec3(0),
1235
+ coverage,
1236
+ resolvedValidity,
1237
+ strictValidFloat,
1238
+ rayError,
1239
+ footprint,
1240
+ );
1241
+ };
1242
+ return Fn(buildFrameSample);
1243
+ };
1244
+ const samplePlanarFrame = createFrameSampler(false);
1245
+ const sampleReprojectedFrame = features.reprojection ? createFrameSampler(true) : null;
1246
+ const buildBlendedSample = ([], builder) => {
1247
+ // An upper-hemisphere atlas has no authored views below the horizon.
1248
+ // Project both frame selection and depth rays onto that horizon together;
1249
+ // clamping selection alone while retaining a below-ground ray makes the
1250
+ // reprojection solver pull samples out of their frames.
1251
+ const samplingCameraLocal = samplingCamera;
1252
+ const centerViewDirection = samplingCameraLocal.normalize();
1253
+ const usePerspectiveCorrection = features.perspectiveCorrection
1254
+ && builder.camera.isPerspectiveCamera;
1255
+ const rayDirection = usePerspectiveCorrection
1256
+ ? samplingCameraLocal.sub(planeLocal).normalize()
1257
+ : centerViewDirection;
1258
+ if (singleView) {
1259
+ const singleFrame = vec2(0, 0);
1260
+ const raw = features.reprojection
1261
+ ? sampleReprojectedFrame(singleFrame, planeLocal, rayDirection)
1262
+ : samplePlanarFrame(singleFrame, planeLocal, rayDirection);
1263
+ // A one-view impostor has no neighboring capture that can fill a ray
1264
+ // which leaves the authored crop or fails to intersect its depth field.
1265
+ // `sampleReprojectedFrame` applies the same optional capture-domain
1266
+ // constraint used by every frame count; this branch only reduces the
1267
+ // already-resolved sample to the common blended representation.
1268
+ const validity = frameMember(raw, 'validity');
1269
+ const capturedCoverage = frameMember(raw, 'surfaceAlpha').mul(validity);
1270
+ const distanceCoverage = min(
1271
+ frameMember(raw, 'contour'),
1272
+ capturedCoverage,
1273
+ );
1274
+ return BlendedSample(
1275
+ frameMember(raw, 'base'),
1276
+ frameMember(raw, 'normalLocal'),
1277
+ frameMember(raw, 'positionLocal'),
1278
+ frameMember(raw, 'orm'),
1279
+ frameMember(raw, 'emissive'),
1280
+ capturedCoverage,
1281
+ distanceCoverage,
1282
+ validity,
1283
+ float(0),
1284
+ float(0),
1285
+ );
1286
+ }
1287
+ const centerGrid = directionToGrid(centerViewDirection).mul(frames.sub(1));
1288
+ // Match every card point to a capture along its physical point-to-camera
1289
+ // ray. Adding the card offset instead mirrors this correction: a shallow
1290
+ // box makes that inversion visible immediately on its near/far corners.
1291
+ const perspectiveGrid = usePerspectiveCorrection
1292
+ ? directionToGrid(
1293
+ samplingCameraLocal.add(planeLocal.mul(PERSPECTIVE_RAY_PLANE_SIGN)).normalize(),
1294
+ ).mul(frames.sub(1))
1295
+ : centerGrid;
1296
+ const maximumBase = vec2(frames.sub(2));
1297
+ const centerBase = min(floor(centerGrid), maximumBase);
1298
+ // Keep one frame triangle for the whole card. Switching discrete atlas
1299
+ // cells per fragment creates visible vertical bands even with perfectly
1300
+ // valid source frames. Perspective correction instead adjusts the three
1301
+ // weights inside the center-selected triangle and clamps to its simplex.
1302
+ const weightGrid = features.cellCorrection
1303
+ ? perspectiveGrid
1304
+ : centerGrid;
1305
+ const base = centerBase;
1306
+ const centerFraction = centerGrid.sub(base);
1307
+ const fraction = weightGrid.sub(base);
1308
+ const horizontal = centerFraction.x.greaterThan(centerFraction.y);
1309
+ const ordinaryFrame1 = base.add(horizontal.select(vec2(1, 0), vec2(0, 1)));
1310
+ const ordinaryWeights = horizontal.select(
1311
+ vec3(float(1).sub(fraction.x), fraction.x.sub(fraction.y), fraction.y),
1312
+ vec3(float(1).sub(fraction.y), fraction.y.sub(fraction.x), fraction.x),
1313
+ );
1314
+ const foldCell = fullSphere
1315
+ ? bool(false)
1316
+ : base.x.add(base.y).equal(frames.sub(2));
1317
+ const baseDirection = gridToDirection(base.div(frames.sub(1)));
1318
+ const rightDirection = gridToDirection(base.add(vec2(1, 0)).div(frames.sub(1)));
1319
+ const upDirection = gridToDirection(base.add(vec2(0, 1)).div(frames.sub(1)));
1320
+ const diagonalDirection = gridToDirection(base.add(1).div(frames.sub(1)));
1321
+ const antiDiagonal = foldCell.or(
1322
+ dot(rightDirection, upDirection).greaterThan(dot(baseDirection, diagonalDirection)),
1323
+ );
1324
+ const antiLower = centerFraction.x.add(centerFraction.y).lessThanEqual(1);
1325
+ const antiFrame0 = antiLower.select(base, base.add(1));
1326
+ const antiFrame1 = antiLower.select(base.add(vec2(1, 0)), base.add(vec2(0, 1)));
1327
+ const antiFrame2 = antiLower.select(base.add(vec2(0, 1)), base.add(vec2(1, 0)));
1328
+ const antiWeights = antiLower.select(
1329
+ vec3(float(1).sub(fraction.x).sub(fraction.y), fraction.x, fraction.y),
1330
+ vec3(fraction.x.add(fraction.y).sub(1), float(1).sub(fraction.x), float(1).sub(fraction.y)),
1331
+ );
1332
+ const frame0 = antiDiagonal.select(antiFrame0, base);
1333
+ const frame1 = antiDiagonal.select(antiFrame1, ordinaryFrame1);
1334
+ const frame2 = antiDiagonal.select(antiFrame2, base.add(1));
1335
+ const weights = max(antiDiagonal.select(antiWeights, ordinaryWeights), vec3(0)).toVar();
1336
+ weights.divAssign(max(dot(weights, vec3(1)), 0.0001));
1337
+ // Compact angular support: on each triangle edge, `blendZone` is the
1338
+ // fraction over which both endpoint captures contribute. Unlike exponent
1339
+ // sharpening, this gives capture vertices a real single-view neighborhood
1340
+ // instead of letting tiny contributors affect virtually the whole cell.
1341
+ weights.assign(max(weights.sub(blendCutoff), vec3(0)));
1342
+ weights.divAssign(max(dot(weights, vec3(1)), 0.0001));
1343
+ const frame0Nearest = weights.x.greaterThanEqual(weights.y)
1344
+ .and(weights.x.greaterThanEqual(weights.z));
1345
+ // TSL expressions are lazy. Snapshot the winner before raw mode mutates
1346
+ // `weights` to [1, 0, 0], otherwise the expression is re-evaluated later
1347
+ // and silently falls back to frame0 instead of the reported nearest frame.
1348
+ const nearestFrame = frame0Nearest.select(
1349
+ frame0,
1350
+ weights.y.greaterThanEqual(weights.z).select(frame1, frame2),
1351
+ ).toVar('impostorNearestFrame');
1352
+ if (!features.interpolation) {
1353
+ const raw = samplePlanarFrame(nearestFrame, planeLocal, rayDirection);
1354
+ return BlendedSample(
1355
+ frameMember(raw, 'base'),
1356
+ frameMember(raw, 'normalLocal'),
1357
+ frameMember(raw, 'positionLocal'),
1358
+ frameMember(raw, 'orm'),
1359
+ frameMember(raw, 'emissive'),
1360
+ frameMember(raw, 'surfaceAlpha'),
1361
+ frameMember(raw, 'surfaceAlpha'),
1362
+ frameMember(raw, 'validity'),
1363
+ float(0),
1364
+ float(0),
1365
+ );
1366
+ }
1367
+ const a = features.reprojection
1368
+ ? sampleReprojectedFrame(frame0, planeLocal, rayDirection)
1369
+ : samplePlanarFrame(frame0, planeLocal, rayDirection);
1370
+ const b = features.reprojection
1371
+ ? sampleReprojectedFrame(frame1, planeLocal, rayDirection)
1372
+ : samplePlanarFrame(frame1, planeLocal, rayDirection);
1373
+ const c = features.reprojection
1374
+ ? sampleReprojectedFrame(frame2, planeLocal, rayDirection)
1375
+ : samplePlanarFrame(frame2, planeLocal, rayDirection);
1376
+ const angularWeights = weights.toVar('impostorAngularWeights');
1377
+ if (features.depthWeights) {
1378
+ // A reprojected frame sample only represents this camera ray while its
1379
+ // residual lies inside the source texel's physical footprint. A
1380
+ // half-texel Gaussian retains subpixel agreement while decisively
1381
+ // rejecting a neighboring frame whose reconstructed surface belongs
1382
+ // to another depth layer. Wider kernels visibly duplicate sparse-view
1383
+ // silhouettes even though their barycentric weights are correct.
1384
+ const residual = vec3(
1385
+ frameMember(a, 'rayError').div(frameMember(a, 'footprint')),
1386
+ frameMember(b, 'rayError').div(frameMember(b, 'footprint')),
1387
+ frameMember(c, 'rayError').div(frameMember(c, 'footprint')),
1388
+ ).div(0.5);
1389
+ // Never let residual weighting amplify an almost-zero barycentric
1390
+ // contributor into the sole visible frame. A small factor floor keeps
1391
+ // the view-space prior authoritative and removes isolated fold-cell
1392
+ // fragments without introducing a hard angular cutoff.
1393
+ weights.mulAssign(max(exp(residual.mul(residual).mul(-0.5)), vec3(0.05)));
1394
+ }
1395
+ // Residual weighting chooses among frames; it is not transparency. Keep
1396
+ // the attribute weights normalized so a uniform residual cannot darken
1397
+ // otherwise opaque material channels.
1398
+ weights.divAssign(max(dot(weights, vec3(1)), 0.0001));
1399
+ // Snapshot the depth-aware visibility distribution before alpha and crop
1400
+ // confidence mutate the attribute weights below.
1401
+ const visibilityWeights = weights.toVar('impostorVisibilityWeights');
1402
+ const resolvedSampleValidity = vec3(
1403
+ frameMember(a, 'validity'),
1404
+ frameMember(b, 'validity'),
1405
+ frameMember(c, 'validity'),
1406
+ );
1407
+ const strictSampleValidity = vec3(
1408
+ frameMember(a, 'strictValidity'),
1409
+ frameMember(b, 'strictValidity'),
1410
+ frameMember(c, 'strictValidity'),
1411
+ );
1412
+ // A converged seed is only a disocclusion fill. Fade every seed out over
1413
+ // the first 1% of bounded-root support so a background fixed point cannot
1414
+ // appear as a second layer behind valid geometry.
1415
+ const strictSupport = dot(angularWeights, strictSampleValidity);
1416
+ const seedValidity = max(resolvedSampleValidity.sub(strictSampleValidity), vec3(0));
1417
+ const seedWeight = float(1).sub(smoothstep(0, 0.01, strictSupport));
1418
+ const sampleValidity = strictSampleValidity.add(seedValidity.mul(seedWeight));
1419
+ const surfaceAlpha = vec3(
1420
+ frameMember(a, 'surfaceAlpha'),
1421
+ frameMember(b, 'surfaceAlpha'),
1422
+ frameMember(c, 'surfaceAlpha'),
1423
+ );
1424
+ const largestAngularWeight = max(
1425
+ angularWeights.x,
1426
+ max(angularWeights.y, angularWeights.z),
1427
+ );
1428
+ const transition = smoothstep(
1429
+ 0,
1430
+ 0.5,
1431
+ float(1).sub(largestAngularWeight),
1432
+ ).toVar('impostorCoverageTransition');
1433
+ weights.mulAssign(surfaceAlpha).mulAssign(sampleValidity);
1434
+ weights.divAssign(max(dot(weights, vec3(1)), 0.0001));
1435
+ const weighted3 = (field) => frameMember(a, field).mul(weights.x)
1436
+ .add(frameMember(b, field).mul(weights.y))
1437
+ .add(frameMember(c, field).mul(weights.z));
1438
+ const weighted4 = (field) => frameMember(a, field).mul(weights.x)
1439
+ .add(frameMember(b, field).mul(weights.y))
1440
+ .add(frameMember(c, field).mul(weights.z));
1441
+ // A weighted average of inside/outside SDFs makes whole features cross the
1442
+ // 0.5 contour together near a frame bisector. Normalized log-sum-exp acts
1443
+ // as a smooth union: it preserves thin features and equals the authored
1444
+ // SDF when one view has unit weight.
1445
+ // Keep the angular width of an unmatched contour contribution roughly
1446
+ // constant as view density changes. Sparse grids need a stronger union to
1447
+ // retain disoccluded thin parts; dense grids can use a near-linear blend,
1448
+ // preventing a tiny-weight frame from popping in a whole feature. This is
1449
+ // derived only from sampling density, never from asset classification.
1450
+ const contourSharpness = impostorContourUnionSharpness(descriptor.frames);
1451
+ // A contour from a newly entering capture must begin as an ordinary
1452
+ // weighted SDF contribution. Applying the full smooth-union temperature
1453
+ // at an infinitesimal angular weight makes an entire disoccluded feature
1454
+ // cross the alpha mask in one sub-degree step. Ramp to the preserving
1455
+ // union only near a balanced transition; exact capture neighborhoods stay
1456
+ // exact and the blend-zone boundary remains visually continuous.
1457
+ const effectiveContourSharpness = mix(
1458
+ float(0.01),
1459
+ float(contourSharpness),
1460
+ transition,
1461
+ );
1462
+ const coverageContributions = visibilityWeights.mul(sampleValidity)
1463
+ .toVar('impostorCoverageContributions');
1464
+ const coverageSupport = dot(coverageContributions, vec3(1))
1465
+ .toVar('impostorCoverageSupport');
1466
+ const coverageWeights = coverageContributions
1467
+ .div(max(coverageSupport, 0.0001))
1468
+ .toVar('impostorCoverageWeights');
1469
+ // Do not normalize occupancy. If only a low-weight capture claims a pixel,
1470
+ // that claim remains low confidence instead of becoming a second opaque
1471
+ // silhouette. Normalization is retained solely for blending attributes of
1472
+ // samples that have already passed this coverage test.
1473
+ const perspectiveCapturedCoverage = dot(
1474
+ coverageContributions,
1475
+ surfaceAlpha,
1476
+ );
1477
+ const coverageDistanceSamples = vec3(
1478
+ frameMember(a, 'contour'),
1479
+ frameMember(b, 'contour'),
1480
+ frameMember(c, 'contour'),
1481
+ );
1482
+ const unionDistanceCoverage = max(
1483
+ dot(coverageWeights, exp(coverageDistanceSamples.mul(effectiveContourSharpness))),
1484
+ 0.0001,
1485
+ ).log().div(effectiveContourSharpness);
1486
+ // The SDF provides a stable subpixel contour, but it may not expand beyond
1487
+ // actual captured occupancy. This cap removes disjoint depth layers that a
1488
+ // smooth union would otherwise preserve from multiple camera frames.
1489
+ const perspectiveDistanceCoverage = min(
1490
+ unionDistanceCoverage,
1491
+ perspectiveCapturedCoverage,
1492
+ );
1493
+ const coverageDistanceMean = dot(coverageWeights, coverageDistanceSamples);
1494
+ const coverageDistanceDeviation = dot(
1495
+ coverageWeights,
1496
+ abs(coverageDistanceSamples.sub(coverageDistanceMean)),
1497
+ );
1498
+ return BlendedSample(
1499
+ weighted4('base'),
1500
+ weighted3('normalLocal').normalize(),
1501
+ weighted3('positionLocal'),
1502
+ weighted3('orm'),
1503
+ weighted3('emissive'),
1504
+ perspectiveCapturedCoverage,
1505
+ perspectiveDistanceCoverage,
1506
+ coverageSupport,
1507
+ // View-domain antialiasing complements screen-space fwidth. It widens
1508
+ // only where the contributing captures disagree about occupancy, so a
1509
+ // moving contour crosses pixels over an angular interval rather than in
1510
+ // one frame while stable interiors remain sharp.
1511
+ coverageDistanceDeviation.mul(0.2).mul(transition),
1512
+ transition,
1513
+ );
1514
+ };
1515
+ const blendImpostor = Fn(buildBlendedSample);
1516
+
1517
+ const sample = blendImpostor().toVar('impostorSample');
1518
+ const reconstructedWorldPosition = modelWorldMatrix.mul(vec4(blendedMember(sample, 'positionLocal'), 1)).xyz;
1519
+ const reconstructedDepth = Fn(([localPosition], builder) => {
1520
+ const viewZ = modelViewMatrix.mul(vec4(localPosition, 1)).z;
1521
+ const resolvedDepth = builder.camera.isPerspectiveCamera
1522
+ ? viewZToPerspectiveDepth(viewZ, cameraNear, cameraFar)
1523
+ : viewZToOrthographicDepth(viewZ, cameraNear, cameraFar);
1524
+ // The light and view cameras reconstruct the surface from different atlas
1525
+ // cells. Offset only the shadow-map writer so tiny cross-view depth
1526
+ // disagreement cannot make an impostor shadow itself. Main-camera depth is
1527
+ // left exact for intersections with surrounding geometry.
1528
+ return builder.material.isShadowPassMaterial
1529
+ ? min(1, resolvedDepth.add(IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS))
1530
+ : resolvedDepth;
1531
+ }, 'float');
1532
+
1533
+ const material = new MeshStandardNodeMaterial({
1534
+ name: 'Needle PBR impostor TSL',
1535
+ side: DoubleSide,
1536
+ transparent: false,
1537
+ depthTest: true,
1538
+ depthWrite: true,
1539
+ });
1540
+ const distanceCoverage = blendedMember(sample, 'distanceCoverage');
1541
+ const coverageWidth = max(
1542
+ max(fwidth(distanceCoverage), blendedMember(sample, 'coverageWidth')),
1543
+ 1 / 255,
1544
+ );
1545
+ const screenDistanceCoverage = smoothstep(
1546
+ float(0.5).sub(coverageWidth),
1547
+ float(0.5).add(coverageWidth),
1548
+ distanceCoverage,
1549
+ );
1550
+ const screenCoverage = screenDistanceCoverage.mul(mappingVisibility);
1551
+ // Use a local-space billboard position instead of a clip-space vertex node.
1552
+ // Three's shadow override copies `positionNode`/`castShadowPositionNode`, but
1553
+ // not `vertexNode`; the latter therefore made the shadow pass rasterize an
1554
+ // unrotated card while writing reconstructed fragment depth. Keeping the
1555
+ // card position in local space makes color, depth, and shadow passes share
1556
+ // the same camera-facing geometry (the shadow camera during a shadow pass).
1557
+ material.positionNode = displayBillboardPosition;
1558
+ material.castShadowPositionNode = displayBillboardPosition;
1559
+ material.colorNode = vec4(blendedMember(sample, 'base').rgb, screenCoverage);
1560
+ material.normalNode = transformNormalToView(blendedMember(sample, 'normalLocal'));
1561
+ material.aoNode = blendedMember(sample, 'orm').r;
1562
+ material.roughnessNode = blendedMember(sample, 'orm').g;
1563
+ material.metalnessNode = blendedMember(sample, 'orm').b;
1564
+ material.emissiveNode = blendedMember(sample, 'emissive');
1565
+ // Values below one four-sample alpha-to-coverage quantum cannot contribute
1566
+ // stable spatial coverage. In the soft 0.25–0.5 transition, also require
1567
+ // meaningful pre-normalization crop support: otherwise a nearly rejected
1568
+ // frame is promoted to a faint rectangular card outline. Opaque contour
1569
+ // samples bypass that gate so real thin features retain silhouette quality.
1570
+ const cropSupported = blendedMember(sample, 'cropSupport').greaterThanEqual(0.25);
1571
+ material.maskNode = screenCoverage.greaterThanEqual(0.25).and(
1572
+ screenCoverage.greaterThanEqual(0.5).or(cropSupported),
1573
+ );
1574
+ material.maskShadowNode = distanceCoverage.mul(mappingVisibility).greaterThanEqual(0.5);
1575
+ material.alphaToCoverage = true;
1576
+ material.depthNode = reconstructedDepth(blendedMember(sample, 'positionLocal'));
1577
+ material.receivedShadowPositionNode = reconstructedWorldPosition;
1578
+ material.toneMapped = true;
1579
+ material.userData.impostorShaderProfile = profile;
1580
+ return material;
1581
+ }