@needle-tools/three-mesh-effects 0.2.2 → 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 (100) hide show
  1. package/CHANGELOG.md +28 -6
  2. package/README.md +76 -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 +85 -31
  7. package/build/deformation-runtime.js.map +4 -4
  8. package/build/hull-effects.js +60 -28
  9. package/build/hull-effects.js.map +3 -3
  10. package/build/impostor-runtime.js +235 -116
  11. package/build/impostor-runtime.js.map +4 -4
  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/fur-surface.js +55 -12
  37. package/build/internal/deformation/fur-surface.js.map +3 -3
  38. package/build/internal/deformation/pin-cloth.js +7 -2
  39. package/build/internal/deformation/pin-cloth.js.map +2 -2
  40. package/build/internal/deformation/rig-runtime.js +85 -31
  41. package/build/internal/deformation/rig-runtime.js.map +4 -4
  42. package/build/internal/impostor/impostor-node-material.js +235 -116
  43. package/build/internal/impostor/impostor-node-material.js.map +4 -4
  44. package/build/internal/rendering/hull-effect-runtime.js +59 -27
  45. package/build/internal/rendering/hull-effect-runtime.js.map +3 -3
  46. package/build/internal/rendering/texture-slot.js +26 -0
  47. package/build/internal/rendering/texture-slot.js.map +7 -0
  48. package/build/internal/rendering/wireframe.js +41 -9
  49. package/build/internal/rendering/wireframe.js.map +2 -2
  50. package/build/internal/rendering/wrap-preview.js +59 -27
  51. package/build/internal/rendering/wrap-preview.js.map +3 -3
  52. package/build/types/box-impostor/box-impostor-display-settings.d.ts +30 -0
  53. package/build/types/box-impostor/box-impostor-display-settings.js +1 -0
  54. package/build/types/box-impostor/box-impostor-display.d.ts +5 -0
  55. package/build/types/box-impostor/box-impostor-display.js +1 -0
  56. package/build/types/box-impostor/box-impostor-face-axes.d.ts +5 -0
  57. package/build/types/box-impostor/box-impostor-face-axes.js +1 -0
  58. package/build/types/box-impostor/box-impostor-faces.d.ts +11 -0
  59. package/build/types/box-impostor/box-impostor-faces.js +1 -0
  60. package/build/types/box-impostor/box-impostor-geometry.d.ts +5 -0
  61. package/build/types/box-impostor/box-impostor-geometry.js +1 -0
  62. package/build/types/box-impostor/box-impostor-material.d.ts +10 -0
  63. package/build/types/box-impostor/box-impostor-material.js +1 -0
  64. package/build/types/box-impostor/box-impostor-metadata.d.ts +31 -0
  65. package/build/types/box-impostor/box-impostor-metadata.js +1 -0
  66. package/build/types/box-impostor/box-impostor-projection.d.ts +19 -0
  67. package/build/types/box-impostor/box-impostor-projection.js +1 -0
  68. package/build/types/box-impostor/box-impostor-runtime.d.ts +25 -0
  69. package/build/types/box-impostor/box-impostor-runtime.js +1 -0
  70. package/build/types/box-impostor/box-impostor-surface-search.d.ts +13 -0
  71. package/build/types/box-impostor/box-impostor-surface-search.js +1 -0
  72. package/build/types/deformation/cloth-surface.d.ts +1 -0
  73. package/build/types/deformation/pin-cloth.d.ts +1 -0
  74. package/build/types/public/box-impostor-runtime.d.ts +6 -0
  75. package/build/types/public/box-impostor-runtime.js +1 -0
  76. package/build/types/public/hull-effects.d.ts +1 -0
  77. package/build/types/public/index.d.ts +1 -1
  78. package/build/types/rendering/texture-slot.d.ts +10 -0
  79. package/build/types/rendering/texture-slot.js +1 -0
  80. package/build/types/rendering/wireframe.d.ts +2 -2
  81. package/package.json +27 -6
  82. package/src/box-impostor/box-impostor-display-settings.js +54 -0
  83. package/src/box-impostor/box-impostor-display.js +38 -0
  84. package/src/box-impostor/box-impostor-face-axes.js +11 -0
  85. package/src/box-impostor/box-impostor-faces.js +118 -0
  86. package/src/box-impostor/box-impostor-geometry.js +140 -0
  87. package/src/box-impostor/box-impostor-material.js +721 -0
  88. package/src/box-impostor/box-impostor-metadata.js +122 -0
  89. package/src/box-impostor/box-impostor-projection.js +287 -0
  90. package/src/box-impostor/box-impostor-runtime.js +122 -0
  91. package/src/box-impostor/box-impostor-surface-search.js +11 -0
  92. package/src/deformation/cloth-surface.ts +28 -17
  93. package/src/deformation/fur-surface.ts +22 -12
  94. package/src/deformation/pin-cloth.ts +9 -3
  95. package/src/impostor/impostor-node-material.js +238 -150
  96. package/src/public/box-impostor-runtime.js +14 -0
  97. package/src/public/hull-effects.js +1 -0
  98. package/src/public/index.js +5 -1
  99. package/src/rendering/texture-slot.js +27 -0
  100. package/src/rendering/wireframe.js +51 -13
@@ -0,0 +1,1005 @@
1
+ // @ts-nocheck
2
+
3
+ // src/box-impostor/box-impostor-material.js
4
+ import {
5
+ DataTexture as DataTexture3,
6
+ FloatType as FloatType3,
7
+ RGBAFormat as RGBAFormat3,
8
+ RedIntegerFormat,
9
+ UnsignedIntType,
10
+ NearestFilter as NearestFilter3,
11
+ LinearFilter,
12
+ MeshStandardNodeMaterial,
13
+ DoubleSide,
14
+ FrontSide
15
+ } from "three/webgpu";
16
+ import {
17
+ Fn as Fn3,
18
+ If as If3,
19
+ Loop,
20
+ Break,
21
+ attribute as attribute3,
22
+ varying,
23
+ positionLocal as positionLocal2,
24
+ modelWorldMatrixInverse,
25
+ cameraPosition,
26
+ cameraWorldMatrix,
27
+ cameraProjectionMatrix,
28
+ vec2 as vec23,
29
+ vec3 as vec33,
30
+ vec4 as vec42,
31
+ float as float3,
32
+ int as int3,
33
+ uint,
34
+ dot as dot3,
35
+ abs as abs3,
36
+ max as max3,
37
+ min,
38
+ sign as sign3,
39
+ texture as texture3,
40
+ textureLoad as textureLoad3,
41
+ ivec2 as ivec23,
42
+ normalize as normalize2,
43
+ floor,
44
+ modelViewMatrix as modelViewMatrix2,
45
+ modelWorldMatrix as modelWorldMatrix2,
46
+ cameraNear as cameraNear2,
47
+ cameraFar as cameraFar2,
48
+ viewZToPerspectiveDepth as viewZToPerspectiveDepth2,
49
+ viewZToOrthographicDepth as viewZToOrthographicDepth2,
50
+ transformNormalToView as transformNormalToView3,
51
+ struct as struct2,
52
+ uniform
53
+ } from "three/tsl";
54
+
55
+ // src/box-impostor/box-impostor-surface-search.js
56
+ function refineSurfaceCrossing({ float: float4, If: If4, Loop: Loop2 }, { lo, hi, loValue, hiValue, height, steps, secant }) {
57
+ const a = lo.toVar(), b = hi.toVar(), fa = loValue.toVar(), fb = secant ? hiValue.toVar() : null;
58
+ Loop2(steps, () => {
59
+ const mid = a.add(b).mul(0.5).toVar(), d = height(mid).toVar();
60
+ If4(d.mul(fa).greaterThan(0), () => {
61
+ a.assign(mid);
62
+ if (secant) fa.assign(d);
63
+ }).Else(() => {
64
+ b.assign(mid);
65
+ if (secant) fb.assign(d);
66
+ });
67
+ });
68
+ 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);
69
+ }
70
+
71
+ // src/box-impostor/box-impostor-faces.js
72
+ import { DataTexture, FloatType, RGBAFormat, NearestFilter } from "three";
73
+ import {
74
+ Fn,
75
+ If,
76
+ attribute,
77
+ positionLocal,
78
+ uv,
79
+ texture,
80
+ textureLoad,
81
+ ivec2,
82
+ vec2,
83
+ vec3,
84
+ float,
85
+ int,
86
+ dot,
87
+ abs,
88
+ max,
89
+ sign,
90
+ transformNormalToView
91
+ } from "three/tsl";
92
+
93
+ // src/box-impostor/box-impostor-display-settings.js
94
+ var DEFAULT_BOX_IMPOSTOR_DISPLAY = Object.freeze({
95
+ depthMode: (
96
+ /** @type {'auto'|'projection'|'depth'} */
97
+ "auto"
98
+ ),
99
+ raySteps: (
100
+ /** @type {8|16|32} */
101
+ 16
102
+ ),
103
+ alphaCutoff: 0.5,
104
+ interpolation: (
105
+ /** @type {'none'|'linear'|'smooth'} */
106
+ "none"
107
+ ),
108
+ transparency: (
109
+ /** @type {'auto'|'cutout'|'dithered'|'blended'} */
110
+ "auto"
111
+ )
112
+ });
113
+ function normalizeBoxImpostorDisplay(input = {}) {
114
+ const value = { ...DEFAULT_BOX_IMPOSTOR_DISPLAY, ...input };
115
+ 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))
116
+ throw new Error("Invalid box impostor display settings.");
117
+ return {
118
+ depthMode: value.depthMode,
119
+ raySteps: value.raySteps,
120
+ alphaCutoff: value.alphaCutoff,
121
+ interpolation: value.interpolation,
122
+ transparency: value.transparency
123
+ };
124
+ }
125
+ function boxTransparency(descriptor, settings) {
126
+ return settings.transparency === "auto" ? descriptor.alphaMode === "blend" ? "blended" : "cutout" : settings.transparency;
127
+ }
128
+ function boxDepthMode(descriptor, settings) {
129
+ if (settings.depthMode !== "auto") return settings.depthMode;
130
+ return descriptor.boxes.every(
131
+ (box) => box.planes?.length === 6 && box.planeErrors?.length === 6 && box.planeErrors.every((error) => error <= 2 / 255)
132
+ ) ? "projection" : "depth";
133
+ }
134
+
135
+ // src/box-impostor/box-impostor-face-axes.js
136
+ var BOX_FACE_AXES = Object.freeze([
137
+ { normal: [1, 0, 0], right: [0, 0, -1], up: [0, 1, 0] },
138
+ { normal: [-1, 0, 0], right: [0, 0, 1], up: [0, 1, 0] },
139
+ { normal: [0, 1, 0], right: [1, 0, 0], up: [0, 0, -1] },
140
+ { normal: [0, -1, 0], right: [1, 0, 0], up: [0, 0, 1] },
141
+ { normal: [0, 0, 1], right: [1, 0, 0], up: [0, 1, 0] },
142
+ { normal: [0, 0, -1], right: [-1, 0, 0], up: [0, 1, 0] }
143
+ ]);
144
+
145
+ // src/box-impostor/box-impostor-metadata.js
146
+ var BOX_OCCUPANCY_RESOLUTION = 8;
147
+ var BOX_OCCUPANCY_WORDS = BOX_OCCUPANCY_RESOLUTION ** 3 / 32;
148
+
149
+ // src/box-impostor/box-impostor-faces.js
150
+ function applyBoxFaces({
151
+ material,
152
+ descriptor,
153
+ maps,
154
+ alphaCutoff,
155
+ transparency,
156
+ half,
157
+ toBox,
158
+ fromBox
159
+ }) {
160
+ const values = new Float32Array(descriptor.boxes.length * 6 * 4);
161
+ descriptor.boxes.forEach((box, i) => {
162
+ for (let face2 = 0; face2 < 6; face2++)
163
+ values[(i * 6 + face2) * 4] = box.planes?.[face2] ?? 0.5;
164
+ });
165
+ const planes = new DataTexture(
166
+ values,
167
+ 6,
168
+ descriptor.boxes.length,
169
+ RGBAFormat,
170
+ FloatType
171
+ );
172
+ planes.minFilter = planes.magFilter = NearestFilter;
173
+ planes.needsUpdate = true;
174
+ material.addEventListener("dispose", () => planes.dispose());
175
+ const face = int(attribute("boxFace", "float"));
176
+ const n = attribute("normal", "vec3");
177
+ const depth = textureLoad(
178
+ planes,
179
+ ivec2(face, int(attribute("boxId", "float")))
180
+ ).r;
181
+ const proxy = positionLocal.sub(
182
+ n.mul(
183
+ dot(abs(toBox(n)), half).mul(depth).mul(2)
184
+ )
185
+ );
186
+ material.positionNode = proxy;
187
+ material.castShadowPositionNode = proxy;
188
+ const base = texture(maps.baseColor, uv()).level(0).toVar("boxFaceColor");
189
+ const orm = texture(maps.orm, uv()).level(0);
190
+ const coverage = max(orm.a, 1e-10);
191
+ const normal = Fn(() => {
192
+ const packed = textureLoad(
193
+ maps.normalDepth,
194
+ ivec2(uv().mul(descriptor.atlasResolution))
195
+ ).rg.mul(2).sub(1);
196
+ const decoded = vec3(
197
+ packed,
198
+ float(1).sub(abs(packed.x)).sub(abs(packed.y))
199
+ ).toVar();
200
+ If(decoded.z.lessThan(0), () => {
201
+ decoded.xy.assign(
202
+ vec2(1).sub(abs(decoded.yx)).mul(sign(decoded.xy.add(1e-20)))
203
+ );
204
+ });
205
+ const result = vec3(0).toVar();
206
+ for (let f = 0; f < 6; f++) {
207
+ const a = BOX_FACE_AXES[f];
208
+ If(face.equal(f), () => {
209
+ result.assign(
210
+ fromBox(
211
+ vec3(...a.right).mul(decoded.x).add(vec3(...a.up).mul(decoded.y)).add(vec3(...a.normal).mul(decoded.z))
212
+ ).normalize()
213
+ );
214
+ });
215
+ }
216
+ return result;
217
+ })();
218
+ material.colorNode = base.rgb.div(coverage);
219
+ material.normalNode = transformNormalToView(normal);
220
+ material.roughnessNode = orm.g.div(coverage);
221
+ material.metalnessNode = orm.b.div(coverage);
222
+ material.aoNode = orm.r.div(coverage);
223
+ material.emissiveNode = texture(maps.emissive, uv()).level(0).rgb.div(coverage);
224
+ material.maskNode = base.a.greaterThanEqual(
225
+ transparency === "cutout" ? alphaCutoff : float(1 / 255)
226
+ );
227
+ material.maskShadowNode = material.maskNode;
228
+ if (transparency !== "cutout") material.opacityNode = base.a;
229
+ material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
230
+ return material;
231
+ }
232
+
233
+ // src/box-impostor/box-impostor-projection.js
234
+ import { DataTexture as DataTexture2, FloatType as FloatType2, RGBAFormat as RGBAFormat2, NearestFilter as NearestFilter2 } from "three";
235
+ import {
236
+ Fn as Fn2,
237
+ If as If2,
238
+ vec2 as vec22,
239
+ vec3 as vec32,
240
+ vec4,
241
+ float as float2,
242
+ int as int2,
243
+ ivec2 as ivec22,
244
+ dot as dot2,
245
+ abs as abs2,
246
+ max as max2,
247
+ sign as sign2,
248
+ normalize,
249
+ texture as texture2,
250
+ textureLoad as textureLoad2,
251
+ attribute as attribute2,
252
+ struct,
253
+ modelViewMatrix,
254
+ modelWorldMatrix,
255
+ cameraNear,
256
+ cameraFar,
257
+ viewZToPerspectiveDepth,
258
+ viewZToOrthographicDepth,
259
+ transformNormalToView as transformNormalToView2
260
+ } from "three/tsl";
261
+ function applyBoxProjection({
262
+ material,
263
+ descriptor,
264
+ maps,
265
+ settings,
266
+ transparency,
267
+ alphaCutoff,
268
+ rects,
269
+ center,
270
+ half,
271
+ toBox,
272
+ fromBox,
273
+ eye,
274
+ viewAxis,
275
+ perspective,
276
+ raster
277
+ }) {
278
+ const data = new Float32Array(descriptor.boxes.length * 24);
279
+ descriptor.boxes.forEach((box, i) => {
280
+ for (let face = 0; face < 6; face++)
281
+ data[(i * 6 + face) * 4] = box.planes?.[face] ?? 0.5;
282
+ });
283
+ const planes = new DataTexture2(
284
+ data,
285
+ 6,
286
+ descriptor.boxes.length,
287
+ RGBAFormat2,
288
+ FloatType2
289
+ );
290
+ planes.minFilter = planes.magFilter = NearestFilter2;
291
+ planes.needsUpdate = true;
292
+ material.addEventListener("dispose", () => planes.dispose());
293
+ const Surface = struct(
294
+ {
295
+ color: "vec3",
296
+ alpha: "float",
297
+ orm: "vec3",
298
+ emission: "vec3",
299
+ normal: "vec3",
300
+ position: "vec3"
301
+ },
302
+ "BoxProjectedSurface"
303
+ );
304
+ const readNormal = (uv2, right, up, n) => {
305
+ const packed = textureLoad2(
306
+ maps.normalDepth,
307
+ ivec22(uv2.mul(descriptor.atlasResolution))
308
+ ).rg.mul(2).sub(1);
309
+ const decoded = vec32(
310
+ packed,
311
+ float2(1).sub(abs2(packed.x)).sub(abs2(packed.y))
312
+ ).toVar();
313
+ If2(decoded.z.lessThan(0), () => {
314
+ decoded.xy.assign(
315
+ vec22(1).sub(abs2(decoded.yx)).mul(sign2(decoded.xy.add(1e-20)))
316
+ );
317
+ });
318
+ return fromBox(
319
+ right.mul(decoded.x).add(up.mul(decoded.y)).add(n.mul(decoded.z))
320
+ ).normalize();
321
+ };
322
+ const surface = Fn2(() => {
323
+ const ray = perspective.select(
324
+ normalize(raster.sub(eye)),
325
+ viewAxis.negate()
326
+ );
327
+ const origin = perspective.select(
328
+ eye,
329
+ raster.sub(ray.mul(half.length().mul(4)))
330
+ );
331
+ const o = toBox(origin.sub(center)).div(half), r = toBox(ray).div(half);
332
+ const look = normalize(toBox(ray).negate()), angles = abs2(look);
333
+ const positions = vec32(0).toVar();
334
+ const selectedUv = vec22(0).toVar(), selectedRight = vec32(1, 0, 0).toVar(), selectedUp = vec32(0, 1, 0).toVar(), selectedNormal = vec32(0, 0, 1).toVar();
335
+ const nearest = float2(1e20).toVar("boxPlaneDistance");
336
+ const opacity = float2(0).toVar();
337
+ const candidates = [];
338
+ for (let axis = 0; axis < 3; axis++) {
339
+ const angle = angles.element(axis);
340
+ const positive = look.element(axis).greaterThanEqual(0), a = BOX_FACE_AXES[axis * 2], b = BOX_FACE_AXES[axis * 2 + 1];
341
+ 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));
342
+ const weight = settings.interpolation === "smooth" ? angle.mul(angle) : angle;
343
+ const candidate = settings.interpolation === "none" ? null : {
344
+ uv: vec22(0).toVar(),
345
+ base: vec4(0).toVar(),
346
+ orm: vec4(0).toVar(),
347
+ t: float2(1e20).toVar(),
348
+ tolerance: float2(0).toVar(),
349
+ right,
350
+ up,
351
+ n,
352
+ weight
353
+ };
354
+ if (candidate) candidates.push(candidate);
355
+ If2(angle.greaterThan(1e-4), () => {
356
+ const face = positive.select(int2(axis * 2), int2(axis * 2 + 1)), id = int2(attribute2("boxId", "float"));
357
+ const plane = float2(1).sub(
358
+ textureLoad2(planes, ivec22(face, id)).r.mul(2)
359
+ );
360
+ const divisor2 = dot2(r, n), safe = sign2(divisor2.add(1e-20)).mul(max2(abs2(divisor2), 1e-10));
361
+ const t = plane.sub(dot2(o, n)).div(safe), point = o.add(r.mul(t));
362
+ const xy = vec22(dot2(point, right), dot2(point, up)).mul(0.5).add(0.5);
363
+ 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));
364
+ if (!candidate) supported = supported.and(t.lessThan(nearest));
365
+ If2(supported, () => {
366
+ const rect = textureLoad2(rects, ivec22(face, id)), uv2 = rect.xy.add(xy.mul(rect.zw));
367
+ const base = texture2(maps.baseColor, uv2).level(0), orm = texture2(maps.orm, uv2).level(0);
368
+ const alpha2 = base.a.clamp(0, 1);
369
+ If2(
370
+ alpha2.greaterThanEqual(
371
+ transparency === "cutout" ? alphaCutoff : float2(1 / 255)
372
+ ).and(orm.a.greaterThan(0)),
373
+ () => {
374
+ If2(t.lessThan(nearest), () => {
375
+ nearest.assign(t);
376
+ selectedUv.assign(uv2);
377
+ opacity.assign(alpha2);
378
+ selectedRight.assign(right);
379
+ selectedUp.assign(up);
380
+ selectedNormal.assign(n);
381
+ positions.assign(center.add(fromBox(point.mul(half))));
382
+ });
383
+ if (candidate) {
384
+ candidate.uv.assign(uv2);
385
+ candidate.base.assign(base);
386
+ candidate.orm.assign(orm);
387
+ candidate.t.assign(t);
388
+ candidate.tolerance.assign(
389
+ max2(
390
+ dot2(abs2(right), half).div(
391
+ rect.z.mul(descriptor.atlasResolution)
392
+ ),
393
+ dot2(abs2(up), half).div(
394
+ rect.w.mul(descriptor.atlasResolution)
395
+ )
396
+ ).mul(4).div(max2(angle, 0.1))
397
+ );
398
+ }
399
+ }
400
+ );
401
+ });
402
+ });
403
+ }
404
+ if (settings.interpolation === "none") {
405
+ const base = texture2(maps.baseColor, selectedUv).level(0), orm = texture2(maps.orm, selectedUv).level(0);
406
+ const coverage = max2(orm.a, 1e-10);
407
+ return Surface(
408
+ base.rgb.div(coverage),
409
+ opacity,
410
+ orm.rgb.div(coverage),
411
+ texture2(maps.emissive, selectedUv).level(0).rgb.div(coverage),
412
+ readNormal(selectedUv, selectedRight, selectedUp, selectedNormal),
413
+ positions
414
+ );
415
+ }
416
+ const colors = vec32(0).toVar(), orms = vec32(0).toVar(), emissions = vec32(0).toVar(), normals = vec32(0).toVar();
417
+ const weights = float2(0).toVar(), support = float2(0).toVar(), alpha = float2(0).toVar();
418
+ for (const c of candidates) {
419
+ If2(
420
+ c.base.a.greaterThan(0).and(c.t.lessThanEqual(nearest.add(c.tolerance))),
421
+ () => {
422
+ const coverage = max2(c.orm.a, 1e-10), w = c.base.a.mul(c.weight);
423
+ weights.addAssign(c.weight.mul(coverage));
424
+ support.assign(max2(support, coverage));
425
+ colors.addAssign(c.base.rgb.div(coverage).mul(w));
426
+ orms.addAssign(c.orm.rgb.div(coverage).mul(w));
427
+ emissions.addAssign(
428
+ texture2(maps.emissive, c.uv).level(0).rgb.div(coverage).mul(w)
429
+ );
430
+ normals.addAssign(readNormal(c.uv, c.right, c.up, c.n).mul(w));
431
+ alpha.addAssign(w);
432
+ }
433
+ );
434
+ }
435
+ const divisor = max2(alpha, 1e-10);
436
+ return Surface(
437
+ colors.div(divisor),
438
+ alpha.div(max2(weights, 1e-10)).mul(support),
439
+ orms.div(divisor),
440
+ emissions.div(divisor),
441
+ normals.div(max2(normals.length(), 1e-10)),
442
+ positions
443
+ );
444
+ })().toVar("boxProjectedSurface");
445
+ material.colorNode = surface.get("color");
446
+ material.normalNode = transformNormalToView2(surface.get("normal"));
447
+ material.roughnessNode = surface.get("orm").g;
448
+ material.metalnessNode = surface.get("orm").b;
449
+ material.aoNode = surface.get("orm").r;
450
+ material.emissiveNode = surface.get("emission");
451
+ material.maskNode = surface.get("alpha").greaterThanEqual(transparency === "cutout" ? alphaCutoff : float2(1 / 255));
452
+ material.maskShadowNode = material.maskNode;
453
+ if (transparency !== "cutout") material.opacityNode = surface.get("alpha");
454
+ material.depthNode = Fn2(() => {
455
+ const z = modelViewMatrix.mul(vec4(surface.get("position"), 1)).z.toVar("boxProjectionDepthZ");
456
+ return perspective.select(
457
+ viewZToPerspectiveDepth(z, cameraNear, cameraFar),
458
+ viewZToOrthographicDepth(z, cameraNear, cameraFar)
459
+ );
460
+ })();
461
+ material.receivedShadowPositionNode = modelWorldMatrix.mul(
462
+ vec4(surface.get("position"), 1)
463
+ ).xyz;
464
+ material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
465
+ return material;
466
+ }
467
+
468
+ // src/box-impostor/box-impostor-material.js
469
+ function createBoxImpostorMaterial(descriptor, maps) {
470
+ const settings = normalizeBoxImpostorDisplay(descriptor);
471
+ const alphaCutoff = uniform(settings.alphaCutoff);
472
+ const transparency = boxTransparency(descriptor, settings);
473
+ const minimumAlpha = transparency === "cutout" ? alphaCutoff : float3(1 / 255);
474
+ for (const map of Object.values(maps)) {
475
+ if (map.minFilter !== LinearFilter || map.magFilter !== LinearFilter) {
476
+ map.minFilter = map.magFilter = LinearFilter;
477
+ map.generateMipmaps = false;
478
+ map.needsUpdate = true;
479
+ }
480
+ }
481
+ const material = new MeshStandardNodeMaterial({
482
+ name: "Box impostor",
483
+ side: descriptor.mode !== "fitted" ? DoubleSide : FrontSide,
484
+ alphaHash: transparency === "dithered",
485
+ transparent: transparency === "blended",
486
+ depthWrite: transparency !== "blended",
487
+ forceSinglePass: true
488
+ });
489
+ const rectData = new Float32Array(descriptor.boxes.length * 6 * 4);
490
+ descriptor.boxes.forEach(
491
+ (b, i) => b.views.forEach(
492
+ (r, j) => rectData.set(
493
+ [
494
+ (r[0] + descriptor.padding) / descriptor.atlasResolution,
495
+ (r[1] + descriptor.padding) / descriptor.atlasResolution,
496
+ (r[2] - 2 * descriptor.padding) / descriptor.atlasResolution,
497
+ (r[3] - 2 * descriptor.padding) / descriptor.atlasResolution
498
+ ],
499
+ (i * 6 + j) * 4
500
+ )
501
+ )
502
+ );
503
+ const rects = new DataTexture3(
504
+ rectData,
505
+ 6,
506
+ descriptor.boxes.length,
507
+ RGBAFormat3,
508
+ FloatType3
509
+ );
510
+ rects.needsUpdate = true;
511
+ rects.magFilter = rects.minFilter = NearestFilter3;
512
+ material.addEventListener("dispose", () => rects.dispose());
513
+ const center = attribute3("boxCenter", "vec3"), half = attribute3("boxHalfSize", "vec3");
514
+ const ax = attribute3("boxAxisX", "vec3"), ay = attribute3("boxAxisY", "vec3"), az = attribute3("boxAxisZ", "vec3");
515
+ const toBox = (p) => vec33(dot3(p, ax), dot3(p, ay), dot3(p, az));
516
+ const fromBox = (p) => ax.mul(p.x).add(ay.mul(p.y)).add(az.mul(p.z));
517
+ const eye = modelWorldMatrixInverse.mul(vec42(cameraPosition, 1)).xyz;
518
+ const viewAxis = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec42(0, 0, 1, 0))).xyz.normalize();
519
+ const perspective = cameraProjectionMatrix.element(3).w.equal(0);
520
+ let proxy = positionLocal2;
521
+ if (descriptor.mode !== "fitted") {
522
+ proxy = Fn3((_, builder) => {
523
+ const forward = perspective.select(normalize2(eye.sub(center)), viewAxis);
524
+ const right = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec42(0, 1, 0, 0))).xyz.cross(forward).normalize();
525
+ const up = forward.cross(right).normalize();
526
+ const radius = half.length();
527
+ const distance = dot3(eye.sub(center), forward);
528
+ const plane = center.add(forward.mul(radius));
529
+ const lo = vec23(1e20).toVar(), hi = vec23(-1e20).toVar();
530
+ for (const x of [-1, 1])
531
+ for (const y of [-1, 1])
532
+ for (const z of [-1, 1]) {
533
+ const corner2 = fromBox(half.mul(vec33(x, y, z)));
534
+ const scale = perspective.select(
535
+ max3(distance.sub(radius), 1e-5).div(
536
+ max3(distance.sub(dot3(corner2, forward)), 1e-5)
537
+ ),
538
+ float3(1)
539
+ );
540
+ const p = vec23(dot3(corner2, right), dot3(corner2, up)).mul(scale);
541
+ lo.assign(min(lo, p));
542
+ hi.assign(max3(hi, p));
543
+ }
544
+ const corner = attribute3("cardCorner", "vec2").add(1).mul(0.5);
545
+ const xy = lo.add(hi.sub(lo).mul(corner));
546
+ return plane.add(right.mul(xy.x)).add(up.mul(xy.y));
547
+ })();
548
+ material.positionNode = proxy;
549
+ material.castShadowPositionNode = proxy;
550
+ }
551
+ const raster = varying(proxy, "boxRasterPosition");
552
+ if (boxDepthMode(descriptor, settings) === "projection" && descriptor.mode === "fitted" && settings.interpolation === "none")
553
+ return applyBoxFaces({
554
+ material,
555
+ descriptor,
556
+ maps,
557
+ alphaCutoff,
558
+ transparency,
559
+ half,
560
+ toBox,
561
+ fromBox
562
+ });
563
+ if (boxDepthMode(descriptor, settings) === "projection")
564
+ return applyBoxProjection({
565
+ material,
566
+ descriptor,
567
+ maps,
568
+ settings,
569
+ transparency,
570
+ alphaCutoff,
571
+ rects,
572
+ center,
573
+ half,
574
+ toBox,
575
+ fromBox,
576
+ eye,
577
+ viewAxis,
578
+ perspective,
579
+ raster
580
+ });
581
+ const accelerated = descriptor.boxes.every((b) => b.depthBounds);
582
+ const gridSize = BOX_OCCUPANCY_RESOLUTION;
583
+ let occupancy;
584
+ if (descriptor.boxes.every((b) => b.occupancy) && descriptor.boxes.some(
585
+ (b) => b.occupancy.some((word) => word !== 4294967295)
586
+ )) {
587
+ const wordsPerBox = gridSize ** 3 / 32;
588
+ const words = new Uint32Array(wordsPerBox * descriptor.boxes.length);
589
+ descriptor.boxes.forEach(
590
+ (box, index) => words.set(box.occupancy, index * wordsPerBox)
591
+ );
592
+ occupancy = new DataTexture3(
593
+ words,
594
+ wordsPerBox,
595
+ descriptor.boxes.length,
596
+ RedIntegerFormat,
597
+ UnsignedIntType
598
+ );
599
+ occupancy.needsUpdate = true;
600
+ material.addEventListener("dispose", () => occupancy.dispose());
601
+ }
602
+ const Result = struct2(
603
+ { uv: "vec2", position: "vec3", normal: "vec3", valid: "float" },
604
+ "BoxImpostorHit"
605
+ );
606
+ const raycast = Fn3((_, builder) => {
607
+ const ray = perspective.select(
608
+ normalize2(raster.sub(eye)),
609
+ viewAxis.negate()
610
+ );
611
+ const origin = perspective.select(
612
+ eye,
613
+ raster.sub(ray.mul(half.length().mul(4)))
614
+ );
615
+ const o = toBox(origin.sub(center)).div(half), r = toBox(ray).div(half);
616
+ const safe = sign3(r.add(1e-20)).mul(max3(abs3(r), 1e-10));
617
+ const a = vec33(-1).sub(o).div(safe), b = vec33(1).sub(o).div(safe);
618
+ const enter = max3(max3(min(a, b).x, min(a, b).y), min(a, b).z).max(0);
619
+ const exit = min(min(max3(a, b).x, max3(a, b).y), max3(a, b).z);
620
+ const occupiedStart = enter.toVar();
621
+ if (occupancy) {
622
+ const gridOrigin = o.add(1).mul(gridSize / 2);
623
+ const gridRay = r.mul(gridSize / 2);
624
+ const step = sign3(gridRay.add(1e-20));
625
+ const cell = floor(gridOrigin.add(gridRay.mul(enter))).clamp(0, gridSize - 1).toVar();
626
+ const inverse = vec33(1).div(safe.mul(gridSize / 2));
627
+ const delta = abs3(inverse);
628
+ const next = cell.add(step.add(1).mul(0.5)).sub(gridOrigin).mul(inverse).toVar();
629
+ const t = enter.toVar();
630
+ occupiedStart.assign(exit.add(1));
631
+ Loop(gridSize * 3 + 1, () => {
632
+ If3(t.greaterThan(exit), () => {
633
+ Break();
634
+ });
635
+ const cellIndex = uint(
636
+ cell.x.add(cell.y.mul(gridSize)).add(cell.z.mul(gridSize ** 2))
637
+ ).toVar();
638
+ const word = textureLoad3(
639
+ occupancy,
640
+ ivec23(int3(cellIndex.shiftRight(5)), int3(attribute3("boxId", "float")))
641
+ ).r;
642
+ const support = word.shiftRight(cellIndex.bitAnd(31)).bitAnd(1);
643
+ If3(support.notEqual(uint(0)), () => {
644
+ occupiedStart.assign(t);
645
+ Break();
646
+ });
647
+ const edge = min(min(next.x, next.y), next.z).toVar();
648
+ const advance = vec33(
649
+ next.x.lessThanEqual(edge).select(1, 0),
650
+ next.y.lessThanEqual(edge).select(1, 0),
651
+ next.z.lessThanEqual(edge).select(1, 0)
652
+ );
653
+ cell.addAssign(advance.mul(step));
654
+ next.addAssign(advance.mul(delta));
655
+ t.assign(edge);
656
+ If3(
657
+ 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)),
658
+ () => {
659
+ Break();
660
+ }
661
+ );
662
+ });
663
+ }
664
+ const look = toBox(ray).negate();
665
+ const bestT = exit.add(1).toVar(), bestUv = vec23(0).toVar(), bestNormal = vec33(0, 0, 1).toVar(), valid = float3(0).toVar(), found = float3(0).toVar();
666
+ const angles = abs3(look).toVar();
667
+ const major = angles.x.greaterThanEqual(angles.y).and(angles.x.greaterThanEqual(angles.z)).select(
668
+ int3(0),
669
+ angles.y.greaterThanEqual(angles.z).select(int3(1), int3(2))
670
+ ).toVar();
671
+ const nextAxis = major.add(1).mod(3), lastAxis = major.add(2).mod(3);
672
+ const second = angles.element(nextAxis).greaterThanEqual(angles.element(lastAxis)).select(nextAxis, lastAxis).toVar();
673
+ const third = int3(3).sub(major).sub(second).toVar();
674
+ Loop(
675
+ { start: 0, end: 6, type: "int", name: "viewIndex" },
676
+ ({ viewIndex: i }) => {
677
+ If3(occupiedStart.greaterThan(exit), () => {
678
+ Break();
679
+ });
680
+ valid.assign(0);
681
+ const rank = i.mod(3);
682
+ const axis = rank.equal(0).select(major, rank.equal(1).select(second, third)).toVar();
683
+ const positive = i.lessThan(3).select(
684
+ look.element(axis).greaterThanEqual(0),
685
+ look.element(axis).lessThan(0)
686
+ );
687
+ const face = axis.mul(2).add(positive.select(int3(0), int3(1)));
688
+ const facing = positive.select(1, -1);
689
+ const n = vec33(
690
+ axis.equal(0).select(facing, 0),
691
+ axis.equal(1).select(facing, 0),
692
+ axis.equal(2).select(facing, 0)
693
+ ).toVar();
694
+ const right = axis.equal(0).select(
695
+ vec33(0, 0, facing.negate()),
696
+ axis.equal(1).select(vec33(1, 0, 0), vec33(facing, 0, 0))
697
+ ).toVar();
698
+ const up = axis.equal(1).select(vec33(0, 0, facing.negate()), vec33(0, 1, 0)).toVar();
699
+ const direction = i.lessThan(3).select(1, -1);
700
+ const rect = textureLoad3(
701
+ rects,
702
+ ivec23(face, int3(attribute3("boxId", "float")))
703
+ ).toVar();
704
+ const sampleUv = (p) => rect.xy.add(
705
+ vec23(dot3(p, right), dot3(p, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
706
+ );
707
+ const decode = (d) => d.b.mul(65280).add(d.a.mul(255)).div(65535);
708
+ const depthAt = (uv2) => decode(texture3(maps.normalDepth, uv2).level(0));
709
+ const distance = (t) => {
710
+ const p = o.add(r.mul(t));
711
+ return dot3(p, n).sub(float3(1).sub(depthAt(sampleUv(p)).mul(2))).mul(direction);
712
+ };
713
+ const acceptHit = (hitT) => {
714
+ const point2 = o.add(r.mul(hitT)), uv2 = sampleUv(point2);
715
+ const texel = ivec23(uv2.mul(descriptor.atlasResolution));
716
+ const nearest = textureLoad3(maps.normalDepth, texel);
717
+ const occupied = textureLoad3(maps.orm, texel).a.greaterThan(0.5);
718
+ const residual = abs3(
719
+ dot3(point2, n).sub(float3(1).sub(decode(nearest).mul(2)))
720
+ );
721
+ const tolerance = max3(
722
+ dot3(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
723
+ dot3(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
724
+ ).div(dot3(abs3(n), half)).mul(4).add(4 / 65535);
725
+ If3(
726
+ residual.lessThanEqual(tolerance).and(occupied).and(
727
+ texture3(maps.baseColor, uv2).level(0).a.greaterThanEqual(minimumAlpha)
728
+ ),
729
+ () => {
730
+ valid.assign(1);
731
+ If3(hitT.lessThan(bestT), () => {
732
+ bestT.assign(hitT);
733
+ bestUv.assign(uv2);
734
+ found.assign(1);
735
+ const packed = texture3(maps.normalDepth, uv2).level(0).rg.div(max3(texture3(maps.orm, uv2).level(0).a, 1e-10)).mul(2).sub(1);
736
+ const normal2 = vec33(
737
+ packed.x,
738
+ packed.y,
739
+ float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))
740
+ ).toVar();
741
+ If3(normal2.z.lessThan(0), () => {
742
+ normal2.xy.assign(
743
+ vec23(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20)))
744
+ );
745
+ });
746
+ bestNormal.assign(
747
+ fromBox(
748
+ right.mul(normal2.x).add(up.mul(normal2.y)).add(n.mul(normal2.z))
749
+ ).normalize()
750
+ );
751
+ bestNormal.mulAssign(
752
+ dot3(bestNormal, ray).greaterThan(0).select(-1, 1)
753
+ );
754
+ });
755
+ }
756
+ );
757
+ };
758
+ const traceInterval = (start, end, steps) => {
759
+ const footprint = vec23(dot3(r, right), dot3(r, up)).abs().mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
760
+ const samples = max3(float3(steps), max3(footprint.x, footprint.y).mul(steps / 8)).div(2).ceil().mul(2).toVar();
761
+ const step = end.sub(start).div(samples);
762
+ const previous = start.toVar(), previousD = distance(start).toVar();
763
+ If3(previousD.lessThanEqual(0), () => {
764
+ acceptHit(start);
765
+ });
766
+ Loop({ start: int3(0), end: int3(samples.div(2)), type: "int" }, ({ i: i2 }) => {
767
+ If3(valid.greaterThan(0.5), () => {
768
+ Break();
769
+ });
770
+ const samples2 = [1, 2].map((offset) => {
771
+ const t = start.add(step.mul(float3(i2.mul(2).add(offset)))).toVar();
772
+ return { t, d: distance(t).toVar() };
773
+ });
774
+ for (const { t, d } of samples2) {
775
+ If3(valid.greaterThan(0.5).or(t.sub(step).greaterThan(bestT)), () => {
776
+ Break();
777
+ });
778
+ If3(valid.lessThan(0.5).and(d.mul(previousD).lessThanEqual(0)), () => {
779
+ const crossing = refineSurfaceCrossing({ float: float3, If: If3, Loop }, { lo: previous, hi: t, loValue: previousD, hiValue: d, height: distance, steps: 3, secant: true });
780
+ acceptHit(crossing);
781
+ If3(bestT.lessThanEqual(t), () => {
782
+ Break();
783
+ });
784
+ });
785
+ previous.assign(t);
786
+ previousD.assign(d);
787
+ }
788
+ });
789
+ };
790
+ If3(
791
+ exit.greaterThanEqual(enter).and(abs3(look.element(axis)).greaterThan(1e-3)),
792
+ () => {
793
+ if (!accelerated) {
794
+ traceInterval(enter, exit, descriptor.raySteps);
795
+ } else {
796
+ const depths = axis.equal(0).select(
797
+ attribute3("boxDepthX", "vec4"),
798
+ axis.equal(1).select(
799
+ attribute3("boxDepthY", "vec4"),
800
+ attribute3("boxDepthZ", "vec4")
801
+ )
802
+ );
803
+ const interval = positive.select(depths.xy, depths.zw);
804
+ const initialDepth = float3(1).sub(dot3(o, n)).mul(0.5);
805
+ const depthSlope = dot3(r, n).negate().mul(0.5);
806
+ const da = interval.x.sub(2 / 65535).sub(initialDepth).div(depthSlope);
807
+ const db = interval.y.add(2 / 65535).sub(initialDepth).div(depthSlope);
808
+ const start = max3(occupiedStart, min(da, db));
809
+ const end = min(min(exit, bestT), max3(da, db));
810
+ If3(
811
+ interval.x.lessThanEqual(interval.y).and(end.greaterThanEqual(start)),
812
+ () => {
813
+ const search = () => traceInterval(start, end, descriptor.raySteps);
814
+ const hasFlatView = descriptor.boxes.some(
815
+ (box) => [0, 2, 4, 6, 8, 10].some(
816
+ (i2) => box.depthBounds[i2 + 1] >= box.depthBounds[i2] && box.depthBounds[i2 + 1] - box.depthBounds[i2] <= 1
817
+ )
818
+ );
819
+ if (hasFlatView) {
820
+ If3(
821
+ interval.y.sub(interval.x).lessThanEqual(1 / 65535),
822
+ () => {
823
+ const t = interval.x.add(interval.y).mul(0.5).sub(initialDepth).div(depthSlope);
824
+ If3(
825
+ t.greaterThanEqual(enter).and(t.lessThanEqual(min(exit, bestT))),
826
+ () => {
827
+ acceptHit(t);
828
+ }
829
+ );
830
+ }
831
+ ).Else(search);
832
+ } else search();
833
+ }
834
+ );
835
+ }
836
+ }
837
+ );
838
+ }
839
+ );
840
+ valid.assign(found);
841
+ const point = o.add(r.mul(bestT));
842
+ return Result(
843
+ bestUv,
844
+ center.add(fromBox(point.mul(half))),
845
+ bestNormal,
846
+ valid
847
+ );
848
+ });
849
+ const hit = raycast().toVar("boxHit");
850
+ const base = texture3(maps.baseColor, hit.get("uv")).level(0), orm = texture3(maps.orm, hit.get("uv")).level(0);
851
+ const coverage = max3(orm.a, 1e-10);
852
+ 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");
853
+ if (settings.interpolation !== "none") {
854
+ const fallbackColor = color, fallbackOrm = surfaceOrm, fallbackEmission = emission, fallbackNormal = normal;
855
+ const Surface = struct2(
856
+ { color: "vec4", orm: "vec3", emission: "vec3", normal: "vec3" },
857
+ "BoxSurfaceBlend"
858
+ );
859
+ const blended = Fn3(() => {
860
+ const point = toBox(hit.get("position").sub(center)).div(half);
861
+ const look = toBox(
862
+ perspective.select(normalize2(eye.sub(hit.get("position"))), viewAxis)
863
+ );
864
+ const colors = vec42(0).toVar(), materials = vec33(0).toVar(), emissions = vec33(0).toVar(), normals = vec33(0).toVar(), weights = float3(0).toVar();
865
+ for (let axis = 0; axis < 3; axis++) {
866
+ const positive = look.element(axis).greaterThanEqual(0);
867
+ const front = BOX_FACE_AXES[axis * 2], back = BOX_FACE_AXES[axis * 2 + 1];
868
+ const n = positive.select(vec33(...front.normal), vec33(...back.normal));
869
+ const right = positive.select(
870
+ vec33(...front.right),
871
+ vec33(...back.right)
872
+ );
873
+ const up = positive.select(vec33(...front.up), vec33(...back.up));
874
+ const face = positive.select(int3(axis * 2), int3(axis * 2 + 1));
875
+ const rect = textureLoad3(
876
+ rects,
877
+ ivec23(face, int3(attribute3("boxId", "float")))
878
+ );
879
+ const uv2 = rect.xy.add(
880
+ vec23(dot3(point, right), dot3(point, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
881
+ );
882
+ const texel = ivec23(uv2.mul(descriptor.atlasResolution));
883
+ const captured = textureLoad3(maps.normalDepth, texel);
884
+ const sampled = texture3(maps.baseColor, uv2).level(0);
885
+ const sampledOrm = texture3(maps.orm, uv2).level(0);
886
+ const occupied = textureLoad3(maps.orm, texel).a.greaterThan(0.5);
887
+ const depth = captured.b.mul(65280).add(captured.a.mul(255)).div(65535);
888
+ const tolerance = max3(
889
+ dot3(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
890
+ dot3(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
891
+ ).div(dot3(abs3(n), half)).mul(4).add(4 / 65535);
892
+ If3(
893
+ occupied.and(sampled.a.greaterThanEqual(minimumAlpha)).and(
894
+ abs3(dot3(point, n).sub(float3(1).sub(depth.mul(2)))).lessThanEqual(
895
+ tolerance
896
+ )
897
+ ),
898
+ () => {
899
+ const angle = abs3(look.element(axis));
900
+ const weight = settings.interpolation === "smooth" ? angle.mul(angle) : angle;
901
+ const coverage2 = max3(sampledOrm.a, 1e-10);
902
+ colors.addAssign(sampled.div(coverage2).mul(weight));
903
+ materials.addAssign(sampledOrm.rgb.div(coverage2).mul(weight));
904
+ emissions.addAssign(
905
+ texture3(maps.emissive, uv2).level(0).rgb.div(coverage2).mul(weight)
906
+ );
907
+ const packed = captured.rg.mul(2).sub(1);
908
+ const decoded = vec33(
909
+ packed,
910
+ float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))
911
+ ).toVar();
912
+ If3(decoded.z.lessThan(0), () => {
913
+ decoded.xy.assign(
914
+ vec23(1).sub(abs3(decoded.yx)).mul(sign3(decoded.xy.add(1e-20)))
915
+ );
916
+ });
917
+ normals.addAssign(
918
+ fromBox(
919
+ right.mul(decoded.x).add(up.mul(decoded.y)).add(n.mul(decoded.z))
920
+ ).normalize().mul(weight)
921
+ );
922
+ weights.addAssign(weight);
923
+ }
924
+ );
925
+ }
926
+ const divisor = max3(weights, 1e-10), valid = weights.greaterThan(1e-10);
927
+ return Surface(
928
+ valid.select(colors.div(divisor), fallbackColor),
929
+ valid.select(materials.div(divisor), fallbackOrm),
930
+ valid.select(emissions.div(divisor), fallbackEmission),
931
+ valid.select(normals.normalize(), fallbackNormal)
932
+ );
933
+ })().toVar("boxBlendedSurface");
934
+ color = blended.get("color");
935
+ surfaceOrm = blended.get("orm");
936
+ emission = blended.get("emission");
937
+ normal = blended.get("normal");
938
+ }
939
+ material.colorNode = color.rgb;
940
+ material.normalNode = transformNormalToView3(normal);
941
+ material.roughnessNode = surfaceOrm.g;
942
+ material.metalnessNode = surfaceOrm.b;
943
+ material.aoNode = surfaceOrm.r;
944
+ material.emissiveNode = emission;
945
+ if (transparency !== "cutout") material.opacityNode = color.a.clamp(0, 1);
946
+ material.maskNode = hit.get("valid").greaterThan(0.5);
947
+ material.maskShadowNode = material.maskNode;
948
+ material.depthNode = Fn3((_, builder) => {
949
+ const z = modelViewMatrix2.mul(vec42(hit.get("position"), 1)).z.toVar("boxHitDepthZ");
950
+ return perspective.select(
951
+ viewZToPerspectiveDepth2(z, cameraNear2, cameraFar2),
952
+ viewZToOrthographicDepth2(z, cameraNear2, cameraFar2)
953
+ );
954
+ })();
955
+ material.receivedShadowPositionNode = modelWorldMatrix2.mul(
956
+ vec42(hit.get("position"), 1)
957
+ ).xyz;
958
+ material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
959
+ return material;
960
+ }
961
+
962
+ // src/box-impostor/box-impostor-display.js
963
+ var variants = /* @__PURE__ */ new WeakMap();
964
+ function setBoxImpostorDisplay(root, options) {
965
+ root.traverse((object) => {
966
+ const mesh = (
967
+ /** @type {import('three').Mesh} */
968
+ object
969
+ );
970
+ const binding = mesh.userData.boxImpostor;
971
+ if (!mesh.isMesh || !binding) return;
972
+ const settings = normalizeBoxImpostorDisplay({ ...binding.descriptor, ...options });
973
+ const descriptor = { ...binding.descriptor, ...settings };
974
+ const keyFor = (s) => `${s.depthMode}/${s.depthMode !== "projection" ? s.raySteps : 0}/${s.interpolation}/${s.transparency}`;
975
+ let cache = variants.get(mesh);
976
+ if (!cache) {
977
+ cache = /* @__PURE__ */ new Map([[
978
+ keyFor(normalizeBoxImpostorDisplay(binding.descriptor)),
979
+ /** @type {ReturnType<typeof createBoxImpostorMaterial>} */
980
+ mesh.material
981
+ ]]);
982
+ variants.set(mesh, cache);
983
+ const owned = cache;
984
+ mesh.geometry.addEventListener("dispose", () => {
985
+ for (const material2 of owned.values()) material2.dispose();
986
+ owned.clear();
987
+ variants.delete(mesh);
988
+ });
989
+ }
990
+ const key = keyFor(settings);
991
+ let material = cache.get(key);
992
+ if (!material) {
993
+ material = createBoxImpostorMaterial(descriptor, binding.maps);
994
+ cache.set(key, material);
995
+ }
996
+ material.userData.boxImpostor.alphaCutoff.value = settings.alphaCutoff;
997
+ material.userData.boxImpostor.descriptor = descriptor;
998
+ mesh.material = material;
999
+ binding.descriptor = descriptor;
1000
+ });
1001
+ }
1002
+ export {
1003
+ setBoxImpostorDisplay
1004
+ };
1005
+ //# sourceMappingURL=box-impostor-display.js.map