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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +28 -6
  2. package/README.md +76 -1
  3. package/SKILL.md +9 -1
  4. package/build/box-impostor-runtime.js +1298 -0
  5. package/build/box-impostor-runtime.js.map +7 -0
  6. package/build/deformation-runtime.js +85 -31
  7. package/build/deformation-runtime.js.map +4 -4
  8. package/build/hull-effects.js +60 -28
  9. package/build/hull-effects.js.map +3 -3
  10. package/build/impostor-runtime.js +235 -116
  11. package/build/impostor-runtime.js.map +4 -4
  12. package/build/index.js +4 -0
  13. package/build/index.js.map +2 -2
  14. package/build/internal/box-impostor/box-impostor-display-settings.js +50 -0
  15. package/build/internal/box-impostor/box-impostor-display-settings.js.map +7 -0
  16. package/build/internal/box-impostor/box-impostor-display.js +1005 -0
  17. package/build/internal/box-impostor/box-impostor-display.js.map +7 -0
  18. package/build/internal/box-impostor/box-impostor-face-axes.js +15 -0
  19. package/build/internal/box-impostor/box-impostor-face-axes.js.map +7 -0
  20. package/build/internal/box-impostor/box-impostor-faces.js +125 -0
  21. package/build/internal/box-impostor/box-impostor-faces.js.map +7 -0
  22. package/build/internal/box-impostor/box-impostor-geometry.js +230 -0
  23. package/build/internal/box-impostor/box-impostor-geometry.js.map +7 -0
  24. package/build/internal/box-impostor/box-impostor-material.js +964 -0
  25. package/build/internal/box-impostor/box-impostor-material.js.map +7 -0
  26. package/build/internal/box-impostor/box-impostor-metadata.js +108 -0
  27. package/build/internal/box-impostor/box-impostor-metadata.js.map +7 -0
  28. package/build/internal/box-impostor/box-impostor-projection.js +256 -0
  29. package/build/internal/box-impostor/box-impostor-projection.js.map +7 -0
  30. package/build/internal/box-impostor/box-impostor-runtime.js +1252 -0
  31. package/build/internal/box-impostor/box-impostor-runtime.js.map +7 -0
  32. package/build/internal/box-impostor/box-impostor-surface-search.js +21 -0
  33. package/build/internal/box-impostor/box-impostor-surface-search.js.map +7 -0
  34. package/build/internal/deformation/cloth-surface.js +23 -17
  35. package/build/internal/deformation/cloth-surface.js.map +3 -3
  36. package/build/internal/deformation/fur-surface.js +55 -12
  37. package/build/internal/deformation/fur-surface.js.map +3 -3
  38. package/build/internal/deformation/pin-cloth.js +7 -2
  39. package/build/internal/deformation/pin-cloth.js.map +2 -2
  40. package/build/internal/deformation/rig-runtime.js +85 -31
  41. package/build/internal/deformation/rig-runtime.js.map +4 -4
  42. package/build/internal/impostor/impostor-node-material.js +235 -116
  43. package/build/internal/impostor/impostor-node-material.js.map +4 -4
  44. package/build/internal/rendering/hull-effect-runtime.js +59 -27
  45. package/build/internal/rendering/hull-effect-runtime.js.map +3 -3
  46. package/build/internal/rendering/texture-slot.js +26 -0
  47. package/build/internal/rendering/texture-slot.js.map +7 -0
  48. package/build/internal/rendering/wireframe.js +41 -9
  49. package/build/internal/rendering/wireframe.js.map +2 -2
  50. package/build/internal/rendering/wrap-preview.js +59 -27
  51. package/build/internal/rendering/wrap-preview.js.map +3 -3
  52. package/build/types/box-impostor/box-impostor-display-settings.d.ts +30 -0
  53. package/build/types/box-impostor/box-impostor-display-settings.js +1 -0
  54. package/build/types/box-impostor/box-impostor-display.d.ts +5 -0
  55. package/build/types/box-impostor/box-impostor-display.js +1 -0
  56. package/build/types/box-impostor/box-impostor-face-axes.d.ts +5 -0
  57. package/build/types/box-impostor/box-impostor-face-axes.js +1 -0
  58. package/build/types/box-impostor/box-impostor-faces.d.ts +11 -0
  59. package/build/types/box-impostor/box-impostor-faces.js +1 -0
  60. package/build/types/box-impostor/box-impostor-geometry.d.ts +5 -0
  61. package/build/types/box-impostor/box-impostor-geometry.js +1 -0
  62. package/build/types/box-impostor/box-impostor-material.d.ts +10 -0
  63. package/build/types/box-impostor/box-impostor-material.js +1 -0
  64. package/build/types/box-impostor/box-impostor-metadata.d.ts +31 -0
  65. package/build/types/box-impostor/box-impostor-metadata.js +1 -0
  66. package/build/types/box-impostor/box-impostor-projection.d.ts +19 -0
  67. package/build/types/box-impostor/box-impostor-projection.js +1 -0
  68. package/build/types/box-impostor/box-impostor-runtime.d.ts +25 -0
  69. package/build/types/box-impostor/box-impostor-runtime.js +1 -0
  70. package/build/types/box-impostor/box-impostor-surface-search.d.ts +13 -0
  71. package/build/types/box-impostor/box-impostor-surface-search.js +1 -0
  72. package/build/types/deformation/cloth-surface.d.ts +1 -0
  73. package/build/types/deformation/pin-cloth.d.ts +1 -0
  74. package/build/types/public/box-impostor-runtime.d.ts +6 -0
  75. package/build/types/public/box-impostor-runtime.js +1 -0
  76. package/build/types/public/hull-effects.d.ts +1 -0
  77. package/build/types/public/index.d.ts +1 -1
  78. package/build/types/rendering/texture-slot.d.ts +10 -0
  79. package/build/types/rendering/texture-slot.js +1 -0
  80. package/build/types/rendering/wireframe.d.ts +2 -2
  81. package/package.json +27 -6
  82. package/src/box-impostor/box-impostor-display-settings.js +54 -0
  83. package/src/box-impostor/box-impostor-display.js +38 -0
  84. package/src/box-impostor/box-impostor-face-axes.js +11 -0
  85. package/src/box-impostor/box-impostor-faces.js +118 -0
  86. package/src/box-impostor/box-impostor-geometry.js +140 -0
  87. package/src/box-impostor/box-impostor-material.js +721 -0
  88. package/src/box-impostor/box-impostor-metadata.js +122 -0
  89. package/src/box-impostor/box-impostor-projection.js +287 -0
  90. package/src/box-impostor/box-impostor-runtime.js +122 -0
  91. package/src/box-impostor/box-impostor-surface-search.js +11 -0
  92. package/src/deformation/cloth-surface.ts +28 -17
  93. package/src/deformation/fur-surface.ts +22 -12
  94. package/src/deformation/pin-cloth.ts +9 -3
  95. package/src/impostor/impostor-node-material.js +238 -150
  96. package/src/public/box-impostor-runtime.js +14 -0
  97. package/src/public/hull-effects.js +1 -0
  98. package/src/public/index.js +5 -1
  99. package/src/rendering/texture-slot.js +27 -0
  100. package/src/rendering/wireframe.js +51 -13
@@ -1,6 +1,7 @@
1
- import { BufferAttribute, MeshPhysicalMaterial, MeshStandardMaterial, SkinnedMesh, type BufferGeometry, type Material, type Object3D, type Texture } from 'three';
1
+ import { BufferAttribute, MeshPhysicalMaterial, MeshStandardMaterial, SkinnedMesh, Vector2, type BufferGeometry, type Material, type Object3D, type Texture } from 'three';
2
2
  import { MeshPhysicalNodeMaterial, MeshStandardNodeMaterial, type Node } from 'three/webgpu';
3
3
  import { attribute, float, mix, normalMap, positionLocal, texture, uniform, uv, varying, vec2, vec3, vec4 } from 'three/tsl';
4
+ import { bindTextureSlot } from '../rendering/texture-slot.js';
4
5
  import type { RigDescriptor } from './rig-extension.js';
5
6
 
6
7
  interface Surface { mesh: SkinnedMesh; geometry: BufferGeometry; modified: BufferGeometry; material: Material | Material[]; variants: MeshStandardNodeMaterial[] }
@@ -79,10 +80,18 @@ export class FurSurface {
79
80
  if (!signal) return material;
80
81
  const depth = attribute('furDepth', 'float' as const).mul(5).clamp(0, 1);
81
82
  const skinnedDelta = varying(positionLocal.sub(attribute('position', 'vec3' as const)), 'furSkinDelta') as Node<'vec3'>;
82
- const dimensions = signal.image as { width?: number; height?: number } | undefined;
83
- const pixel = vec2(1 / Math.max(1, dimensions?.width ?? 1024), 1 / Math.max(1, dimensions?.height ?? 1024));
83
+ const signalSlot = ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'aoMap', 'alphaMap'].find(slot => Reflect.get(source, slot) === signal) ?? 'furHeightMap';
84
+ const pixel = uniform(new Vector2());
85
+ const updatePixel = (map: Texture) => {
86
+ const dimensions = map.image as { width?: number; height?: number } | undefined;
87
+ pixel.value.set(1 / Math.max(1, dimensions?.width ?? 1024), 1 / Math.max(1, dimensions?.height ?? 1024));
88
+ };
89
+ updatePixel(signal);
84
90
  const movement = projectMotionToUv(skinnedDelta, coordinates).clamp(pixel.mul(-1.5), pixel.mul(1.5));
85
- const height = this.height ? texture(this.height, uv(this.height.channel)).r : float(.5);
91
+ const heightNode = this.height ? texture(this.height, uv(this.height.channel)) : null;
92
+ if (heightNode && this.height) bindTextureSlot(material, 'furHeightMap', this.height,
93
+ [heightNode], value => { this.height = value; if (signalSlot === 'furHeightMap') updatePixel(value); });
94
+ const height = heightNode ? heightNode.r : float(.5);
86
95
  const raised = mix(.65, 1.35, height);
87
96
  const phase = coordinates.dot(vec2(31, 43)).add(height.sub(.5).mul(2.4)).add(this.clock.mul(this.wind).mul(1.7));
88
97
  const gust = vec2(phase.sin(), phase.mul(1.31).cos()).mul(pixel).mul(this.wind.mul(.65));
@@ -91,20 +100,21 @@ export class FurSurface {
91
100
  // with wind; height modulates movement rather than drawing synthetic hair.
92
101
  const shift = movement.add(gust).mul(depth).mul(raised)
93
102
  .clamp(pixel.mul(-2), pixel.mul(2)).toVar('furTextureShift');
94
- const sample = (map: Texture) => {
103
+ const sample = (map: Texture, slot: string) => {
95
104
  const node = texture(map, uv(map.channel).add(shift));
96
105
  node.updateMatrix = true;
106
+ bindTextureSlot(material, slot, map, [node], value => { Reflect.set(source, slot, value); if (signalSlot === slot) updatePixel(value); });
97
107
  return node;
98
108
  };
99
- const base = source.map ? sample(source.map) : vec4(1);
109
+ const base = source.map ? sample(source.map, 'map') : vec4(1);
100
110
  material.colorNode = base.mul(vec4(source.color.r, source.color.g, source.color.b, 1));
101
- if (source.alphaMap) material.opacityNode = sample(source.alphaMap).g;
102
- if (source.normalMap) material.normalNode = normalMap(sample(source.normalMap).xyz,
111
+ if (source.alphaMap) material.opacityNode = sample(source.alphaMap, 'alphaMap').g;
112
+ if (source.normalMap) material.normalNode = normalMap(sample(source.normalMap, 'normalMap').xyz,
103
113
  vec2(source.normalScale.x, source.normalScale.y));
104
- material.roughnessNode = source.roughnessMap ? sample(source.roughnessMap).g.mul(source.roughness) : float(source.roughness);
105
- material.metalnessNode = source.metalnessMap ? sample(source.metalnessMap).b.mul(source.metalness) : float(source.metalness);
106
- if (source.aoMap) material.aoNode = float(1).sub(float(1).sub(sample(source.aoMap).r).mul(source.aoMapIntensity));
107
- if (source.emissiveMap) material.emissiveNode = sample(source.emissiveMap).rgb.mul(vec3(
114
+ material.roughnessNode = source.roughnessMap ? sample(source.roughnessMap, 'roughnessMap').g.mul(source.roughness) : float(source.roughness);
115
+ material.metalnessNode = source.metalnessMap ? sample(source.metalnessMap, 'metalnessMap').b.mul(source.metalness) : float(source.metalness);
116
+ if (source.aoMap) material.aoNode = float(1).sub(float(1).sub(sample(source.aoMap, 'aoMap').r).mul(source.aoMapIntensity));
117
+ if (source.emissiveMap) material.emissiveNode = sample(source.emissiveMap, 'emissiveMap').rgb.mul(vec3(
108
118
  source.emissive.r * source.emissiveIntensity,
109
119
  source.emissive.g * source.emissiveIntensity,
110
120
  source.emissive.b * source.emissiveIntensity));
@@ -56,7 +56,8 @@ export class PinCloth {
56
56
  private particles = new Map<string, { position: Vector3; previous: Vector3 }>();
57
57
  private layout = '';
58
58
  private windTime = 0;
59
- reset() { this.particles.clear(); this.layout = ''; this.windTime = 0; }
59
+ private accumulator = 0;
60
+ reset() { this.particles.clear(); this.layout = ''; this.windTime = 0; this.accumulator = 0; }
60
61
  step(pins: readonly PinRecord[], parents: PinParents, seconds: number, links: readonly ClothLink[], colliders: readonly ClothCollider[] = [], windStrength = 0): { pins: readonly PinRecord[]; active: boolean } {
61
62
  const cloth = pins.filter(p => p.cloth && !p.guide);
62
63
  if (!cloth.length) { this.reset(); return { pins, active: false }; }
@@ -67,7 +68,12 @@ export class PinCloth {
67
68
  const position = new Vector3().fromArray(pin.pose.position);
68
69
  this.particles.set(pin.id, { position, previous: position.clone() });
69
70
  }
70
- const dt = Math.min(Math.max(seconds, 0), .05), steps = Math.max(1, Math.ceil(dt / (1 / 60))), h = dt / steps;
71
+ // Verlet stores displacement per step. Changing the step with render
72
+ // timing changes its velocity and keeps a calm sheet moving.
73
+ const h = 1 / 60;
74
+ this.accumulator += Math.min(Math.max(seconds, 0), .05);
75
+ const steps = Math.floor((this.accumulator + 1e-12) / h);
76
+ this.accumulator = Math.max(0, this.accumulator - steps * h);
71
77
  const scale = Math.max(1e-4, ...links.map(link => link.length));
72
78
  // A sampled voxel shell can contain thousands of spheres. Bin it once
73
79
  // per frame, then refresh each particle's nearby set after integration so
@@ -95,7 +101,7 @@ export class PinCloth {
95
101
  } else for (const collider of colliders) search(collider);
96
102
  return found;
97
103
  };
98
- for (let substep = 0; substep < steps && dt > 0; substep++) {
104
+ for (let substep = 0; substep < steps; substep++) {
99
105
  this.windTime += h;
100
106
  for (const pin of cloth) {
101
107
  const particle = this.particles.get(pin.id)!;
@@ -22,6 +22,7 @@ import {
22
22
  Fn,
23
23
  If,
24
24
  Loop,
25
+ Break,
25
26
  abs,
26
27
  any,
27
28
  bool,
@@ -48,6 +49,7 @@ import {
48
49
  smoothstep,
49
50
  texture,
50
51
  textureLoad,
52
+ textureSize,
51
53
  transformNormalToView,
52
54
  uniformArray,
53
55
  vec2,
@@ -57,6 +59,7 @@ import {
57
59
  viewZToPerspectiveDepth,
58
60
  } from 'three/tsl';
59
61
  import { NEEDLE_MESH_IMPOSTOR } from './impostor-metadata.js';
62
+ import { bindTextureSlot } from '../rendering/texture-slot.js';
60
63
  import { PERSPECTIVE_RAY_PLANE_SIGN } from './octahedral.js';
61
64
  import {
62
65
  REPROJECTION_CONFIDENCE_INNER_TEXELS,
@@ -560,6 +563,21 @@ function createCompatibleImpostorNodeMaterial(descriptor, maps) {
560
563
  float halfTexel = 0.5001 / frameResolution;
561
564
  return (frame + clamp(insideCell, vec2(halfTexel), vec2(1.0 - halfTexel))) / frames;
562
565
  }
566
+ vec4 sampleColorAtlas(vec2 coordinates) {
567
+ vec2 size = vec2(textureSize(baseColorAtlas, 0));
568
+ vec2 grid = vec2(frames);
569
+ #if COMPACT_COLOR && COMPACT_EMISSIVE
570
+ grid.x *= 2.0;
571
+ #endif
572
+ vec2 pixels = coordinates * size;
573
+ float footprint = max(length(dFdx(pixels)), length(dFdy(pixels)));
574
+ float gutter = padding * size.y / (frames * frameResolution);
575
+ float lod = clamp(log2(max(footprint, 1.0)), 0.0, floor(log2(max(gutter, 1.0))));
576
+ vec2 cell = floor(clamp(coordinates * grid, vec2(0.0), grid - 0.00001));
577
+ vec2 guard = vec2(0.5001 * exp2(lod)) / size;
578
+ vec2 safe = clamp(coordinates, cell / grid + guard, (cell + 1.0) / grid - guard);
579
+ return textureLod(baseColorAtlas, safe, lod);
580
+ }
563
581
  void main() {
564
582
  vec3 cameraLocal = (inverse(modelMatrix) * vec4(cameraPosition, 1.0)).xyz;
565
583
  vec3 cameraDirection = normalize(cameraLocal);
@@ -594,7 +612,7 @@ function createCompatibleImpostorNodeMaterial(descriptor, maps) {
594
612
  #if COMPACT_COLOR
595
613
  colorUv.x *= COMPACT_EMISSIVE == 1 ? 0.5 : 1.0;
596
614
  #endif
597
- vec4 base = texture(baseColorAtlas, colorUv);
615
+ vec4 base = sampleColorAtlas(colorUv);
598
616
  vec4 geometry = texture(geometryAtlas, atlas);
599
617
  float contour = base.a;
600
618
  float depthValue;
@@ -690,14 +708,30 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
690
708
  uvNode.y,
691
709
  )
692
710
  : uvNode;
711
+ const mapLod = (atlas, coordinates) => {
712
+ const size = vec2(textureSize(atlas));
713
+ const pixels = coordinates.mul(size);
714
+ const footprint = max(pixels.dFdx().length(), pixels.dFdy().length());
715
+ const gutter = padding.mul(size.y).div(frames.mul(frameResolution));
716
+ return max(footprint, 1).log2().clamp(0, max(gutter, 1).log2().floor());
717
+ };
718
+ const sampleAtlas = (atlas, coordinates, lod = float(0), columns = frames) => {
719
+ const size = vec2(textureSize(atlas));
720
+ const grid = vec2(columns, frames);
721
+ const cell = coordinates.mul(grid).clamp(0, grid.sub(0.00001)).floor();
722
+ const guard = float(0.5001).mul(float(2).pow(lod)).div(size);
723
+ const safe = coordinates.clamp(cell.div(grid).add(guard), cell.add(1).div(grid).sub(guard));
724
+ return texture(atlas, safe).level(lod);
725
+ };
726
+ const colorColumns = frames.mul(compactLayout && compactEmissive ? 2 : 1);
693
727
  const sampleCapturedAlpha = (uvNode) => compressedGeometry
694
- ? texture(baseColorAtlas, colorAtlasUv(uvNode)).level(0).a
695
- : texture(baseColorAtlas, uvNode).level(0).a;
728
+ ? sampleAtlas(baseColorAtlas, colorAtlasUv(uvNode), float(0), colorColumns).a
729
+ : sampleAtlas(baseColorAtlas, uvNode).a;
696
730
  const sampleContour = (uvNode) => compressedGeometry
697
731
  ? texture(geometryAtlas, uvNode).level(0).a
698
732
  : descriptor.coverageEncoding === 'sdf-base-alpha'
699
- ? texture(baseColorAtlas, uvNode).level(0).a
700
- : texture(ormAtlas, uvNode).level(0).a;
733
+ ? sampleAtlas(baseColorAtlas, uvNode).a
734
+ : sampleAtlas(ormAtlas, uvNode).a;
701
735
  const viewBounds = uniformArray(
702
736
  Array.from({ length: descriptor.frames * descriptor.frames }, (_, index) => new Vector4(
703
737
  descriptor.viewBounds[index * 4],
@@ -708,12 +742,6 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
708
742
  'vec4',
709
743
  );
710
744
  const atlasResolution = float(descriptor.frames * descriptor.frameResolution);
711
- const materialAtlasResolution = float(
712
- descriptor.frames * (descriptor.compression?.materialFrameResolution ?? descriptor.frameResolution),
713
- );
714
- // Stop before the atlas gutter becomes sub-texel, otherwise adjacent views
715
- // bleed into one another in the generated mip chain.
716
- const maximumSafeAtlasLod = float(Math.max(0, Math.floor(Math.log2(Math.max(1, descriptor.padding)))));
717
745
 
718
746
  const FrameBasis = NAMED_STRUCT_FACTORY(
719
747
  { right: 'vec3', up: 'vec3' },
@@ -801,22 +829,6 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
801
829
  const halfTexel = float(0.5001).div(frameResolution);
802
830
  return frame.add(insideCell.clamp(halfTexel, float(1).sub(halfTexel))).div(frames);
803
831
  }, 'vec2');
804
- const atlasLod = Fn(([uvNode]) => {
805
- const texelCoordinate = uvNode.mul(atlasResolution);
806
- const footprint = max(
807
- texelCoordinate.dFdx().length(),
808
- texelCoordinate.dFdy().length(),
809
- );
810
- return max(footprint, 1).log2().clamp(0, maximumSafeAtlasLod);
811
- }, 'float');
812
- const materialAtlasLod = Fn(([uvNode]) => {
813
- const texelCoordinate = uvNode.mul(materialAtlasResolution);
814
- const footprint = max(
815
- texelCoordinate.dFdx().length(),
816
- texelCoordinate.dFdy().length(),
817
- );
818
- return max(footprint, 1).log2().clamp(0, maximumSafeAtlasLod);
819
- }, 'float');
820
832
  const decodeDepth16 = Fn(([packed]) => {
821
833
  if (descriptor.compression?.depthEncoding === 'lossless-geometry10-rgba') {
822
834
  const bytes = floor(packed.rg.mul(255).add(0.5));
@@ -973,83 +985,186 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
973
985
  const rootFound = bool(false).toVar();
974
986
  const rootLower = float(0).toVar();
975
987
  const rootUpper = float(1).toVar();
976
- const previousHasSurface = bool(false).toVar();
977
- const previousSearchDepth = float(0).toVar();
978
- const previousSurfaceDepth = float(1).toVar();
979
- const coarseStep = float(1).div(coarseSearchSteps);
980
- Loop(coarseSearchSteps, ({ i }) => {
981
- const searchDepth = float(i).add(1).mul(coarseStep);
982
- const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));
983
- const searchRayPosition = planePosition.add(rayDirection.mul(
984
- searchPlaneDepth.sub(dot(planePosition, frameDirection))
985
- .div(safeRayPlaneDenominator),
986
- ));
987
- const searchUv = vec2(
988
- dot(searchRayPosition, right),
989
- dot(searchRayPosition, up),
990
- ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
991
- const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv)))
992
- .or(any(searchUv.greaterThan(vec2(maximumFrameUv))));
993
- If(searchOutOfBounds, () => {
994
- previousHasSurface.assign(false);
988
+ // Empty billboard pixels must not traverse the whole capture volume.
989
+ // The source AABB is conservative, with one texel for filtered edges.
990
+ const safeRay = vec3(
991
+ nonZeroSign(rayDirection.x),
992
+ nonZeroSign(rayDirection.y),
993
+ nonZeroSign(rayDirection.z),
994
+ ).mul(max(abs(rayDirection), vec3(1e-7)));
995
+ const boundsGuard = radius.mul(2).div(interiorResolution);
996
+ const boxT0 = vec3(...descriptor.boundsMin).sub(boundsGuard)
997
+ .sub(planePosition).div(safeRay);
998
+ const boxT1 = vec3(...descriptor.boundsMax).add(boundsGuard)
999
+ .sub(planePosition).div(safeRay);
1000
+ const boxLow = min(boxT0, boxT1), boxHigh = max(boxT0, boxT1);
1001
+ const boxStart = max(boxLow.x, max(boxLow.y, boxLow.z));
1002
+ const boxEnd = min(boxHigh.x, min(boxHigh.y, boxHigh.z));
1003
+ const intersectsBounds = boxStart.lessThanEqual(boxEnd);
1004
+ const captureDepthAt = (t) => radius.sub(
1005
+ dot(planePosition.add(rayDirection.mul(t)), frameDirection),
1006
+ ).div(radius.mul(2));
1007
+ const depth0 = captureDepthAt(boxStart), depth1 = captureDepthAt(boxEnd);
1008
+ // UV is affine in capture depth. Clipping to the capture crop spends
1009
+ // the existing march budget on possible surfaces instead of empty space.
1010
+ const uvDepthSlope = vec2(dot(rayDirection, right), dot(rayDirection, up))
1011
+ .mul(radius.mul(-2).div(safeRayPlaneDenominator))
1012
+ .div(bounds.zw.sub(bounds.xy));
1013
+ const safeSlope = vec2(
1014
+ nonZeroSign(uvDepthSlope.x), nonZeroSign(uvDepthSlope.y),
1015
+ ).mul(max(abs(uvDepthSlope), vec2(1e-7)));
1016
+ const uvStart = projectedFrameUv.sub(uvDepthSlope.mul(0.5));
1017
+ const t0 = vec2(minimumFrameUv).sub(uvStart).div(safeSlope);
1018
+ const t1 = vec2(maximumFrameUv).sub(uvStart).div(safeSlope);
1019
+ const lower = min(t0, t1), upper = max(t0, t1);
1020
+ const searchStart = max(min(depth0, depth1), max(0, max(lower.x, lower.y)));
1021
+ const searchEnd = min(max(depth0, depth1), min(1, min(upper.x, upper.y)));
1022
+ const searchRange = max(searchEnd.sub(searchStart), 1e-6);
1023
+ const coarseStep = searchRange.div(coarseSearchSteps);
1024
+ const validateRoot = () => {
1025
+ If(rootSolved, () => {
1026
+ const at = atlasUv(frame, frameUv);
1027
+ const surface = reconstructPosition(frameUv, bounds, frameDirection, right, up, sampleDepth16(at));
1028
+ const closest = planePosition.add(rayDirection.mul(dot(surface.sub(planePosition), rayDirection)));
1029
+ const footprint = max(bounds.z.sub(bounds.x), bounds.w.sub(bounds.y)).div(interiorResolution);
1030
+ const nearestPixel = floor(at.mul(atlasResolution));
1031
+ const nearestDepth = loadDepth16(nearestPixel);
1032
+ const depthJump = abs(sampleDepth16(at).sub(nearestDepth)).mul(radius).mul(2);
1033
+ const discontinuity = bool(false).toVar();
1034
+ If(depthJump.greaterThan(footprint.mul(4)), () => {
1035
+ const neighbor = (offset) => loadDepth16(nearestPixel.add(offset).clamp(
1036
+ frame.mul(frameResolution), frame.add(1).mul(frameResolution).sub(1),
1037
+ ));
1038
+ // A steep plane can change depth arbitrarily fast. Unlike a slope
1039
+ // cap, second differences reject interpolated depth steps without
1040
+ // rejecting a continuous plane merely because it is steep.
1041
+ const curvature = max(
1042
+ abs(neighbor(vec2(-1, 0)).add(neighbor(vec2(1, 0))).sub(nearestDepth.mul(2))),
1043
+ abs(neighbor(vec2(0, -1)).add(neighbor(vec2(0, 1))).sub(nearestDepth.mul(2))),
1044
+ ).mul(radius).mul(2);
1045
+ discontinuity.assign(curvature.greaterThan(footprint.mul(4)));
1046
+ });
1047
+ If(surface.sub(closest).length().greaterThan(footprint.mul(4))
1048
+ .or(discontinuity)
1049
+ .or(sampleCapturedAlpha(at).lessThan(reprojectionSurfaceCutoff)), () => {
1050
+ rootFound.assign(false);
1051
+ rootSolved.assign(false);
1052
+ strictRootSolved.assign(false);
1053
+ });
995
1054
  });
996
- If(searchOutOfBounds.not(), () => {
997
- const searchAtlasUv = atlasUv(frame, searchUv);
998
- const searchCoverage = sampleCapturedAlpha(searchAtlasUv);
999
- const searchSurfaceDepth = sampleDepth16(searchAtlasUv);
1000
- // Only captured coverage represents geometry. The transition SDF
1001
- // deliberately extends outside the silhouette; accepting it as a
1002
- // ray hit turns that band into repeated depth shells and streaks.
1003
- const hasSurface = searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff);
1004
- const depthDelta = searchDepth.sub(searchSurfaceDepth);
1005
- const crossesDepth = previousHasSurface
1006
- .and(previousSearchDepth.lessThan(previousSurfaceDepth))
1007
- .and(depthDelta.greaterThanEqual(0));
1008
- const continuousDepthStep = abs(searchSurfaceDepth.sub(previousSurfaceDepth))
1009
- .lessThanEqual(coarseStep.mul(2));
1010
- const crossesCoveredSurface = crossesDepth.and(continuousDepthStep);
1011
- // A thin captured feature can occupy less than one coarse ray step,
1012
- // so its first covered sample may already lie just behind the stored
1013
- // surface. Only accept that entry when the root is inside the
1014
- // immediately preceding march interval. A late silhouette entry is
1015
- // not a height-field crossing and must not become a second layer.
1016
- const entersAtSurface = previousHasSurface.not()
1017
- .and(depthDelta.greaterThanEqual(0))
1018
- .and(depthDelta.lessThanEqual(coarseStep.mul(1.15)));
1019
- const boundedRoot = crossesCoveredSurface.or(entersAtSurface);
1020
- If(
1021
- rootFound.not()
1022
- .and(hasSurface)
1023
- .and(features.boundedReprojection
1024
- ? boundedRoot
1025
- : depthDelta.greaterThanEqual(0)),
1026
- () => {
1027
- rootLower.assign(max(searchDepth.sub(coarseStep), 0));
1055
+ };
1056
+ const refineRoot = () => {
1057
+ If(rootFound, () => {
1058
+ Loop(profile.depthSamples, () => {
1059
+ const searchDepth = rootLower.add(rootUpper).mul(0.5);
1060
+ const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));
1061
+ const searchRayPosition = planePosition.add(rayDirection.mul(
1062
+ searchPlaneDepth.sub(dot(planePosition, frameDirection))
1063
+ .div(safeRayPlaneDenominator),
1064
+ ));
1065
+ const searchUv = vec2(
1066
+ dot(searchRayPosition, right),
1067
+ dot(searchRayPosition, up),
1068
+ ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
1069
+ const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv)))
1070
+ .or(any(searchUv.greaterThan(vec2(maximumFrameUv))));
1071
+ const midpointIsUpper = bool(false).toVar();
1072
+ If(searchOutOfBounds.not(), () => {
1073
+ const searchAtlasUv = atlasUv(frame, searchUv);
1074
+ const searchCoverage = sampleCapturedAlpha(searchAtlasUv);
1075
+ const searchSurfaceDepth = sampleDepth16(searchAtlasUv);
1076
+ midpointIsUpper.assign(
1077
+ searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff)
1078
+ .and(searchDepth.greaterThanEqual(searchSurfaceDepth)),
1079
+ );
1080
+ });
1081
+ If(midpointIsUpper, () => {
1028
1082
  rootUpper.assign(searchDepth);
1029
- rootFound.assign(true);
1030
- rootSolved.assign(true);
1031
- strictRootSolved.assign(true);
1032
- },
1033
- );
1034
- If(rootFound.not().and(hasSurface), () => {
1035
- previousHasSurface.assign(true);
1036
- previousSearchDepth.assign(searchDepth);
1037
- previousSurfaceDepth.assign(searchSurfaceDepth);
1083
+ });
1084
+ If(midpointIsUpper.not(), () => {
1085
+ rootLower.assign(searchDepth);
1086
+ });
1038
1087
  });
1039
- If(hasSurface.not(), () => {
1040
- previousHasSurface.assign(false);
1088
+ const residualAt = (depth) => {
1089
+ const planeDepth = radius.sub(depth.mul(radius).mul(2));
1090
+ const position = planePosition.add(rayDirection.mul(
1091
+ planeDepth.sub(dot(planePosition, frameDirection)).div(safeRayPlaneDenominator),
1092
+ ));
1093
+ const address = vec2(dot(position, right), dot(position, up))
1094
+ .sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
1095
+ return depth.sub(sampleDepth16(atlasUv(frame,address)));
1096
+ };
1097
+ // A midpoint leaves large physical errors on a steep height field.
1098
+ // Secant interpolation is exact for a plane and stays in the bracket.
1099
+ const lowResidual = residualAt(rootLower), highResidual = residualAt(rootUpper);
1100
+ const difference = lowResidual.sub(highResidual);
1101
+ const fraction = lowResidual.div(
1102
+ nonZeroSign(difference).mul(max(abs(difference), 1e-8)),
1103
+ ).clamp(0, 1);
1104
+ const rootDepth = mix(rootLower,rootUpper,fraction);
1105
+
1106
+ const rootPlaneDepth = radius.sub(rootDepth.mul(radius).mul(2));
1107
+ const rootRayPosition = planePosition.add(rayDirection.mul(
1108
+ rootPlaneDepth.sub(dot(planePosition, frameDirection))
1109
+ .div(safeRayPlaneDenominator),
1110
+ ));
1111
+ frameUv.assign(vec2(
1112
+ dot(rootRayPosition, right),
1113
+ dot(rootRayPosition, up),
1114
+ ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy)).clamp(
1115
+ minimumFrameUv,
1116
+ maximumFrameUv,
1117
+ ));
1118
+ });
1119
+ };
1120
+ const traceInterval = (steps, start = searchStart, end = searchEnd) => {
1121
+ const coarseStep = max(end.sub(start), 1e-6).div(float(steps));
1122
+ Loop({ start: 0, end: steps, type: 'int' }, ({ i }) => {
1123
+ If(rootFound.or(intersectsBounds.not()).or(end.lessThan(start)), () => { Break(); });
1124
+ const searchDepth = start.add(float(i).add(1).mul(coarseStep));
1125
+ const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));
1126
+ const searchRayPosition = planePosition.add(rayDirection.mul(
1127
+ searchPlaneDepth.sub(dot(planePosition, frameDirection))
1128
+ .div(safeRayPlaneDenominator),
1129
+ ));
1130
+ const searchUv = vec2(
1131
+ dot(searchRayPosition, right),
1132
+ dot(searchRayPosition, up),
1133
+ ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
1134
+ const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv)))
1135
+ .or(any(searchUv.greaterThan(vec2(maximumFrameUv))));
1136
+ If(searchOutOfBounds.not(), () => {
1137
+ const searchAtlasUv = atlasUv(frame, searchUv);
1138
+ const searchCoverage = sampleCapturedAlpha(searchAtlasUv);
1139
+ const hasSurface = searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff);
1140
+ If(hasSurface, () => {
1141
+ const searchSurfaceDepth = sampleDepth16(searchAtlasUv);
1142
+ const depthDelta = searchDepth.sub(searchSurfaceDepth);
1143
+ If(
1144
+ rootFound.not()
1145
+ .and(hasSurface)
1146
+ .and(depthDelta.greaterThanEqual(0)),
1147
+ () => {
1148
+ rootLower.assign(max(searchDepth.sub(coarseStep), 0));
1149
+ rootUpper.assign(searchDepth);
1150
+ rootFound.assign(true);
1151
+ rootSolved.assign(true);
1152
+ strictRootSolved.assign(true);
1153
+ refineRoot();
1154
+ if (features.boundedReprojection) validateRoot();
1155
+ },
1156
+ );
1157
+ });
1041
1158
  });
1042
1159
  });
1043
- });
1044
- // The bounded march deliberately rejects height-field discontinuities.
1045
- // Near a dense capture direction, a valid surface can still be too steep
1046
- // to form a coarse bracket. Use the center-plane depth only as a seed for
1047
- // a fixed-point solve, and accept it solely after the projected UV/depth
1048
- // pair converges inside captured coverage. Unlike the removed planar
1049
- // fallback, this path produces a point on the runtime camera ray and
1050
- // never contributes an unconverged card layer.
1051
- If(rootFound.not(), () => {
1052
- const iterativeUv = frameUv.toVar();
1160
+ };
1161
+ traceInterval(int(coarseSearchSteps));
1162
+ // A fixed-point solution can recover a grazing ray with no sign bracket.
1163
+ // Retain it only after convergence inside captured coverage; blend-time
1164
+ // seed suppression still prevents an unrelated background layer.
1165
+ If(rootFound.not().and(intersectsBounds), () => {
1166
+ // A rejected march root must not seed itself back into validity.
1167
+ const iterativeUv = projectedFrameUv.clamp(minimumFrameUv, maximumFrameUv).toVar();
1053
1168
  const iterativeDepth = sampleDepth16(atlasUv(frame, iterativeUv)).toVar();
1054
1169
  const iterationResidual = float(1).toVar();
1055
1170
  const iterationValid = bool(true).toVar();
@@ -1087,58 +1202,12 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1087
1202
  () => {
1088
1203
  frameUv.assign(iterativeUv);
1089
1204
  rootSolved.assign(true);
1205
+ if (features.boundedReprojection) validateRoot();
1090
1206
  },
1091
1207
  );
1092
1208
  });
1093
- If(rootFound, () => {
1094
- Loop(profile.depthSamples, () => {
1095
- const searchDepth = rootLower.add(rootUpper).mul(0.5);
1096
- const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));
1097
- const searchRayPosition = planePosition.add(rayDirection.mul(
1098
- searchPlaneDepth.sub(dot(planePosition, frameDirection))
1099
- .div(safeRayPlaneDenominator),
1100
- ));
1101
- const searchUv = vec2(
1102
- dot(searchRayPosition, right),
1103
- dot(searchRayPosition, up),
1104
- ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
1105
- const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv)))
1106
- .or(any(searchUv.greaterThan(vec2(maximumFrameUv))));
1107
- const midpointIsUpper = bool(false).toVar();
1108
- If(searchOutOfBounds.not(), () => {
1109
- const searchAtlasUv = atlasUv(frame, searchUv);
1110
- const searchCoverage = sampleCapturedAlpha(searchAtlasUv);
1111
- const searchSurfaceDepth = sampleDepth16(searchAtlasUv);
1112
- midpointIsUpper.assign(
1113
- searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff)
1114
- .and(searchDepth.greaterThanEqual(searchSurfaceDepth)),
1115
- );
1116
- });
1117
- If(midpointIsUpper, () => {
1118
- rootUpper.assign(searchDepth);
1119
- });
1120
- If(midpointIsUpper.not(), () => {
1121
- rootLower.assign(searchDepth);
1122
- });
1123
- });
1124
- const rootDepth = rootLower.add(rootUpper).mul(0.5);
1125
- const rootPlaneDepth = radius.sub(rootDepth.mul(radius).mul(2));
1126
- const rootRayPosition = planePosition.add(rayDirection.mul(
1127
- rootPlaneDepth.sub(dot(planePosition, frameDirection))
1128
- .div(safeRayPlaneDenominator),
1129
- ));
1130
- frameUv.assign(vec2(
1131
- dot(rootRayPosition, right),
1132
- dot(rootRayPosition, up),
1133
- ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy)).clamp(
1134
- minimumFrameUv,
1135
- maximumFrameUv,
1136
- ));
1137
- });
1138
1209
  }
1139
1210
  const uvNode = atlasUv(frame, frameUv);
1140
- const lod = atlasLod(uvNode);
1141
- const materialLod = compactLayout ? materialAtlasLod(uvNode) : lod;
1142
1211
  reconstructed.assign(reconstructPosition(
1143
1212
  frameUv,
1144
1213
  bounds,
@@ -1147,7 +1216,7 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1147
1216
  up,
1148
1217
  sampleDepth16(uvNode),
1149
1218
  ));
1150
- const shadingSample = texture(normalDepthAtlas, uvNode).level(materialLod);
1219
+ const shadingSample = sampleAtlas(normalDepthAtlas, uvNode, mapLod(normalDepthAtlas, uvNode));
1151
1220
  const geometrySample = compressedGeometry
1152
1221
  ? texture(geometryAtlas, uvNode).level(0)
1153
1222
  : null;
@@ -1202,12 +1271,13 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1202
1271
  ? alignedConfidence.mul(strictRootSolved)
1203
1272
  : float(1),
1204
1273
  );
1205
- const baseColor = texture(baseColorAtlas, colorAtlasUv(uvNode)).level(materialLod);
1274
+ const colorUv = colorAtlasUv(uvNode);
1275
+ const baseColor = sampleAtlas(baseColorAtlas, colorUv, mapLod(baseColorAtlas, colorUv), colorColumns);
1206
1276
  const capturedAlpha = sampleCapturedAlpha(uvNode);
1207
1277
  const orm = compactLayout
1208
1278
  ? vec4(geometrySample.b, shadingSample.b, shadingSample.a, 1)
1209
1279
  : ormAtlas
1210
- ? texture(ormAtlas, uvNode).level(lod)
1280
+ ? sampleAtlas(ormAtlas, uvNode, mapLod(ormAtlas, uvNode))
1211
1281
  : vec4(
1212
1282
  descriptor.material.occlusion,
1213
1283
  descriptor.material.roughness,
@@ -1230,7 +1300,7 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1230
1300
  reconstructed,
1231
1301
  orm.rgb,
1232
1302
  emissiveAtlas
1233
- ? texture(emissiveAtlas, colorAtlasUv(uvNode, true)).level(materialLod).rgb
1303
+ ? sampleAtlas(emissiveAtlas, colorAtlasUv(uvNode, true), mapLod(emissiveAtlas, colorAtlasUv(uvNode, true)), colorColumns).rgb
1234
1304
  : vec3(0),
1235
1305
  coverage,
1236
1306
  resolvedValidity,
@@ -1577,5 +1647,23 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1577
1647
  material.receivedShadowPositionNode = reconstructedWorldPosition;
1578
1648
  material.toneMapped = true;
1579
1649
  material.userData.impostorShaderProfile = profile;
1650
+ bindTextureSlot(material, 'baseColorAtlas', maps.baseColor, [baseColorAtlas, ...(compactLayout && compactEmissive && emissiveAtlas ? [emissiveAtlas] : [])], value => {
1651
+ maps.baseColor = value;
1652
+ if (compactLayout && compactEmissive) maps.emissive = value;
1653
+ if (material.userData.impostor) {
1654
+ material.userData.impostor.atlases.baseColor = value;
1655
+ if (compactLayout && compactEmissive) material.userData.impostor.atlases.emissive = value;
1656
+ }
1657
+ });
1658
+ bindTextureSlot(material, 'normalDepthAtlas', maps.normalDepth, [normalDepthAtlas, ...(compactLayout && ormAtlas ? [ormAtlas] : []), ...(!compressedGeometry ? [geometryAtlas] : [])], value => {
1659
+ maps.normalDepth = value;
1660
+ if (compactLayout) maps.orm = value;
1661
+ if (material.userData.impostor) {
1662
+ material.userData.impostor.atlases.normalDepth = value;
1663
+ if (compactLayout) material.userData.impostor.atlases.orm = value;
1664
+ }
1665
+ });
1666
+ if (!compactLayout && maps.orm && ormAtlas) bindTextureSlot(material, 'ormAtlas', maps.orm, [ormAtlas], value => { maps.orm = value; });
1667
+ if (!compactLayout && maps.emissive && emissiveAtlas) bindTextureSlot(material, 'emissiveAtlas', maps.emissive, [emissiveAtlas], value => { maps.emissive = value; });
1580
1668
  return material;
1581
1669
  }
@@ -0,0 +1,14 @@
1
+ // @ts-check
2
+ export {
3
+ NEEDLE_BOX_IMPOSTOR,
4
+ parseBoxImpostorDescriptor,
5
+ } from '../box-impostor/box-impostor-metadata.js';
6
+ export { createBoxImpostorGeometry } from '../box-impostor/box-impostor-geometry.js';
7
+ export { createBoxImpostorMaterial } from '../box-impostor/box-impostor-material.js';
8
+ export {
9
+ NeedleBoxImpostorLoaderPlugin,
10
+ registerNeedleBoxImpostorLoader,
11
+ } from '../box-impostor/box-impostor-runtime.js';
12
+
13
+ export { DEFAULT_BOX_IMPOSTOR_DISPLAY, normalizeBoxImpostorDisplay } from '../box-impostor/box-impostor-display-settings.js';
14
+ export { setBoxImpostorDisplay } from '../box-impostor/box-impostor-display.js';
@@ -1,4 +1,5 @@
1
1
  // @ts-check
2
+ /** @typedef {import('../rendering/wireframe.js').WireframeBlendMode} WireframeBlendMode */
2
3
 
3
4
  export { bindHull, getHullEffect, NeedleHullEffectLoaderPlugin } from '../rendering/hull-effect-runtime.js';
4
5
  export { NEEDLE_HULL_EFFECT, parseHullEffectDescriptor } from '../rendering/hull-effect-metadata.js';
@@ -5,7 +5,7 @@
5
5
  /** @typedef {import('three/addons/loaders/GLTFLoader.js').GLTF} GLTF */
6
6
  /** @typedef {import('../impostor/impostor-node-material.js').ImpostorRenderer} Renderer */
7
7
 
8
- /** @typedef {'NEEDLE_deformation_rig' | 'NEEDLE_mesh_impostor' | 'NEEDLE_pixel_impostor' | 'NEEDLE_hull_effect'} NeedleExtension */
8
+ /** @typedef {'NEEDLE_deformation_rig' | 'NEEDLE_mesh_impostor' | 'NEEDLE_pixel_impostor' | 'NEEDLE_hull_effect' | 'NEEDLE_box_impostor'} NeedleExtension */
9
9
  /** @typedef {{disable?: readonly NeedleExtension[]}} LoaderOptions */
10
10
 
11
11
  /** @type {WeakMap<GLTFLoader, {renderer: Renderer, disabled: Set<NeedleExtension>}>} */
@@ -69,5 +69,9 @@ export function useLoader(loader, renderer, options = {}) {
69
69
  const { NeedleHullEffectLoaderPlugin } = await import('@needle-tools/three-mesh-effects/hull-effects');
70
70
  await new NeedleHullEffectLoaderPlugin(parser).afterRoot(result);
71
71
  });
72
+ register('NEEDLE_box_impostor', async (parser, result, renderer) => {
73
+ const { NeedleBoxImpostorLoaderPlugin } = await import('@needle-tools/three-mesh-effects/box-impostor-runtime');
74
+ await new NeedleBoxImpostorLoaderPlugin(parser, { renderer }).afterRoot(result);
75
+ });
72
76
  return loader;
73
77
  }