@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
@@ -20,7 +20,7 @@ import {
20
20
  Break,
21
21
  attribute,
22
22
  varying,
23
- positionLocal,
23
+ positionGeometry,
24
24
  positionViewDirection,
25
25
  modelWorldMatrixInverse,
26
26
  cameraPosition,
@@ -49,7 +49,9 @@ import {
49
49
  struct,
50
50
  uniform,
51
51
  } from "three/tsl";
52
+ import { instanceSpace } from '../rendering/instance-space.js';
52
53
  import {CapturedSurfaceMaterial} from '../rendering/captured-surface-material.js';
54
+ import {createBoxRayBounds} from './box-impostor-ray-bounds.js';
53
55
  import {refineSurfaceCrossing} from './box-impostor-surface-search.js';
54
56
  import { applyBoxFaces } from "./box-impostor-faces.js";
55
57
  import { applyBoxProjection } from "./box-impostor-projection.js";
@@ -72,7 +74,7 @@ export function createBoxImpostorMaterial(descriptor, maps) {
72
74
  }
73
75
 
74
76
  /** Internal compile-time variants for matched quality and cost measurements. */
75
- export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering = false} = {}) {
77
+ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering = false, boundSearch = true} = {}) {
76
78
  const settings = normalizeBoxImpostorDisplay(descriptor);
77
79
  const alphaCutoff = uniform(settings.alphaCutoff);
78
80
  const transparency = boxTransparency(descriptor, settings);
@@ -80,12 +82,13 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
80
82
  // Opaque/masked captures store geometric coverage in base alpha as well.
81
83
  // This also supports older MRT captures whose unused ORM alpha was opaque.
82
84
  const surfaceCoverage = (ormAlpha,baseAlpha) => filtering && descriptor.alphaMode !== 'blend' ? min(ormAlpha,baseAlpha) : ormAlpha;
83
- const decodeNormal = encoded => {
85
+ const unpackNormal = encoded => {
84
86
  const packed=encoded.mul(2).sub(1);
85
87
  const normal=vec3(packed,float(1).sub(abs(packed.x)).sub(abs(packed.y))).toVar();
86
88
  If(normal.z.lessThan(0),()=>{normal.xy.assign(vec2(1).sub(abs(normal.yx)).mul(sign(normal.xy.add(1e-20))));});
87
- return normal.normalize();
89
+ return normal;
88
90
  };
91
+ const decodeNormal = encoded => unpackNormal(encoded).normalize();
89
92
  const filteredNormal = (uv,depth,tolerance,nearest,alpha,sampled=texture(maps.normalDepth,uv).level(0),ormAlpha=texture(maps.orm,uv).level(0).a) => {
90
93
  sampled=sampled.toVar();
91
94
  const coverage=max(descriptor.alphaMode==='blend'?ormAlpha:alpha,1e-10);
@@ -160,25 +163,34 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
160
163
  az = attribute("boxAxisZ", "vec3");
161
164
  const toBox = (p) => vec3(dot(p, ax), dot(p, ay), dot(p, az));
162
165
  const fromBox = (p) => ax.mul(p.x).add(ay.mul(p.y)).add(az.mul(p.z));
163
- const eye = modelWorldMatrixInverse.mul(vec4(cameraPosition, 1)).xyz;
164
- const viewAxis = modelWorldMatrixInverse
165
- .mul(cameraWorldMatrix.mul(vec4(0, 0, 1, 0)))
166
- .xyz.normalize();
166
+ // An instance traces in its own space; lighting, depth and shadows use the mesh's.
167
+ const meshVertex = (p) => Fn((_, builder) => instanceSpace(builder)?.toMeshPoint(p) ?? p)();
168
+ const meshPoint = (p) => Fn((_, builder) => instanceSpace(builder)?.fragment.toMeshPoint(p) ?? p)();
169
+ const meshNormal = (n) => Fn((_, builder) => instanceSpace(builder)?.fragment.toMeshNormal(n) ?? n)();
170
+ const meshEye = modelWorldMatrixInverse.mul(vec4(cameraPosition, 1)).xyz;
171
+ const meshViewAxis = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec4(0, 0, 1, 0))).xyz;
172
+ // The fragment stage derives these from the instance transform it already
173
+ // receives; this shader has no vertex outputs to spare for them.
174
+ const eye = Fn((_, builder) => instanceSpace(builder)?.fragment.toLocalPoint(meshEye) ?? meshEye)();
175
+ const viewAxis = Fn((_, builder) => instanceSpace(builder)?.fragment.toLocalDirection(meshViewAxis) ?? meshViewAxis)().normalize();
176
+ const vertexEye = Fn((_, builder) => instanceSpace(builder)?.toLocalPoint(meshEye) ?? meshEye)();
177
+ const vertexViewAxis = Fn((_, builder) => instanceSpace(builder)?.toLocalDirection(meshViewAxis) ?? meshViewAxis)().normalize();
178
+ const cameraUp = Fn((_, builder) => {
179
+ const up = modelWorldMatrixInverse.mul(cameraWorldMatrix.mul(vec4(0, 1, 0, 0))).xyz;
180
+ return instanceSpace(builder)?.toLocalDirection(up) ?? up;
181
+ })();
167
182
  const perspective = cameraProjectionMatrix.element(3).w.equal(0);
168
- let proxy = positionLocal;
183
+ let proxy = positionGeometry;
169
184
  if (descriptor.mode !== "fitted") {
170
185
  proxy = Fn((_, builder) => {
171
- const delta = eye.sub(center);
172
- const forward = perspective.and(delta.length().greaterThan(1e-6)).select(normalize(delta), viewAxis);
173
- const right = modelWorldMatrixInverse
174
- .mul(cameraWorldMatrix.mul(vec4(0, 1, 0, 0)))
175
- .xyz.cross(forward)
176
- .normalize();
186
+ const delta = vertexEye.sub(center);
187
+ const forward = perspective.and(delta.length().greaterThan(1e-6)).select(normalize(delta), vertexViewAxis);
188
+ const right = cameraUp.cross(forward).normalize();
177
189
  const up = forward.cross(right).normalize();
178
190
  // Project all box corners onto the nearest eye-facing plane. This is a
179
191
  // conservative perspective bound, including views close to a thin box.
180
192
  const radius = half.length();
181
- const distance = dot(eye.sub(center), forward);
193
+ const distance = dot(vertexEye.sub(center), forward);
182
194
  const planeOffset = perspective.select(min(radius, distance.sub(cameraNear.mul(2))), radius);
183
195
  const plane = center.add(forward.mul(planeOffset));
184
196
  const lo = vec2(1e20).toVar(),
@@ -201,8 +213,8 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
201
213
  const xy = lo.add(hi.sub(lo).mul(corner));
202
214
  return plane.add(right.mul(xy.x)).add(up.mul(xy.y));
203
215
  })();
204
- material.positionNode = proxy;
205
- material.castShadowPositionNode = proxy;
216
+ material.positionNode = meshVertex(proxy);
217
+ material.castShadowPositionNode = material.positionNode;
206
218
  }
207
219
  const raster = varying(proxy, "boxRasterPosition");
208
220
  if (
@@ -220,6 +232,8 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
220
232
  half,
221
233
  toBox,
222
234
  fromBox,
235
+ meshVertex,
236
+ meshNormal,
223
237
  });
224
238
  }
225
239
  if (boxDepthMode(descriptor, settings) === "projection")
@@ -239,6 +253,8 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
239
253
  viewAxis,
240
254
  perspective,
241
255
  raster,
256
+ meshPoint,
257
+ meshNormal,
242
258
  });
243
259
  const accelerated = descriptor.boxes.every((b) => b.depthBounds);
244
260
  const gridSize = BOX_OCCUPANCY_RESOLUTION;
@@ -264,15 +280,33 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
264
280
  occupancy.needsUpdate = true;
265
281
  material.addEventListener("dispose", () => occupancy.dispose());
266
282
  }
283
+ const preferFacingCapture = filtering && descriptor.alphaMode === "opaque" && settings.interpolation === "none";
284
+ const viewBounds = boundSearch ? createBoxRayBounds(descriptor, maps, rects, material) : null;
267
285
  const Result = struct(
268
- { uv: "vec2", position: "vec3", normal: "vec3", valid: "float" },
286
+ { uv: "vec2", position: "vec3", face: "int", valid: "float" },
269
287
  "BoxImpostorHit",
270
288
  );
289
+ const faceBasis = (axis, facing) => {
290
+ const n = vec3(
291
+ axis.equal(0).select(facing, 0),
292
+ axis.equal(1).select(facing, 0),
293
+ axis.equal(2).select(facing, 0),
294
+ ).toVar();
295
+ const right = axis
296
+ .equal(0)
297
+ .select(
298
+ vec3(0, 0, facing.negate()),
299
+ axis.equal(1).select(vec3(1, 0, 0), vec3(facing, 0, 0)),
300
+ )
301
+ .toVar();
302
+ const up = axis
303
+ .equal(1)
304
+ .select(vec3(0, 0, facing.negate()), vec3(0, 1, 0))
305
+ .toVar();
306
+ return { n, right, up };
307
+ };
308
+ const ray = perspective.select(normalize(raster.sub(eye)), viewAxis.negate());
271
309
  const raycast = Fn((_, builder) => {
272
- const ray = perspective.select(
273
- normalize(raster.sub(eye)),
274
- viewAxis.negate(),
275
- );
276
310
  const origin = perspective.select(
277
311
  eye,
278
312
  raster.sub(ray.mul(half.length().mul(4))),
@@ -284,6 +318,7 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
284
318
  b = vec3(1).sub(o).div(safe);
285
319
  const enter = max(max(min(a, b).x, min(a, b).y), min(a, b).z).max(0);
286
320
  const exit = min(min(max(a, b).x, max(a, b).y), max(a, b).z);
321
+ const rayBounds = viewBounds?.(builder, int(attribute("boxId", "float")), o, r, enter, exit);
287
322
  const occupiedStart = enter.toVar();
288
323
  // This cover contains whole source voxel cubes. Only the empty space is
289
324
  // skipped; the depth fields still determine the full-resolution surface.
@@ -345,7 +380,8 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
345
380
  const look = toBox(ray).negate();
346
381
  const bestT = exit.add(1).toVar(),
347
382
  bestUv = vec2(0).toVar(),
348
- bestNormal = vec3(0, 0, 1).toVar(),
383
+ bestFace = int(0).toVar(),
384
+ appearanceNear = preferFacingCapture ? float(0).toVar() : null,
349
385
  valid = float(0).toVar(),
350
386
  found = float(0).toVar();
351
387
  // A face-on capture can miss a nearer surface visible from another axis.
@@ -386,23 +422,9 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
386
422
  look.element(axis).lessThan(0),
387
423
  );
388
424
  const face = axis.mul(2).add(positive.select(int(0), int(1)));
425
+ const bounds = rayBounds?.(face, enter, exit);
389
426
  const facing = positive.select(1, -1);
390
- const n = vec3(
391
- axis.equal(0).select(facing, 0),
392
- axis.equal(1).select(facing, 0),
393
- axis.equal(2).select(facing, 0),
394
- ).toVar();
395
- const right = axis
396
- .equal(0)
397
- .select(
398
- vec3(0, 0, facing.negate()),
399
- axis.equal(1).select(vec3(1, 0, 0), vec3(facing, 0, 0)),
400
- )
401
- .toVar();
402
- const up = axis
403
- .equal(1)
404
- .select(vec3(0, 0, facing.negate()), vec3(0, 1, 0))
405
- .toVar();
427
+ const { n, right, up } = faceBasis(axis, facing);
406
428
  const direction = i.lessThan(3).select(1, -1);
407
429
  const rect = textureLoad(
408
430
  rects,
@@ -418,10 +440,19 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
418
440
  );
419
441
  const decode = (d) => d.b.mul(65280).add(d.a.mul(255)).div(65535);
420
442
  const depthAt = (uv) => decode(texture(maps.normalDepth, uv).level(0));
443
+ // A capture sees an affine ray. Project it once per face so stepping
444
+ // and refinement only need its position along that ray.
445
+ const projectedOrigin = vec2(dot(o, right), dot(o, up)).toVar();
446
+ const projectedRay = vec2(dot(r, right), dot(r, up)).toVar();
447
+ const axialOrigin = dot(o, n).toVar();
448
+ const axialRay = dot(r, n).toVar();
421
449
  const distance = (t) => {
422
- const p = o.add(r.mul(t));
423
- return dot(p, n)
424
- .sub(float(1).sub(depthAt(sampleUv(p)).mul(2)))
450
+ const uv = rect.xy.add(
451
+ projectedOrigin.add(projectedRay.mul(t)).mul(0.5).add(0.5)
452
+ .clamp(0, 1).mul(rect.zw),
453
+ );
454
+ return axialOrigin.add(axialRay.mul(t))
455
+ .sub(float(1).sub(depthAt(uv).mul(2)))
425
456
  .mul(direction);
426
457
  };
427
458
  const acceptHit = (hitT) => {
@@ -456,36 +487,27 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
456
487
  valid.assign(1);
457
488
  If(hitT.lessThan(bestT), () => {
458
489
  bestT.assign(hitT);
459
- bestUv.assign(uv);
460
- found.assign(1);
461
- const packed = texture(maps.normalDepth, uv)
462
- .level(0)
463
- .rg.div(max(surfaceCoverage(texture(maps.orm, uv).level(0).a,capturedBase.a), 1e-10))
464
- .mul(2)
465
- .sub(1);
466
- const normal = vec3(
467
- packed.x,
468
- packed.y,
469
- float(1).sub(abs(packed.x)).sub(abs(packed.y)),
470
- ).toVar();
471
- If(normal.z.lessThan(0), () => {
472
- normal.xy.assign(
473
- vec2(1)
474
- .sub(abs(normal.yx))
475
- .mul(sign(normal.xy.add(1e-20))),
490
+ const useAppearance = () => {
491
+ bestUv.assign(uv);
492
+ bestFace.assign(face);
493
+ };
494
+ if (preferFacingCapture) {
495
+ // The more face-on capture was visited first. Keep it only
496
+ // while the two depth estimates overlap within one texel.
497
+ const texel = max(
498
+ dot(abs(right), half).div(rect.z),
499
+ dot(abs(up), half).div(rect.w),
500
+ ).div(descriptor.atlasResolution);
501
+ const uncertainty = min(
502
+ texel,
503
+ residual.add(2 / 65535).div(abs(axialRay).max(1e-10)),
476
504
  );
477
- });
478
- bestNormal.assign(
479
- fromBox(
480
- right
481
- .mul(normal.x)
482
- .add(up.mul(normal.y))
483
- .add(n.mul(normal.z)),
484
- ).normalize(),
485
- );
486
- bestNormal.mulAssign(
487
- dot(bestNormal, ray).greaterThan(0).select(-1, 1),
488
- );
505
+ If(found.lessThan(0.5).or(hitT.add(uncertainty).lessThan(appearanceNear)), () => {
506
+ appearanceNear.assign(hitT.sub(uncertainty));
507
+ useAppearance();
508
+ });
509
+ } else useAppearance();
510
+ found.assign(1);
489
511
  });
490
512
  },
491
513
  );
@@ -495,48 +517,68 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
495
517
  end,
496
518
  steps,
497
519
  ) => {
498
- // Sample every crossed texel; a fixed interval budget skips thin
499
- // surfaces when an oblique ray spans hundreds of capture pixels.
500
- const footprint = vec2(dot(r, right), dot(r, up)).abs().mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
501
- const samples = max(float(steps), max(footprint.x,footprint.y).mul(steps/8)).div(2).ceil().mul(2).toVar();
502
- const step=end.sub(start).div(samples);
503
- const previous = start.toVar(),
504
- previousD = distance(start).toVar();
505
- // At interval entry the refinement bracket has zero width. Resolve it
506
- // once rather than resampling the same depth through every bisection.
507
- If(previousD.lessThanEqual(0), () => {
520
+ const footprint = vec2(dot(r, right), dot(r, up)).abs()
521
+ .mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
522
+ let density = steps / 8;
523
+ if (descriptor.alphaMode === "blend" && transparency === "blended" && steps < 32) {
524
+ // Overlapping blended carriers each trace their dominant capture more densely.
525
+ density = i.equal(0).select(steps / 16, steps / 32);
526
+ } else if (descriptor.alphaMode === "opaque" && steps === 16) {
527
+ // Use the full density until the silhouette is established. Later
528
+ // captures look for closer occluders at one sample per crossed texel.
529
+ density = found.greaterThan(0.5).select(1, 2);
530
+ }
531
+ const samples = max(float(steps), max(footprint.x, footprint.y).mul(density))
532
+ .div(2).ceil().mul(2).toVar();
533
+ const step = end.sub(start).div(samples).toVar();
534
+ const pairs = int(samples.div(2));
535
+ // Keep the original bracket indices. Restarting at a clipped bound
536
+ // moves the samples and can lose thin surfaces between them.
537
+ const pairAt = t => t.sub(start).div(max(step.mul(2), 1e-15));
538
+ const firstPair = bounds ? int(floor(pairAt(bounds.start))).clamp(0, pairs).toVar() : int(0);
539
+ const lastPair = bounds ? int(pairAt(bounds.end).ceil()).clamp(0, pairs).toVar() : pairs;
540
+ const previous = start.toVar();
541
+ if (bounds) If(firstPair.greaterThan(0), () => {
542
+ previous.assign(start.add(step.mul(float(firstPair.mul(2)))));
543
+ });
544
+ const previousD = distance(previous).toVar();
545
+ const atEntry = bounds ? firstPair.equal(0).and(start.greaterThanEqual(bounds.start)).and(start.lessThanEqual(bounds.end)) : null;
546
+ If(atEntry ? atEntry.and(previousD.lessThanEqual(0)) : previousD.lessThanEqual(0), () => {
508
547
  acceptHit(start);
509
548
  });
510
- Loop({ start: int(0), end: int(samples.div(2)), type: "int" }, ({ i }) => {
511
- If(valid.greaterThan(0.5), () => {
549
+ Loop({ start: firstPair, end: lastPair, type: "int" }, ({ i }) => {
550
+ If(valid.greaterThan(0.5).or(previous.greaterThan(bestT)), () => {
512
551
  Break();
513
552
  });
514
- // Issue independent depth reads together, then resolve crossings in
515
- // their original order before refining either crossing direction.
516
- const samples = [1, 2].map((offset) => {
553
+ const [first, second] = [1, 2].map((offset) => {
517
554
  const t = start.add(step.mul(float(i.mul(2).add(offset)))).toVar();
518
555
  return { t, d: distance(t).toVar() };
519
556
  });
520
- for (const { t, d } of samples) {
521
- If(valid.greaterThan(0.5).or(t.sub(step).greaterThan(bestT)), () => {
522
- Break();
523
- });
524
- If(valid.lessThan(.5).and(d.mul(previousD).lessThanEqual(0)), () => {
525
- const crossing=refineSurfaceCrossing({float,If,Loop},{lo:previous,hi:t,loValue:previousD,hiValue:d,height:distance,steps:3,secant:true});
526
- acceptHit(crossing);
527
- If(bestT.lessThanEqual(t), () => {
528
- Break();
557
+ const crossesFirst = first.d.mul(previousD).lessThanEqual(0);
558
+ const crossesSecond = second.d.mul(first.d).lessThanEqual(0);
559
+ // Most pairs have no crossing. Skip the per-bracket work together,
560
+ // while retaining both brackets for thin surfaces and reversals.
561
+ If(crossesFirst.or(crossesSecond), () => {
562
+ for (const [{ t, d }, crosses] of [[first, crossesFirst], [second, crossesSecond]]) {
563
+ If(crosses.and(valid.lessThan(0.5)).and(previous.lessThanEqual(bestT)), () => {
564
+ const crossing = refineSurfaceCrossing({ float, If, Loop }, {
565
+ lo: previous, hi: t, loValue: previousD, hiValue: d,
566
+ height: distance, steps: 3, secant: true,
567
+ });
568
+ acceptHit(crossing);
529
569
  });
530
- });
531
- previous.assign(t);
532
- previousD.assign(d);
533
- }
570
+ previous.assign(t);
571
+ previousD.assign(d);
572
+ }
573
+ }).Else(() => {
574
+ previous.assign(second.t);
575
+ previousD.assign(second.d);
576
+ });
534
577
  });
535
578
  };
579
+ const supported = exit.greaterThanEqual(enter).and(abs(look.element(axis)).greaterThan(0.001));
536
580
  If(
537
- exit
538
- .greaterThanEqual(enter)
539
- .and(abs(look.element(axis)).greaterThan(0.001)),
581
+ bounds ? supported.and(bounds.start.lessThanEqual(bestT)).and(bounds.end.greaterThanEqual(occupiedStart)) : supported,
540
582
  () => {
541
583
  if (!accelerated) {
542
584
  traceInterval(enter, exit, descriptor.raySteps);
@@ -611,7 +653,7 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
611
653
  return Result(
612
654
  bestUv,
613
655
  center.add(fromBox(point.mul(half))),
614
- bestNormal,
656
+ bestFace,
615
657
  valid,
616
658
  );
617
659
  });
@@ -623,10 +665,20 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
623
665
  // attributes by geometric coverage; an
624
666
  // empty neighbor must not turn a rough edge into a glossy highlight.
625
667
  const coverage = max(surfaceCoverage(orm.a,base.a), 1e-10);
668
+ // Decode only the winning capture. Visibility and depth passes need just
669
+ // the hit, and shaded passes already fetch its base color and coverage.
670
+ const hitNormal = Fn(() => {
671
+ const face = hit.get("face");
672
+ const { n, right, up } = faceBasis(face.div(2), face.mod(2).equal(0).select(1, -1));
673
+ const sampled = texture(maps.normalDepth, hit.get("uv")).level(0);
674
+ const local = unpackNormal(sampled.rg.div(coverage));
675
+ const direction = fromBox(right.mul(local.x).add(up.mul(local.y)).add(n.mul(local.z))).normalize().toVar();
676
+ return direction.mul(dot(direction, ray).greaterThan(0).select(-1, 1));
677
+ })();
626
678
  let color = base.div(coverage),
627
679
  surfaceOrm = orm.rgb.div(coverage),
628
680
  emission = texture(maps.emissive, hit.get("uv")).level(0).rgb.div(coverage),
629
- normal = hit.get("normal");
681
+ normal = hitNormal;
630
682
  if (settings.interpolation !== "none") {
631
683
  const fallbackColor = color,
632
684
  fallbackOrm = surfaceOrm,
@@ -753,9 +805,10 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
753
805
  emission = blended.get("emission");
754
806
  normal = blended.get("normal");
755
807
  }
756
- material.capturedPositionNode = hit.get("position");
808
+ const position = meshPoint(hit.get("position")).toVar("boxHitMeshPosition");
809
+ material.capturedPositionNode = position;
757
810
  material.colorNode = color.rgb;
758
- material.normalNode = transformNormalToView(normal);
811
+ material.normalNode = transformNormalToView(meshNormal(normal));
759
812
  material.roughnessNode = surfaceOrm.g;
760
813
  material.metalnessNode = surfaceOrm.b;
761
814
  material.aoNode = surfaceOrm.r;
@@ -770,9 +823,9 @@ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering =
770
823
  }
771
824
  material.maskNode = hit.get("valid").greaterThan(0.5);
772
825
  material.maskShadowNode = material.maskNode;
773
- material.depthNode = capturedSurfaceDepth(hit.get("position"));
826
+ material.depthNode = capturedSurfaceDepth(position);
774
827
  material.receivedShadowPositionNode = modelWorldMatrix.mul(
775
- vec4(hit.get("position"), 1),
828
+ vec4(position, 1),
776
829
  ).xyz;
777
830
  material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
778
831
  return material;
@@ -43,6 +43,8 @@ export function applyBoxProjection({
43
43
  viewAxis,
44
44
  perspective,
45
45
  raster,
46
+ meshPoint,
47
+ meshNormal,
46
48
  }) {
47
49
  const data = new Float32Array(descriptor.boxes.length * 24);
48
50
  descriptor.boxes.forEach((box, i) => {
@@ -255,9 +257,10 @@ export function applyBoxProjection({
255
257
  positions,
256
258
  );
257
259
  })().toVar('boxProjectedSurface');
258
- material.capturedPositionNode = surface.get('position');
260
+ const position = meshPoint(surface.get('position')).toVar('boxProjectedMeshPosition');
261
+ material.capturedPositionNode = position;
259
262
  material.colorNode = surface.get('color');
260
- material.normalNode = transformNormalToView(surface.get('normal'));
263
+ material.normalNode = transformNormalToView(meshNormal(surface.get('normal')));
261
264
  material.roughnessNode = surface.get('orm').g;
262
265
  material.metalnessNode = surface.get('orm').b;
263
266
  material.aoNode = surface.get('orm').r;
@@ -267,9 +270,9 @@ export function applyBoxProjection({
267
270
  .greaterThanEqual(transparency === 'cutout' ? alphaCutoff : float(1 / 255));
268
271
  material.maskShadowNode = material.maskNode;
269
272
  if (transparency !== 'cutout') material.opacityNode = surface.get('alpha');
270
- material.depthNode = capturedSurfaceDepth(surface.get('position'));
273
+ material.depthNode = capturedSurfaceDepth(position);
271
274
  material.receivedShadowPositionNode = modelWorldMatrix.mul(
272
- vec4(surface.get('position'), 1),
275
+ vec4(position, 1),
273
276
  ).xyz;
274
277
  material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
275
278
  return material;