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

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