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

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 (113) hide show
  1. package/CHANGELOG.md +34 -8
  2. package/README.md +86 -3
  3. package/SKILL.md +14 -4
  4. package/build/box-impostor-runtime.js +1423 -0
  5. package/build/box-impostor-runtime.js.map +7 -0
  6. package/build/deformation-runtime.js +30 -19
  7. package/build/deformation-runtime.js.map +3 -3
  8. package/build/hull-effects.js +60 -28
  9. package/build/hull-effects.js.map +3 -3
  10. package/build/impostor-runtime.js +264 -133
  11. package/build/impostor-runtime.js.map +4 -4
  12. package/build/index.js +8 -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 +1102 -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 +1056 -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 +276 -0
  29. package/build/internal/box-impostor/box-impostor-projection.js.map +7 -0
  30. package/build/internal/box-impostor/box-impostor-runtime.js +1369 -0
  31. package/build/internal/box-impostor/box-impostor-runtime.js.map +7 -0
  32. package/build/internal/box-impostor/box-impostor-surface-search.js +21 -0
  33. package/build/internal/box-impostor/box-impostor-surface-search.js.map +7 -0
  34. package/build/internal/deformation/cloth-surface.js +23 -17
  35. package/build/internal/deformation/cloth-surface.js.map +3 -3
  36. package/build/internal/deformation/pin-cloth.js +7 -2
  37. package/build/internal/deformation/pin-cloth.js.map +2 -2
  38. package/build/internal/deformation/rig-runtime.js +30 -19
  39. package/build/internal/deformation/rig-runtime.js.map +3 -3
  40. package/build/internal/impostor/impostor-node-material.js +264 -133
  41. package/build/internal/impostor/impostor-node-material.js.map +4 -4
  42. package/build/internal/pixel-impostor/pixel-impostor-display.js +84 -38
  43. package/build/internal/pixel-impostor/pixel-impostor-display.js.map +4 -4
  44. package/build/internal/rendering/captured-surface-depth.js +35 -0
  45. package/build/internal/rendering/captured-surface-depth.js.map +7 -0
  46. package/build/internal/rendering/captured-surface-material.js +28 -0
  47. package/build/internal/rendering/captured-surface-material.js.map +7 -0
  48. package/build/internal/rendering/hull-effect-runtime.js +59 -27
  49. package/build/internal/rendering/hull-effect-runtime.js.map +3 -3
  50. package/build/internal/rendering/renderer-support.js +31 -0
  51. package/build/internal/rendering/renderer-support.js.map +7 -0
  52. package/build/internal/rendering/wireframe.js +41 -9
  53. package/build/internal/rendering/wireframe.js.map +2 -2
  54. package/build/internal/rendering/wrap-preview.js +59 -27
  55. package/build/internal/rendering/wrap-preview.js.map +3 -3
  56. package/build/pixel-impostor-runtime.js +84 -38
  57. package/build/pixel-impostor-runtime.js.map +4 -4
  58. package/build/types/box-impostor/box-impostor-display-settings.d.ts +30 -0
  59. package/build/types/box-impostor/box-impostor-display-settings.js +1 -0
  60. package/build/types/box-impostor/box-impostor-display.d.ts +13 -0
  61. package/build/types/box-impostor/box-impostor-display.js +1 -0
  62. package/build/types/box-impostor/box-impostor-face-axes.d.ts +5 -0
  63. package/build/types/box-impostor/box-impostor-face-axes.js +1 -0
  64. package/build/types/box-impostor/box-impostor-faces.d.ts +11 -0
  65. package/build/types/box-impostor/box-impostor-faces.js +1 -0
  66. package/build/types/box-impostor/box-impostor-geometry.d.ts +5 -0
  67. package/build/types/box-impostor/box-impostor-geometry.js +1 -0
  68. package/build/types/box-impostor/box-impostor-material.d.ts +14 -0
  69. package/build/types/box-impostor/box-impostor-material.js +1 -0
  70. package/build/types/box-impostor/box-impostor-metadata.d.ts +31 -0
  71. package/build/types/box-impostor/box-impostor-metadata.js +1 -0
  72. package/build/types/box-impostor/box-impostor-projection.d.ts +19 -0
  73. package/build/types/box-impostor/box-impostor-projection.js +1 -0
  74. package/build/types/box-impostor/box-impostor-runtime.d.ts +19 -0
  75. package/build/types/box-impostor/box-impostor-runtime.js +1 -0
  76. package/build/types/box-impostor/box-impostor-surface-search.d.ts +13 -0
  77. package/build/types/box-impostor/box-impostor-surface-search.js +1 -0
  78. package/build/types/deformation/cloth-surface.d.ts +1 -0
  79. package/build/types/deformation/pin-cloth.d.ts +1 -0
  80. package/build/types/impostor/impostor-node-material.d.ts +2 -15
  81. package/build/types/public/box-impostor-runtime.d.ts +6 -0
  82. package/build/types/public/box-impostor-runtime.js +1 -0
  83. package/build/types/public/hull-effects.d.ts +1 -0
  84. package/build/types/public/index.d.ts +1 -1
  85. package/build/types/rendering/captured-surface-depth.d.ts +5 -0
  86. package/build/types/rendering/captured-surface-depth.js +1 -0
  87. package/build/types/rendering/captured-surface-material.d.ts +8 -0
  88. package/build/types/rendering/captured-surface-material.js +1 -0
  89. package/build/types/rendering/renderer-support.d.ts +27 -0
  90. package/build/types/rendering/renderer-support.js +1 -0
  91. package/build/types/rendering/wireframe.d.ts +2 -2
  92. package/package.json +29 -8
  93. package/src/box-impostor/box-impostor-display-settings.js +54 -0
  94. package/src/box-impostor/box-impostor-display.js +50 -0
  95. package/src/box-impostor/box-impostor-face-axes.js +11 -0
  96. package/src/box-impostor/box-impostor-faces.js +118 -0
  97. package/src/box-impostor/box-impostor-geometry.js +140 -0
  98. package/src/box-impostor/box-impostor-material.js +771 -0
  99. package/src/box-impostor/box-impostor-metadata.js +122 -0
  100. package/src/box-impostor/box-impostor-projection.js +276 -0
  101. package/src/box-impostor/box-impostor-runtime.js +124 -0
  102. package/src/box-impostor/box-impostor-surface-search.js +11 -0
  103. package/src/deformation/cloth-surface.ts +28 -17
  104. package/src/deformation/pin-cloth.ts +9 -3
  105. package/src/impostor/impostor-node-material.js +188 -157
  106. package/src/pixel-impostor/pixel-impostor-display.js +5 -13
  107. package/src/public/box-impostor-runtime.js +14 -0
  108. package/src/public/hull-effects.js +1 -0
  109. package/src/public/index.js +10 -1
  110. package/src/rendering/captured-surface-depth.js +55 -0
  111. package/src/rendering/captured-surface-material.js +27 -0
  112. package/src/rendering/renderer-support.js +50 -0
  113. package/src/rendering/wireframe.js +51 -13
@@ -4,6 +4,11 @@
4
4
  // their declared member layout.
5
5
  // @ts-nocheck
6
6
 
7
+ import { enableRendererNodeMaterials, rendererSupportsImpostorNodeMaterials } from '../rendering/renderer-support.js';
8
+ export { rendererSupportsImpostorNodeMaterials } from '../rendering/renderer-support.js';
9
+
10
+ import { CapturedSurfaceMaterial } from '../rendering/captured-surface-material.js';
11
+ import { capturedSurfaceDepth } from '../rendering/captured-surface-depth.js';
7
12
  import {
8
13
  ClampToEdgeWrapping,
9
14
  DoubleSide,
@@ -22,11 +27,10 @@ import {
22
27
  Fn,
23
28
  If,
24
29
  Loop,
30
+ Break,
25
31
  abs,
26
32
  any,
27
33
  bool,
28
- cameraFar,
29
- cameraNear,
30
34
  cameraPosition,
31
35
  cameraWorldMatrix,
32
36
  cross,
@@ -41,7 +45,6 @@ import {
41
45
  max,
42
46
  min,
43
47
  mix,
44
- modelViewMatrix,
45
48
  modelWorldMatrix,
46
49
  modelWorldMatrixInverse,
47
50
  positionGeometry,
@@ -54,8 +57,6 @@ import {
54
57
  vec2,
55
58
  vec3,
56
59
  vec4,
57
- viewZToOrthographicDepth,
58
- viewZToPerspectiveDepth,
59
60
  } from 'three/tsl';
60
61
  import { NEEDLE_MESH_IMPOSTOR } from './impostor-metadata.js';
61
62
  import { bindTextureSlot } from '../rendering/texture-slot.js';
@@ -72,13 +73,7 @@ const NAMED_STRUCT_FACTORY = Reflect.get(TSL, 'struct');
72
73
 
73
74
  /** @import { ImpostorDescriptor } from './impostor-metadata.js' */
74
75
 
75
- /**
76
- * @typedef {object} ImpostorRenderer
77
- * @property {boolean=} isWebGPURenderer
78
- * @property {boolean=} isWebGLRenderer
79
- * @property {(object & {supportsNodeMaterials?: boolean})=} capabilities
80
- */
81
-
76
+ /** @typedef {import('../rendering/renderer-support.js').ImpostorRenderer} ImpostorRenderer */
82
77
  /**
83
78
  * @typedef {object} ImpostorRuntimeFeatures
84
79
  * @property {boolean} interpolation
@@ -125,18 +120,6 @@ export const IMPOSTOR_RUNTIME_SAMPLE_LIMITS = Object.freeze({
125
120
  const IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS = 0.002;
126
121
  const HEMISPHERE_HORIZON_TRANSITION_SINE = Math.sin(Math.PI / 180);
127
122
 
128
- /**
129
- * Reports whether a renderer can compile Baker's TSL impostor material.
130
- * WebGPURenderer supports node materials directly. Classic WebGLRenderer
131
- * integrations must advertise that they installed a compatible nodes handler.
132
- *
133
- * @param {ImpostorRenderer | undefined} renderer
134
- */
135
- export function rendererSupportsImpostorNodeMaterials(renderer) {
136
- if (typeof NAMED_STRUCT_FACTORY !== 'function') return false;
137
- return renderer?.isWebGPURenderer === true
138
- || renderer?.capabilities?.supportsNodeMaterials === true;
139
- }
140
123
 
141
124
  /**
142
125
  * @param {ImpostorDescriptor} descriptor
@@ -374,6 +357,7 @@ export class NeedleImpostorLoaderPlugin {
374
357
 
375
358
  /** @param {import('three/addons/loaders/GLTFLoader.js').GLTF} result */
376
359
  async afterRoot(result) {
360
+ await enableRendererNodeMaterials(this.options.renderer);
377
361
  const parser = /** @type {{
378
362
  * json: {meshes?: Array<{primitives: Array<{extensions?: Record<string, unknown>}>}>},
379
363
  * associations: Map<import('three').Object3D, {meshes?: number, primitives?: number}>,
@@ -984,83 +968,186 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
984
968
  const rootFound = bool(false).toVar();
985
969
  const rootLower = float(0).toVar();
986
970
  const rootUpper = float(1).toVar();
987
- const previousHasSurface = bool(false).toVar();
988
- const previousSearchDepth = float(0).toVar();
989
- const previousSurfaceDepth = float(1).toVar();
990
- const coarseStep = float(1).div(coarseSearchSteps);
991
- Loop(coarseSearchSteps, ({ i }) => {
992
- const searchDepth = float(i).add(1).mul(coarseStep);
993
- const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));
994
- const searchRayPosition = planePosition.add(rayDirection.mul(
995
- searchPlaneDepth.sub(dot(planePosition, frameDirection))
996
- .div(safeRayPlaneDenominator),
997
- ));
998
- const searchUv = vec2(
999
- dot(searchRayPosition, right),
1000
- dot(searchRayPosition, up),
1001
- ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
1002
- const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv)))
1003
- .or(any(searchUv.greaterThan(vec2(maximumFrameUv))));
1004
- If(searchOutOfBounds, () => {
1005
- previousHasSurface.assign(false);
971
+ // Empty billboard pixels must not traverse the whole capture volume.
972
+ // The source AABB is conservative, with one texel for filtered edges.
973
+ const safeRay = vec3(
974
+ nonZeroSign(rayDirection.x),
975
+ nonZeroSign(rayDirection.y),
976
+ nonZeroSign(rayDirection.z),
977
+ ).mul(max(abs(rayDirection), vec3(1e-7)));
978
+ const boundsGuard = radius.mul(2).div(interiorResolution);
979
+ const boxT0 = vec3(...descriptor.boundsMin).sub(boundsGuard)
980
+ .sub(planePosition).div(safeRay);
981
+ const boxT1 = vec3(...descriptor.boundsMax).add(boundsGuard)
982
+ .sub(planePosition).div(safeRay);
983
+ const boxLow = min(boxT0, boxT1), boxHigh = max(boxT0, boxT1);
984
+ const boxStart = max(boxLow.x, max(boxLow.y, boxLow.z));
985
+ const boxEnd = min(boxHigh.x, min(boxHigh.y, boxHigh.z));
986
+ const intersectsBounds = boxStart.lessThanEqual(boxEnd);
987
+ const captureDepthAt = (t) => radius.sub(
988
+ dot(planePosition.add(rayDirection.mul(t)), frameDirection),
989
+ ).div(radius.mul(2));
990
+ const depth0 = captureDepthAt(boxStart), depth1 = captureDepthAt(boxEnd);
991
+ // UV is affine in capture depth. Clipping to the capture crop spends
992
+ // the existing march budget on possible surfaces instead of empty space.
993
+ const uvDepthSlope = vec2(dot(rayDirection, right), dot(rayDirection, up))
994
+ .mul(radius.mul(-2).div(safeRayPlaneDenominator))
995
+ .div(bounds.zw.sub(bounds.xy));
996
+ const safeSlope = vec2(
997
+ nonZeroSign(uvDepthSlope.x), nonZeroSign(uvDepthSlope.y),
998
+ ).mul(max(abs(uvDepthSlope), vec2(1e-7)));
999
+ const uvStart = projectedFrameUv.sub(uvDepthSlope.mul(0.5));
1000
+ const t0 = vec2(minimumFrameUv).sub(uvStart).div(safeSlope);
1001
+ const t1 = vec2(maximumFrameUv).sub(uvStart).div(safeSlope);
1002
+ const lower = min(t0, t1), upper = max(t0, t1);
1003
+ const searchStart = max(min(depth0, depth1), max(0, max(lower.x, lower.y)));
1004
+ const searchEnd = min(max(depth0, depth1), min(1, min(upper.x, upper.y)));
1005
+ const searchRange = max(searchEnd.sub(searchStart), 1e-6);
1006
+ const coarseStep = searchRange.div(coarseSearchSteps);
1007
+ const validateRoot = () => {
1008
+ If(rootSolved, () => {
1009
+ const at = atlasUv(frame, frameUv);
1010
+ const surface = reconstructPosition(frameUv, bounds, frameDirection, right, up, sampleDepth16(at));
1011
+ const closest = planePosition.add(rayDirection.mul(dot(surface.sub(planePosition), rayDirection)));
1012
+ const footprint = max(bounds.z.sub(bounds.x), bounds.w.sub(bounds.y)).div(interiorResolution);
1013
+ const nearestPixel = floor(at.mul(atlasResolution));
1014
+ const nearestDepth = loadDepth16(nearestPixel);
1015
+ const depthJump = abs(sampleDepth16(at).sub(nearestDepth)).mul(radius).mul(2);
1016
+ const discontinuity = bool(false).toVar();
1017
+ If(depthJump.greaterThan(footprint.mul(4)), () => {
1018
+ const neighbor = (offset) => loadDepth16(nearestPixel.add(offset).clamp(
1019
+ frame.mul(frameResolution), frame.add(1).mul(frameResolution).sub(1),
1020
+ ));
1021
+ // A steep plane can change depth arbitrarily fast. Unlike a slope
1022
+ // cap, second differences reject interpolated depth steps without
1023
+ // rejecting a continuous plane merely because it is steep.
1024
+ const curvature = max(
1025
+ abs(neighbor(vec2(-1, 0)).add(neighbor(vec2(1, 0))).sub(nearestDepth.mul(2))),
1026
+ abs(neighbor(vec2(0, -1)).add(neighbor(vec2(0, 1))).sub(nearestDepth.mul(2))),
1027
+ ).mul(radius).mul(2);
1028
+ discontinuity.assign(curvature.greaterThan(footprint.mul(4)));
1029
+ });
1030
+ If(surface.sub(closest).length().greaterThan(footprint.mul(4))
1031
+ .or(discontinuity)
1032
+ .or(sampleCapturedAlpha(at).lessThan(reprojectionSurfaceCutoff)), () => {
1033
+ rootFound.assign(false);
1034
+ rootSolved.assign(false);
1035
+ strictRootSolved.assign(false);
1036
+ });
1006
1037
  });
1007
- If(searchOutOfBounds.not(), () => {
1008
- const searchAtlasUv = atlasUv(frame, searchUv);
1009
- const searchCoverage = sampleCapturedAlpha(searchAtlasUv);
1010
- const searchSurfaceDepth = sampleDepth16(searchAtlasUv);
1011
- // Only captured coverage represents geometry. The transition SDF
1012
- // deliberately extends outside the silhouette; accepting it as a
1013
- // ray hit turns that band into repeated depth shells and streaks.
1014
- const hasSurface = searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff);
1015
- const depthDelta = searchDepth.sub(searchSurfaceDepth);
1016
- const crossesDepth = previousHasSurface
1017
- .and(previousSearchDepth.lessThan(previousSurfaceDepth))
1018
- .and(depthDelta.greaterThanEqual(0));
1019
- const continuousDepthStep = abs(searchSurfaceDepth.sub(previousSurfaceDepth))
1020
- .lessThanEqual(coarseStep.mul(2));
1021
- const crossesCoveredSurface = crossesDepth.and(continuousDepthStep);
1022
- // A thin captured feature can occupy less than one coarse ray step,
1023
- // so its first covered sample may already lie just behind the stored
1024
- // surface. Only accept that entry when the root is inside the
1025
- // immediately preceding march interval. A late silhouette entry is
1026
- // not a height-field crossing and must not become a second layer.
1027
- const entersAtSurface = previousHasSurface.not()
1028
- .and(depthDelta.greaterThanEqual(0))
1029
- .and(depthDelta.lessThanEqual(coarseStep.mul(1.15)));
1030
- const boundedRoot = crossesCoveredSurface.or(entersAtSurface);
1031
- If(
1032
- rootFound.not()
1033
- .and(hasSurface)
1034
- .and(features.boundedReprojection
1035
- ? boundedRoot
1036
- : depthDelta.greaterThanEqual(0)),
1037
- () => {
1038
- rootLower.assign(max(searchDepth.sub(coarseStep), 0));
1038
+ };
1039
+ const refineRoot = () => {
1040
+ If(rootFound, () => {
1041
+ Loop(profile.depthSamples, () => {
1042
+ const searchDepth = rootLower.add(rootUpper).mul(0.5);
1043
+ const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));
1044
+ const searchRayPosition = planePosition.add(rayDirection.mul(
1045
+ searchPlaneDepth.sub(dot(planePosition, frameDirection))
1046
+ .div(safeRayPlaneDenominator),
1047
+ ));
1048
+ const searchUv = vec2(
1049
+ dot(searchRayPosition, right),
1050
+ dot(searchRayPosition, up),
1051
+ ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
1052
+ const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv)))
1053
+ .or(any(searchUv.greaterThan(vec2(maximumFrameUv))));
1054
+ const midpointIsUpper = bool(false).toVar();
1055
+ If(searchOutOfBounds.not(), () => {
1056
+ const searchAtlasUv = atlasUv(frame, searchUv);
1057
+ const searchCoverage = sampleCapturedAlpha(searchAtlasUv);
1058
+ const searchSurfaceDepth = sampleDepth16(searchAtlasUv);
1059
+ midpointIsUpper.assign(
1060
+ searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff)
1061
+ .and(searchDepth.greaterThanEqual(searchSurfaceDepth)),
1062
+ );
1063
+ });
1064
+ If(midpointIsUpper, () => {
1039
1065
  rootUpper.assign(searchDepth);
1040
- rootFound.assign(true);
1041
- rootSolved.assign(true);
1042
- strictRootSolved.assign(true);
1043
- },
1044
- );
1045
- If(rootFound.not().and(hasSurface), () => {
1046
- previousHasSurface.assign(true);
1047
- previousSearchDepth.assign(searchDepth);
1048
- previousSurfaceDepth.assign(searchSurfaceDepth);
1066
+ });
1067
+ If(midpointIsUpper.not(), () => {
1068
+ rootLower.assign(searchDepth);
1069
+ });
1049
1070
  });
1050
- If(hasSurface.not(), () => {
1051
- previousHasSurface.assign(false);
1071
+ const residualAt = (depth) => {
1072
+ const planeDepth = radius.sub(depth.mul(radius).mul(2));
1073
+ const position = planePosition.add(rayDirection.mul(
1074
+ planeDepth.sub(dot(planePosition, frameDirection)).div(safeRayPlaneDenominator),
1075
+ ));
1076
+ const address = vec2(dot(position, right), dot(position, up))
1077
+ .sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
1078
+ return depth.sub(sampleDepth16(atlasUv(frame,address)));
1079
+ };
1080
+ // A midpoint leaves large physical errors on a steep height field.
1081
+ // Secant interpolation is exact for a plane and stays in the bracket.
1082
+ const lowResidual = residualAt(rootLower), highResidual = residualAt(rootUpper);
1083
+ const difference = lowResidual.sub(highResidual);
1084
+ const fraction = lowResidual.div(
1085
+ nonZeroSign(difference).mul(max(abs(difference), 1e-8)),
1086
+ ).clamp(0, 1);
1087
+ const rootDepth = mix(rootLower,rootUpper,fraction);
1088
+
1089
+ const rootPlaneDepth = radius.sub(rootDepth.mul(radius).mul(2));
1090
+ const rootRayPosition = planePosition.add(rayDirection.mul(
1091
+ rootPlaneDepth.sub(dot(planePosition, frameDirection))
1092
+ .div(safeRayPlaneDenominator),
1093
+ ));
1094
+ frameUv.assign(vec2(
1095
+ dot(rootRayPosition, right),
1096
+ dot(rootRayPosition, up),
1097
+ ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy)).clamp(
1098
+ minimumFrameUv,
1099
+ maximumFrameUv,
1100
+ ));
1101
+ });
1102
+ };
1103
+ const traceInterval = (steps, start = searchStart, end = searchEnd) => {
1104
+ const coarseStep = max(end.sub(start), 1e-6).div(float(steps));
1105
+ Loop({ start: 0, end: steps, type: 'int' }, ({ i }) => {
1106
+ If(rootFound.or(intersectsBounds.not()).or(end.lessThan(start)), () => { Break(); });
1107
+ const searchDepth = start.add(float(i).add(1).mul(coarseStep));
1108
+ const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));
1109
+ const searchRayPosition = planePosition.add(rayDirection.mul(
1110
+ searchPlaneDepth.sub(dot(planePosition, frameDirection))
1111
+ .div(safeRayPlaneDenominator),
1112
+ ));
1113
+ const searchUv = vec2(
1114
+ dot(searchRayPosition, right),
1115
+ dot(searchRayPosition, up),
1116
+ ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
1117
+ const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv)))
1118
+ .or(any(searchUv.greaterThan(vec2(maximumFrameUv))));
1119
+ If(searchOutOfBounds.not(), () => {
1120
+ const searchAtlasUv = atlasUv(frame, searchUv);
1121
+ const searchCoverage = sampleCapturedAlpha(searchAtlasUv);
1122
+ const hasSurface = searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff);
1123
+ If(hasSurface, () => {
1124
+ const searchSurfaceDepth = sampleDepth16(searchAtlasUv);
1125
+ const depthDelta = searchDepth.sub(searchSurfaceDepth);
1126
+ If(
1127
+ rootFound.not()
1128
+ .and(hasSurface)
1129
+ .and(depthDelta.greaterThanEqual(0)),
1130
+ () => {
1131
+ rootLower.assign(max(searchDepth.sub(coarseStep), 0));
1132
+ rootUpper.assign(searchDepth);
1133
+ rootFound.assign(true);
1134
+ rootSolved.assign(true);
1135
+ strictRootSolved.assign(true);
1136
+ refineRoot();
1137
+ if (features.boundedReprojection) validateRoot();
1138
+ },
1139
+ );
1140
+ });
1052
1141
  });
1053
1142
  });
1054
- });
1055
- // The bounded march deliberately rejects height-field discontinuities.
1056
- // Near a dense capture direction, a valid surface can still be too steep
1057
- // to form a coarse bracket. Use the center-plane depth only as a seed for
1058
- // a fixed-point solve, and accept it solely after the projected UV/depth
1059
- // pair converges inside captured coverage. Unlike the removed planar
1060
- // fallback, this path produces a point on the runtime camera ray and
1061
- // never contributes an unconverged card layer.
1062
- If(rootFound.not(), () => {
1063
- const iterativeUv = frameUv.toVar();
1143
+ };
1144
+ traceInterval(int(coarseSearchSteps));
1145
+ // A fixed-point solution can recover a grazing ray with no sign bracket.
1146
+ // Retain it only after convergence inside captured coverage; blend-time
1147
+ // seed suppression still prevents an unrelated background layer.
1148
+ If(rootFound.not().and(intersectsBounds), () => {
1149
+ // A rejected march root must not seed itself back into validity.
1150
+ const iterativeUv = projectedFrameUv.clamp(minimumFrameUv, maximumFrameUv).toVar();
1064
1151
  const iterativeDepth = sampleDepth16(atlasUv(frame, iterativeUv)).toVar();
1065
1152
  const iterationResidual = float(1).toVar();
1066
1153
  const iterationValid = bool(true).toVar();
@@ -1098,54 +1185,10 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1098
1185
  () => {
1099
1186
  frameUv.assign(iterativeUv);
1100
1187
  rootSolved.assign(true);
1188
+ if (features.boundedReprojection) validateRoot();
1101
1189
  },
1102
1190
  );
1103
1191
  });
1104
- If(rootFound, () => {
1105
- Loop(profile.depthSamples, () => {
1106
- const searchDepth = rootLower.add(rootUpper).mul(0.5);
1107
- const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));
1108
- const searchRayPosition = planePosition.add(rayDirection.mul(
1109
- searchPlaneDepth.sub(dot(planePosition, frameDirection))
1110
- .div(safeRayPlaneDenominator),
1111
- ));
1112
- const searchUv = vec2(
1113
- dot(searchRayPosition, right),
1114
- dot(searchRayPosition, up),
1115
- ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
1116
- const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv)))
1117
- .or(any(searchUv.greaterThan(vec2(maximumFrameUv))));
1118
- const midpointIsUpper = bool(false).toVar();
1119
- If(searchOutOfBounds.not(), () => {
1120
- const searchAtlasUv = atlasUv(frame, searchUv);
1121
- const searchCoverage = sampleCapturedAlpha(searchAtlasUv);
1122
- const searchSurfaceDepth = sampleDepth16(searchAtlasUv);
1123
- midpointIsUpper.assign(
1124
- searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff)
1125
- .and(searchDepth.greaterThanEqual(searchSurfaceDepth)),
1126
- );
1127
- });
1128
- If(midpointIsUpper, () => {
1129
- rootUpper.assign(searchDepth);
1130
- });
1131
- If(midpointIsUpper.not(), () => {
1132
- rootLower.assign(searchDepth);
1133
- });
1134
- });
1135
- const rootDepth = rootLower.add(rootUpper).mul(0.5);
1136
- const rootPlaneDepth = radius.sub(rootDepth.mul(radius).mul(2));
1137
- const rootRayPosition = planePosition.add(rayDirection.mul(
1138
- rootPlaneDepth.sub(dot(planePosition, frameDirection))
1139
- .div(safeRayPlaneDenominator),
1140
- ));
1141
- frameUv.assign(vec2(
1142
- dot(rootRayPosition, right),
1143
- dot(rootRayPosition, up),
1144
- ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy)).clamp(
1145
- minimumFrameUv,
1146
- maximumFrameUv,
1147
- ));
1148
- });
1149
1192
  }
1150
1193
  const uvNode = atlasUv(frame, frameUv);
1151
1194
  reconstructed.assign(reconstructPosition(
@@ -1526,21 +1569,7 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1526
1569
 
1527
1570
  const sample = blendImpostor().toVar('impostorSample');
1528
1571
  const reconstructedWorldPosition = modelWorldMatrix.mul(vec4(blendedMember(sample, 'positionLocal'), 1)).xyz;
1529
- const reconstructedDepth = Fn(([localPosition], builder) => {
1530
- const viewZ = modelViewMatrix.mul(vec4(localPosition, 1)).z;
1531
- const resolvedDepth = builder.camera.isPerspectiveCamera
1532
- ? viewZToPerspectiveDepth(viewZ, cameraNear, cameraFar)
1533
- : viewZToOrthographicDepth(viewZ, cameraNear, cameraFar);
1534
- // The light and view cameras reconstruct the surface from different atlas
1535
- // cells. Offset only the shadow-map writer so tiny cross-view depth
1536
- // disagreement cannot make an impostor shadow itself. Main-camera depth is
1537
- // left exact for intersections with surrounding geometry.
1538
- return builder.material.isShadowPassMaterial
1539
- ? min(1, resolvedDepth.add(IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS))
1540
- : resolvedDepth;
1541
- }, 'float');
1542
-
1543
- const material = new MeshStandardNodeMaterial({
1572
+ const material = new CapturedSurfaceMaterial({
1544
1573
  name: 'Needle PBR impostor TSL',
1545
1574
  side: DoubleSide,
1546
1575
  transparent: false,
@@ -1583,7 +1612,9 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1583
1612
  );
1584
1613
  material.maskShadowNode = distanceCoverage.mul(mappingVisibility).greaterThanEqual(0.5);
1585
1614
  material.alphaToCoverage = true;
1586
- material.depthNode = reconstructedDepth(blendedMember(sample, 'positionLocal'));
1615
+ material.capturedPositionNode = blendedMember(sample, 'positionLocal');
1616
+ // Offset only the shadow writer: different capture views can disagree slightly.
1617
+ material.depthNode = capturedSurfaceDepth(material.capturedPositionNode, IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS);
1587
1618
  material.receivedShadowPositionNode = reconstructedWorldPosition;
1588
1619
  material.toneMapped = true;
1589
1620
  material.userData.impostorShaderProfile = profile;
@@ -1,4 +1,6 @@
1
1
  // @ts-check
2
+ import { CapturedSurfaceMaterial } from '../rendering/captured-surface-material.js';
3
+ import { capturedSurfaceDepth } from '../rendering/captured-surface-depth.js';
2
4
  import * as THREE from 'three';
3
5
  import { MeshBasicNodeMaterial, MeshStandardNodeMaterial } from 'three/webgpu';
4
6
  import {
@@ -10,8 +12,6 @@ import {
10
12
  attribute,
11
13
  cameraProjectionMatrix,
12
14
  cameraProjectionMatrixInverse,
13
- cameraFar,
14
- cameraNear,
15
15
  cameraPosition,
16
16
  cameraWorldMatrix,
17
17
  ceil,
@@ -45,8 +45,6 @@ import {
45
45
  vec3,
46
46
  vec4,
47
47
  vertexColor,
48
- viewZToOrthographicDepth,
49
- viewZToPerspectiveDepth,
50
48
  } from 'three/tsl';
51
49
 
52
50
  /**
@@ -255,13 +253,6 @@ export function createPixelImpostorRaycastPreview(asset, bounds, descriptor) {
255
253
  const traceVolume = /** @type {(sampleOffset: import('three/webgpu').Node<'vec2'>) => import('three/webgpu').Node<'vec4'>} */ (
256
254
  /** @type {unknown} */ (traceVolumeNode)
257
255
  );
258
- // @ts-ignore -- TSL's Fn declaration erases tuple and builder member types.
259
- const reconstructedDepth = Fn(([localPosition], builder) => {
260
- const viewZ = modelViewMatrix.mul(vec4(localPosition, 1)).z;
261
- return builder.camera.isPerspectiveCamera
262
- ? viewZToPerspectiveDepth(viewZ, cameraNear, cameraFar)
263
- : viewZToOrthographicDepth(viewZ, cameraNear, cameraFar);
264
- }, 'float');
265
256
  const createRaycastMaterial = (
266
257
  /** @type {boolean} */ antialias,
267
258
  /** @type {boolean} */ pbr,
@@ -350,7 +341,7 @@ export function createPixelImpostorRaycastPreview(asset, bounds, descriptor) {
350
341
  .select(bakedNormal.negate(), bakedNormal);
351
342
  const shadingNormal = mix(geometricNormal, projectedNormal, projectedNormalMix).normalize();
352
343
  const materialName = `Pixel impostor · volume raycast · ${antialias ? 'AA' : 'fast'} · ${pbr ? 'PBR maps' : 'plain lit'}`;
353
- const material = new MeshStandardNodeMaterial({
344
+ const material = new CapturedSurfaceMaterial({
354
345
  name: materialName,
355
346
  side: THREE.FrontSide,
356
347
  depthTest: true,
@@ -371,7 +362,8 @@ export function createPixelImpostorRaycastPreview(asset, bounds, descriptor) {
371
362
  );
372
363
  material.maskShadowNode = antialias ? coverage.greaterThanEqual(0.5) : occupied;
373
364
  material.alphaToCoverage = antialias;
374
- material.depthNode = reconstructedDepth(hitPosition);
365
+ material.capturedPositionNode = hitPosition;
366
+ material.depthNode = capturedSurfaceDepth(hitPosition);
375
367
  material.toneMapped = true;
376
368
  material.userData.screenPixelSize = screenPixelSize;
377
369
  material.userData.pixelImpostorRaycastAntialias = antialias;
@@ -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>}>} */
@@ -48,6 +48,11 @@ export function useLoader(loader, renderer, options = {}) {
48
48
  if (json.extensionsRequired?.includes(name)) throw new Error(`Required glTF extension ${name} is disabled in useLoader.`);
49
49
  return;
50
50
  }
51
+ if (renderer?.isWebGLRenderer && renderer.setNodesHandler &&
52
+ !renderer.capabilities?.supportsNodeMaterials) {
53
+ const {enableRendererNodeMaterials} = await import('@needle-tools/three-mesh-effects/internal/rendering/renderer-support');
54
+ await enableRendererNodeMaterials(renderer);
55
+ }
51
56
  await apply(parser, result, renderer);
52
57
  },
53
58
  };
@@ -69,5 +74,9 @@ export function useLoader(loader, renderer, options = {}) {
69
74
  const { NeedleHullEffectLoaderPlugin } = await import('@needle-tools/three-mesh-effects/hull-effects');
70
75
  await new NeedleHullEffectLoaderPlugin(parser).afterRoot(result);
71
76
  });
77
+ register('NEEDLE_box_impostor', async (parser, result, renderer) => {
78
+ const { NeedleBoxImpostorLoaderPlugin } = await import('@needle-tools/three-mesh-effects/box-impostor-runtime');
79
+ await new NeedleBoxImpostorLoaderPlugin(parser, { renderer }).afterRoot(result);
80
+ });
72
81
  return loader;
73
82
  }
@@ -0,0 +1,55 @@
1
+ // @ts-check
2
+ import {
3
+ Fn,
4
+ cameraFar,
5
+ cameraNear,
6
+ cameraProjectionMatrix,
7
+ modelViewMatrix,
8
+ vec4,
9
+ viewZToLogarithmicDepth,
10
+ viewZToOrthographicDepth,
11
+ viewZToPerspectiveDepth,
12
+ viewZToReversedOrthographicDepth,
13
+ viewZToReversedPerspectiveDepth,
14
+ } from 'three/tsl';
15
+
16
+ /** Match the renderer's depth convention after reconstructing a local hit.
17
+ * @param {import('three/webgpu').Node<'vec3'>} position
18
+ * @param {number} [shadowBias]
19
+ */
20
+ export function capturedSurfaceDepth(position, shadowBias = 0) {
21
+ return Fn(
22
+ (
23
+ /** @type {unknown} */ _,
24
+ /** @type {import('three/webgpu').NodeBuilder} */ builder,
25
+ ) => {
26
+ // Resolve the shared hit before either projection branch consumes it.
27
+ const z = modelViewMatrix
28
+ .mul(vec4(position, 1))
29
+ .z.toVar('capturedSurfaceViewZ');
30
+ const reversed = builder.renderer.reversedDepthBuffer === true;
31
+ // One material can alternate between a perspective view and orthographic
32
+ // shadow cameras without a new pipeline; select using the active projection.
33
+ const perspective = cameraProjectionMatrix
34
+ .mul(vec4(0, 0, 0, 1))
35
+ .w.equal(0);
36
+ const perspectiveDepth =
37
+ builder.renderer.logarithmicDepthBuffer === true
38
+ ? viewZToLogarithmicDepth(z, cameraNear, cameraFar)
39
+ : (reversed
40
+ ? viewZToReversedPerspectiveDepth
41
+ : viewZToPerspectiveDepth)(z, cameraNear, cameraFar);
42
+ const result = perspective.select(
43
+ perspectiveDepth,
44
+ (reversed
45
+ ? viewZToReversedOrthographicDepth
46
+ : viewZToOrthographicDepth)(z, cameraNear, cameraFar),
47
+ );
48
+ return shadowBias &&
49
+ 'isShadowPassMaterial' in builder.material &&
50
+ builder.material.isShadowPassMaterial
51
+ ? result.add(reversed ? -shadowBias : shadowBias).clamp(0, 1)
52
+ : result;
53
+ },
54
+ )();
55
+ }
@@ -0,0 +1,27 @@
1
+ // @ts-check
2
+ import { MeshStandardNodeMaterial } from 'three/webgpu';
3
+ import { context, modelViewMatrix, modelWorldMatrix, vec4 } from 'three/tsl';
4
+
5
+ /** Light reconstructed surfaces at their hit position, not the carrier face.
6
+ * View directions stay on the same ray; local lights also need the hit distance.
7
+ */
8
+ export class CapturedSurfaceMaterial extends MeshStandardNodeMaterial {
9
+ /** @type {import('three/webgpu').Node<'vec3'> | null} */
10
+ capturedPositionNode = null;
11
+
12
+ /**
13
+ * @override
14
+ * @param {import('three/webgpu').NodeBuilder} builder
15
+ */
16
+ setupLighting(builder) {
17
+ const lighting = super.setupLighting(builder);
18
+ if (!this.capturedPositionNode) return lighting;
19
+ const world = modelWorldMatrix.mul(vec4(this.capturedPositionNode, 1)).xyz;
20
+ const view = modelViewMatrix.mul(vec4(this.capturedPositionNode, 1)).xyz;
21
+ return context(lighting, {
22
+ positionView: view,
23
+ positionWorld: world,
24
+ shadowPositionWorld: world,
25
+ });
26
+ }
27
+ }