@needle-tools/three-mesh-effects 0.3.6 → 0.4.0

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 (61) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +14 -1
  3. package/build/box-impostor-runtime.js +836 -315
  4. package/build/box-impostor-runtime.js.map +4 -4
  5. package/build/impostor-runtime.js +944 -202
  6. package/build/impostor-runtime.js.map +4 -4
  7. package/build/index.js +7 -7
  8. package/build/index.js.map +2 -2
  9. package/build/internal/box-impostor/box-impostor-display.js +844 -321
  10. package/build/internal/box-impostor/box-impostor-display.js.map +4 -4
  11. package/build/internal/box-impostor/box-impostor-faces.js +8 -6
  12. package/build/internal/box-impostor/box-impostor-faces.js.map +2 -2
  13. package/build/internal/box-impostor/box-impostor-material.js +844 -321
  14. package/build/internal/box-impostor/box-impostor-material.js.map +4 -4
  15. package/build/internal/box-impostor/box-impostor-projection.js +8 -5
  16. package/build/internal/box-impostor/box-impostor-projection.js.map +2 -2
  17. package/build/internal/box-impostor/box-impostor-ray-bounds.js +369 -0
  18. package/build/internal/box-impostor/box-impostor-ray-bounds.js.map +7 -0
  19. package/build/internal/box-impostor/box-impostor-runtime.js +836 -315
  20. package/build/internal/box-impostor/box-impostor-runtime.js.map +4 -4
  21. package/build/internal/impostor/adaptive-impostor-renderer.js +434 -0
  22. package/build/internal/impostor/adaptive-impostor-renderer.js.map +7 -0
  23. package/build/internal/impostor/impostor-node-material.js +944 -202
  24. package/build/internal/impostor/impostor-node-material.js.map +4 -4
  25. package/build/internal/impostor/impostor-performance.js +136 -0
  26. package/build/internal/impostor/impostor-performance.js.map +7 -0
  27. package/build/internal/pixel-impostor/pixel-impostor-runtime.js +6 -1
  28. package/build/internal/pixel-impostor/pixel-impostor-runtime.js.map +2 -2
  29. package/build/internal/rendering/instance-space.js +110 -0
  30. package/build/internal/rendering/instance-space.js.map +7 -0
  31. package/build/internal/rendering/renderer-support.js +6 -1
  32. package/build/internal/rendering/renderer-support.js.map +2 -2
  33. package/build/pixel-impostor-runtime.js +6 -1
  34. package/build/pixel-impostor-runtime.js.map +2 -2
  35. package/build/types/box-impostor/box-impostor-faces.d.ts +3 -1
  36. package/build/types/box-impostor/box-impostor-material.d.ts +2 -1
  37. package/build/types/box-impostor/box-impostor-projection.d.ts +3 -1
  38. package/build/types/box-impostor/box-impostor-ray-bounds.d.ts +6 -0
  39. package/build/types/box-impostor/box-impostor-ray-bounds.js +1 -0
  40. package/build/types/impostor/adaptive-impostor-renderer.d.ts +74 -0
  41. package/build/types/impostor/adaptive-impostor-renderer.js +1 -0
  42. package/build/types/impostor/impostor-node-material.d.ts +5 -1
  43. package/build/types/impostor/impostor-performance.d.ts +90 -0
  44. package/build/types/impostor/impostor-performance.js +1 -0
  45. package/build/types/public/impostor-runtime.d.ts +2 -0
  46. package/build/types/public/index.d.ts +3 -0
  47. package/build/types/rendering/instance-space.d.ts +26 -0
  48. package/build/types/rendering/instance-space.js +1 -0
  49. package/build/types/rendering/renderer-support.d.ts +13 -0
  50. package/package.json +2 -2
  51. package/src/box-impostor/box-impostor-faces.js +7 -5
  52. package/src/box-impostor/box-impostor-material.js +162 -109
  53. package/src/box-impostor/box-impostor-projection.js +7 -4
  54. package/src/box-impostor/box-impostor-ray-bounds.js +452 -0
  55. package/src/impostor/adaptive-impostor-renderer.js +423 -0
  56. package/src/impostor/impostor-node-material.js +347 -157
  57. package/src/impostor/impostor-performance.js +152 -0
  58. package/src/public/impostor-runtime.js +2 -0
  59. package/src/public/index.js +12 -9
  60. package/src/rendering/instance-space.js +121 -0
  61. package/src/rendering/renderer-support.js +9 -0
@@ -32,9 +32,9 @@ function capturedSurfaceDepth(position, shadowBias = 0) {
32
32
 
33
33
  // src/box-impostor/box-impostor-material.js
34
34
  import {
35
- DataTexture as DataTexture3,
36
- FloatType as FloatType3,
37
- RGBAFormat as RGBAFormat3,
35
+ DataTexture as DataTexture4,
36
+ FloatType as FloatType4,
37
+ RGBAFormat as RGBAFormat4,
38
38
  RedIntegerFormat,
39
39
  UnsignedIntType,
40
40
  NearestFilter as NearestFilter3,
@@ -44,34 +44,34 @@ import {
44
44
  FrontSide
45
45
  } from "three/webgpu";
46
46
  import {
47
- Fn as Fn4,
48
- If as If3,
49
- Loop,
47
+ Fn as Fn5,
48
+ If as If4,
49
+ Loop as Loop2,
50
50
  Break,
51
51
  attribute as attribute3,
52
- varying,
53
- positionLocal as positionLocal2,
52
+ varying as varying2,
53
+ positionGeometry as positionGeometry2,
54
54
  positionViewDirection,
55
55
  modelWorldMatrixInverse,
56
56
  cameraPosition,
57
57
  cameraWorldMatrix,
58
58
  cameraProjectionMatrix as cameraProjectionMatrix2,
59
- vec2 as vec23,
60
- vec3 as vec33,
61
- vec4 as vec44,
62
- float as float3,
63
- int as int3,
64
- uint,
65
- dot as dot3,
59
+ vec2 as vec24,
60
+ vec3 as vec35,
61
+ vec4 as vec46,
62
+ float as float4,
63
+ int as int5,
64
+ uint as uint2,
65
+ dot as dot4,
66
66
  abs as abs3,
67
- max as max3,
68
- min,
67
+ max as max4,
68
+ min as min2,
69
69
  sign as sign3,
70
70
  texture as texture3,
71
- textureLoad as textureLoad3,
72
- ivec2 as ivec23,
71
+ textureLoad as textureLoad5,
72
+ ivec2 as ivec25,
73
73
  normalize as normalize2,
74
- floor,
74
+ floor as floor2,
75
75
  fract,
76
76
  modelWorldMatrix as modelWorldMatrix3,
77
77
  cameraNear as cameraNear2,
@@ -80,9 +80,114 @@ import {
80
80
  uniform
81
81
  } from "three/tsl";
82
82
 
83
+ // src/rendering/instance-space.js
84
+ import { DataTexture, DynamicDrawUsage, FloatType, InstancedInterleavedBuffer, InterpolationSamplingType, NodeUpdateType, RGBAFormat } from "three/webgpu";
85
+ import { cross, dot, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, ivec2, textureLoad, varying, vec3, vec4 as vec42 } from "three/tsl";
86
+ var spaces = /* @__PURE__ */ new WeakMap();
87
+ var webglSpaces = /* @__PURE__ */ new WeakMap();
88
+ function instanceColumns(object, matrix, useTexture) {
89
+ const columns = [0, 1, 2, 3];
90
+ if (useTexture) {
91
+ const rowSize = Math.ceil(Math.sqrt(matrix.count) / 2);
92
+ const rows = Math.ceil(matrix.count / rowSize);
93
+ const data = new Float32Array(rowSize * rows * 16);
94
+ const texture4 = new DataTexture(data, rowSize * 4, rows, RGBAFormat, FloatType);
95
+ const upload = () => {
96
+ data.set(matrix.array);
97
+ texture4.needsUpdate = true;
98
+ };
99
+ upload();
100
+ const release = () => {
101
+ object.removeEventListener("dispose", release);
102
+ texture4.dispose();
103
+ webglSpaces.delete(matrix);
104
+ };
105
+ object.addEventListener("dispose", release);
106
+ const x = instanceIndex.mod(rowSize).mul(4);
107
+ const y = instanceIndex.div(rowSize);
108
+ return { nodes: columns.map((column) => textureLoad(texture4, ivec2(int(x.add(column)), int(y)))), upload };
109
+ }
110
+ const interleaved = new InstancedInterleavedBuffer(matrix.array, 16, 1);
111
+ const read = matrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
112
+ return {
113
+ nodes: columns.map((column) => read(
114
+ interleaved,
115
+ /** @type {const} */
116
+ "vec4",
117
+ 16,
118
+ column * 4
119
+ )),
120
+ upload: () => {
121
+ interleaved.needsUpdate = true;
122
+ }
123
+ };
124
+ }
125
+ function instanceSpace(builder) {
126
+ const object = (
127
+ /** @type {InstancedMesh} */
128
+ builder.object
129
+ );
130
+ const matrix = object?.isInstancedMesh ? object.instanceMatrix : null;
131
+ if (!matrix) return null;
132
+ const backend = (
133
+ /** @type {{isWebGPUBackend?: boolean} | undefined} */
134
+ builder.renderer.backend
135
+ );
136
+ const useTexture = !backend?.isWebGPUBackend && matrix.count * 64 > (builder.getUniformBufferLimit?.() ?? 16384);
137
+ const cache = useTexture ? webglSpaces : spaces;
138
+ const cached = cache.get(matrix);
139
+ if (cached) return cached;
140
+ const { nodes, upload } = instanceColumns(object, matrix, useTexture);
141
+ let version = matrix.version;
142
+ nodes[0].updateBeforeType = NodeUpdateType.OBJECT;
143
+ nodes[0].updateBefore = () => {
144
+ if (matrix.version !== version) {
145
+ version = matrix.version;
146
+ upload();
147
+ }
148
+ return void 0;
149
+ };
150
+ const [a, b, c, d] = nodes.map((node) => node.xyz);
151
+ const determinant = dot(a, cross(b, c));
152
+ const rows = [cross(b, c), cross(c, a), cross(a, b)].map((row) => row.div(determinant));
153
+ const toLocalDirection = (v) => vec3(dot(rows[0], v), dot(rows[1], v), dot(rows[2], v));
154
+ const toMeshDirection = (v) => a.mul(v.x).add(b.mul(v.y)).add(c.mul(v.z));
155
+ const translation = [d.x, d.y, d.z];
156
+ const packed = [a, b, c].map(
157
+ (column, k) => varying(vec42(column, translation[k]), `instanceSpace${k}`).setInterpolation(InterpolationSamplingType.FLAT)
158
+ );
159
+ const [fa, fb, fc] = packed.map((column) => column.xyz);
160
+ const cofactors = () => [cross(fb, fc), cross(fc, fa), cross(fa, fb)];
161
+ const space = {
162
+ toLocalPoint: (p) => toLocalDirection(p.sub(d)),
163
+ toLocalDirection,
164
+ toMeshPoint: (p) => toMeshDirection(p).add(d),
165
+ toMeshDirection,
166
+ fragment: {
167
+ toMeshPoint: (p) => fa.mul(p.x).add(fb.mul(p.y)).add(fc.mul(p.z)).add(vec3(packed[0].w, packed[1].w, packed[2].w)),
168
+ toMeshDirection: (v) => fa.mul(v.x).add(fb.mul(v.y)).add(fc.mul(v.z)),
169
+ toMeshNormal: (n) => {
170
+ const [x, y, z] = cofactors();
171
+ return x.mul(n.x).add(y.mul(n.y)).add(z.mul(n.z)).mul(dot(fa, x).sign()).normalize();
172
+ },
173
+ toLocalDirection: (v) => {
174
+ const [x, y, z] = cofactors();
175
+ return vec3(dot(x, v), dot(y, v), dot(z, v)).div(dot(fa, x));
176
+ },
177
+ toLocalPoint: (p) => {
178
+ const [x, y, z] = cofactors();
179
+ const v = p.sub(vec3(packed[0].w, packed[1].w, packed[2].w));
180
+ return vec3(dot(x, v), dot(y, v), dot(z, v)).div(dot(fa, x));
181
+ }
182
+ }
183
+ };
184
+ cache.set(matrix, space);
185
+ return space;
186
+ }
187
+
83
188
  // src/rendering/captured-surface-material.js
84
189
  import { MeshStandardNodeMaterial } from "three/webgpu";
85
- import { context, modelViewMatrix as modelViewMatrix2, modelWorldMatrix, vec4 as vec42 } from "three/tsl";
190
+ import { context, modelViewMatrix as modelViewMatrix2, modelWorldMatrix, vec4 as vec43 } from "three/tsl";
86
191
  var CapturedSurfaceMaterial = class extends MeshStandardNodeMaterial {
87
192
  /** @type {import('three/webgpu').Node<'vec3'> | null} */
88
193
  capturedPositionNode = null;
@@ -93,8 +198,8 @@ var CapturedSurfaceMaterial = class extends MeshStandardNodeMaterial {
93
198
  setupLighting(builder) {
94
199
  const lighting = super.setupLighting(builder);
95
200
  if (!this.capturedPositionNode) return lighting;
96
- const world = modelWorldMatrix.mul(vec42(this.capturedPositionNode, 1)).xyz;
97
- const view = modelViewMatrix2.mul(vec42(this.capturedPositionNode, 1)).xyz;
201
+ const world = modelWorldMatrix.mul(vec43(this.capturedPositionNode, 1)).xyz;
202
+ const view = modelViewMatrix2.mul(vec43(this.capturedPositionNode, 1)).xyz;
98
203
  return context(lighting, {
99
204
  positionView: view,
100
205
  positionWorld: world,
@@ -103,12 +208,376 @@ var CapturedSurfaceMaterial = class extends MeshStandardNodeMaterial {
103
208
  }
104
209
  };
105
210
 
211
+ // src/box-impostor/box-impostor-ray-bounds.js
212
+ import { Matrix4, NodeUpdateType as NodeUpdateType2, StorageBufferAttribute, Vector3 } from "three/webgpu";
213
+ import {
214
+ Fn as Fn2,
215
+ If,
216
+ Loop,
217
+ atomicMin,
218
+ atomicStore,
219
+ clamp,
220
+ float,
221
+ floor,
222
+ instanceIndex as instanceIndex2,
223
+ int as int2,
224
+ ivec2 as ivec22,
225
+ max,
226
+ min,
227
+ storage,
228
+ textureLoad as textureLoad2,
229
+ uint,
230
+ vec2,
231
+ vec3 as vec32,
232
+ vec4 as vec44
233
+ } from "three/tsl";
234
+
235
+ // src/box-impostor/box-impostor-face-axes.js
236
+ var BOX_FACE_AXES = Object.freeze([
237
+ { normal: [1, 0, 0], right: [0, 0, -1], up: [0, 1, 0] },
238
+ { normal: [-1, 0, 0], right: [0, 0, 1], up: [0, 1, 0] },
239
+ { normal: [0, 1, 0], right: [1, 0, 0], up: [0, 0, -1] },
240
+ { normal: [0, -1, 0], right: [1, 0, 0], up: [0, 0, 1] },
241
+ { normal: [0, 0, 1], right: [1, 0, 0], up: [0, 1, 0] },
242
+ { normal: [0, 0, -1], right: [-1, 0, 0], up: [0, 1, 0] }
243
+ ]);
244
+
245
+ // src/box-impostor/box-impostor-ray-bounds.js
246
+ var MIN_TILE_SIZE = 3;
247
+ var MAX_CAPTURE_TILES = 512 * 1024;
248
+ var REFRESH_ANGLE_SQUARED = Math.tan(Math.PI / 360) ** 2;
249
+ var DEPTH_MAX = 65535;
250
+ var MAX_VIEW_BYTES = 16 * 1024 * 1024;
251
+ var MAX_CACHED_VIEW_BYTES = 64 * 1024 * 1024;
252
+ function buffer(length, components = 1, Type = Float32Array) {
253
+ return new StorageBufferAttribute(length, components, Type);
254
+ }
255
+ function captureTiles(descriptor) {
256
+ const faces = descriptor.boxes.flatMap(
257
+ (box, id) => BOX_FACE_AXES.map((axes, face) => {
258
+ const [, , width, height] = box.views[face];
259
+ const w = width - 2 * descriptor.padding, h = height - 2 * descriptor.padding;
260
+ const right = axes.right.findIndex(Boolean), up = axes.up.findIndex(Boolean);
261
+ const tolerance = 4 * Math.max(box.halfSize[right] / w, box.halfSize[up] / h) / box.halfSize[face >> 1] + 5 / DEPTH_MAX;
262
+ return { key: id * 6 + face, w, h, tolerance };
263
+ })
264
+ );
265
+ const countFor = (size2) => faces.reduce((n, f) => n + Math.ceil((f.w + 2) / size2) * Math.ceil((f.h + 2) / size2), 0);
266
+ let size = MIN_TILE_SIZE;
267
+ while (countFor(size) > MAX_CAPTURE_TILES) size *= 2;
268
+ const tiles = buffer(countFor(size), 4);
269
+ let offset = 0;
270
+ for (const { key, w, h, tolerance } of faces) {
271
+ for (let y = -1; y <= h; y += size) {
272
+ for (let x = -1; x <= w; x += size) {
273
+ tiles.array[offset] = key;
274
+ tiles.array[offset + 1] = x;
275
+ tiles.array[offset + 2] = y;
276
+ tiles.array[offset + 3] = tolerance;
277
+ offset += 4;
278
+ }
279
+ }
280
+ }
281
+ return { tiles, size };
282
+ }
283
+ function buildPatches(descriptor, maps, rects, tiles, size, output) {
284
+ const descriptions = storage(tiles, "vec4", tiles.count).toReadOnly();
285
+ const patches = storage(output, "vec4", output.count);
286
+ return Fn2(() => {
287
+ const meta = descriptions.element(instanceIndex2).toVar();
288
+ const key = int2(meta.x), face = key.mod(6), axis = face.div(2);
289
+ const rect = textureLoad2(rects, ivec22(face, key.div(6))).mul(descriptor.atlasResolution).round().toVar();
290
+ const extent = ivec22(rect.zw.add(1).sub(meta.yz)).min(ivec22(size));
291
+ const origin = ivec22(rect.xy.add(meta.yz));
292
+ const near = float(1).toVar(), far = float(0).toVar();
293
+ function visit(process) {
294
+ Loop({ start: int2(0), end: extent.y, type: "int", name: "row" }, ({ row }) => {
295
+ Loop({ start: int2(0), end: extent.x, type: "int", name: "column" }, ({ column }) => {
296
+ const pixel = origin.add(ivec22(column, row));
297
+ If(textureLoad2(maps.orm, pixel).a.greaterThan(0.5), () => {
298
+ const packed = textureLoad2(maps.normalDepth, pixel);
299
+ const depth = packed.b.mul(65280).add(packed.a.mul(255)).div(DEPTH_MAX).toVar();
300
+ process(column, row, depth);
301
+ });
302
+ });
303
+ });
304
+ }
305
+ visit((x, y, depth) => {
306
+ near.assign(min(near, depth));
307
+ far.assign(max(far, depth));
308
+ });
309
+ const middle = near.add(far).mul(0.5).toVar();
310
+ const low = [vec32(2).toVar(), vec32(2).toVar()], high = [vec32(-2).toVar(), vec32(-2).toVar()];
311
+ visit((x, y, depth) => {
312
+ const uv2 = meta.yz.add(vec2(x, y)).div(rect.zw).mul(2).sub(1);
313
+ const lo = vec32(uv2.clamp(-1, 1), float(1).sub(depth.mul(2)).sub(meta.w).max(-1)).toVar();
314
+ const hi = vec32(
315
+ uv2.add(vec2(2).div(rect.zw)).clamp(-1, 1),
316
+ float(1).sub(depth.mul(2)).add(meta.w).min(1)
317
+ ).toVar();
318
+ lo.toStack();
319
+ hi.toStack();
320
+ const extend = (group) => {
321
+ low[group].assign(min(low[group], lo));
322
+ high[group].assign(max(high[group], hi));
323
+ };
324
+ If(depth.lessThanEqual(middle), () => {
325
+ extend(0);
326
+ }).Else(() => {
327
+ extend(1);
328
+ });
329
+ });
330
+ const facing = face.mod(2).equal(0).select(1, -1);
331
+ const right = axis.equal(0).select(vec32(0, 0, facing.negate()), axis.equal(1).select(vec32(1, 0, 0), vec32(facing, 0, 0)));
332
+ const up = axis.equal(1).select(vec32(0, 0, facing.negate()), vec32(0, 1, 0));
333
+ const normal = right.cross(up);
334
+ const rotate = (p) => right.mul(p.x).add(up.mul(p.y)).add(normal.mul(p.z));
335
+ for (let group = 0; group < 2; group++) {
336
+ const a = rotate(low[group]), b = rotate(high[group]), slot = instanceIndex2.mul(4).add(group * 2);
337
+ const valid = low[group].x.lessThanEqual(high[group].x);
338
+ patches.element(slot).assign(vec44(min(a, b), valid.select(meta.x, -1)));
339
+ patches.element(slot.add(1)).assign(vec44(max(a, b), 0));
340
+ }
341
+ })().compute(tiles.count);
342
+ }
343
+ function makeViewPasses(patchBuffer, views, ranges, count, resolution) {
344
+ const table = storage(ranges, "uint", count).toAtomic();
345
+ const reset = Fn2(() => {
346
+ atomicStore(table.element(instanceIndex2), uint(DEPTH_MAX));
347
+ })().compute(count);
348
+ const patches = storage(patchBuffer, "vec4", patchBuffer.count).toReadOnly();
349
+ const scatter = Fn2(() => {
350
+ const a = patches.element(instanceIndex2.mul(2)).toVar(), b = patches.element(instanceIndex2.mul(2).add(1)).toVar();
351
+ If(a.w.greaterThanEqual(0), () => {
352
+ const key = int2(a.w), box = key.div(6);
353
+ const mapping = views.element(box.mul(2)), reference = views.element(box.mul(2).add(1));
354
+ If(reference.w.greaterThanEqual(0), () => {
355
+ const axis = int2(reference.w).mod(3), x = axis.add(1).mod(3), y = axis.add(2).mod(3);
356
+ const e = vec2(reference.element(x), reference.element(y)), ez = reference.element(axis);
357
+ const za = a.element(axis), zb = b.element(axis);
358
+ const weight = reference.w.lessThan(3).select(1, 0).toVar();
359
+ const eyeSlope = e.div(ez).toVar(), inverseDistance = weight.div(ez).toVar();
360
+ const project = (v, z) => v.sub(eyeSlope.mul(z)).div(float(1).sub(inverseDistance.mul(z)));
361
+ const l = vec2(a.element(x), a.element(y)), h = vec2(b.element(x), b.element(y));
362
+ const cell = (v, bias) => ivec22(floor(v.sub(mapping.xy).mul(mapping.zw).add(bias)).clamp(0, resolution - 1));
363
+ const lo = cell(min(project(l, za), project(l, zb)), -5e-3);
364
+ const hi = cell(max(project(h, za), project(h, zb)), 5e-3);
365
+ const padding = vec2(0.506).div(mapping.zw).mul(inverseDistance.abs().add(1)).add(2e-6);
366
+ Loop({ start: lo.y, end: hi.y.add(1), type: "int", name: "row" }, ({ row }) => {
367
+ Loop({ start: lo.x, end: hi.x.add(1), type: "int", name: "column" }, ({ column }) => {
368
+ const uv2 = vec2(column, row).add(0.5).div(mapping.zw).add(mapping.xy);
369
+ const slope = eyeSlope.sub(uv2.mul(inverseDistance)).toVar();
370
+ const safe = slope.add(1e-30).sign().mul(slope.abs().max(1e-12));
371
+ const ta = l.sub(padding).sub(uv2).div(safe).toVar(), tb = h.add(padding).sub(uv2).div(safe).toVar();
372
+ const begin = max(za, max(min(ta.x, tb.x), min(ta.y, tb.y))), end = min(zb, min(max(ta.x, tb.x), max(ta.y, tb.y)));
373
+ If(begin.lessThanEqual(end), () => {
374
+ const depths = floor(
375
+ vec2(begin.add(1), float(1).sub(end)).mul(DEPTH_MAX / 2).sub(0.02)
376
+ ).max(0);
377
+ const i = key.mul(resolution).add(row).mul(resolution).add(column).mul(2);
378
+ atomicMin(table.element(i), uint(depths.x));
379
+ atomicMin(table.element(i.add(1)), uint(depths.y));
380
+ });
381
+ });
382
+ });
383
+ });
384
+ });
385
+ })().compute(patchBuffer.count / 2);
386
+ return { reset, scatter, table };
387
+ }
388
+ function setProjection(data, descriptor, reference, orthographic, resolution) {
389
+ for (const [id, box] of descriptor.boxes.entries()) {
390
+ const p = box.axes.map(
391
+ (axis2, i) => axis2.reduce(
392
+ (sum, v, k) => sum + v * (orthographic ? reference[k] : reference[k] - box.center[k]),
393
+ 0
394
+ ) / box.halfSize[i]
395
+ );
396
+ const axis = p.map(Math.abs).indexOf(Math.max(...p.map(Math.abs)));
397
+ const ez = p[axis], offset = id * 8;
398
+ if (orthographic ? Math.abs(ez) < 1e-12 : Math.abs(ez) <= 1.01) {
399
+ data[offset + 7] = -1;
400
+ continue;
401
+ }
402
+ for (let j = 0; j < 2; j++) {
403
+ const e = p[(axis + 1 + j) % 3];
404
+ const project = (v, z) => orthographic ? v - z * e / ez : (v * ez - z * e) / (ez - z);
405
+ const low = Math.min(project(-1, -1), project(-1, 1));
406
+ const high = Math.max(project(1, -1), project(1, 1));
407
+ data[offset + j] = low;
408
+ data[offset + j + 2] = resolution / (high - low);
409
+ }
410
+ data.set(p, offset + 4);
411
+ data[offset + 7] = axis + (orthographic ? 3 : 0);
412
+ }
413
+ }
414
+ function createBoxRayBounds(descriptor, maps, rects, material) {
415
+ const boxes = descriptor.boxes.length;
416
+ const resolution = Math.min(128, Math.floor(Math.sqrt(MAX_VIEW_BYTES / (48 * boxes))));
417
+ if (resolution < 32 || descriptor.atlasResolution < 512 || [maps.normalDepth, maps.orm].some((map) => map.isRenderTargetTexture || map.isVideoTexture))
418
+ return null;
419
+ const count = boxes * 6 * resolution ** 2 * 2;
420
+ const maxViews = Math.max(1, Math.floor(MAX_CACHED_VIEW_BYTES / (count * 4 + boxes * 32)));
421
+ const inactiveView = buffer(boxes * 2, 4);
422
+ for (let i = 0; i < boxes; i++) inactiveView.array.set([0, 0, 1, 1, 2, 0, 0, -1], i * 8);
423
+ const inactiveRanges = buffer(1, 1, Uint32Array);
424
+ const views = storage(inactiveView, "vec4", boxes * 2).toReadOnly();
425
+ const ranges = storage(inactiveRanges, "uint").toReadOnly();
426
+ const inverse = new Matrix4(), eye = new Vector3(), center = new Vector3();
427
+ const states = /* @__PURE__ */ new Map();
428
+ let tiles, patches, reduce, passes;
429
+ function prepare({ renderer, camera, object }) {
430
+ views.value = inactiveView;
431
+ ranges.value = inactiveRanges;
432
+ if (!renderer.backend?.isWebGPUBackend || renderer.xr?.isPresenting || object.isInstancedMesh || !camera.isPerspectiveCamera && !camera.isOrthographicCamera || camera.isArrayCamera)
433
+ return;
434
+ inverse.copy(object.matrixWorld).invert();
435
+ const ortho = camera.isOrthographicCamera === true;
436
+ if (ortho) camera.getWorldDirection(eye).transformDirection(inverse);
437
+ else eye.setFromMatrixPosition(camera.matrixWorld).applyMatrix4(inverse);
438
+ if (!Number.isFinite(eye.lengthSq())) return;
439
+ let state = states.get(renderer);
440
+ if (!state) {
441
+ state = { slots: [], initialized: false };
442
+ states.set(renderer, state);
443
+ }
444
+ if (!tiles) {
445
+ const capture = captureTiles(descriptor);
446
+ tiles = capture.tiles;
447
+ patches = buffer(tiles.count * 4, 4);
448
+ reduce = buildPatches(descriptor, maps, rects, tiles, capture.size, patches);
449
+ const computeViews = storage(inactiveView, "vec4", boxes * 2).toReadOnly();
450
+ passes = {
451
+ ...makeViewPasses(patches, computeViews, inactiveRanges, count, resolution),
452
+ views: computeViews
453
+ };
454
+ }
455
+ if (!state.initialized || state.depthVersion !== maps.normalDepth.version || state.coverageVersion !== maps.orm.version) {
456
+ renderer.compute(reduce);
457
+ for (const slot2 of state.slots) slot2.ready = false;
458
+ state.depthVersion = maps.normalDepth.version;
459
+ state.coverageVersion = maps.orm.version;
460
+ state.initialized = true;
461
+ }
462
+ const frame = renderer.info.render.calls;
463
+ const compatible = (v) => v.ready && v.ortho === ortho && v.eye.distanceToSquared(eye) <= v.radiusSq;
464
+ let slot = state.slots.find((v) => v.object.deref() === object && v.camera.deref() === camera);
465
+ if (!slot || !compatible(slot)) {
466
+ const shared = state.slots.find(compatible);
467
+ if (shared) {
468
+ shared.frame = frame;
469
+ views.value = shared.view;
470
+ ranges.value = shared.ranges;
471
+ return;
472
+ }
473
+ if (slot?.frame === frame) slot = void 0;
474
+ }
475
+ if (!slot) {
476
+ if (state.slots.length < maxViews) {
477
+ slot = { view: buffer(boxes * 2, 4), ranges: buffer(count, 1, Uint32Array), eye: new Vector3() };
478
+ state.slots.push(slot);
479
+ } else {
480
+ slot = state.slots.reduce((oldest, v) => v.frame < oldest.frame ? v : oldest);
481
+ if (slot.frame === frame) {
482
+ let nearest = Infinity;
483
+ for (const v of state.slots) {
484
+ if (!v.ready || v.ortho !== ortho) continue;
485
+ const distance = v.eye.distanceToSquared(eye);
486
+ if (distance < nearest) {
487
+ nearest = distance;
488
+ views.value = v.view;
489
+ ranges.value = v.ranges;
490
+ }
491
+ }
492
+ return;
493
+ }
494
+ }
495
+ slot.object = new WeakRef(object);
496
+ slot.camera = new WeakRef(camera);
497
+ slot.ready = false;
498
+ }
499
+ slot.frame = frame;
500
+ views.value = slot.view;
501
+ ranges.value = slot.ranges;
502
+ if (compatible(slot)) return;
503
+ setProjection(slot.view.array, descriptor, eye.toArray(), ortho, resolution);
504
+ slot.view.needsUpdate = true;
505
+ passes.views.value = slot.view;
506
+ passes.table.value = slot.ranges;
507
+ renderer.compute([passes.reset, passes.scatter]);
508
+ const distanceSquared = ortho ? 1 : Math.min(...descriptor.boxes.map((box) => eye.distanceToSquared(center.fromArray(box.center))));
509
+ slot.radiusSq = distanceSquared * REFRESH_ANGLE_SQUARED;
510
+ slot.eye.copy(eye);
511
+ slot.ortho = ortho;
512
+ slot.ready = true;
513
+ }
514
+ views.updateBeforeType = NodeUpdateType2.OBJECT;
515
+ views.updateBefore = prepare;
516
+ material.addEventListener("dispose", () => {
517
+ for (const state of states.values()) {
518
+ for (const slot of state.slots) {
519
+ slot.view.dispose();
520
+ slot.ranges.dispose();
521
+ }
522
+ }
523
+ states.clear();
524
+ reduce?.dispose();
525
+ passes?.reset.dispose();
526
+ passes?.scatter.dispose();
527
+ tiles?.dispose();
528
+ patches?.dispose();
529
+ inactiveView.dispose();
530
+ inactiveRanges.dispose();
531
+ });
532
+ return (builder, id, o, r, enter, exit) => {
533
+ if (!builder.renderer.backend?.isWebGPUBackend) return null;
534
+ const mapping = views.element(id.mul(2)).toVar();
535
+ const ref = views.element(id.mul(2).add(1)).toVar();
536
+ const axis = int2(max(ref.w, 0)).mod(3), x = axis.add(1).mod(3), y = axis.add(2).mod(3);
537
+ const rz = r.element(axis).toVar(), oz = o.element(axis).toVar();
538
+ const ez = ref.element(axis), e = vec2(ref.element(x), ref.element(y));
539
+ const eyeSlope = e.div(ez), inverseDistance = ref.w.lessThan(3).select(1, 0).div(ez);
540
+ const project = (t) => {
541
+ const point = o.add(r.mul(t)), v = vec2(point.element(x), point.element(y)), z = point.element(axis);
542
+ const p = v.sub(eyeSlope.mul(z)).div(float(1).sub(inverseDistance.mul(z)));
543
+ return p.sub(mapping.xy).mul(mapping.zw);
544
+ };
545
+ const a = project(enter).toVar(), b = project(exit).toVar();
546
+ const cellLo = ivec22(floor(min(a, b).sub(1e-3)).clamp(0, resolution - 1)).toVar();
547
+ const cellHi = ivec22(floor(max(a, b).add(1e-3)).clamp(0, resolution - 1)).toVar();
548
+ const valid = ref.w.greaterThanEqual(0).and(rz.abs().greaterThan(1e-12)).and(cellHi.sub(cellLo).lessThanEqual(ivec22(2)).all()).toVar();
549
+ return (face, enter2, exit2) => {
550
+ const start = enter2.toVar(), end = exit2.toVar();
551
+ If(valid, () => {
552
+ const base = id.mul(6).add(face).mul(resolution ** 2);
553
+ const at = (u, v) => base.add(v.mul(resolution)).add(u).mul(2);
554
+ const idx = at(cellLo.x, cellLo.y).toVar();
555
+ const lower = ranges.element(idx).toVar(), upper = ranges.element(idx.add(1)).toVar();
556
+ If(cellHi.notEqual(cellLo).any(), () => {
557
+ Loop({ start: cellLo.y, end: cellHi.y.add(1), type: "int", name: "by" }, ({ by }) => {
558
+ Loop({ start: cellLo.x, end: cellHi.x.add(1), type: "int", name: "bx" }, ({ bx }) => {
559
+ const p = at(bx, by);
560
+ lower.assign(min(lower, ranges.element(p)));
561
+ upper.assign(min(upper, ranges.element(p.add(1))));
562
+ });
563
+ });
564
+ });
565
+ const lo = float(lower).mul(2 / DEPTH_MAX).sub(1), hi = float(1).sub(float(upper).mul(2 / DEPTH_MAX));
566
+ const a2 = lo.sub(oz).div(rz), b2 = hi.sub(oz).div(rz);
567
+ start.assign(min(a2, b2));
568
+ end.assign(lo.lessThanEqual(hi).select(max(a2, b2), enter2.sub(1)));
569
+ });
570
+ return { start, end };
571
+ };
572
+ };
573
+ }
574
+
106
575
  // src/box-impostor/box-impostor-surface-search.js
107
- function refineSurfaceCrossing({ float: float4, If: If4, Loop: Loop2 }, { lo, hi, loValue, hiValue, height, steps, secant }) {
576
+ function refineSurfaceCrossing({ float: float5, If: If5, Loop: Loop3 }, { lo, hi, loValue, hiValue, height, steps, secant }) {
108
577
  const a = lo.toVar(), b = hi.toVar(), fa = loValue.toVar(), fb = secant ? hiValue.toVar() : null;
109
- Loop2(steps, () => {
578
+ Loop3(steps, () => {
110
579
  const mid = a.add(b).mul(0.5).toVar(), d = height(mid).toVar();
111
- If4(d.mul(fa).greaterThan(0), () => {
580
+ If5(d.mul(fa).greaterThan(0), () => {
112
581
  a.assign(mid);
113
582
  if (secant) fa.assign(d);
114
583
  }).Else(() => {
@@ -120,23 +589,23 @@ function refineSurfaceCrossing({ float: float4, If: If4, Loop: Loop2 }, { lo, hi
120
589
  }
121
590
 
122
591
  // src/box-impostor/box-impostor-faces.js
123
- import { DataTexture, FloatType, RGBAFormat, NearestFilter } from "three";
592
+ import { DataTexture as DataTexture2, FloatType as FloatType2, RGBAFormat as RGBAFormat2, NearestFilter } from "three";
124
593
  import {
125
- Fn as Fn2,
126
- If,
594
+ Fn as Fn3,
595
+ If as If2,
127
596
  attribute,
128
- positionLocal,
597
+ positionGeometry,
129
598
  uv,
130
599
  texture,
131
- textureLoad,
132
- ivec2,
133
- vec2,
134
- vec3,
135
- float,
136
- int,
137
- dot,
600
+ textureLoad as textureLoad3,
601
+ ivec2 as ivec23,
602
+ vec2 as vec22,
603
+ vec3 as vec33,
604
+ float as float2,
605
+ int as int3,
606
+ dot as dot2,
138
607
  abs,
139
- max,
608
+ max as max2,
140
609
  sign,
141
610
  transformNormalToView
142
611
  } from "three/tsl";
@@ -183,16 +652,6 @@ function boxDepthMode(descriptor, settings) {
183
652
  ) ? "projection" : "depth";
184
653
  }
185
654
 
186
- // src/box-impostor/box-impostor-face-axes.js
187
- var BOX_FACE_AXES = Object.freeze([
188
- { normal: [1, 0, 0], right: [0, 0, -1], up: [0, 1, 0] },
189
- { normal: [-1, 0, 0], right: [0, 0, 1], up: [0, 1, 0] },
190
- { normal: [0, 1, 0], right: [1, 0, 0], up: [0, 0, -1] },
191
- { normal: [0, -1, 0], right: [1, 0, 0], up: [0, 0, 1] },
192
- { normal: [0, 0, 1], right: [1, 0, 0], up: [0, 1, 0] },
193
- { normal: [0, 0, -1], right: [-1, 0, 0], up: [0, 1, 0] }
194
- ]);
195
-
196
655
  // src/box-impostor/box-impostor-metadata.js
197
656
  var BOX_OCCUPANCY_RESOLUTION = 8;
198
657
  var BOX_OCCUPANCY_WORDS = BOX_OCCUPANCY_RESOLUTION ** 3 / 32;
@@ -206,60 +665,62 @@ function applyBoxFaces({
206
665
  transparency,
207
666
  half,
208
667
  toBox,
209
- fromBox
668
+ fromBox,
669
+ meshVertex,
670
+ meshNormal
210
671
  }) {
211
672
  const values = new Float32Array(descriptor.boxes.length * 6 * 4);
212
673
  descriptor.boxes.forEach((box, i) => {
213
674
  for (let face2 = 0; face2 < 6; face2++)
214
675
  values[(i * 6 + face2) * 4] = box.planes?.[face2] ?? 0.5;
215
676
  });
216
- const planes = new DataTexture(
677
+ const planes = new DataTexture2(
217
678
  values,
218
679
  6,
219
680
  descriptor.boxes.length,
220
- RGBAFormat,
221
- FloatType
681
+ RGBAFormat2,
682
+ FloatType2
222
683
  );
223
684
  planes.minFilter = planes.magFilter = NearestFilter;
224
685
  planes.needsUpdate = true;
225
686
  material.addEventListener("dispose", () => planes.dispose());
226
- const face = int(attribute("boxFace", "float"));
687
+ const face = int3(attribute("boxFace", "float"));
227
688
  const n = attribute("normal", "vec3");
228
- const depth = textureLoad(
689
+ const depth = textureLoad3(
229
690
  planes,
230
- ivec2(face, int(attribute("boxId", "float")))
691
+ ivec23(face, int3(attribute("boxId", "float")))
231
692
  ).r;
232
- const proxy = positionLocal.sub(
693
+ const proxy = positionGeometry.sub(
233
694
  n.mul(
234
- dot(abs(toBox(n)), half).mul(depth).mul(2)
695
+ dot2(abs(toBox(n)), half).mul(depth).mul(2)
235
696
  )
236
697
  );
237
- material.positionNode = proxy;
238
- material.castShadowPositionNode = proxy;
698
+ material.positionNode = meshVertex(proxy);
699
+ material.castShadowPositionNode = material.positionNode;
239
700
  const base = texture(maps.baseColor, uv()).level(0).toVar("boxFaceColor");
240
701
  const orm = texture(maps.orm, uv()).level(0);
241
- const coverage = max(orm.a, 1e-10);
242
- const normal = Fn2(() => {
243
- const packed = textureLoad(
702
+ const coverage = max2(orm.a, 1e-10);
703
+ const normal = Fn3(() => {
704
+ const packed = textureLoad3(
244
705
  maps.normalDepth,
245
- ivec2(uv().mul(descriptor.atlasResolution))
706
+ ivec23(uv().mul(descriptor.atlasResolution))
246
707
  ).rg.mul(2).sub(1);
247
- const decoded = vec3(
708
+ const decoded = vec33(
248
709
  packed,
249
- float(1).sub(abs(packed.x)).sub(abs(packed.y))
710
+ float2(1).sub(abs(packed.x)).sub(abs(packed.y))
250
711
  ).toVar();
251
- If(decoded.z.lessThan(0), () => {
712
+ If2(decoded.z.lessThan(0), () => {
252
713
  decoded.xy.assign(
253
- vec2(1).sub(abs(decoded.yx)).mul(sign(decoded.xy.add(1e-20)))
714
+ vec22(1).sub(abs(decoded.yx)).mul(sign(decoded.xy.add(1e-20)))
254
715
  );
255
716
  });
256
- const result = vec3(0).toVar();
717
+ const result = vec33(0).toVar();
257
718
  for (let f = 0; f < 6; f++) {
258
719
  const a = BOX_FACE_AXES[f];
259
- If(face.equal(f), () => {
720
+ If2(face.equal(f), () => {
260
721
  result.assign(
261
722
  fromBox(
262
- vec3(...a.right).mul(decoded.x).add(vec3(...a.up).mul(decoded.y)).add(vec3(...a.normal).mul(decoded.z))
723
+ vec33(...a.right).mul(decoded.x).add(vec33(...a.up).mul(decoded.y)).add(vec33(...a.normal).mul(decoded.z))
263
724
  ).normalize()
264
725
  );
265
726
  });
@@ -267,13 +728,13 @@ function applyBoxFaces({
267
728
  return result;
268
729
  })();
269
730
  material.colorNode = base.rgb.div(coverage);
270
- material.normalNode = transformNormalToView(normal);
731
+ material.normalNode = transformNormalToView(meshNormal(normal));
271
732
  material.roughnessNode = orm.g.div(coverage);
272
733
  material.metalnessNode = orm.b.div(coverage);
273
734
  material.aoNode = orm.r.div(coverage);
274
735
  material.emissiveNode = texture(maps.emissive, uv()).level(0).rgb.div(coverage);
275
736
  material.maskNode = base.a.greaterThanEqual(
276
- transparency === "cutout" ? alphaCutoff : float(1 / 255)
737
+ transparency === "cutout" ? alphaCutoff : float2(1 / 255)
277
738
  );
278
739
  material.maskShadowNode = material.maskNode;
279
740
  if (transparency !== "cutout") material.opacityNode = base.a;
@@ -282,23 +743,23 @@ function applyBoxFaces({
282
743
  }
283
744
 
284
745
  // src/box-impostor/box-impostor-projection.js
285
- import { DataTexture as DataTexture2, FloatType as FloatType2, RGBAFormat as RGBAFormat2, NearestFilter as NearestFilter2 } from "three";
746
+ import { DataTexture as DataTexture3, FloatType as FloatType3, RGBAFormat as RGBAFormat3, NearestFilter as NearestFilter2 } from "three";
286
747
  import {
287
- Fn as Fn3,
288
- If as If2,
289
- vec2 as vec22,
290
- vec3 as vec32,
291
- vec4 as vec43,
292
- float as float2,
293
- int as int2,
294
- ivec2 as ivec22,
295
- dot as dot2,
748
+ Fn as Fn4,
749
+ If as If3,
750
+ vec2 as vec23,
751
+ vec3 as vec34,
752
+ vec4 as vec45,
753
+ float as float3,
754
+ int as int4,
755
+ ivec2 as ivec24,
756
+ dot as dot3,
296
757
  abs as abs2,
297
- max as max2,
758
+ max as max3,
298
759
  sign as sign2,
299
760
  normalize,
300
761
  texture as texture2,
301
- textureLoad as textureLoad2,
762
+ textureLoad as textureLoad4,
302
763
  attribute as attribute2,
303
764
  struct,
304
765
  modelWorldMatrix as modelWorldMatrix2,
@@ -319,19 +780,21 @@ function applyBoxProjection({
319
780
  eye,
320
781
  viewAxis,
321
782
  perspective,
322
- raster
783
+ raster,
784
+ meshPoint,
785
+ meshNormal
323
786
  }) {
324
787
  const data = new Float32Array(descriptor.boxes.length * 24);
325
788
  descriptor.boxes.forEach((box, i) => {
326
789
  for (let face = 0; face < 6; face++)
327
790
  data[(i * 6 + face) * 4] = box.planes?.[face] ?? 0.5;
328
791
  });
329
- const planes = new DataTexture2(
792
+ const planes = new DataTexture3(
330
793
  data,
331
794
  6,
332
795
  descriptor.boxes.length,
333
- RGBAFormat2,
334
- FloatType2
796
+ RGBAFormat3,
797
+ FloatType3
335
798
  );
336
799
  planes.minFilter = planes.magFilter = NearestFilter2;
337
800
  planes.needsUpdate = true;
@@ -348,24 +811,24 @@ function applyBoxProjection({
348
811
  "BoxProjectedSurface"
349
812
  );
350
813
  const readNormal = (uv2, right, up, n) => {
351
- const packed = textureLoad2(
814
+ const packed = textureLoad4(
352
815
  maps.normalDepth,
353
- ivec22(uv2.mul(descriptor.atlasResolution))
816
+ ivec24(uv2.mul(descriptor.atlasResolution))
354
817
  ).rg.mul(2).sub(1);
355
- const decoded = vec32(
818
+ const decoded = vec34(
356
819
  packed,
357
- float2(1).sub(abs2(packed.x)).sub(abs2(packed.y))
820
+ float3(1).sub(abs2(packed.x)).sub(abs2(packed.y))
358
821
  ).toVar();
359
- If2(decoded.z.lessThan(0), () => {
822
+ If3(decoded.z.lessThan(0), () => {
360
823
  decoded.xy.assign(
361
- vec22(1).sub(abs2(decoded.yx)).mul(sign2(decoded.xy.add(1e-20)))
824
+ vec23(1).sub(abs2(decoded.yx)).mul(sign2(decoded.xy.add(1e-20)))
362
825
  );
363
826
  });
364
827
  return fromBox(
365
828
  right.mul(decoded.x).add(up.mul(decoded.y)).add(n.mul(decoded.z))
366
829
  ).normalize();
367
830
  };
368
- const surface = Fn3(() => {
831
+ const surface = Fn4(() => {
369
832
  const ray = perspective.select(
370
833
  normalize(raster.sub(eye)),
371
834
  viewAxis.negate()
@@ -376,48 +839,48 @@ function applyBoxProjection({
376
839
  );
377
840
  const o = toBox(origin.sub(center)).div(half), r = toBox(ray).div(half);
378
841
  const look = normalize(toBox(ray).negate()), angles = abs2(look);
379
- const positions = vec32(0).toVar();
380
- const selectedUv = vec22(0).toVar(), selectedRight = vec32(1, 0, 0).toVar(), selectedUp = vec32(0, 1, 0).toVar(), selectedNormal = vec32(0, 0, 1).toVar();
381
- const nearest = float2(1e20).toVar("boxPlaneDistance");
382
- const opacity = float2(0).toVar();
842
+ const positions = vec34(0).toVar();
843
+ const selectedUv = vec23(0).toVar(), selectedRight = vec34(1, 0, 0).toVar(), selectedUp = vec34(0, 1, 0).toVar(), selectedNormal = vec34(0, 0, 1).toVar();
844
+ const nearest = float3(1e20).toVar("boxPlaneDistance");
845
+ const opacity = float3(0).toVar();
383
846
  const candidates = [];
384
847
  for (let axis = 0; axis < 3; axis++) {
385
848
  const angle = angles.element(axis);
386
849
  const positive = look.element(axis).greaterThanEqual(0), a = BOX_FACE_AXES[axis * 2], b = BOX_FACE_AXES[axis * 2 + 1];
387
- 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));
850
+ const n = positive.select(vec34(...a.normal), vec34(...b.normal)), right = positive.select(vec34(...a.right), vec34(...b.right)), up = positive.select(vec34(...a.up), vec34(...b.up));
388
851
  const weight = settings.interpolation === "smooth" ? angle.mul(angle) : angle;
389
852
  const candidate = settings.interpolation === "none" ? null : {
390
- uv: vec22(0).toVar(),
391
- base: vec43(0).toVar(),
392
- orm: vec43(0).toVar(),
393
- t: float2(1e20).toVar(),
394
- tolerance: float2(0).toVar(),
853
+ uv: vec23(0).toVar(),
854
+ base: vec45(0).toVar(),
855
+ orm: vec45(0).toVar(),
856
+ t: float3(1e20).toVar(),
857
+ tolerance: float3(0).toVar(),
395
858
  right,
396
859
  up,
397
860
  n,
398
861
  weight
399
862
  };
400
863
  if (candidate) candidates.push(candidate);
401
- If2(angle.greaterThan(1e-4), () => {
402
- const face = positive.select(int2(axis * 2), int2(axis * 2 + 1)), id = int2(attribute2("boxId", "float"));
403
- const plane = float2(1).sub(
404
- textureLoad2(planes, ivec22(face, id)).r.mul(2)
864
+ If3(angle.greaterThan(1e-4), () => {
865
+ const face = positive.select(int4(axis * 2), int4(axis * 2 + 1)), id = int4(attribute2("boxId", "float"));
866
+ const plane = float3(1).sub(
867
+ textureLoad4(planes, ivec24(face, id)).r.mul(2)
405
868
  );
406
- const divisor2 = dot2(r, n), safe = sign2(divisor2.add(1e-20)).mul(max2(abs2(divisor2), 1e-10));
407
- const t = plane.sub(dot2(o, n)).div(safe), point = o.add(r.mul(t));
408
- const xy = vec22(dot2(point, right), dot2(point, up)).mul(0.5).add(0.5);
869
+ const divisor2 = dot3(r, n), safe = sign2(divisor2.add(1e-20)).mul(max3(abs2(divisor2), 1e-10));
870
+ const t = plane.sub(dot3(o, n)).div(safe), point = o.add(r.mul(t));
871
+ const xy = vec23(dot3(point, right), dot3(point, up)).mul(0.5).add(0.5);
409
872
  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));
410
873
  if (!candidate) supported = supported.and(t.lessThan(nearest));
411
- If2(supported, () => {
412
- const rect = textureLoad2(rects, ivec22(face, id)), uv2 = rect.xy.add(xy.mul(rect.zw));
874
+ If3(supported, () => {
875
+ const rect = textureLoad4(rects, ivec24(face, id)), uv2 = rect.xy.add(xy.mul(rect.zw));
413
876
  const base = texture2(maps.baseColor, uv2).level(0), orm = texture2(maps.orm, uv2).level(0);
414
877
  const alpha2 = base.a.clamp(0, 1);
415
- If2(
878
+ If3(
416
879
  alpha2.greaterThanEqual(
417
- transparency === "cutout" ? alphaCutoff : float2(1 / 255)
880
+ transparency === "cutout" ? alphaCutoff : float3(1 / 255)
418
881
  ).and(orm.a.greaterThan(0)),
419
882
  () => {
420
- If2(t.lessThan(nearest), () => {
883
+ If3(t.lessThan(nearest), () => {
421
884
  nearest.assign(t);
422
885
  selectedUv.assign(uv2);
423
886
  opacity.assign(alpha2);
@@ -432,14 +895,14 @@ function applyBoxProjection({
432
895
  candidate.orm.assign(orm);
433
896
  candidate.t.assign(t);
434
897
  candidate.tolerance.assign(
435
- max2(
436
- dot2(abs2(right), half).div(
898
+ max3(
899
+ dot3(abs2(right), half).div(
437
900
  rect.z.mul(descriptor.atlasResolution)
438
901
  ),
439
- dot2(abs2(up), half).div(
902
+ dot3(abs2(up), half).div(
440
903
  rect.w.mul(descriptor.atlasResolution)
441
904
  )
442
- ).mul(4).div(max2(angle, 0.1))
905
+ ).mul(4).div(max3(angle, 0.1))
443
906
  );
444
907
  }
445
908
  }
@@ -449,7 +912,7 @@ function applyBoxProjection({
449
912
  }
450
913
  if (settings.interpolation === "none") {
451
914
  const base = texture2(maps.baseColor, selectedUv).level(0), orm = texture2(maps.orm, selectedUv).level(0);
452
- const coverage = max2(orm.a, 1e-10);
915
+ const coverage = max3(orm.a, 1e-10);
453
916
  return Surface(
454
917
  base.rgb.div(coverage),
455
918
  opacity,
@@ -459,15 +922,15 @@ function applyBoxProjection({
459
922
  positions
460
923
  );
461
924
  }
462
- const colors = vec32(0).toVar(), orms = vec32(0).toVar(), emissions = vec32(0).toVar(), normals = vec32(0).toVar();
463
- const weights = float2(0).toVar(), support = float2(0).toVar(), alpha = float2(0).toVar();
925
+ const colors = vec34(0).toVar(), orms = vec34(0).toVar(), emissions = vec34(0).toVar(), normals = vec34(0).toVar();
926
+ const weights = float3(0).toVar(), support = float3(0).toVar(), alpha = float3(0).toVar();
464
927
  for (const c of candidates) {
465
- If2(
928
+ If3(
466
929
  c.base.a.greaterThan(0).and(c.t.lessThanEqual(nearest.add(c.tolerance))),
467
930
  () => {
468
- const coverage = max2(c.orm.a, 1e-10), w = c.base.a.mul(c.weight);
931
+ const coverage = max3(c.orm.a, 1e-10), w = c.base.a.mul(c.weight);
469
932
  weights.addAssign(c.weight.mul(coverage));
470
- support.assign(max2(support, coverage));
933
+ support.assign(max3(support, coverage));
471
934
  colors.addAssign(c.base.rgb.div(coverage).mul(w));
472
935
  orms.addAssign(c.orm.rgb.div(coverage).mul(w));
473
936
  emissions.addAssign(
@@ -478,29 +941,30 @@ function applyBoxProjection({
478
941
  }
479
942
  );
480
943
  }
481
- const divisor = max2(alpha, 1e-10);
944
+ const divisor = max3(alpha, 1e-10);
482
945
  return Surface(
483
946
  colors.div(divisor),
484
- alpha.div(max2(weights, 1e-10)).mul(support),
947
+ alpha.div(max3(weights, 1e-10)).mul(support),
485
948
  orms.div(divisor),
486
949
  emissions.div(divisor),
487
- normals.div(max2(normals.length(), 1e-10)),
950
+ normals.div(max3(normals.length(), 1e-10)),
488
951
  positions
489
952
  );
490
953
  })().toVar("boxProjectedSurface");
491
- material.capturedPositionNode = surface.get("position");
954
+ const position = meshPoint(surface.get("position")).toVar("boxProjectedMeshPosition");
955
+ material.capturedPositionNode = position;
492
956
  material.colorNode = surface.get("color");
493
- material.normalNode = transformNormalToView2(surface.get("normal"));
957
+ material.normalNode = transformNormalToView2(meshNormal(surface.get("normal")));
494
958
  material.roughnessNode = surface.get("orm").g;
495
959
  material.metalnessNode = surface.get("orm").b;
496
960
  material.aoNode = surface.get("orm").r;
497
961
  material.emissiveNode = surface.get("emission");
498
- material.maskNode = surface.get("alpha").greaterThanEqual(transparency === "cutout" ? alphaCutoff : float2(1 / 255));
962
+ material.maskNode = surface.get("alpha").greaterThanEqual(transparency === "cutout" ? alphaCutoff : float3(1 / 255));
499
963
  material.maskShadowNode = material.maskNode;
500
964
  if (transparency !== "cutout") material.opacityNode = surface.get("alpha");
501
- material.depthNode = capturedSurfaceDepth(surface.get("position"));
965
+ material.depthNode = capturedSurfaceDepth(position);
502
966
  material.receivedShadowPositionNode = modelWorldMatrix2.mul(
503
- vec43(surface.get("position"), 1)
967
+ vec45(position, 1)
504
968
  ).xyz;
505
969
  material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
506
970
  return material;
@@ -510,39 +974,40 @@ function applyBoxProjection({
510
974
  function createBoxImpostorMaterial(descriptor, maps) {
511
975
  return createBoxImpostorMaterialVariant(descriptor, maps, { filtering: true });
512
976
  }
513
- function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false } = {}) {
977
+ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false, boundSearch = true } = {}) {
514
978
  const settings = normalizeBoxImpostorDisplay(descriptor);
515
979
  const alphaCutoff = uniform(settings.alphaCutoff);
516
980
  const transparency = boxTransparency(descriptor, settings);
517
- const minimumAlpha = transparency === "cutout" ? alphaCutoff : float3(1 / 255);
518
- const surfaceCoverage = (ormAlpha, baseAlpha) => filtering && descriptor.alphaMode !== "blend" ? min(ormAlpha, baseAlpha) : ormAlpha;
519
- const decodeNormal = (encoded) => {
981
+ const minimumAlpha = transparency === "cutout" ? alphaCutoff : float4(1 / 255);
982
+ const surfaceCoverage = (ormAlpha, baseAlpha) => filtering && descriptor.alphaMode !== "blend" ? min2(ormAlpha, baseAlpha) : ormAlpha;
983
+ const unpackNormal = (encoded) => {
520
984
  const packed = encoded.mul(2).sub(1);
521
- const normal2 = vec33(packed, float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))).toVar();
522
- If3(normal2.z.lessThan(0), () => {
523
- normal2.xy.assign(vec23(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20))));
985
+ const normal2 = vec35(packed, float4(1).sub(abs3(packed.x)).sub(abs3(packed.y))).toVar();
986
+ If4(normal2.z.lessThan(0), () => {
987
+ normal2.xy.assign(vec24(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20))));
524
988
  });
525
- return normal2.normalize();
989
+ return normal2;
526
990
  };
991
+ const decodeNormal = (encoded) => unpackNormal(encoded).normalize();
527
992
  const filteredNormal = (uv2, depth, tolerance, nearest, alpha, sampled = texture3(maps.normalDepth, uv2).level(0), ormAlpha = texture3(maps.orm, uv2).level(0).a) => {
528
993
  sampled = sampled.toVar();
529
- const coverage2 = max3(descriptor.alphaMode === "blend" ? ormAlpha : alpha, 1e-10);
994
+ const coverage2 = max4(descriptor.alphaMode === "blend" ? ormAlpha : alpha, 1e-10);
530
995
  const nearestNormal = decodeNormal(nearest.rg), result = decodeNormal(sampled.rg.div(coverage2)).toVar();
531
996
  const sampledDepth = sampled.b.mul(65280).add(sampled.a.mul(255)).div(65535);
532
997
  const nearestDepth = nearest.b.mul(65280).add(nearest.a.mul(255)).div(65535);
533
- If3(nearestNormal.z.lessThan(0).or(dot3(result, nearestNormal).lessThan(0.75)).or(coverage2.lessThan(0.9999)).or(abs3(sampledDepth.sub(nearestDepth)).greaterThan(tolerance)), () => {
534
- const p = uv2.mul(descriptor.atlasResolution).sub(0.5), lo = floor(p), f = fract(p);
535
- const normal2 = vec33(0).toVar(), weights = float3(0).toVar();
998
+ If4(nearestNormal.z.lessThan(0).or(dot4(result, nearestNormal).lessThan(0.75)).or(coverage2.lessThan(0.9999)).or(abs3(sampledDepth.sub(nearestDepth)).greaterThan(tolerance)), () => {
999
+ const p = uv2.mul(descriptor.atlasResolution).sub(0.5), lo = floor2(p), f = fract(p);
1000
+ const normal2 = vec35(0).toVar(), weights = float4(0).toVar();
536
1001
  for (const [x, y] of [[0, 0], [1, 0], [0, 1], [1, 1]]) {
537
- const texel = ivec23(lo.add(vec23(x, y)).clamp(0, descriptor.atlasResolution - 1));
538
- const packed = textureLoad3(maps.normalDepth, texel).toVar();
539
- const alpha2 = textureLoad3(maps.baseColor, texel).a;
540
- const coverage3 = descriptor.alphaMode === "blend" ? textureLoad3(maps.orm, texel).a : alpha2;
1002
+ const texel = ivec25(lo.add(vec24(x, y)).clamp(0, descriptor.atlasResolution - 1));
1003
+ const packed = textureLoad5(maps.normalDepth, texel).toVar();
1004
+ const alpha2 = textureLoad5(maps.baseColor, texel).a;
1005
+ const coverage3 = descriptor.alphaMode === "blend" ? textureLoad5(maps.orm, texel).a : alpha2;
541
1006
  const capturedDepth = packed.b.mul(65280).add(packed.a.mul(255)).div(65535);
542
1007
  const supported = coverage3.greaterThan(1e-4).and(alpha2.greaterThanEqual(minimumAlpha.mul(coverage3))).and(abs3(capturedDepth.sub(depth)).lessThanEqual(tolerance));
543
- If3(supported, () => {
544
- const weight = (x ? f.x : float3(1).sub(f.x)).mul(y ? f.y : float3(1).sub(f.y)).mul(coverage3);
545
- normal2.addAssign(decodeNormal(packed.rg.div(max3(coverage3, 1e-10))).mul(weight));
1008
+ If4(supported, () => {
1009
+ const weight = (x ? f.x : float4(1).sub(f.x)).mul(y ? f.y : float4(1).sub(f.y)).mul(coverage3);
1010
+ normal2.addAssign(decodeNormal(packed.rg.div(max4(coverage3, 1e-10))).mul(weight));
546
1011
  weights.addAssign(weight);
547
1012
  });
548
1013
  }
@@ -579,57 +1044,68 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
579
1044
  )
580
1045
  )
581
1046
  );
582
- const rects = new DataTexture3(
1047
+ const rects = new DataTexture4(
583
1048
  rectData,
584
1049
  6,
585
1050
  descriptor.boxes.length,
586
- RGBAFormat3,
587
- FloatType3
1051
+ RGBAFormat4,
1052
+ FloatType4
588
1053
  );
589
1054
  rects.needsUpdate = true;
590
1055
  rects.magFilter = rects.minFilter = NearestFilter3;
591
1056
  material.addEventListener("dispose", () => rects.dispose());
592
1057
  const center = attribute3("boxCenter", "vec3"), half = attribute3("boxHalfSize", "vec3");
593
1058
  const ax = attribute3("boxAxisX", "vec3"), ay = attribute3("boxAxisY", "vec3"), az = attribute3("boxAxisZ", "vec3");
594
- const toBox = (p) => vec33(dot3(p, ax), dot3(p, ay), dot3(p, az));
1059
+ const toBox = (p) => vec35(dot4(p, ax), dot4(p, ay), dot4(p, az));
595
1060
  const fromBox = (p) => ax.mul(p.x).add(ay.mul(p.y)).add(az.mul(p.z));
596
- const eye = modelWorldMatrixInverse.mul(vec44(cameraPosition, 1)).xyz;
597
- const viewAxis = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec44(0, 0, 1, 0))).xyz.normalize();
1061
+ const meshVertex = (p) => Fn5((_, builder) => instanceSpace(builder)?.toMeshPoint(p) ?? p)();
1062
+ const meshPoint = (p) => Fn5((_, builder) => instanceSpace(builder)?.fragment.toMeshPoint(p) ?? p)();
1063
+ const meshNormal = (n) => Fn5((_, builder) => instanceSpace(builder)?.fragment.toMeshNormal(n) ?? n)();
1064
+ const meshEye = modelWorldMatrixInverse.mul(vec46(cameraPosition, 1)).xyz;
1065
+ const meshViewAxis = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec46(0, 0, 1, 0))).xyz;
1066
+ const eye = Fn5((_, builder) => instanceSpace(builder)?.fragment.toLocalPoint(meshEye) ?? meshEye)();
1067
+ const viewAxis = Fn5((_, builder) => instanceSpace(builder)?.fragment.toLocalDirection(meshViewAxis) ?? meshViewAxis)().normalize();
1068
+ const vertexEye = Fn5((_, builder) => instanceSpace(builder)?.toLocalPoint(meshEye) ?? meshEye)();
1069
+ const vertexViewAxis = Fn5((_, builder) => instanceSpace(builder)?.toLocalDirection(meshViewAxis) ?? meshViewAxis)().normalize();
1070
+ const cameraUp = Fn5((_, builder) => {
1071
+ const up = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec46(0, 1, 0, 0))).xyz;
1072
+ return instanceSpace(builder)?.toLocalDirection(up) ?? up;
1073
+ })();
598
1074
  const perspective = cameraProjectionMatrix2.element(3).w.equal(0);
599
- let proxy = positionLocal2;
1075
+ let proxy = positionGeometry2;
600
1076
  if (descriptor.mode !== "fitted") {
601
- proxy = Fn4((_, builder) => {
602
- const delta = eye.sub(center);
603
- const forward = perspective.and(delta.length().greaterThan(1e-6)).select(normalize2(delta), viewAxis);
604
- const right = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec44(0, 1, 0, 0))).xyz.cross(forward).normalize();
1077
+ proxy = Fn5((_, builder) => {
1078
+ const delta = vertexEye.sub(center);
1079
+ const forward = perspective.and(delta.length().greaterThan(1e-6)).select(normalize2(delta), vertexViewAxis);
1080
+ const right = cameraUp.cross(forward).normalize();
605
1081
  const up = forward.cross(right).normalize();
606
1082
  const radius = half.length();
607
- const distance = dot3(eye.sub(center), forward);
608
- const planeOffset = perspective.select(min(radius, distance.sub(cameraNear2.mul(2))), radius);
1083
+ const distance = dot4(vertexEye.sub(center), forward);
1084
+ const planeOffset = perspective.select(min2(radius, distance.sub(cameraNear2.mul(2))), radius);
609
1085
  const plane = center.add(forward.mul(planeOffset));
610
- const lo = vec23(1e20).toVar(), hi = vec23(-1e20).toVar();
1086
+ const lo = vec24(1e20).toVar(), hi = vec24(-1e20).toVar();
611
1087
  for (const x of [-1, 1])
612
1088
  for (const y of [-1, 1])
613
1089
  for (const z of [-1, 1]) {
614
- const corner2 = fromBox(half.mul(vec33(x, y, z)));
1090
+ const corner2 = fromBox(half.mul(vec35(x, y, z)));
615
1091
  const scale = perspective.select(
616
- max3(distance.sub(planeOffset), 1e-5).div(
617
- max3(distance.sub(dot3(corner2, forward)), 1e-5)
1092
+ max4(distance.sub(planeOffset), 1e-5).div(
1093
+ max4(distance.sub(dot4(corner2, forward)), 1e-5)
618
1094
  ),
619
- float3(1)
1095
+ float4(1)
620
1096
  );
621
- const p = vec23(dot3(corner2, right), dot3(corner2, up)).mul(scale);
622
- lo.assign(min(lo, p));
623
- hi.assign(max3(hi, p));
1097
+ const p = vec24(dot4(corner2, right), dot4(corner2, up)).mul(scale);
1098
+ lo.assign(min2(lo, p));
1099
+ hi.assign(max4(hi, p));
624
1100
  }
625
1101
  const corner = attribute3("cardCorner", "vec2").add(1).mul(0.5);
626
1102
  const xy = lo.add(hi.sub(lo).mul(corner));
627
1103
  return plane.add(right.mul(xy.x)).add(up.mul(xy.y));
628
1104
  })();
629
- material.positionNode = proxy;
630
- material.castShadowPositionNode = proxy;
1105
+ material.positionNode = meshVertex(proxy);
1106
+ material.castShadowPositionNode = material.positionNode;
631
1107
  }
632
- const raster = varying(proxy, "boxRasterPosition");
1108
+ const raster = varying2(proxy, "boxRasterPosition");
633
1109
  if (boxDepthMode(descriptor, settings) === "projection" && descriptor.mode === "fitted" && settings.interpolation === "none") {
634
1110
  material.side = FrontSide;
635
1111
  return applyBoxFaces({
@@ -640,7 +1116,9 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
640
1116
  transparency,
641
1117
  half,
642
1118
  toBox,
643
- fromBox
1119
+ fromBox,
1120
+ meshVertex,
1121
+ meshNormal
644
1122
  });
645
1123
  }
646
1124
  if (boxDepthMode(descriptor, settings) === "projection")
@@ -659,7 +1137,9 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
659
1137
  eye,
660
1138
  viewAxis,
661
1139
  perspective,
662
- raster
1140
+ raster,
1141
+ meshPoint,
1142
+ meshNormal
663
1143
  });
664
1144
  const accelerated = descriptor.boxes.every((b) => b.depthBounds);
665
1145
  const gridSize = BOX_OCCUPANCY_RESOLUTION;
@@ -672,7 +1152,7 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
672
1152
  descriptor.boxes.forEach(
673
1153
  (box, index) => words.set(box.occupancy, index * wordsPerBox)
674
1154
  );
675
- occupancy = new DataTexture3(
1155
+ occupancy = new DataTexture4(
676
1156
  words,
677
1157
  wordsPerBox,
678
1158
  descriptor.boxes.length,
@@ -682,53 +1162,66 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
682
1162
  occupancy.needsUpdate = true;
683
1163
  material.addEventListener("dispose", () => occupancy.dispose());
684
1164
  }
1165
+ const preferFacingCapture = filtering && descriptor.alphaMode === "opaque" && settings.interpolation === "none";
1166
+ const viewBounds = boundSearch ? createBoxRayBounds(descriptor, maps, rects, material) : null;
685
1167
  const Result = struct2(
686
- { uv: "vec2", position: "vec3", normal: "vec3", valid: "float" },
1168
+ { uv: "vec2", position: "vec3", face: "int", valid: "float" },
687
1169
  "BoxImpostorHit"
688
1170
  );
689
- const raycast = Fn4((_, builder) => {
690
- const ray = perspective.select(
691
- normalize2(raster.sub(eye)),
692
- viewAxis.negate()
693
- );
1171
+ const faceBasis = (axis, facing) => {
1172
+ const n = vec35(
1173
+ axis.equal(0).select(facing, 0),
1174
+ axis.equal(1).select(facing, 0),
1175
+ axis.equal(2).select(facing, 0)
1176
+ ).toVar();
1177
+ const right = axis.equal(0).select(
1178
+ vec35(0, 0, facing.negate()),
1179
+ axis.equal(1).select(vec35(1, 0, 0), vec35(facing, 0, 0))
1180
+ ).toVar();
1181
+ const up = axis.equal(1).select(vec35(0, 0, facing.negate()), vec35(0, 1, 0)).toVar();
1182
+ return { n, right, up };
1183
+ };
1184
+ const ray = perspective.select(normalize2(raster.sub(eye)), viewAxis.negate());
1185
+ const raycast = Fn5((_, builder) => {
694
1186
  const origin = perspective.select(
695
1187
  eye,
696
1188
  raster.sub(ray.mul(half.length().mul(4)))
697
1189
  );
698
1190
  const o = toBox(origin.sub(center)).div(half), r = toBox(ray).div(half);
699
- const safe = sign3(r.add(1e-20)).mul(max3(abs3(r), 1e-10));
700
- const a = vec33(-1).sub(o).div(safe), b = vec33(1).sub(o).div(safe);
701
- const enter = max3(max3(min(a, b).x, min(a, b).y), min(a, b).z).max(0);
702
- const exit = min(min(max3(a, b).x, max3(a, b).y), max3(a, b).z);
1191
+ const safe = sign3(r.add(1e-20)).mul(max4(abs3(r), 1e-10));
1192
+ const a = vec35(-1).sub(o).div(safe), b = vec35(1).sub(o).div(safe);
1193
+ const enter = max4(max4(min2(a, b).x, min2(a, b).y), min2(a, b).z).max(0);
1194
+ const exit = min2(min2(max4(a, b).x, max4(a, b).y), max4(a, b).z);
1195
+ const rayBounds = viewBounds?.(builder, int5(attribute3("boxId", "float")), o, r, enter, exit);
703
1196
  const occupiedStart = enter.toVar();
704
1197
  if (occupancy) {
705
1198
  const gridOrigin = o.add(1).mul(gridSize / 2);
706
1199
  const gridRay = r.mul(gridSize / 2);
707
1200
  const step = sign3(gridRay.add(1e-20));
708
- const cell = floor(gridOrigin.add(gridRay.mul(enter))).clamp(0, gridSize - 1).toVar();
709
- const inverse = vec33(1).div(safe.mul(gridSize / 2));
1201
+ const cell = floor2(gridOrigin.add(gridRay.mul(enter))).clamp(0, gridSize - 1).toVar();
1202
+ const inverse = vec35(1).div(safe.mul(gridSize / 2));
710
1203
  const delta = abs3(inverse);
711
1204
  const next = cell.add(step.add(1).mul(0.5)).sub(gridOrigin).mul(inverse).toVar();
712
1205
  const t = enter.toVar();
713
1206
  occupiedStart.assign(exit.add(1));
714
- Loop(gridSize * 3 + 1, () => {
715
- If3(t.greaterThan(exit), () => {
1207
+ Loop2(gridSize * 3 + 1, () => {
1208
+ If4(t.greaterThan(exit), () => {
716
1209
  Break();
717
1210
  });
718
- const cellIndex = uint(
1211
+ const cellIndex = uint2(
719
1212
  cell.x.add(cell.y.mul(gridSize)).add(cell.z.mul(gridSize ** 2))
720
1213
  ).toVar();
721
- const word = textureLoad3(
1214
+ const word = textureLoad5(
722
1215
  occupancy,
723
- ivec23(int3(cellIndex.shiftRight(5)), int3(attribute3("boxId", "float")))
1216
+ ivec25(int5(cellIndex.shiftRight(5)), int5(attribute3("boxId", "float")))
724
1217
  ).r;
725
1218
  const support = word.shiftRight(cellIndex.bitAnd(31)).bitAnd(1);
726
- If3(support.notEqual(uint(0)), () => {
1219
+ If4(support.notEqual(uint2(0)), () => {
727
1220
  occupiedStart.assign(t);
728
1221
  Break();
729
1222
  });
730
- const edge = min(min(next.x, next.y), next.z).toVar();
731
- const advance = vec33(
1223
+ const edge = min2(min2(next.x, next.y), next.z).toVar();
1224
+ const advance = vec35(
732
1225
  next.x.lessThanEqual(edge).select(1, 0),
733
1226
  next.y.lessThanEqual(edge).select(1, 0),
734
1227
  next.z.lessThanEqual(edge).select(1, 0)
@@ -736,7 +1229,7 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
736
1229
  cell.addAssign(advance.mul(step));
737
1230
  next.addAssign(advance.mul(delta));
738
1231
  t.assign(edge);
739
- If3(
1232
+ If4(
740
1233
  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)),
741
1234
  () => {
742
1235
  Break();
@@ -745,19 +1238,19 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
745
1238
  });
746
1239
  }
747
1240
  const look = toBox(ray).negate();
748
- const bestT = exit.add(1).toVar(), bestUv = vec23(0).toVar(), bestNormal = vec33(0, 0, 1).toVar(), valid = float3(0).toVar(), found = float3(0).toVar();
1241
+ const bestT = exit.add(1).toVar(), bestUv = vec24(0).toVar(), bestFace = int5(0).toVar(), appearanceNear = preferFacingCapture ? float4(0).toVar() : null, valid = float4(0).toVar(), found = float4(0).toVar();
749
1242
  const angles = abs3(look).toVar();
750
1243
  const major = angles.x.greaterThanEqual(angles.y).and(angles.x.greaterThanEqual(angles.z)).select(
751
- int3(0),
752
- angles.y.greaterThanEqual(angles.z).select(int3(1), int3(2))
1244
+ int5(0),
1245
+ angles.y.greaterThanEqual(angles.z).select(int5(1), int5(2))
753
1246
  ).toVar();
754
1247
  const nextAxis = major.add(1).mod(3), lastAxis = major.add(2).mod(3);
755
1248
  const second = angles.element(nextAxis).greaterThanEqual(angles.element(lastAxis)).select(nextAxis, lastAxis).toVar();
756
- const third = int3(3).sub(major).sub(second).toVar();
757
- Loop(
1249
+ const third = int5(3).sub(major).sub(second).toVar();
1250
+ Loop2(
758
1251
  { start: 0, end: 6, type: "int", name: "viewIndex" },
759
1252
  ({ viewIndex: i }) => {
760
- If3(occupiedStart.greaterThan(exit), () => {
1253
+ If4(occupiedStart.greaterThan(exit), () => {
761
1254
  Break();
762
1255
  });
763
1256
  valid.assign(0);
@@ -767,112 +1260,133 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
767
1260
  look.element(axis).greaterThanEqual(0),
768
1261
  look.element(axis).lessThan(0)
769
1262
  );
770
- const face = axis.mul(2).add(positive.select(int3(0), int3(1)));
1263
+ const face = axis.mul(2).add(positive.select(int5(0), int5(1)));
1264
+ const bounds = rayBounds?.(face, enter, exit);
771
1265
  const facing = positive.select(1, -1);
772
- const n = vec33(
773
- axis.equal(0).select(facing, 0),
774
- axis.equal(1).select(facing, 0),
775
- axis.equal(2).select(facing, 0)
776
- ).toVar();
777
- const right = axis.equal(0).select(
778
- vec33(0, 0, facing.negate()),
779
- axis.equal(1).select(vec33(1, 0, 0), vec33(facing, 0, 0))
780
- ).toVar();
781
- const up = axis.equal(1).select(vec33(0, 0, facing.negate()), vec33(0, 1, 0)).toVar();
1266
+ const { n, right, up } = faceBasis(axis, facing);
782
1267
  const direction = i.lessThan(3).select(1, -1);
783
- const rect = textureLoad3(
1268
+ const rect = textureLoad5(
784
1269
  rects,
785
- ivec23(face, int3(attribute3("boxId", "float")))
1270
+ ivec25(face, int5(attribute3("boxId", "float")))
786
1271
  ).toVar();
787
1272
  const sampleUv = (p) => rect.xy.add(
788
- vec23(dot3(p, right), dot3(p, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
1273
+ vec24(dot4(p, right), dot4(p, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
789
1274
  );
790
1275
  const decode = (d) => d.b.mul(65280).add(d.a.mul(255)).div(65535);
791
1276
  const depthAt = (uv2) => decode(texture3(maps.normalDepth, uv2).level(0));
1277
+ const projectedOrigin = vec24(dot4(o, right), dot4(o, up)).toVar();
1278
+ const projectedRay = vec24(dot4(r, right), dot4(r, up)).toVar();
1279
+ const axialOrigin = dot4(o, n).toVar();
1280
+ const axialRay = dot4(r, n).toVar();
792
1281
  const distance = (t) => {
793
- const p = o.add(r.mul(t));
794
- return dot3(p, n).sub(float3(1).sub(depthAt(sampleUv(p)).mul(2))).mul(direction);
1282
+ const uv2 = rect.xy.add(
1283
+ projectedOrigin.add(projectedRay.mul(t)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
1284
+ );
1285
+ return axialOrigin.add(axialRay.mul(t)).sub(float4(1).sub(depthAt(uv2).mul(2))).mul(direction);
795
1286
  };
796
1287
  const acceptHit = (hitT) => {
797
1288
  const point2 = o.add(r.mul(hitT)), uv2 = sampleUv(point2);
798
- const texel = ivec23(uv2.mul(descriptor.atlasResolution));
799
- const nearest = textureLoad3(maps.normalDepth, texel);
1289
+ const texel = ivec25(uv2.mul(descriptor.atlasResolution));
1290
+ const nearest = textureLoad5(maps.normalDepth, texel);
800
1291
  const capturedBase = texture3(maps.baseColor, uv2).level(0);
801
- const occupied = textureLoad3(maps.orm, texel).a.greaterThan(0.5);
1292
+ const occupied = textureLoad5(maps.orm, texel).a.greaterThan(0.5);
802
1293
  const residual = abs3(
803
- dot3(point2, n).sub(float3(1).sub(decode(nearest).mul(2)))
1294
+ dot4(point2, n).sub(float4(1).sub(decode(nearest).mul(2)))
804
1295
  );
805
- const tolerance = max3(
806
- dot3(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
807
- dot3(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
808
- ).div(dot3(abs3(n), half)).mul(4).add(4 / 65535);
809
- If3(
1296
+ const tolerance = max4(
1297
+ dot4(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
1298
+ dot4(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
1299
+ ).div(dot4(abs3(n), half)).mul(4).add(4 / 65535);
1300
+ If4(
810
1301
  residual.lessThanEqual(tolerance).and(occupied).and(
811
1302
  capturedBase.a.greaterThanEqual(minimumAlpha)
812
1303
  ),
813
1304
  () => {
814
1305
  valid.assign(1);
815
- If3(hitT.lessThan(bestT), () => {
1306
+ If4(hitT.lessThan(bestT), () => {
816
1307
  bestT.assign(hitT);
817
- bestUv.assign(uv2);
818
- found.assign(1);
819
- const packed = texture3(maps.normalDepth, uv2).level(0).rg.div(max3(surfaceCoverage(texture3(maps.orm, uv2).level(0).a, capturedBase.a), 1e-10)).mul(2).sub(1);
820
- const normal2 = vec33(
821
- packed.x,
822
- packed.y,
823
- float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))
824
- ).toVar();
825
- If3(normal2.z.lessThan(0), () => {
826
- normal2.xy.assign(
827
- vec23(1).sub(abs3(normal2.yx)).mul(sign3(normal2.xy.add(1e-20)))
1308
+ const useAppearance = () => {
1309
+ bestUv.assign(uv2);
1310
+ bestFace.assign(face);
1311
+ };
1312
+ if (preferFacingCapture) {
1313
+ const texel2 = max4(
1314
+ dot4(abs3(right), half).div(rect.z),
1315
+ dot4(abs3(up), half).div(rect.w)
1316
+ ).div(descriptor.atlasResolution);
1317
+ const uncertainty = min2(
1318
+ texel2,
1319
+ residual.add(2 / 65535).div(abs3(axialRay).max(1e-10))
828
1320
  );
829
- });
830
- bestNormal.assign(
831
- fromBox(
832
- right.mul(normal2.x).add(up.mul(normal2.y)).add(n.mul(normal2.z))
833
- ).normalize()
834
- );
835
- bestNormal.mulAssign(
836
- dot3(bestNormal, ray).greaterThan(0).select(-1, 1)
837
- );
1321
+ If4(found.lessThan(0.5).or(hitT.add(uncertainty).lessThan(appearanceNear)), () => {
1322
+ appearanceNear.assign(hitT.sub(uncertainty));
1323
+ useAppearance();
1324
+ });
1325
+ } else useAppearance();
1326
+ found.assign(1);
838
1327
  });
839
1328
  }
840
1329
  );
841
1330
  };
842
1331
  const traceInterval = (start, end, steps) => {
843
- const footprint = vec23(dot3(r, right), dot3(r, up)).abs().mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
844
- const samples = max3(float3(steps), max3(footprint.x, footprint.y).mul(steps / 8)).div(2).ceil().mul(2).toVar();
845
- const step = end.sub(start).div(samples);
846
- const previous = start.toVar(), previousD = distance(start).toVar();
847
- If3(previousD.lessThanEqual(0), () => {
1332
+ const footprint = vec24(dot4(r, right), dot4(r, up)).abs().mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
1333
+ let density = steps / 8;
1334
+ if (descriptor.alphaMode === "blend" && transparency === "blended" && steps < 32) {
1335
+ density = i.equal(0).select(steps / 16, steps / 32);
1336
+ } else if (descriptor.alphaMode === "opaque" && steps === 16) {
1337
+ density = found.greaterThan(0.5).select(1, 2);
1338
+ }
1339
+ const samples = max4(float4(steps), max4(footprint.x, footprint.y).mul(density)).div(2).ceil().mul(2).toVar();
1340
+ const step = end.sub(start).div(samples).toVar();
1341
+ const pairs = int5(samples.div(2));
1342
+ const pairAt = (t) => t.sub(start).div(max4(step.mul(2), 1e-15));
1343
+ const firstPair = bounds ? int5(floor2(pairAt(bounds.start))).clamp(0, pairs).toVar() : int5(0);
1344
+ const lastPair = bounds ? int5(pairAt(bounds.end).ceil()).clamp(0, pairs).toVar() : pairs;
1345
+ const previous = start.toVar();
1346
+ if (bounds) If4(firstPair.greaterThan(0), () => {
1347
+ previous.assign(start.add(step.mul(float4(firstPair.mul(2)))));
1348
+ });
1349
+ const previousD = distance(previous).toVar();
1350
+ const atEntry = bounds ? firstPair.equal(0).and(start.greaterThanEqual(bounds.start)).and(start.lessThanEqual(bounds.end)) : null;
1351
+ If4(atEntry ? atEntry.and(previousD.lessThanEqual(0)) : previousD.lessThanEqual(0), () => {
848
1352
  acceptHit(start);
849
1353
  });
850
- Loop({ start: int3(0), end: int3(samples.div(2)), type: "int" }, ({ i: i2 }) => {
851
- If3(valid.greaterThan(0.5), () => {
1354
+ Loop2({ start: firstPair, end: lastPair, type: "int" }, ({ i: i2 }) => {
1355
+ If4(valid.greaterThan(0.5).or(previous.greaterThan(bestT)), () => {
852
1356
  Break();
853
1357
  });
854
- const samples2 = [1, 2].map((offset) => {
855
- const t = start.add(step.mul(float3(i2.mul(2).add(offset)))).toVar();
1358
+ const [first, second2] = [1, 2].map((offset) => {
1359
+ const t = start.add(step.mul(float4(i2.mul(2).add(offset)))).toVar();
856
1360
  return { t, d: distance(t).toVar() };
857
1361
  });
858
- for (const { t, d } of samples2) {
859
- If3(valid.greaterThan(0.5).or(t.sub(step).greaterThan(bestT)), () => {
860
- Break();
861
- });
862
- If3(valid.lessThan(0.5).and(d.mul(previousD).lessThanEqual(0)), () => {
863
- const crossing = refineSurfaceCrossing({ float: float3, If: If3, Loop }, { lo: previous, hi: t, loValue: previousD, hiValue: d, height: distance, steps: 3, secant: true });
864
- acceptHit(crossing);
865
- If3(bestT.lessThanEqual(t), () => {
866
- Break();
1362
+ const crossesFirst = first.d.mul(previousD).lessThanEqual(0);
1363
+ const crossesSecond = second2.d.mul(first.d).lessThanEqual(0);
1364
+ If4(crossesFirst.or(crossesSecond), () => {
1365
+ for (const [{ t, d }, crosses] of [[first, crossesFirst], [second2, crossesSecond]]) {
1366
+ If4(crosses.and(valid.lessThan(0.5)).and(previous.lessThanEqual(bestT)), () => {
1367
+ const crossing = refineSurfaceCrossing({ float: float4, If: If4, Loop: Loop2 }, {
1368
+ lo: previous,
1369
+ hi: t,
1370
+ loValue: previousD,
1371
+ hiValue: d,
1372
+ height: distance,
1373
+ steps: 3,
1374
+ secant: true
1375
+ });
1376
+ acceptHit(crossing);
867
1377
  });
868
- });
869
- previous.assign(t);
870
- previousD.assign(d);
871
- }
1378
+ previous.assign(t);
1379
+ previousD.assign(d);
1380
+ }
1381
+ }).Else(() => {
1382
+ previous.assign(second2.t);
1383
+ previousD.assign(second2.d);
1384
+ });
872
1385
  });
873
1386
  };
874
- If3(
875
- exit.greaterThanEqual(enter).and(abs3(look.element(axis)).greaterThan(1e-3)),
1387
+ const supported = exit.greaterThanEqual(enter).and(abs3(look.element(axis)).greaterThan(1e-3));
1388
+ If4(
1389
+ bounds ? supported.and(bounds.start.lessThanEqual(bestT)).and(bounds.end.greaterThanEqual(occupiedStart)) : supported,
876
1390
  () => {
877
1391
  if (!accelerated) {
878
1392
  traceInterval(enter, exit, descriptor.raySteps);
@@ -885,13 +1399,13 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
885
1399
  )
886
1400
  );
887
1401
  const interval = positive.select(depths.xy, depths.zw);
888
- const initialDepth = float3(1).sub(dot3(o, n)).mul(0.5);
889
- const depthSlope = dot3(r, n).negate().mul(0.5);
1402
+ const initialDepth = float4(1).sub(dot4(o, n)).mul(0.5);
1403
+ const depthSlope = dot4(r, n).negate().mul(0.5);
890
1404
  const da = interval.x.sub(2 / 65535).sub(initialDepth).div(depthSlope);
891
1405
  const db = interval.y.add(2 / 65535).sub(initialDepth).div(depthSlope);
892
- const start = max3(occupiedStart, min(da, db));
893
- const end = min(min(exit, bestT), max3(da, db));
894
- If3(
1406
+ const start = max4(occupiedStart, min2(da, db));
1407
+ const end = min2(min2(exit, bestT), max4(da, db));
1408
+ If4(
895
1409
  interval.x.lessThanEqual(interval.y).and(end.greaterThanEqual(start)),
896
1410
  () => {
897
1411
  const search = () => traceInterval(start, end, descriptor.raySteps);
@@ -901,12 +1415,12 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
901
1415
  )
902
1416
  );
903
1417
  if (hasFlatView) {
904
- If3(
1418
+ If4(
905
1419
  interval.y.sub(interval.x).lessThanEqual(1 / 65535),
906
1420
  () => {
907
1421
  const t = interval.x.add(interval.y).mul(0.5).sub(initialDepth).div(depthSlope);
908
- If3(
909
- t.greaterThanEqual(enter).and(t.lessThanEqual(min(exit, bestT))),
1422
+ If4(
1423
+ t.greaterThanEqual(enter).and(t.lessThanEqual(min2(exit, bestT))),
910
1424
  () => {
911
1425
  acceptHit(t);
912
1426
  }
@@ -926,57 +1440,65 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
926
1440
  return Result(
927
1441
  bestUv,
928
1442
  center.add(fromBox(point.mul(half))),
929
- bestNormal,
1443
+ bestFace,
930
1444
  valid
931
1445
  );
932
1446
  });
933
1447
  const hit = raycast().toVar("boxHit");
934
1448
  hit.toStack();
935
1449
  const base = texture3(maps.baseColor, hit.get("uv")).level(0), orm = texture3(maps.orm, hit.get("uv")).level(0);
936
- const coverage = max3(surfaceCoverage(orm.a, base.a), 1e-10);
937
- 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");
1450
+ const coverage = max4(surfaceCoverage(orm.a, base.a), 1e-10);
1451
+ const hitNormal = Fn5(() => {
1452
+ const face = hit.get("face");
1453
+ const { n, right, up } = faceBasis(face.div(2), face.mod(2).equal(0).select(1, -1));
1454
+ const sampled = texture3(maps.normalDepth, hit.get("uv")).level(0);
1455
+ const local = unpackNormal(sampled.rg.div(coverage));
1456
+ const direction = fromBox(right.mul(local.x).add(up.mul(local.y)).add(n.mul(local.z))).normalize().toVar();
1457
+ return direction.mul(dot4(direction, ray).greaterThan(0).select(-1, 1));
1458
+ })();
1459
+ let color = base.div(coverage), surfaceOrm = orm.rgb.div(coverage), emission = texture3(maps.emissive, hit.get("uv")).level(0).rgb.div(coverage), normal = hitNormal;
938
1460
  if (settings.interpolation !== "none") {
939
1461
  const fallbackColor = color, fallbackOrm = surfaceOrm, fallbackEmission = emission, fallbackNormal = normal;
940
1462
  const Surface = struct2(
941
1463
  { color: "vec4", orm: "vec3", emission: "vec3", normal: "vec3" },
942
1464
  "BoxSurfaceBlend"
943
1465
  );
944
- const blended = Fn4(() => {
1466
+ const blended = Fn5(() => {
945
1467
  const point = toBox(hit.get("position").sub(center)).div(half);
946
1468
  const look = toBox(
947
1469
  perspective.select(normalize2(eye.sub(hit.get("position"))), viewAxis)
948
1470
  );
949
- const colors = vec44(0).toVar(), materials = vec33(0).toVar(), emissions = vec33(0).toVar(), normals = vec33(0).toVar(), weights = float3(0).toVar();
1471
+ const colors = vec46(0).toVar(), materials = vec35(0).toVar(), emissions = vec35(0).toVar(), normals = vec35(0).toVar(), weights = float4(0).toVar();
950
1472
  for (let axis = 0; axis < 3; axis++) {
951
1473
  const positive = look.element(axis).greaterThanEqual(0);
952
1474
  const front = BOX_FACE_AXES[axis * 2], back = BOX_FACE_AXES[axis * 2 + 1];
953
- const n = positive.select(vec33(...front.normal), vec33(...back.normal));
1475
+ const n = positive.select(vec35(...front.normal), vec35(...back.normal));
954
1476
  const right = positive.select(
955
- vec33(...front.right),
956
- vec33(...back.right)
1477
+ vec35(...front.right),
1478
+ vec35(...back.right)
957
1479
  );
958
- const up = positive.select(vec33(...front.up), vec33(...back.up));
959
- const face = positive.select(int3(axis * 2), int3(axis * 2 + 1));
960
- const rect = textureLoad3(
1480
+ const up = positive.select(vec35(...front.up), vec35(...back.up));
1481
+ const face = positive.select(int5(axis * 2), int5(axis * 2 + 1));
1482
+ const rect = textureLoad5(
961
1483
  rects,
962
- ivec23(face, int3(attribute3("boxId", "float")))
1484
+ ivec25(face, int5(attribute3("boxId", "float")))
963
1485
  );
964
1486
  const uv2 = rect.xy.add(
965
- vec23(dot3(point, right), dot3(point, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
1487
+ vec24(dot4(point, right), dot4(point, up)).mul(0.5).add(0.5).clamp(0, 1).mul(rect.zw)
966
1488
  );
967
- const texel = ivec23(uv2.mul(descriptor.atlasResolution));
968
- const captured = textureLoad3(maps.normalDepth, texel);
1489
+ const texel = ivec25(uv2.mul(descriptor.atlasResolution));
1490
+ const captured = textureLoad5(maps.normalDepth, texel);
969
1491
  const sampled = texture3(maps.baseColor, uv2).level(0);
970
1492
  const sampledOrm = texture3(maps.orm, uv2).level(0);
971
- const occupied = textureLoad3(maps.orm, texel).a.greaterThan(0.5);
1493
+ const occupied = textureLoad5(maps.orm, texel).a.greaterThan(0.5);
972
1494
  const depth = captured.b.mul(65280).add(captured.a.mul(255)).div(65535);
973
- const tolerance = max3(
974
- dot3(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
975
- dot3(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
976
- ).div(dot3(abs3(n), half)).mul(4).add(4 / 65535);
977
- If3(
1495
+ const tolerance = max4(
1496
+ dot4(abs3(right), half).div(rect.z.mul(descriptor.atlasResolution)),
1497
+ dot4(abs3(up), half).div(rect.w.mul(descriptor.atlasResolution))
1498
+ ).div(dot4(abs3(n), half)).mul(4).add(4 / 65535);
1499
+ If4(
978
1500
  occupied.and(sampled.a.greaterThanEqual(minimumAlpha)).and(
979
- abs3(dot3(point, n).sub(float3(1).sub(depth.mul(2)))).lessThanEqual(
1501
+ abs3(dot4(point, n).sub(float4(1).sub(depth.mul(2)))).lessThanEqual(
980
1502
  tolerance
981
1503
  )
982
1504
  ),
@@ -985,28 +1507,28 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
985
1507
  const filtered = filtering ? texture3(maps.normalDepth, uv2).level(0).toVar() : captured;
986
1508
  let weight = settings.interpolation === "smooth" ? angle.mul(angle) : angle;
987
1509
  if (filtering) {
988
- const error = abs3(dot3(point, n).sub(float3(1).sub(
1510
+ const error = abs3(dot4(point, n).sub(float4(1).sub(
989
1511
  filtered.b.mul(65280).add(filtered.a.mul(255)).div(65535).mul(2)
990
1512
  )));
991
- weight = weight.mul(float3(1).sub(error.div(tolerance)).clamp(0, 1));
1513
+ weight = weight.mul(float4(1).sub(error.div(tolerance)).clamp(0, 1));
992
1514
  }
993
- const coverage2 = max3(surfaceCoverage(sampledOrm.a, sampled.a), 1e-10);
1515
+ const coverage2 = max4(surfaceCoverage(sampledOrm.a, sampled.a), 1e-10);
994
1516
  colors.addAssign(sampled.div(coverage2).mul(weight));
995
1517
  materials.addAssign(sampledOrm.rgb.div(coverage2).mul(weight));
996
1518
  emissions.addAssign(
997
1519
  texture3(maps.emissive, uv2).level(0).rgb.div(coverage2).mul(weight)
998
1520
  );
999
1521
  let shadingNormal;
1000
- if (filtering) shadingNormal = filteredNormal(uv2, float3(1).sub(dot3(point, n)).mul(0.5), tolerance.mul(0.5), captured, sampled.a, filtered, sampledOrm.a);
1522
+ if (filtering) shadingNormal = filteredNormal(uv2, float4(1).sub(dot4(point, n)).mul(0.5), tolerance.mul(0.5), captured, sampled.a, filtered, sampledOrm.a);
1001
1523
  else {
1002
1524
  const packed = captured.rg.mul(2).sub(1);
1003
- const decoded = vec33(
1525
+ const decoded = vec35(
1004
1526
  packed,
1005
- float3(1).sub(abs3(packed.x)).sub(abs3(packed.y))
1527
+ float4(1).sub(abs3(packed.x)).sub(abs3(packed.y))
1006
1528
  ).toVar();
1007
- If3(decoded.z.lessThan(0), () => {
1529
+ If4(decoded.z.lessThan(0), () => {
1008
1530
  decoded.xy.assign(
1009
- vec23(1).sub(abs3(decoded.yx)).mul(sign3(decoded.xy.add(1e-20)))
1531
+ vec24(1).sub(abs3(decoded.yx)).mul(sign3(decoded.xy.add(1e-20)))
1010
1532
  );
1011
1533
  });
1012
1534
  shadingNormal = decoded;
@@ -1020,7 +1542,7 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1020
1542
  }
1021
1543
  );
1022
1544
  }
1023
- const divisor = max3(weights, 1e-10), valid = weights.greaterThan(1e-10);
1545
+ const divisor = max4(weights, 1e-10), valid = weights.greaterThan(1e-10);
1024
1546
  return Surface(
1025
1547
  valid.select(colors.div(divisor), fallbackColor),
1026
1548
  valid.select(materials.div(divisor), fallbackOrm),
@@ -1033,9 +1555,10 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1033
1555
  emission = blended.get("emission");
1034
1556
  normal = blended.get("normal");
1035
1557
  }
1036
- material.capturedPositionNode = hit.get("position");
1558
+ const position = meshPoint(hit.get("position")).toVar("boxHitMeshPosition");
1559
+ material.capturedPositionNode = position;
1037
1560
  material.colorNode = color.rgb;
1038
- material.normalNode = transformNormalToView3(normal);
1561
+ material.normalNode = transformNormalToView3(meshNormal(normal));
1039
1562
  material.roughnessNode = surfaceOrm.g;
1040
1563
  material.metalnessNode = surfaceOrm.b;
1041
1564
  material.aoNode = surfaceOrm.r;
@@ -1050,9 +1573,9 @@ function createBoxImpostorMaterialVariant(descriptor, maps, { filtering = false
1050
1573
  }
1051
1574
  material.maskNode = hit.get("valid").greaterThan(0.5);
1052
1575
  material.maskShadowNode = material.maskNode;
1053
- material.depthNode = capturedSurfaceDepth(hit.get("position"));
1576
+ material.depthNode = capturedSurfaceDepth(position);
1054
1577
  material.receivedShadowPositionNode = modelWorldMatrix3.mul(
1055
- vec44(hit.get("position"), 1)
1578
+ vec46(position, 1)
1056
1579
  ).xyz;
1057
1580
  material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
1058
1581
  return material;