@needle-tools/three-mesh-effects 0.2.3 → 0.3.2

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 (113) hide show
  1. package/CHANGELOG.md +34 -8
  2. package/README.md +86 -3
  3. package/SKILL.md +14 -4
  4. package/build/box-impostor-runtime.js +1423 -0
  5. package/build/box-impostor-runtime.js.map +7 -0
  6. package/build/deformation-runtime.js +30 -19
  7. package/build/deformation-runtime.js.map +3 -3
  8. package/build/hull-effects.js +60 -28
  9. package/build/hull-effects.js.map +3 -3
  10. package/build/impostor-runtime.js +264 -133
  11. package/build/impostor-runtime.js.map +4 -4
  12. package/build/index.js +8 -0
  13. package/build/index.js.map +2 -2
  14. package/build/internal/box-impostor/box-impostor-display-settings.js +50 -0
  15. package/build/internal/box-impostor/box-impostor-display-settings.js.map +7 -0
  16. package/build/internal/box-impostor/box-impostor-display.js +1102 -0
  17. package/build/internal/box-impostor/box-impostor-display.js.map +7 -0
  18. package/build/internal/box-impostor/box-impostor-face-axes.js +15 -0
  19. package/build/internal/box-impostor/box-impostor-face-axes.js.map +7 -0
  20. package/build/internal/box-impostor/box-impostor-faces.js +125 -0
  21. package/build/internal/box-impostor/box-impostor-faces.js.map +7 -0
  22. package/build/internal/box-impostor/box-impostor-geometry.js +230 -0
  23. package/build/internal/box-impostor/box-impostor-geometry.js.map +7 -0
  24. package/build/internal/box-impostor/box-impostor-material.js +1056 -0
  25. package/build/internal/box-impostor/box-impostor-material.js.map +7 -0
  26. package/build/internal/box-impostor/box-impostor-metadata.js +108 -0
  27. package/build/internal/box-impostor/box-impostor-metadata.js.map +7 -0
  28. package/build/internal/box-impostor/box-impostor-projection.js +276 -0
  29. package/build/internal/box-impostor/box-impostor-projection.js.map +7 -0
  30. package/build/internal/box-impostor/box-impostor-runtime.js +1369 -0
  31. package/build/internal/box-impostor/box-impostor-runtime.js.map +7 -0
  32. package/build/internal/box-impostor/box-impostor-surface-search.js +21 -0
  33. package/build/internal/box-impostor/box-impostor-surface-search.js.map +7 -0
  34. package/build/internal/deformation/cloth-surface.js +23 -17
  35. package/build/internal/deformation/cloth-surface.js.map +3 -3
  36. package/build/internal/deformation/pin-cloth.js +7 -2
  37. package/build/internal/deformation/pin-cloth.js.map +2 -2
  38. package/build/internal/deformation/rig-runtime.js +30 -19
  39. package/build/internal/deformation/rig-runtime.js.map +3 -3
  40. package/build/internal/impostor/impostor-node-material.js +264 -133
  41. package/build/internal/impostor/impostor-node-material.js.map +4 -4
  42. package/build/internal/pixel-impostor/pixel-impostor-display.js +84 -38
  43. package/build/internal/pixel-impostor/pixel-impostor-display.js.map +4 -4
  44. package/build/internal/rendering/captured-surface-depth.js +35 -0
  45. package/build/internal/rendering/captured-surface-depth.js.map +7 -0
  46. package/build/internal/rendering/captured-surface-material.js +28 -0
  47. package/build/internal/rendering/captured-surface-material.js.map +7 -0
  48. package/build/internal/rendering/hull-effect-runtime.js +59 -27
  49. package/build/internal/rendering/hull-effect-runtime.js.map +3 -3
  50. package/build/internal/rendering/renderer-support.js +31 -0
  51. package/build/internal/rendering/renderer-support.js.map +7 -0
  52. package/build/internal/rendering/wireframe.js +41 -9
  53. package/build/internal/rendering/wireframe.js.map +2 -2
  54. package/build/internal/rendering/wrap-preview.js +59 -27
  55. package/build/internal/rendering/wrap-preview.js.map +3 -3
  56. package/build/pixel-impostor-runtime.js +84 -38
  57. package/build/pixel-impostor-runtime.js.map +4 -4
  58. package/build/types/box-impostor/box-impostor-display-settings.d.ts +30 -0
  59. package/build/types/box-impostor/box-impostor-display-settings.js +1 -0
  60. package/build/types/box-impostor/box-impostor-display.d.ts +13 -0
  61. package/build/types/box-impostor/box-impostor-display.js +1 -0
  62. package/build/types/box-impostor/box-impostor-face-axes.d.ts +5 -0
  63. package/build/types/box-impostor/box-impostor-face-axes.js +1 -0
  64. package/build/types/box-impostor/box-impostor-faces.d.ts +11 -0
  65. package/build/types/box-impostor/box-impostor-faces.js +1 -0
  66. package/build/types/box-impostor/box-impostor-geometry.d.ts +5 -0
  67. package/build/types/box-impostor/box-impostor-geometry.js +1 -0
  68. package/build/types/box-impostor/box-impostor-material.d.ts +14 -0
  69. package/build/types/box-impostor/box-impostor-material.js +1 -0
  70. package/build/types/box-impostor/box-impostor-metadata.d.ts +31 -0
  71. package/build/types/box-impostor/box-impostor-metadata.js +1 -0
  72. package/build/types/box-impostor/box-impostor-projection.d.ts +19 -0
  73. package/build/types/box-impostor/box-impostor-projection.js +1 -0
  74. package/build/types/box-impostor/box-impostor-runtime.d.ts +19 -0
  75. package/build/types/box-impostor/box-impostor-runtime.js +1 -0
  76. package/build/types/box-impostor/box-impostor-surface-search.d.ts +13 -0
  77. package/build/types/box-impostor/box-impostor-surface-search.js +1 -0
  78. package/build/types/deformation/cloth-surface.d.ts +1 -0
  79. package/build/types/deformation/pin-cloth.d.ts +1 -0
  80. package/build/types/impostor/impostor-node-material.d.ts +2 -15
  81. package/build/types/public/box-impostor-runtime.d.ts +6 -0
  82. package/build/types/public/box-impostor-runtime.js +1 -0
  83. package/build/types/public/hull-effects.d.ts +1 -0
  84. package/build/types/public/index.d.ts +1 -1
  85. package/build/types/rendering/captured-surface-depth.d.ts +5 -0
  86. package/build/types/rendering/captured-surface-depth.js +1 -0
  87. package/build/types/rendering/captured-surface-material.d.ts +8 -0
  88. package/build/types/rendering/captured-surface-material.js +1 -0
  89. package/build/types/rendering/renderer-support.d.ts +27 -0
  90. package/build/types/rendering/renderer-support.js +1 -0
  91. package/build/types/rendering/wireframe.d.ts +2 -2
  92. package/package.json +29 -8
  93. package/src/box-impostor/box-impostor-display-settings.js +54 -0
  94. package/src/box-impostor/box-impostor-display.js +50 -0
  95. package/src/box-impostor/box-impostor-face-axes.js +11 -0
  96. package/src/box-impostor/box-impostor-faces.js +118 -0
  97. package/src/box-impostor/box-impostor-geometry.js +140 -0
  98. package/src/box-impostor/box-impostor-material.js +771 -0
  99. package/src/box-impostor/box-impostor-metadata.js +122 -0
  100. package/src/box-impostor/box-impostor-projection.js +276 -0
  101. package/src/box-impostor/box-impostor-runtime.js +124 -0
  102. package/src/box-impostor/box-impostor-surface-search.js +11 -0
  103. package/src/deformation/cloth-surface.ts +28 -17
  104. package/src/deformation/pin-cloth.ts +9 -3
  105. package/src/impostor/impostor-node-material.js +188 -157
  106. package/src/pixel-impostor/pixel-impostor-display.js +5 -13
  107. package/src/public/box-impostor-runtime.js +14 -0
  108. package/src/public/hull-effects.js +1 -0
  109. package/src/public/index.js +10 -1
  110. package/src/rendering/captured-surface-depth.js +55 -0
  111. package/src/rendering/captured-surface-material.js +27 -0
  112. package/src/rendering/renderer-support.js +50 -0
  113. package/src/rendering/wireframe.js +51 -13
@@ -0,0 +1,1423 @@
1
+ // @ts-nocheck
2
+
3
+ // src/box-impostor/box-impostor-display-settings.js
4
+ var DEFAULT_BOX_IMPOSTOR_DISPLAY = Object.freeze({
5
+ depthMode: (
6
+ /** @type {'auto'|'projection'|'depth'} */
7
+ "auto"
8
+ ),
9
+ raySteps: (
10
+ /** @type {8|16|32} */
11
+ 16
12
+ ),
13
+ alphaCutoff: 0.5,
14
+ interpolation: (
15
+ /** @type {'none'|'linear'|'smooth'} */
16
+ "none"
17
+ ),
18
+ transparency: (
19
+ /** @type {'auto'|'cutout'|'dithered'|'blended'} */
20
+ "auto"
21
+ )
22
+ });
23
+ function normalizeBoxImpostorDisplay(input = {}) {
24
+ const value = { ...DEFAULT_BOX_IMPOSTOR_DISPLAY, ...input };
25
+ if (!["auto", "projection", "depth"].includes(value.depthMode) || ![8, 16, 32].includes(value.raySteps) || !Number.isFinite(value.alphaCutoff) || value.alphaCutoff <= 0 || value.alphaCutoff >= 1 || !["none", "linear", "smooth"].includes(value.interpolation) || !["auto", "cutout", "dithered", "blended"].includes(value.transparency))
26
+ throw new Error("Invalid box impostor display settings.");
27
+ return {
28
+ depthMode: value.depthMode,
29
+ raySteps: value.raySteps,
30
+ alphaCutoff: value.alphaCutoff,
31
+ interpolation: value.interpolation,
32
+ transparency: value.transparency
33
+ };
34
+ }
35
+ function boxTransparency(descriptor, settings) {
36
+ return settings.transparency === "auto" ? descriptor.alphaMode === "blend" ? "blended" : "cutout" : settings.transparency;
37
+ }
38
+ function boxDepthMode(descriptor, settings) {
39
+ if (settings.depthMode !== "auto") return settings.depthMode;
40
+ return descriptor.boxes.every(
41
+ (box) => box.planes?.length === 6 && box.planeErrors?.length === 6 && box.planeErrors.every((error) => error <= 2 / 255)
42
+ ) ? "projection" : "depth";
43
+ }
44
+
45
+ // src/box-impostor/box-impostor-face-axes.js
46
+ var BOX_FACE_AXES = Object.freeze([
47
+ { normal: [1, 0, 0], right: [0, 0, -1], up: [0, 1, 0] },
48
+ { normal: [-1, 0, 0], right: [0, 0, 1], up: [0, 1, 0] },
49
+ { normal: [0, 1, 0], right: [1, 0, 0], up: [0, 0, -1] },
50
+ { normal: [0, -1, 0], right: [1, 0, 0], up: [0, 0, 1] },
51
+ { normal: [0, 0, 1], right: [1, 0, 0], up: [0, 1, 0] },
52
+ { normal: [0, 0, -1], right: [-1, 0, 0], up: [0, 1, 0] }
53
+ ]);
54
+
55
+ // src/box-impostor/box-impostor-metadata.js
56
+ var NEEDLE_BOX_IMPOSTOR = "NEEDLE_box_impostor";
57
+ var BOX_OCCUPANCY_RESOLUTION = 8;
58
+ var BOX_OCCUPANCY_WORDS = BOX_OCCUPANCY_RESOLUTION ** 3 / 32;
59
+ function parseBoxImpostorDescriptor(raw) {
60
+ const d = (
61
+ /** @type {BoxImpostorDescriptor} */
62
+ raw
63
+ );
64
+ const fail = () => {
65
+ throw new Error("Invalid NEEDLE_box_impostor descriptor.");
66
+ };
67
+ const vector = (v) => Array.isArray(v) && v.length === 3 && v.every(Number.isFinite);
68
+ if (!d || d.version !== 1 || !["basic", "cards", "fitted"].includes(d.mode) || ![8, 16, 32].includes(d.raySteps) || !Number.isInteger(d.atlasResolution) || d.atlasResolution < 32 || d.atlasResolution > 8192 || !Number.isInteger(d.padding) || d.padding < 1 || d.padding > 16 || !Number.isFinite(d.alphaCutoff) || d.alphaCutoff <= 0 || d.alphaCutoff >= 1 || !Array.isArray(d.boxes) || !d.boxes.length || d.boxes.length > 64)
69
+ fail();
70
+ if (d.alphaMode !== void 0 && !["opaque", "mask", "blend"].includes(d.alphaMode))
71
+ fail();
72
+ if (d.mode === "basic" && d.boxes.length !== 1) fail();
73
+ for (const b of d.boxes) {
74
+ if (b.occupancy !== void 0 && (!Array.isArray(b.occupancy) || b.occupancy.length !== BOX_OCCUPANCY_WORDS || !b.occupancy.every(
75
+ (v) => Number.isInteger(v) && v >= 0 && v <= 4294967295
76
+ )))
77
+ fail();
78
+ if (b.depthBounds !== void 0 && (!Array.isArray(b.depthBounds) || b.depthBounds.length !== 12 || !b.depthBounds.every(
79
+ (v) => Number.isInteger(v) && v >= 0 && v <= 65535
80
+ )))
81
+ fail();
82
+ if (b.planeErrors !== void 0 && (!Array.isArray(b.planeErrors) || b.planeErrors.length !== 6 || !b.planeErrors.every((v) => Number.isFinite(v) && v >= 0 && v <= 1)))
83
+ fail();
84
+ if (b.planes !== void 0 && (!Array.isArray(b.planes) || b.planes.length !== 6 || !b.planes.every((v) => Number.isFinite(v) && v >= 0 && v <= 1)))
85
+ fail();
86
+ if (!vector(b.center) || !vector(b.halfSize) || b.halfSize.some((v) => v <= 0) || !Array.isArray(b.axes) || b.axes.length !== 3 || !b.axes.every(vector) || !Array.isArray(b.views) || b.views.length !== 6)
87
+ fail();
88
+ for (let i = 0; i < 3; i++)
89
+ for (let j = 0; j < 3; j++) {
90
+ const dot4 = b.axes[i].reduce((s, v, k) => s + v * b.axes[j][k], 0);
91
+ if (Math.abs(dot4 - (i === j ? 1 : 0)) > 1e-4) fail();
92
+ }
93
+ const [x, y, z] = b.axes;
94
+ if ((x[1] * y[2] - x[2] * y[1]) * z[0] + (x[2] * y[0] - x[0] * y[2]) * z[1] + (x[0] * y[1] - x[1] * y[0]) * z[2] < 0.999)
95
+ fail();
96
+ for (const r of b.views)
97
+ if (!Array.isArray(r) || r.length !== 4 || !r.every(Number.isInteger) || r[0] < 0 || r[1] < 0 || r[2] <= d.padding * 2 || r[3] <= d.padding * 2 || r[0] + r[2] > d.atlasResolution || r[1] + r[3] > d.atlasResolution)
98
+ fail();
99
+ }
100
+ return {
101
+ version: d.version,
102
+ mode: d.mode,
103
+ atlasResolution: d.atlasResolution,
104
+ padding: d.padding,
105
+ boxes: d.boxes,
106
+ ...d.alphaMode ? { alphaMode: d.alphaMode } : {},
107
+ ...normalizeBoxImpostorDisplay(d)
108
+ };
109
+ }
110
+
111
+ // src/box-impostor/box-impostor-geometry.js
112
+ import {
113
+ BufferGeometry,
114
+ Float32BufferAttribute,
115
+ InterleavedBuffer,
116
+ InterleavedBufferAttribute
117
+ } from "three";
118
+ function createBoxImpostorGeometry(input) {
119
+ const d = parseBoxImpostorDescriptor(input);
120
+ const depths = (
121
+ /** @type {number[][]} */
122
+ [[], [], []]
123
+ );
124
+ const positions = [], normals = [], uvs = [], indices = [], centers = [], halves = [], axisX = [], axisY = [], axisZ = [], boxIds = [], faces = [], corners = [];
125
+ for (const [id, b] of d.boxes.entries())
126
+ for (const f of d.mode !== "fitted" ? [4] : [0, 1, 2, 3, 4, 5]) {
127
+ const face = BOX_FACE_AXES[f], base = positions.length / 3, r = b.views[f], p = d.padding;
128
+ for (const [x, y] of [
129
+ [-1, -1],
130
+ [1, -1],
131
+ [1, 1],
132
+ [-1, 1]
133
+ ]) {
134
+ const local = face.normal.map(
135
+ (n, a) => (n + face.right[a] * x + face.up[a] * y) * b.halfSize[a]
136
+ );
137
+ positions.push(
138
+ ...b.center.map(
139
+ (c, a) => c + local.reduce((s, v, i) => s + v * b.axes[i][a], 0)
140
+ )
141
+ );
142
+ normals.push(
143
+ ...[0, 1, 2].map(
144
+ (a) => face.normal.reduce((s, v, i) => s + v * b.axes[i][a], 0)
145
+ )
146
+ );
147
+ uvs.push(
148
+ (r[0] + p + (x + 1) * 0.5 * (r[2] - 2 * p)) / d.atlasResolution,
149
+ (r[1] + p + (y + 1) * 0.5 * (r[3] - 2 * p)) / d.atlasResolution
150
+ );
151
+ centers.push(...b.center);
152
+ halves.push(...b.halfSize);
153
+ axisX.push(...b.axes[0]);
154
+ axisY.push(...b.axes[1]);
155
+ axisZ.push(...b.axes[2]);
156
+ for (let axis = 0; axis < 3; axis++)
157
+ depths[axis].push(
158
+ ...(b.depthBounds?.slice(axis * 4, axis * 4 + 4) ?? [
159
+ 0,
160
+ 65535,
161
+ 0,
162
+ 65535
163
+ ]).map((v) => v / 65535)
164
+ );
165
+ boxIds.push(id);
166
+ faces.push(f);
167
+ corners.push(x, y);
168
+ }
169
+ indices.push(base, base + 1, base + 2, base, base + 2, base + 3);
170
+ }
171
+ const geometry = new BufferGeometry();
172
+ for (
173
+ const [name, data2, size] of
174
+ /** @type {[string,number[],number][]} */
175
+ [
176
+ ["position", positions, 3],
177
+ ["normal", normals, 3],
178
+ ["uv", uvs, 2],
179
+ ["boxCenter", centers, 3],
180
+ ["boxHalfSize", halves, 3],
181
+ ["boxAxisX", axisX, 3],
182
+ ["boxAxisY", axisY, 3],
183
+ ["boxAxisZ", axisZ, 3],
184
+ ["boxDepthX", depths[0], 4],
185
+ ["boxDepthY", depths[1], 4],
186
+ ["boxDepthZ", depths[2], 4],
187
+ ["boxId", boxIds, 1],
188
+ ["boxFace", faces, 1],
189
+ ["cardCorner", corners, 2]
190
+ ]
191
+ )
192
+ geometry.setAttribute(name, new Float32BufferAttribute(data2, size));
193
+ const names = [
194
+ "boxCenter",
195
+ "boxHalfSize",
196
+ "boxAxisX",
197
+ "boxAxisY",
198
+ "boxAxisZ",
199
+ "boxDepthX",
200
+ "boxDepthY",
201
+ "boxDepthZ",
202
+ "boxId",
203
+ "boxFace",
204
+ "cardCorner"
205
+ ];
206
+ const stride = names.reduce(
207
+ (sum, name) => sum + geometry.getAttribute(name).itemSize,
208
+ 0
209
+ );
210
+ const data = new Float32Array(centers.length / 3 * stride), buffer = new InterleavedBuffer(data, stride);
211
+ let offset = 0;
212
+ for (const name of names) {
213
+ const attribute4 = geometry.getAttribute(name);
214
+ for (let vertex = 0; vertex < attribute4.count; vertex++)
215
+ for (let component = 0; component < attribute4.itemSize; component++)
216
+ data[vertex * stride + offset + component] = attribute4.getComponent(
217
+ vertex,
218
+ component
219
+ );
220
+ geometry.setAttribute(
221
+ name,
222
+ new InterleavedBufferAttribute(buffer, attribute4.itemSize, offset)
223
+ );
224
+ offset += attribute4.itemSize;
225
+ }
226
+ geometry.userData.previewWireframeEdgeMasks = Float32Array.from(
227
+ { length: indices.length },
228
+ (_, i) => [1, 0, 1, 1, 1, 0][i % 6]
229
+ );
230
+ geometry.setIndex(indices);
231
+ geometry.computeBoundingBox();
232
+ geometry.computeBoundingSphere();
233
+ return geometry;
234
+ }
235
+
236
+ // src/rendering/captured-surface-depth.js
237
+ import {
238
+ Fn,
239
+ cameraFar,
240
+ cameraNear,
241
+ cameraProjectionMatrix,
242
+ modelViewMatrix,
243
+ vec4,
244
+ viewZToLogarithmicDepth,
245
+ viewZToOrthographicDepth,
246
+ viewZToPerspectiveDepth,
247
+ viewZToReversedOrthographicDepth,
248
+ viewZToReversedPerspectiveDepth
249
+ } from "three/tsl";
250
+ function capturedSurfaceDepth(position, shadowBias = 0) {
251
+ return Fn(
252
+ (_, builder) => {
253
+ const z = modelViewMatrix.mul(vec4(position, 1)).z.toVar("capturedSurfaceViewZ");
254
+ const reversed = builder.renderer.reversedDepthBuffer === true;
255
+ const perspective = cameraProjectionMatrix.mul(vec4(0, 0, 0, 1)).w.equal(0);
256
+ const perspectiveDepth = builder.renderer.logarithmicDepthBuffer === true ? viewZToLogarithmicDepth(z, cameraNear, cameraFar) : (reversed ? viewZToReversedPerspectiveDepth : viewZToPerspectiveDepth)(z, cameraNear, cameraFar);
257
+ const result = perspective.select(
258
+ perspectiveDepth,
259
+ (reversed ? viewZToReversedOrthographicDepth : viewZToOrthographicDepth)(z, cameraNear, cameraFar)
260
+ );
261
+ return shadowBias && "isShadowPassMaterial" in builder.material && builder.material.isShadowPassMaterial ? result.add(reversed ? -shadowBias : shadowBias).clamp(0, 1) : result;
262
+ }
263
+ )();
264
+ }
265
+
266
+ // src/box-impostor/box-impostor-material.js
267
+ import {
268
+ DataTexture as DataTexture3,
269
+ FloatType as FloatType3,
270
+ RGBAFormat as RGBAFormat3,
271
+ RedIntegerFormat,
272
+ UnsignedIntType,
273
+ NearestFilter as NearestFilter3,
274
+ LinearFilter,
275
+ DoubleSide,
276
+ BackSide,
277
+ FrontSide
278
+ } from "three/webgpu";
279
+ import {
280
+ Fn as Fn4,
281
+ If as If3,
282
+ Loop,
283
+ Break,
284
+ attribute as attribute3,
285
+ varying,
286
+ positionLocal as positionLocal2,
287
+ modelWorldMatrixInverse,
288
+ cameraPosition,
289
+ cameraWorldMatrix,
290
+ cameraProjectionMatrix as cameraProjectionMatrix2,
291
+ vec2 as vec23,
292
+ vec3 as vec33,
293
+ vec4 as vec44,
294
+ float as float3,
295
+ int as int3,
296
+ uint,
297
+ dot as dot3,
298
+ abs as abs3,
299
+ max as max3,
300
+ min,
301
+ sign as sign3,
302
+ texture as texture3,
303
+ textureLoad as textureLoad3,
304
+ ivec2 as ivec23,
305
+ normalize as normalize2,
306
+ floor,
307
+ fract,
308
+ modelWorldMatrix as modelWorldMatrix3,
309
+ cameraNear as cameraNear2,
310
+ transformNormalToView as transformNormalToView3,
311
+ struct as struct2,
312
+ uniform
313
+ } from "three/tsl";
314
+
315
+ // src/rendering/captured-surface-material.js
316
+ import { MeshStandardNodeMaterial } from "three/webgpu";
317
+ import { context, modelViewMatrix as modelViewMatrix2, modelWorldMatrix, vec4 as vec42 } from "three/tsl";
318
+ var CapturedSurfaceMaterial = class extends MeshStandardNodeMaterial {
319
+ /** @type {import('three/webgpu').Node<'vec3'> | null} */
320
+ capturedPositionNode = null;
321
+ /**
322
+ * @override
323
+ * @param {import('three/webgpu').NodeBuilder} builder
324
+ */
325
+ setupLighting(builder) {
326
+ const lighting = super.setupLighting(builder);
327
+ if (!this.capturedPositionNode) return lighting;
328
+ const world = modelWorldMatrix.mul(vec42(this.capturedPositionNode, 1)).xyz;
329
+ const view = modelViewMatrix2.mul(vec42(this.capturedPositionNode, 1)).xyz;
330
+ return context(lighting, {
331
+ positionView: view,
332
+ positionWorld: world,
333
+ shadowPositionWorld: world
334
+ });
335
+ }
336
+ };
337
+
338
+ // src/box-impostor/box-impostor-surface-search.js
339
+ function refineSurfaceCrossing({ float: float4, If: If4, Loop: Loop2 }, { lo, hi, loValue, hiValue, height, steps, secant }) {
340
+ const a = lo.toVar(), b = hi.toVar(), fa = loValue.toVar(), fb = secant ? hiValue.toVar() : null;
341
+ Loop2(steps, () => {
342
+ const mid = a.add(b).mul(0.5).toVar(), d = height(mid).toVar();
343
+ If4(d.mul(fa).greaterThan(0), () => {
344
+ a.assign(mid);
345
+ if (secant) fa.assign(d);
346
+ }).Else(() => {
347
+ b.assign(mid);
348
+ if (secant) fb.assign(d);
349
+ });
350
+ });
351
+ return secant ? a.add(b.sub(a).mul(fa.abs().div(fa.abs().add(fb.abs()).max(1e-20)).clamp(0, 1))) : a.add(b).mul(0.5);
352
+ }
353
+
354
+ // src/box-impostor/box-impostor-faces.js
355
+ import { DataTexture, FloatType, RGBAFormat, NearestFilter } from "three";
356
+ import {
357
+ Fn as Fn2,
358
+ If,
359
+ attribute,
360
+ positionLocal,
361
+ uv,
362
+ texture,
363
+ textureLoad,
364
+ ivec2,
365
+ vec2,
366
+ vec3,
367
+ float,
368
+ int,
369
+ dot,
370
+ abs,
371
+ max,
372
+ sign,
373
+ transformNormalToView
374
+ } from "three/tsl";
375
+ function applyBoxFaces({
376
+ material,
377
+ descriptor,
378
+ maps,
379
+ alphaCutoff,
380
+ transparency,
381
+ half,
382
+ toBox,
383
+ fromBox
384
+ }) {
385
+ const values = new Float32Array(descriptor.boxes.length * 6 * 4);
386
+ descriptor.boxes.forEach((box, i) => {
387
+ for (let face2 = 0; face2 < 6; face2++)
388
+ values[(i * 6 + face2) * 4] = box.planes?.[face2] ?? 0.5;
389
+ });
390
+ const planes = new DataTexture(
391
+ values,
392
+ 6,
393
+ descriptor.boxes.length,
394
+ RGBAFormat,
395
+ FloatType
396
+ );
397
+ planes.minFilter = planes.magFilter = NearestFilter;
398
+ planes.needsUpdate = true;
399
+ material.addEventListener("dispose", () => planes.dispose());
400
+ const face = int(attribute("boxFace", "float"));
401
+ const n = attribute("normal", "vec3");
402
+ const depth = textureLoad(
403
+ planes,
404
+ ivec2(face, int(attribute("boxId", "float")))
405
+ ).r;
406
+ const proxy = positionLocal.sub(
407
+ n.mul(
408
+ dot(abs(toBox(n)), half).mul(depth).mul(2)
409
+ )
410
+ );
411
+ material.positionNode = proxy;
412
+ material.castShadowPositionNode = proxy;
413
+ const base = texture(maps.baseColor, uv()).level(0).toVar("boxFaceColor");
414
+ const orm = texture(maps.orm, uv()).level(0);
415
+ const coverage = max(orm.a, 1e-10);
416
+ const normal = Fn2(() => {
417
+ const packed = textureLoad(
418
+ maps.normalDepth,
419
+ ivec2(uv().mul(descriptor.atlasResolution))
420
+ ).rg.mul(2).sub(1);
421
+ const decoded = vec3(
422
+ packed,
423
+ float(1).sub(abs(packed.x)).sub(abs(packed.y))
424
+ ).toVar();
425
+ If(decoded.z.lessThan(0), () => {
426
+ decoded.xy.assign(
427
+ vec2(1).sub(abs(decoded.yx)).mul(sign(decoded.xy.add(1e-20)))
428
+ );
429
+ });
430
+ const result = vec3(0).toVar();
431
+ for (let f = 0; f < 6; f++) {
432
+ const a = BOX_FACE_AXES[f];
433
+ If(face.equal(f), () => {
434
+ result.assign(
435
+ fromBox(
436
+ vec3(...a.right).mul(decoded.x).add(vec3(...a.up).mul(decoded.y)).add(vec3(...a.normal).mul(decoded.z))
437
+ ).normalize()
438
+ );
439
+ });
440
+ }
441
+ return result;
442
+ })();
443
+ material.colorNode = base.rgb.div(coverage);
444
+ material.normalNode = transformNormalToView(normal);
445
+ material.roughnessNode = orm.g.div(coverage);
446
+ material.metalnessNode = orm.b.div(coverage);
447
+ material.aoNode = orm.r.div(coverage);
448
+ material.emissiveNode = texture(maps.emissive, uv()).level(0).rgb.div(coverage);
449
+ material.maskNode = base.a.greaterThanEqual(
450
+ transparency === "cutout" ? alphaCutoff : float(1 / 255)
451
+ );
452
+ material.maskShadowNode = material.maskNode;
453
+ if (transparency !== "cutout") material.opacityNode = base.a;
454
+ material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
455
+ return material;
456
+ }
457
+
458
+ // src/box-impostor/box-impostor-projection.js
459
+ import { DataTexture as DataTexture2, FloatType as FloatType2, RGBAFormat as RGBAFormat2, NearestFilter as NearestFilter2 } from "three";
460
+ import {
461
+ Fn as Fn3,
462
+ If as If2,
463
+ vec2 as vec22,
464
+ vec3 as vec32,
465
+ vec4 as vec43,
466
+ float as float2,
467
+ int as int2,
468
+ ivec2 as ivec22,
469
+ dot as dot2,
470
+ abs as abs2,
471
+ max as max2,
472
+ sign as sign2,
473
+ normalize,
474
+ texture as texture2,
475
+ textureLoad as textureLoad2,
476
+ attribute as attribute2,
477
+ struct,
478
+ modelWorldMatrix as modelWorldMatrix2,
479
+ transformNormalToView as transformNormalToView2
480
+ } from "three/tsl";
481
+ function applyBoxProjection({
482
+ material,
483
+ descriptor,
484
+ maps,
485
+ settings,
486
+ transparency,
487
+ alphaCutoff,
488
+ rects,
489
+ center,
490
+ half,
491
+ toBox,
492
+ fromBox,
493
+ eye,
494
+ viewAxis,
495
+ perspective,
496
+ raster
497
+ }) {
498
+ const data = new Float32Array(descriptor.boxes.length * 24);
499
+ descriptor.boxes.forEach((box, i) => {
500
+ for (let face = 0; face < 6; face++)
501
+ data[(i * 6 + face) * 4] = box.planes?.[face] ?? 0.5;
502
+ });
503
+ const planes = new DataTexture2(
504
+ data,
505
+ 6,
506
+ descriptor.boxes.length,
507
+ RGBAFormat2,
508
+ FloatType2
509
+ );
510
+ planes.minFilter = planes.magFilter = NearestFilter2;
511
+ planes.needsUpdate = true;
512
+ material.addEventListener("dispose", () => planes.dispose());
513
+ const Surface = struct(
514
+ {
515
+ color: "vec3",
516
+ alpha: "float",
517
+ orm: "vec3",
518
+ emission: "vec3",
519
+ normal: "vec3",
520
+ position: "vec3"
521
+ },
522
+ "BoxProjectedSurface"
523
+ );
524
+ const readNormal = (uv2, right, up, n) => {
525
+ const packed = textureLoad2(
526
+ maps.normalDepth,
527
+ ivec22(uv2.mul(descriptor.atlasResolution))
528
+ ).rg.mul(2).sub(1);
529
+ const decoded = vec32(
530
+ packed,
531
+ float2(1).sub(abs2(packed.x)).sub(abs2(packed.y))
532
+ ).toVar();
533
+ If2(decoded.z.lessThan(0), () => {
534
+ decoded.xy.assign(
535
+ vec22(1).sub(abs2(decoded.yx)).mul(sign2(decoded.xy.add(1e-20)))
536
+ );
537
+ });
538
+ return fromBox(
539
+ right.mul(decoded.x).add(up.mul(decoded.y)).add(n.mul(decoded.z))
540
+ ).normalize();
541
+ };
542
+ const surface = Fn3(() => {
543
+ const ray = perspective.select(
544
+ normalize(raster.sub(eye)),
545
+ viewAxis.negate()
546
+ );
547
+ const origin = perspective.select(
548
+ eye,
549
+ raster.sub(ray.mul(half.length().mul(4)))
550
+ );
551
+ const o = toBox(origin.sub(center)).div(half), r = toBox(ray).div(half);
552
+ const look = normalize(toBox(ray).negate()), angles = abs2(look);
553
+ const positions = vec32(0).toVar();
554
+ const selectedUv = vec22(0).toVar(), selectedRight = vec32(1, 0, 0).toVar(), selectedUp = vec32(0, 1, 0).toVar(), selectedNormal = vec32(0, 0, 1).toVar();
555
+ const nearest = float2(1e20).toVar("boxPlaneDistance");
556
+ const opacity = float2(0).toVar();
557
+ const candidates = [];
558
+ for (let axis = 0; axis < 3; axis++) {
559
+ const angle = angles.element(axis);
560
+ const positive = look.element(axis).greaterThanEqual(0), a = BOX_FACE_AXES[axis * 2], b = BOX_FACE_AXES[axis * 2 + 1];
561
+ const n = positive.select(vec32(...a.normal), vec32(...b.normal)), right = positive.select(vec32(...a.right), vec32(...b.right)), up = positive.select(vec32(...a.up), vec32(...b.up));
562
+ const weight = settings.interpolation === "smooth" ? angle.mul(angle) : angle;
563
+ const candidate = settings.interpolation === "none" ? null : {
564
+ uv: vec22(0).toVar(),
565
+ base: vec43(0).toVar(),
566
+ orm: vec43(0).toVar(),
567
+ t: float2(1e20).toVar(),
568
+ tolerance: float2(0).toVar(),
569
+ right,
570
+ up,
571
+ n,
572
+ weight
573
+ };
574
+ if (candidate) candidates.push(candidate);
575
+ If2(angle.greaterThan(1e-4), () => {
576
+ const face = positive.select(int2(axis * 2), int2(axis * 2 + 1)), id = int2(attribute2("boxId", "float"));
577
+ const plane = float2(1).sub(
578
+ textureLoad2(planes, ivec22(face, id)).r.mul(2)
579
+ );
580
+ const divisor2 = dot2(r, n), safe = sign2(divisor2.add(1e-20)).mul(max2(abs2(divisor2), 1e-10));
581
+ const t = plane.sub(dot2(o, n)).div(safe), point = o.add(r.mul(t));
582
+ const xy = vec22(dot2(point, right), dot2(point, up)).mul(0.5).add(0.5);
583
+ let supported = t.greaterThanEqual(0).and(xy.x.greaterThanEqual(0)).and(xy.y.greaterThanEqual(0)).and(xy.x.lessThanEqual(1)).and(xy.y.lessThanEqual(1));
584
+ if (!candidate) supported = supported.and(t.lessThan(nearest));
585
+ If2(supported, () => {
586
+ const rect = textureLoad2(rects, ivec22(face, id)), uv2 = rect.xy.add(xy.mul(rect.zw));
587
+ const base = texture2(maps.baseColor, uv2).level(0), orm = texture2(maps.orm, uv2).level(0);
588
+ const alpha2 = base.a.clamp(0, 1);
589
+ If2(
590
+ alpha2.greaterThanEqual(
591
+ transparency === "cutout" ? alphaCutoff : float2(1 / 255)
592
+ ).and(orm.a.greaterThan(0)),
593
+ () => {
594
+ If2(t.lessThan(nearest), () => {
595
+ nearest.assign(t);
596
+ selectedUv.assign(uv2);
597
+ opacity.assign(alpha2);
598
+ selectedRight.assign(right);
599
+ selectedUp.assign(up);
600
+ selectedNormal.assign(n);
601
+ positions.assign(center.add(fromBox(point.mul(half))));
602
+ });
603
+ if (candidate) {
604
+ candidate.uv.assign(uv2);
605
+ candidate.base.assign(base);
606
+ candidate.orm.assign(orm);
607
+ candidate.t.assign(t);
608
+ candidate.tolerance.assign(
609
+ max2(
610
+ dot2(abs2(right), half).div(
611
+ rect.z.mul(descriptor.atlasResolution)
612
+ ),
613
+ dot2(abs2(up), half).div(
614
+ rect.w.mul(descriptor.atlasResolution)
615
+ )
616
+ ).mul(4).div(max2(angle, 0.1))
617
+ );
618
+ }
619
+ }
620
+ );
621
+ });
622
+ });
623
+ }
624
+ if (settings.interpolation === "none") {
625
+ const base = texture2(maps.baseColor, selectedUv).level(0), orm = texture2(maps.orm, selectedUv).level(0);
626
+ const coverage = max2(orm.a, 1e-10);
627
+ return Surface(
628
+ base.rgb.div(coverage),
629
+ opacity,
630
+ orm.rgb.div(coverage),
631
+ texture2(maps.emissive, selectedUv).level(0).rgb.div(coverage),
632
+ readNormal(selectedUv, selectedRight, selectedUp, selectedNormal),
633
+ positions
634
+ );
635
+ }
636
+ const colors = vec32(0).toVar(), orms = vec32(0).toVar(), emissions = vec32(0).toVar(), normals = vec32(0).toVar();
637
+ const weights = float2(0).toVar(), support = float2(0).toVar(), alpha = float2(0).toVar();
638
+ for (const c of candidates) {
639
+ If2(
640
+ c.base.a.greaterThan(0).and(c.t.lessThanEqual(nearest.add(c.tolerance))),
641
+ () => {
642
+ const coverage = max2(c.orm.a, 1e-10), w = c.base.a.mul(c.weight);
643
+ weights.addAssign(c.weight.mul(coverage));
644
+ support.assign(max2(support, coverage));
645
+ colors.addAssign(c.base.rgb.div(coverage).mul(w));
646
+ orms.addAssign(c.orm.rgb.div(coverage).mul(w));
647
+ emissions.addAssign(
648
+ texture2(maps.emissive, c.uv).level(0).rgb.div(coverage).mul(w)
649
+ );
650
+ normals.addAssign(readNormal(c.uv, c.right, c.up, c.n).mul(w));
651
+ alpha.addAssign(w);
652
+ }
653
+ );
654
+ }
655
+ const divisor = max2(alpha, 1e-10);
656
+ return Surface(
657
+ colors.div(divisor),
658
+ alpha.div(max2(weights, 1e-10)).mul(support),
659
+ orms.div(divisor),
660
+ emissions.div(divisor),
661
+ normals.div(max2(normals.length(), 1e-10)),
662
+ positions
663
+ );
664
+ })().toVar("boxProjectedSurface");
665
+ material.capturedPositionNode = surface.get("position");
666
+ material.colorNode = surface.get("color");
667
+ material.normalNode = transformNormalToView2(surface.get("normal"));
668
+ material.roughnessNode = surface.get("orm").g;
669
+ material.metalnessNode = surface.get("orm").b;
670
+ material.aoNode = surface.get("orm").r;
671
+ material.emissiveNode = surface.get("emission");
672
+ material.maskNode = surface.get("alpha").greaterThanEqual(transparency === "cutout" ? alphaCutoff : float2(1 / 255));
673
+ material.maskShadowNode = material.maskNode;
674
+ if (transparency !== "cutout") material.opacityNode = surface.get("alpha");
675
+ material.depthNode = capturedSurfaceDepth(surface.get("position"));
676
+ material.receivedShadowPositionNode = modelWorldMatrix2.mul(
677
+ vec43(surface.get("position"), 1)
678
+ ).xyz;
679
+ material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
680
+ return material;
681
+ }
682
+
683
+ // src/box-impostor/box-impostor-material.js
684
+ function createBoxImpostorMaterial(descriptor, maps) {
685
+ return createBoxImpostorMaterialVariant(descriptor, maps, { filtering: true });
686
+ }
687
+ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false } = {}) {
688
+ const settings = normalizeBoxImpostorDisplay(descriptor);
689
+ const alphaCutoff = uniform(settings.alphaCutoff);
690
+ const transparency = boxTransparency(descriptor, settings);
691
+ const minimumAlpha = transparency === "cutout" ? alphaCutoff : float3(1 / 255);
692
+ const surfaceCoverage = (ormAlpha, baseAlpha) => filtering && descriptor.alphaMode !== "blend" ? min(ormAlpha, baseAlpha) : ormAlpha;
693
+ const decodeNormal = (encoded) => {
694
+ const packed = encoded.mul(2).sub(1);
695
+ const normal2 = vec33(packed, float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))).toVar();
696
+ If3(normal2.z.lessThan(0), () => {
697
+ normal2.xy.assign(vec23(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20))));
698
+ });
699
+ return normal2.normalize();
700
+ };
701
+ const filteredNormal = (uv2, depth, tolerance, nearest, alpha, sampled = texture3(maps.normalDepth, uv2).level(0), ormAlpha = texture3(maps.orm, uv2).level(0).a) => {
702
+ sampled = sampled.toVar();
703
+ const coverage2 = max3(descriptor.alphaMode === "blend" ? ormAlpha : alpha, 1e-10);
704
+ const nearestNormal = decodeNormal(nearest.rg), result = decodeNormal(sampled.rg.div(coverage2)).toVar();
705
+ const sampledDepth = sampled.b.mul(65280).add(sampled.a.mul(255)).div(65535);
706
+ const nearestDepth = nearest.b.mul(65280).add(nearest.a.mul(255)).div(65535);
707
+ If3(nearestNormal.z.lessThan(0).or(dot3(result, nearestNormal).lessThan(0.75)).or(coverage2.lessThan(0.9999)).or(abs3(sampledDepth.sub(nearestDepth)).greaterThan(tolerance)), () => {
708
+ const p = uv2.mul(descriptor.atlasResolution).sub(0.5), lo = floor(p), f = fract(p);
709
+ const normal2 = vec33(0).toVar(), weights = float3(0).toVar();
710
+ for (const [x, y] of [[0, 0], [1, 0], [0, 1], [1, 1]]) {
711
+ const texel = ivec23(lo.add(vec23(x, y)).clamp(0, descriptor.atlasResolution - 1));
712
+ const packed = textureLoad3(maps.normalDepth, texel).toVar();
713
+ const alpha2 = textureLoad3(maps.baseColor, texel).a;
714
+ const coverage3 = descriptor.alphaMode === "blend" ? textureLoad3(maps.orm, texel).a : alpha2;
715
+ const capturedDepth = packed.b.mul(65280).add(packed.a.mul(255)).div(65535);
716
+ const supported = coverage3.greaterThan(1e-4).and(alpha2.greaterThanEqual(minimumAlpha.mul(coverage3))).and(abs3(capturedDepth.sub(depth)).lessThanEqual(tolerance));
717
+ If3(supported, () => {
718
+ const weight = (x ? f.x : float3(1).sub(f.x)).mul(y ? f.y : float3(1).sub(f.y)).mul(coverage3);
719
+ normal2.addAssign(decodeNormal(packed.rg.div(max3(coverage3, 1e-10))).mul(weight));
720
+ weights.addAssign(weight);
721
+ });
722
+ }
723
+ result.assign(weights.greaterThan(1e-10).select(normal2.normalize(), nearestNormal));
724
+ });
725
+ return result;
726
+ };
727
+ for (const map of Object.values(maps)) {
728
+ if (map.minFilter !== LinearFilter || map.magFilter !== LinearFilter) {
729
+ map.minFilter = map.magFilter = LinearFilter;
730
+ map.generateMipmaps = false;
731
+ map.needsUpdate = true;
732
+ }
733
+ }
734
+ const material = new CapturedSurfaceMaterial({
735
+ name: "Box impostor",
736
+ side: descriptor.mode !== "fitted" ? DoubleSide : BackSide,
737
+ alphaHash: transparency === "dithered",
738
+ transparent: transparency === "blended",
739
+ depthWrite: transparency !== "blended",
740
+ forceSinglePass: true
741
+ });
742
+ const rectData = new Float32Array(descriptor.boxes.length * 6 * 4);
743
+ descriptor.boxes.forEach(
744
+ (b, i) => b.views.forEach(
745
+ (r, j) => rectData.set(
746
+ [
747
+ (r[0] + descriptor.padding) / descriptor.atlasResolution,
748
+ (r[1] + descriptor.padding) / descriptor.atlasResolution,
749
+ (r[2] - 2 * descriptor.padding) / descriptor.atlasResolution,
750
+ (r[3] - 2 * descriptor.padding) / descriptor.atlasResolution
751
+ ],
752
+ (i * 6 + j) * 4
753
+ )
754
+ )
755
+ );
756
+ const rects = new DataTexture3(
757
+ rectData,
758
+ 6,
759
+ descriptor.boxes.length,
760
+ RGBAFormat3,
761
+ FloatType3
762
+ );
763
+ rects.needsUpdate = true;
764
+ rects.magFilter = rects.minFilter = NearestFilter3;
765
+ material.addEventListener("dispose", () => rects.dispose());
766
+ const center = attribute3("boxCenter", "vec3"), half = attribute3("boxHalfSize", "vec3");
767
+ const ax = attribute3("boxAxisX", "vec3"), ay = attribute3("boxAxisY", "vec3"), az = attribute3("boxAxisZ", "vec3");
768
+ const toBox = (p) => vec33(dot3(p, ax), dot3(p, ay), dot3(p, az));
769
+ const fromBox = (p) => ax.mul(p.x).add(ay.mul(p.y)).add(az.mul(p.z));
770
+ const eye = modelWorldMatrixInverse.mul(vec44(cameraPosition, 1)).xyz;
771
+ const viewAxis = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec44(0, 0, 1, 0))).xyz.normalize();
772
+ const perspective = cameraProjectionMatrix2.element(3).w.equal(0);
773
+ let proxy = positionLocal2;
774
+ if (descriptor.mode !== "fitted") {
775
+ proxy = Fn4((_, builder) => {
776
+ const delta = eye.sub(center);
777
+ const forward = perspective.and(delta.length().greaterThan(1e-6)).select(normalize2(delta), viewAxis);
778
+ const right = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec44(0, 1, 0, 0))).xyz.cross(forward).normalize();
779
+ const up = forward.cross(right).normalize();
780
+ const radius = half.length();
781
+ const distance = dot3(eye.sub(center), forward);
782
+ const planeOffset = perspective.select(min(radius, distance.sub(cameraNear2.mul(2))), radius);
783
+ const plane = center.add(forward.mul(planeOffset));
784
+ const lo = vec23(1e20).toVar(), hi = vec23(-1e20).toVar();
785
+ for (const x of [-1, 1])
786
+ for (const y of [-1, 1])
787
+ for (const z of [-1, 1]) {
788
+ const corner2 = fromBox(half.mul(vec33(x, y, z)));
789
+ const scale = perspective.select(
790
+ max3(distance.sub(planeOffset), 1e-5).div(
791
+ max3(distance.sub(dot3(corner2, forward)), 1e-5)
792
+ ),
793
+ float3(1)
794
+ );
795
+ const p = vec23(dot3(corner2, right), dot3(corner2, up)).mul(scale);
796
+ lo.assign(min(lo, p));
797
+ hi.assign(max3(hi, p));
798
+ }
799
+ const corner = attribute3("cardCorner", "vec2").add(1).mul(0.5);
800
+ const xy = lo.add(hi.sub(lo).mul(corner));
801
+ return plane.add(right.mul(xy.x)).add(up.mul(xy.y));
802
+ })();
803
+ material.positionNode = proxy;
804
+ material.castShadowPositionNode = proxy;
805
+ }
806
+ const raster = varying(proxy, "boxRasterPosition");
807
+ if (boxDepthMode(descriptor, settings) === "projection" && descriptor.mode === "fitted" && settings.interpolation === "none") {
808
+ material.side = FrontSide;
809
+ return applyBoxFaces({
810
+ material,
811
+ descriptor,
812
+ maps,
813
+ alphaCutoff,
814
+ transparency,
815
+ half,
816
+ toBox,
817
+ fromBox
818
+ });
819
+ }
820
+ if (boxDepthMode(descriptor, settings) === "projection")
821
+ return applyBoxProjection({
822
+ material,
823
+ descriptor,
824
+ maps,
825
+ settings,
826
+ transparency,
827
+ alphaCutoff,
828
+ rects,
829
+ center,
830
+ half,
831
+ toBox,
832
+ fromBox,
833
+ eye,
834
+ viewAxis,
835
+ perspective,
836
+ raster
837
+ });
838
+ const accelerated = descriptor.boxes.every((b) => b.depthBounds);
839
+ const gridSize = BOX_OCCUPANCY_RESOLUTION;
840
+ let occupancy;
841
+ if (descriptor.boxes.every((b) => b.occupancy) && descriptor.boxes.some(
842
+ (b) => b.occupancy.some((word) => word !== 4294967295)
843
+ )) {
844
+ const wordsPerBox = gridSize ** 3 / 32;
845
+ const words = new Uint32Array(wordsPerBox * descriptor.boxes.length);
846
+ descriptor.boxes.forEach(
847
+ (box, index) => words.set(box.occupancy, index * wordsPerBox)
848
+ );
849
+ occupancy = new DataTexture3(
850
+ words,
851
+ wordsPerBox,
852
+ descriptor.boxes.length,
853
+ RedIntegerFormat,
854
+ UnsignedIntType
855
+ );
856
+ occupancy.needsUpdate = true;
857
+ material.addEventListener("dispose", () => occupancy.dispose());
858
+ }
859
+ const Result = struct2(
860
+ { uv: "vec2", position: "vec3", normal: "vec3", valid: "float" },
861
+ "BoxImpostorHit"
862
+ );
863
+ const raycast = Fn4((_, builder) => {
864
+ const ray = perspective.select(
865
+ normalize2(raster.sub(eye)),
866
+ viewAxis.negate()
867
+ );
868
+ const origin = perspective.select(
869
+ eye,
870
+ raster.sub(ray.mul(half.length().mul(4)))
871
+ );
872
+ const o = toBox(origin.sub(center)).div(half), r = toBox(ray).div(half);
873
+ const safe = sign3(r.add(1e-20)).mul(max3(abs3(r), 1e-10));
874
+ const a = vec33(-1).sub(o).div(safe), b = vec33(1).sub(o).div(safe);
875
+ const enter = max3(max3(min(a, b).x, min(a, b).y), min(a, b).z).max(0);
876
+ const exit = min(min(max3(a, b).x, max3(a, b).y), max3(a, b).z);
877
+ const occupiedStart = enter.toVar();
878
+ if (occupancy) {
879
+ const gridOrigin = o.add(1).mul(gridSize / 2);
880
+ const gridRay = r.mul(gridSize / 2);
881
+ const step = sign3(gridRay.add(1e-20));
882
+ const cell = floor(gridOrigin.add(gridRay.mul(enter))).clamp(0, gridSize - 1).toVar();
883
+ const inverse = vec33(1).div(safe.mul(gridSize / 2));
884
+ const delta = abs3(inverse);
885
+ const next = cell.add(step.add(1).mul(0.5)).sub(gridOrigin).mul(inverse).toVar();
886
+ const t = enter.toVar();
887
+ occupiedStart.assign(exit.add(1));
888
+ Loop(gridSize * 3 + 1, () => {
889
+ If3(t.greaterThan(exit), () => {
890
+ Break();
891
+ });
892
+ const cellIndex = uint(
893
+ cell.x.add(cell.y.mul(gridSize)).add(cell.z.mul(gridSize ** 2))
894
+ ).toVar();
895
+ const word = textureLoad3(
896
+ occupancy,
897
+ ivec23(int3(cellIndex.shiftRight(5)), int3(attribute3("boxId", "float")))
898
+ ).r;
899
+ const support = word.shiftRight(cellIndex.bitAnd(31)).bitAnd(1);
900
+ If3(support.notEqual(uint(0)), () => {
901
+ occupiedStart.assign(t);
902
+ Break();
903
+ });
904
+ const edge = min(min(next.x, next.y), next.z).toVar();
905
+ const advance = vec33(
906
+ next.x.lessThanEqual(edge).select(1, 0),
907
+ next.y.lessThanEqual(edge).select(1, 0),
908
+ next.z.lessThanEqual(edge).select(1, 0)
909
+ );
910
+ cell.addAssign(advance.mul(step));
911
+ next.addAssign(advance.mul(delta));
912
+ t.assign(edge);
913
+ If3(
914
+ cell.x.lessThan(0).or(cell.x.greaterThan(gridSize - 1)).or(cell.y.lessThan(0)).or(cell.y.greaterThan(gridSize - 1)).or(cell.z.lessThan(0)).or(cell.z.greaterThan(gridSize - 1)),
915
+ () => {
916
+ Break();
917
+ }
918
+ );
919
+ });
920
+ }
921
+ const look = toBox(ray).negate();
922
+ const bestT = exit.add(1).toVar(), bestUv = vec23(0).toVar(), bestNormal = vec33(0, 0, 1).toVar(), valid = float3(0).toVar(), found = float3(0).toVar();
923
+ const angles = abs3(look).toVar();
924
+ const major = angles.x.greaterThanEqual(angles.y).and(angles.x.greaterThanEqual(angles.z)).select(
925
+ int3(0),
926
+ angles.y.greaterThanEqual(angles.z).select(int3(1), int3(2))
927
+ ).toVar();
928
+ const nextAxis = major.add(1).mod(3), lastAxis = major.add(2).mod(3);
929
+ const second = angles.element(nextAxis).greaterThanEqual(angles.element(lastAxis)).select(nextAxis, lastAxis).toVar();
930
+ const third = int3(3).sub(major).sub(second).toVar();
931
+ Loop(
932
+ { start: 0, end: 6, type: "int", name: "viewIndex" },
933
+ ({ viewIndex: i }) => {
934
+ If3(occupiedStart.greaterThan(exit), () => {
935
+ Break();
936
+ });
937
+ valid.assign(0);
938
+ const rank = i.mod(3);
939
+ const axis = rank.equal(0).select(major, rank.equal(1).select(second, third)).toVar();
940
+ const positive = i.lessThan(3).select(
941
+ look.element(axis).greaterThanEqual(0),
942
+ look.element(axis).lessThan(0)
943
+ );
944
+ const face = axis.mul(2).add(positive.select(int3(0), int3(1)));
945
+ const facing = positive.select(1, -1);
946
+ const n = vec33(
947
+ axis.equal(0).select(facing, 0),
948
+ axis.equal(1).select(facing, 0),
949
+ axis.equal(2).select(facing, 0)
950
+ ).toVar();
951
+ const right = axis.equal(0).select(
952
+ vec33(0, 0, facing.negate()),
953
+ axis.equal(1).select(vec33(1, 0, 0), vec33(facing, 0, 0))
954
+ ).toVar();
955
+ const up = axis.equal(1).select(vec33(0, 0, facing.negate()), vec33(0, 1, 0)).toVar();
956
+ const direction = i.lessThan(3).select(1, -1);
957
+ const rect = textureLoad3(
958
+ rects,
959
+ ivec23(face, int3(attribute3("boxId", "float")))
960
+ ).toVar();
961
+ const sampleUv = (p) => rect.xy.add(
962
+ vec23(dot3(p, right), dot3(p, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
963
+ );
964
+ const decode = (d) => d.b.mul(65280).add(d.a.mul(255)).div(65535);
965
+ const depthAt = (uv2) => decode(texture3(maps.normalDepth, uv2).level(0));
966
+ const distance = (t) => {
967
+ const p = o.add(r.mul(t));
968
+ return dot3(p, n).sub(float3(1).sub(depthAt(sampleUv(p)).mul(2))).mul(direction);
969
+ };
970
+ const acceptHit = (hitT) => {
971
+ const point2 = o.add(r.mul(hitT)), uv2 = sampleUv(point2);
972
+ const texel = ivec23(uv2.mul(descriptor.atlasResolution));
973
+ const nearest = textureLoad3(maps.normalDepth, texel);
974
+ const capturedBase = texture3(maps.baseColor, uv2).level(0);
975
+ const occupied = textureLoad3(maps.orm, texel).a.greaterThan(0.5);
976
+ const residual = abs3(
977
+ dot3(point2, n).sub(float3(1).sub(decode(nearest).mul(2)))
978
+ );
979
+ const tolerance = max3(
980
+ dot3(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
981
+ dot3(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
982
+ ).div(dot3(abs3(n), half)).mul(4).add(4 / 65535);
983
+ If3(
984
+ residual.lessThanEqual(tolerance).and(occupied).and(
985
+ capturedBase.a.greaterThanEqual(minimumAlpha)
986
+ ),
987
+ () => {
988
+ valid.assign(1);
989
+ If3(hitT.lessThan(bestT), () => {
990
+ bestT.assign(hitT);
991
+ bestUv.assign(uv2);
992
+ found.assign(1);
993
+ const packed = texture3(maps.normalDepth, uv2).level(0).rg.div(max3(surfaceCoverage(texture3(maps.orm, uv2).level(0).a, capturedBase.a), 1e-10)).mul(2).sub(1);
994
+ const normal2 = vec33(
995
+ packed.x,
996
+ packed.y,
997
+ float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))
998
+ ).toVar();
999
+ If3(normal2.z.lessThan(0), () => {
1000
+ normal2.xy.assign(
1001
+ vec23(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20)))
1002
+ );
1003
+ });
1004
+ bestNormal.assign(
1005
+ fromBox(
1006
+ right.mul(normal2.x).add(up.mul(normal2.y)).add(n.mul(normal2.z))
1007
+ ).normalize()
1008
+ );
1009
+ bestNormal.mulAssign(
1010
+ dot3(bestNormal, ray).greaterThan(0).select(-1, 1)
1011
+ );
1012
+ });
1013
+ }
1014
+ );
1015
+ };
1016
+ const traceInterval = (start, end, steps) => {
1017
+ const footprint = vec23(dot3(r, right), dot3(r, up)).abs().mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
1018
+ const samples = max3(float3(steps), max3(footprint.x, footprint.y).mul(steps / 8)).div(2).ceil().mul(2).toVar();
1019
+ const step = end.sub(start).div(samples);
1020
+ const previous = start.toVar(), previousD = distance(start).toVar();
1021
+ If3(previousD.lessThanEqual(0), () => {
1022
+ acceptHit(start);
1023
+ });
1024
+ Loop({ start: int3(0), end: int3(samples.div(2)), type: "int" }, ({ i: i2 }) => {
1025
+ If3(valid.greaterThan(0.5), () => {
1026
+ Break();
1027
+ });
1028
+ const samples2 = [1, 2].map((offset) => {
1029
+ const t = start.add(step.mul(float3(i2.mul(2).add(offset)))).toVar();
1030
+ return { t, d: distance(t).toVar() };
1031
+ });
1032
+ for (const { t, d } of samples2) {
1033
+ If3(valid.greaterThan(0.5).or(t.sub(step).greaterThan(bestT)), () => {
1034
+ Break();
1035
+ });
1036
+ If3(valid.lessThan(0.5).and(d.mul(previousD).lessThanEqual(0)), () => {
1037
+ const crossing = refineSurfaceCrossing({ float: float3, If: If3, Loop }, { lo: previous, hi: t, loValue: previousD, hiValue: d, height: distance, steps: 3, secant: true });
1038
+ acceptHit(crossing);
1039
+ If3(bestT.lessThanEqual(t), () => {
1040
+ Break();
1041
+ });
1042
+ });
1043
+ previous.assign(t);
1044
+ previousD.assign(d);
1045
+ }
1046
+ });
1047
+ };
1048
+ If3(
1049
+ exit.greaterThanEqual(enter).and(abs3(look.element(axis)).greaterThan(1e-3)),
1050
+ () => {
1051
+ if (!accelerated) {
1052
+ traceInterval(enter, exit, descriptor.raySteps);
1053
+ } else {
1054
+ const depths = axis.equal(0).select(
1055
+ attribute3("boxDepthX", "vec4"),
1056
+ axis.equal(1).select(
1057
+ attribute3("boxDepthY", "vec4"),
1058
+ attribute3("boxDepthZ", "vec4")
1059
+ )
1060
+ );
1061
+ const interval = positive.select(depths.xy, depths.zw);
1062
+ const initialDepth = float3(1).sub(dot3(o, n)).mul(0.5);
1063
+ const depthSlope = dot3(r, n).negate().mul(0.5);
1064
+ const da = interval.x.sub(2 / 65535).sub(initialDepth).div(depthSlope);
1065
+ const db = interval.y.add(2 / 65535).sub(initialDepth).div(depthSlope);
1066
+ const start = max3(occupiedStart, min(da, db));
1067
+ const end = min(min(exit, bestT), max3(da, db));
1068
+ If3(
1069
+ interval.x.lessThanEqual(interval.y).and(end.greaterThanEqual(start)),
1070
+ () => {
1071
+ const search = () => traceInterval(start, end, descriptor.raySteps);
1072
+ const hasFlatView = descriptor.boxes.some(
1073
+ (box) => [0, 2, 4, 6, 8, 10].some(
1074
+ (i2) => box.depthBounds[i2 + 1] >= box.depthBounds[i2] && box.depthBounds[i2 + 1] - box.depthBounds[i2] <= 1
1075
+ )
1076
+ );
1077
+ if (hasFlatView) {
1078
+ If3(
1079
+ interval.y.sub(interval.x).lessThanEqual(1 / 65535),
1080
+ () => {
1081
+ const t = interval.x.add(interval.y).mul(0.5).sub(initialDepth).div(depthSlope);
1082
+ If3(
1083
+ t.greaterThanEqual(enter).and(t.lessThanEqual(min(exit, bestT))),
1084
+ () => {
1085
+ acceptHit(t);
1086
+ }
1087
+ );
1088
+ }
1089
+ ).Else(search);
1090
+ } else search();
1091
+ }
1092
+ );
1093
+ }
1094
+ }
1095
+ );
1096
+ }
1097
+ );
1098
+ valid.assign(found);
1099
+ const point = o.add(r.mul(bestT));
1100
+ return Result(
1101
+ bestUv,
1102
+ center.add(fromBox(point.mul(half))),
1103
+ bestNormal,
1104
+ valid
1105
+ );
1106
+ });
1107
+ const hit = raycast().toVar("boxHit");
1108
+ hit.toStack();
1109
+ const base = texture3(maps.baseColor, hit.get("uv")).level(0), orm = texture3(maps.orm, hit.get("uv")).level(0);
1110
+ const coverage = max3(surfaceCoverage(orm.a, base.a), 1e-10);
1111
+ let color = base.div(coverage), surfaceOrm = orm.rgb.div(coverage), emission = texture3(maps.emissive, hit.get("uv")).level(0).rgb.div(coverage), normal = hit.get("normal");
1112
+ if (settings.interpolation !== "none") {
1113
+ const fallbackColor = color, fallbackOrm = surfaceOrm, fallbackEmission = emission, fallbackNormal = normal;
1114
+ const Surface = struct2(
1115
+ { color: "vec4", orm: "vec3", emission: "vec3", normal: "vec3" },
1116
+ "BoxSurfaceBlend"
1117
+ );
1118
+ const blended = Fn4(() => {
1119
+ const point = toBox(hit.get("position").sub(center)).div(half);
1120
+ const look = toBox(
1121
+ perspective.select(normalize2(eye.sub(hit.get("position"))), viewAxis)
1122
+ );
1123
+ const colors = vec44(0).toVar(), materials = vec33(0).toVar(), emissions = vec33(0).toVar(), normals = vec33(0).toVar(), weights = float3(0).toVar();
1124
+ for (let axis = 0; axis < 3; axis++) {
1125
+ const positive = look.element(axis).greaterThanEqual(0);
1126
+ const front = BOX_FACE_AXES[axis * 2], back = BOX_FACE_AXES[axis * 2 + 1];
1127
+ const n = positive.select(vec33(...front.normal), vec33(...back.normal));
1128
+ const right = positive.select(
1129
+ vec33(...front.right),
1130
+ vec33(...back.right)
1131
+ );
1132
+ const up = positive.select(vec33(...front.up), vec33(...back.up));
1133
+ const face = positive.select(int3(axis * 2), int3(axis * 2 + 1));
1134
+ const rect = textureLoad3(
1135
+ rects,
1136
+ ivec23(face, int3(attribute3("boxId", "float")))
1137
+ );
1138
+ const uv2 = rect.xy.add(
1139
+ vec23(dot3(point, right), dot3(point, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
1140
+ );
1141
+ const texel = ivec23(uv2.mul(descriptor.atlasResolution));
1142
+ const captured = textureLoad3(maps.normalDepth, texel);
1143
+ const sampled = texture3(maps.baseColor, uv2).level(0);
1144
+ const sampledOrm = texture3(maps.orm, uv2).level(0);
1145
+ const occupied = textureLoad3(maps.orm, texel).a.greaterThan(0.5);
1146
+ const depth = captured.b.mul(65280).add(captured.a.mul(255)).div(65535);
1147
+ const tolerance = max3(
1148
+ dot3(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
1149
+ dot3(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
1150
+ ).div(dot3(abs3(n), half)).mul(4).add(4 / 65535);
1151
+ If3(
1152
+ occupied.and(sampled.a.greaterThanEqual(minimumAlpha)).and(
1153
+ abs3(dot3(point, n).sub(float3(1).sub(depth.mul(2)))).lessThanEqual(
1154
+ tolerance
1155
+ )
1156
+ ),
1157
+ () => {
1158
+ const angle = abs3(look.element(axis));
1159
+ const filtered = filtering ? texture3(maps.normalDepth, uv2).level(0).toVar() : captured;
1160
+ let weight = settings.interpolation === "smooth" ? angle.mul(angle) : angle;
1161
+ if (filtering) {
1162
+ const error = abs3(dot3(point, n).sub(float3(1).sub(
1163
+ filtered.b.mul(65280).add(filtered.a.mul(255)).div(65535).mul(2)
1164
+ )));
1165
+ weight = weight.mul(float3(1).sub(error.div(tolerance)).clamp(0, 1));
1166
+ }
1167
+ const coverage2 = max3(surfaceCoverage(sampledOrm.a, sampled.a), 1e-10);
1168
+ colors.addAssign(sampled.div(coverage2).mul(weight));
1169
+ materials.addAssign(sampledOrm.rgb.div(coverage2).mul(weight));
1170
+ emissions.addAssign(
1171
+ texture3(maps.emissive, uv2).level(0).rgb.div(coverage2).mul(weight)
1172
+ );
1173
+ let shadingNormal;
1174
+ if (filtering) shadingNormal = filteredNormal(uv2, float3(1).sub(dot3(point, n)).mul(0.5), tolerance.mul(0.5), captured, sampled.a, filtered, sampledOrm.a);
1175
+ else {
1176
+ const packed = captured.rg.mul(2).sub(1);
1177
+ const decoded = vec33(
1178
+ packed,
1179
+ float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))
1180
+ ).toVar();
1181
+ If3(decoded.z.lessThan(0), () => {
1182
+ decoded.xy.assign(
1183
+ vec23(1).sub(abs3(decoded.yx)).mul(sign3(decoded.xy.add(1e-20)))
1184
+ );
1185
+ });
1186
+ shadingNormal = decoded;
1187
+ }
1188
+ normals.addAssign(
1189
+ fromBox(
1190
+ right.mul(shadingNormal.x).add(up.mul(shadingNormal.y)).add(n.mul(shadingNormal.z))
1191
+ ).normalize().mul(weight)
1192
+ );
1193
+ weights.addAssign(weight);
1194
+ }
1195
+ );
1196
+ }
1197
+ const divisor = max3(weights, 1e-10), valid = weights.greaterThan(1e-10);
1198
+ return Surface(
1199
+ valid.select(colors.div(divisor), fallbackColor),
1200
+ valid.select(materials.div(divisor), fallbackOrm),
1201
+ valid.select(emissions.div(divisor), fallbackEmission),
1202
+ valid.select(normals.normalize(), fallbackNormal)
1203
+ );
1204
+ })().toVar("boxBlendedSurface");
1205
+ color = blended.get("color");
1206
+ surfaceOrm = blended.get("orm");
1207
+ emission = blended.get("emission");
1208
+ normal = blended.get("normal");
1209
+ }
1210
+ material.capturedPositionNode = hit.get("position");
1211
+ material.colorNode = color.rgb;
1212
+ material.normalNode = transformNormalToView3(normal);
1213
+ material.roughnessNode = surfaceOrm.g;
1214
+ material.metalnessNode = surfaceOrm.b;
1215
+ material.aoNode = surfaceOrm.r;
1216
+ material.emissiveNode = emission;
1217
+ if (transparency !== "cutout") material.opacityNode = color.a.clamp(0, 1);
1218
+ material.maskNode = hit.get("valid").greaterThan(0.5);
1219
+ material.maskShadowNode = material.maskNode;
1220
+ material.depthNode = capturedSurfaceDepth(hit.get("position"));
1221
+ material.receivedShadowPositionNode = modelWorldMatrix3.mul(
1222
+ vec44(hit.get("position"), 1)
1223
+ ).xyz;
1224
+ material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
1225
+ return material;
1226
+ }
1227
+
1228
+ // src/box-impostor/box-impostor-runtime.js
1229
+ import {
1230
+ ClampToEdgeWrapping,
1231
+ LinearFilter as LinearFilter2,
1232
+ NearestFilter as NearestFilter4,
1233
+ NoColorSpace,
1234
+ SRGBColorSpace
1235
+ } from "three";
1236
+
1237
+ // src/rendering/renderer-support.js
1238
+ import * as TSL from "three/tsl";
1239
+ function rendererSupportsImpostorNodeMaterials(renderer) {
1240
+ if (typeof Reflect.get(TSL, "struct") !== "function") return false;
1241
+ return renderer?.isWebGPURenderer === true || renderer?.capabilities?.supportsNodeMaterials === true;
1242
+ }
1243
+ var pending = /* @__PURE__ */ new WeakMap();
1244
+ async function enableRendererNodeMaterials(renderer) {
1245
+ if (rendererSupportsImpostorNodeMaterials(renderer) || !renderer?.isWebGLRenderer || !renderer.setNodesHandler || typeof Reflect.get(TSL, "struct") !== "function") return;
1246
+ let setup = pending.get(renderer);
1247
+ if (!setup) {
1248
+ setup = import("three/addons/tsl/WebGLNodesHandler.js").then(({ WebGLNodesHandler }) => {
1249
+ if (rendererSupportsImpostorNodeMaterials(renderer)) return;
1250
+ renderer.setNodesHandler?.(new WebGLNodesHandler());
1251
+ renderer.capabilities ??= {};
1252
+ renderer.capabilities.supportsNodeMaterials = true;
1253
+ }).catch((error) => {
1254
+ pending.delete(renderer);
1255
+ throw error;
1256
+ });
1257
+ pending.set(renderer, setup);
1258
+ }
1259
+ await setup;
1260
+ }
1261
+
1262
+ // src/box-impostor/box-impostor-runtime.js
1263
+ var NeedleBoxImpostorLoaderPlugin = class {
1264
+ /** @param {import('three/addons/loaders/GLTFLoader.js').GLTFParser} parser
1265
+ * @param {{renderer?:import('../rendering/renderer-support.js').ImpostorRenderer}} [options] */
1266
+ constructor(parser, options = {}) {
1267
+ this.name = NEEDLE_BOX_IMPOSTOR;
1268
+ this.parser = parser;
1269
+ this.options = options;
1270
+ }
1271
+ /** @param {import('three/addons/loaders/GLTFLoader.js').GLTF} result */
1272
+ async afterRoot(result) {
1273
+ await enableRendererNodeMaterials(this.options.renderer);
1274
+ const seen = /* @__PURE__ */ new Set();
1275
+ const geometries = /* @__PURE__ */ new Set();
1276
+ const materials = /* @__PURE__ */ new Set();
1277
+ const scenes = result.scenes ?? [result.scene];
1278
+ const pending2 = (
1279
+ /** @type {Promise<void>[]} */
1280
+ []
1281
+ );
1282
+ for (const scene of scenes)
1283
+ scene?.traverse((object) => {
1284
+ const mesh = (
1285
+ /** @type {import('three').Mesh} */
1286
+ object
1287
+ );
1288
+ if (!mesh.isMesh || seen.has(mesh)) return;
1289
+ seen.add(mesh);
1290
+ const a = (
1291
+ /** @type {{meshes?:number,primitives?:number}|undefined} */
1292
+ this.parser.associations.get(mesh)
1293
+ );
1294
+ if (a?.meshes === void 0 || a.primitives === void 0) return;
1295
+ const raw = this.parser.json.meshes?.[a.meshes]?.primitives[a.primitives]?.extensions?.[NEEDLE_BOX_IMPOSTOR];
1296
+ if (raw === void 0) return;
1297
+ const descriptor = parseBoxImpostorDescriptor(raw);
1298
+ if (!rendererSupportsImpostorNodeMaterials(this.options.renderer)) {
1299
+ if (this.parser.json.extensionsRequired?.includes(NEEDLE_BOX_IMPOSTOR))
1300
+ throw new Error(
1301
+ "NEEDLE_box_impostor requires Three WebGPURenderer or a renderer with compatible node-material support."
1302
+ );
1303
+ mesh.userData.boxImpostorFallback = true;
1304
+ return;
1305
+ }
1306
+ pending2.push(
1307
+ (async () => {
1308
+ const entries = await Promise.all(
1309
+ ["baseColor", "normalDepth", "orm", "emissive"].map(
1310
+ async (role) => {
1311
+ const index = raw.textures?.[role]?.index;
1312
+ if (!Number.isInteger(index) || index < 0)
1313
+ throw new Error(
1314
+ `NEEDLE_box_impostor has no valid ${role} texture.`
1315
+ );
1316
+ const texture4 = await this.parser.getDependency(
1317
+ "texture",
1318
+ index
1319
+ );
1320
+ texture4.colorSpace = role === "baseColor" || role === "emissive" ? SRGBColorSpace : NoColorSpace;
1321
+ texture4.magFilter = texture4.minFilter = role === "normalDepth" ? NearestFilter4 : LinearFilter2;
1322
+ texture4.wrapS = texture4.wrapT = ClampToEdgeWrapping;
1323
+ texture4.generateMipmaps = false;
1324
+ texture4.needsUpdate = true;
1325
+ return [role, texture4];
1326
+ }
1327
+ )
1328
+ );
1329
+ const maps = (
1330
+ /** @type {Parameters<typeof createBoxImpostorMaterial>[1]} */
1331
+ Object.fromEntries(entries)
1332
+ );
1333
+ geometries.add(mesh.geometry);
1334
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material])
1335
+ materials.add(material);
1336
+ mesh.geometry = createBoxImpostorGeometry(descriptor);
1337
+ mesh.material = createBoxImpostorMaterial(descriptor, maps);
1338
+ mesh.userData.boxImpostor = { descriptor, maps };
1339
+ mesh.frustumCulled = descriptor.mode === "fitted";
1340
+ })()
1341
+ );
1342
+ });
1343
+ await Promise.all(pending2);
1344
+ for (const scene of scenes)
1345
+ scene?.traverse((object) => {
1346
+ const mesh = (
1347
+ /** @type {import('three').Mesh} */
1348
+ object
1349
+ );
1350
+ if (!mesh.isMesh) return;
1351
+ geometries.delete(mesh.geometry);
1352
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material])
1353
+ materials.delete(material);
1354
+ });
1355
+ for (const geometry of geometries) geometry.dispose();
1356
+ for (const material of materials) material.dispose();
1357
+ }
1358
+ };
1359
+ function registerNeedleBoxImpostorLoader(loader, options = {}) {
1360
+ loader.register(
1361
+ (parser) => new NeedleBoxImpostorLoaderPlugin(parser, options)
1362
+ );
1363
+ return loader;
1364
+ }
1365
+
1366
+ // src/box-impostor/box-impostor-display.js
1367
+ var variants = /* @__PURE__ */ new WeakMap();
1368
+ function setBoxImpostorDisplay(root, options) {
1369
+ root.traverse((object) => {
1370
+ const mesh = (
1371
+ /** @type {import('three').Mesh} */
1372
+ object
1373
+ );
1374
+ const binding = mesh.userData.boxImpostor;
1375
+ if (!mesh.isMesh || !binding) return;
1376
+ const settings = normalizeBoxImpostorDisplay({ ...binding.descriptor, ...options });
1377
+ const descriptor = { ...binding.descriptor, ...settings };
1378
+ const keyFor = (s) => `${s.depthMode}/${s.depthMode !== "projection" ? s.raySteps : 0}/${s.interpolation}/${s.transparency}`;
1379
+ let cache = variants.get(mesh);
1380
+ if (!cache) {
1381
+ const initial = (
1382
+ /** @type {ReturnType<typeof createBoxImpostorMaterial>} */
1383
+ mesh.material
1384
+ );
1385
+ const materials = /* @__PURE__ */ new Map([[keyFor(normalizeBoxImpostorDisplay(binding.descriptor)), initial]]);
1386
+ const release = (event) => {
1387
+ const owned = [...materials.values()];
1388
+ materials.clear();
1389
+ variants.delete(mesh);
1390
+ for (const material2 of owned) {
1391
+ material2.removeEventListener("dispose", release);
1392
+ if (material2 !== event.target) material2.dispose();
1393
+ }
1394
+ };
1395
+ cache = { materials, release };
1396
+ variants.set(mesh, cache);
1397
+ initial.addEventListener("dispose", release);
1398
+ }
1399
+ const key = keyFor(settings);
1400
+ let material = cache.materials.get(key);
1401
+ if (!material) {
1402
+ material = createBoxImpostorMaterial(descriptor, binding.maps);
1403
+ material.addEventListener("dispose", cache.release);
1404
+ cache.materials.set(key, material);
1405
+ }
1406
+ material.userData.boxImpostor.alphaCutoff.value = settings.alphaCutoff;
1407
+ material.userData.boxImpostor.descriptor = descriptor;
1408
+ mesh.material = material;
1409
+ binding.descriptor = descriptor;
1410
+ });
1411
+ }
1412
+ export {
1413
+ DEFAULT_BOX_IMPOSTOR_DISPLAY,
1414
+ NEEDLE_BOX_IMPOSTOR,
1415
+ NeedleBoxImpostorLoaderPlugin,
1416
+ createBoxImpostorGeometry,
1417
+ createBoxImpostorMaterial,
1418
+ normalizeBoxImpostorDisplay,
1419
+ parseBoxImpostorDescriptor,
1420
+ registerNeedleBoxImpostorLoader,
1421
+ setBoxImpostorDisplay
1422
+ };
1423
+ //# sourceMappingURL=box-impostor-runtime.js.map