@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
@@ -1,5 +1,83 @@
1
1
  // @ts-nocheck
2
2
 
3
+ // src/rendering/renderer-support.js
4
+ import * as TSL from "three/tsl";
5
+ function rendererSupportsImpostorNodeMaterials(renderer) {
6
+ if (typeof Reflect.get(TSL, "struct") !== "function") return false;
7
+ return renderer?.isWebGPURenderer === true || renderer?.capabilities?.supportsNodeMaterials === true;
8
+ }
9
+ var pending = /* @__PURE__ */ new WeakMap();
10
+ async function enableRendererNodeMaterials(renderer) {
11
+ if (rendererSupportsImpostorNodeMaterials(renderer) || !renderer?.isWebGLRenderer || !renderer.setNodesHandler || typeof Reflect.get(TSL, "struct") !== "function") return;
12
+ let setup = pending.get(renderer);
13
+ if (!setup) {
14
+ setup = import("three/addons/tsl/WebGLNodesHandler.js").then(({ WebGLNodesHandler }) => {
15
+ if (rendererSupportsImpostorNodeMaterials(renderer)) return;
16
+ renderer.setNodesHandler?.(new WebGLNodesHandler());
17
+ renderer.capabilities ??= {};
18
+ renderer.capabilities.supportsNodeMaterials = true;
19
+ }).catch((error) => {
20
+ pending.delete(renderer);
21
+ throw error;
22
+ });
23
+ pending.set(renderer, setup);
24
+ }
25
+ await setup;
26
+ }
27
+
28
+ // src/rendering/captured-surface-material.js
29
+ import { MeshStandardNodeMaterial } from "three/webgpu";
30
+ import { context, modelViewMatrix, modelWorldMatrix, vec4 } from "three/tsl";
31
+ var CapturedSurfaceMaterial = class extends MeshStandardNodeMaterial {
32
+ /** @type {import('three/webgpu').Node<'vec3'> | null} */
33
+ capturedPositionNode = null;
34
+ /**
35
+ * @override
36
+ * @param {import('three/webgpu').NodeBuilder} builder
37
+ */
38
+ setupLighting(builder) {
39
+ const lighting = super.setupLighting(builder);
40
+ if (!this.capturedPositionNode) return lighting;
41
+ const world = modelWorldMatrix.mul(vec4(this.capturedPositionNode, 1)).xyz;
42
+ const view = modelViewMatrix.mul(vec4(this.capturedPositionNode, 1)).xyz;
43
+ return context(lighting, {
44
+ positionView: view,
45
+ positionWorld: world,
46
+ shadowPositionWorld: world
47
+ });
48
+ }
49
+ };
50
+
51
+ // src/rendering/captured-surface-depth.js
52
+ import {
53
+ Fn,
54
+ cameraFar,
55
+ cameraNear,
56
+ cameraProjectionMatrix,
57
+ modelViewMatrix as modelViewMatrix2,
58
+ vec4 as vec42,
59
+ viewZToLogarithmicDepth,
60
+ viewZToOrthographicDepth,
61
+ viewZToPerspectiveDepth,
62
+ viewZToReversedOrthographicDepth,
63
+ viewZToReversedPerspectiveDepth
64
+ } from "three/tsl";
65
+ function capturedSurfaceDepth(position, shadowBias = 0) {
66
+ return Fn(
67
+ (_, builder) => {
68
+ const z = modelViewMatrix2.mul(vec42(position, 1)).z.toVar("capturedSurfaceViewZ");
69
+ const reversed = builder.renderer.reversedDepthBuffer === true;
70
+ const perspective = cameraProjectionMatrix.mul(vec42(0, 0, 0, 1)).w.equal(0);
71
+ const perspectiveDepth = builder.renderer.logarithmicDepthBuffer === true ? viewZToLogarithmicDepth(z, cameraNear, cameraFar) : (reversed ? viewZToReversedPerspectiveDepth : viewZToPerspectiveDepth)(z, cameraNear, cameraFar);
72
+ const result = perspective.select(
73
+ perspectiveDepth,
74
+ (reversed ? viewZToReversedOrthographicDepth : viewZToOrthographicDepth)(z, cameraNear, cameraFar)
75
+ );
76
+ return shadowBias && "isShadowPassMaterial" in builder.material && builder.material.isShadowPassMaterial ? result.add(reversed ? -shadowBias : shadowBias).clamp(0, 1) : result;
77
+ }
78
+ )();
79
+ }
80
+
3
81
  // src/impostor/impostor-node-material.js
4
82
  import {
5
83
  ClampToEdgeWrapping,
@@ -7,23 +85,22 @@ import {
7
85
  GLSL3,
8
86
  LinearFilter,
9
87
  LinearMipmapLinearFilter,
10
- MeshStandardNodeMaterial,
88
+ MeshStandardNodeMaterial as MeshStandardNodeMaterial2,
11
89
  NoColorSpace,
12
90
  SRGBColorSpace,
13
91
  ShaderMaterial,
14
92
  Vector3,
15
93
  Vector4
16
94
  } from "three/webgpu";
17
- import * as TSL from "three/tsl";
95
+ import * as TSL2 from "three/tsl";
18
96
  import {
19
- Fn,
97
+ Fn as Fn2,
20
98
  If,
21
99
  Loop,
100
+ Break,
22
101
  abs,
23
102
  any,
24
103
  bool,
25
- cameraFar,
26
- cameraNear,
27
104
  cameraPosition,
28
105
  cameraWorldMatrix,
29
106
  cross,
@@ -38,8 +115,7 @@ import {
38
115
  max,
39
116
  min,
40
117
  mix,
41
- modelViewMatrix,
42
- modelWorldMatrix,
118
+ modelWorldMatrix as modelWorldMatrix2,
43
119
  modelWorldMatrixInverse,
44
120
  positionGeometry,
45
121
  smoothstep,
@@ -50,9 +126,7 @@ import {
50
126
  uniformArray,
51
127
  vec2,
52
128
  vec3,
53
- vec4,
54
- viewZToOrthographicDepth,
55
- viewZToPerspectiveDepth
129
+ vec4 as vec43
56
130
  } from "three/tsl";
57
131
 
58
132
  // src/impostor/impostor-metadata.js
@@ -182,7 +256,7 @@ function createImpostorViewBoundsTexture(descriptor) {
182
256
  }
183
257
 
184
258
  // src/impostor/impostor-node-material.js
185
- var NAMED_STRUCT_FACTORY = Reflect.get(TSL, "struct");
259
+ var NAMED_STRUCT_FACTORY = Reflect.get(TSL2, "struct");
186
260
  var RUNTIME_FEATURE_NAMES = (
187
261
  /** @type {const} */
188
262
  [
@@ -208,10 +282,6 @@ var IMPOSTOR_RUNTIME_SAMPLE_LIMITS = Object.freeze({
208
282
  });
209
283
  var IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS = 2e-3;
210
284
  var HEMISPHERE_HORIZON_TRANSITION_SINE = Math.sin(Math.PI / 180);
211
- function rendererSupportsImpostorNodeMaterials(renderer) {
212
- if (typeof NAMED_STRUCT_FACTORY !== "function") return false;
213
- return renderer?.isWebGPURenderer === true || renderer?.capabilities?.supportsNodeMaterials === true;
214
- }
215
285
  function resolveImpostorRuntimeFeatures(descriptor, input = {}) {
216
286
  const requested = {
217
287
  ...DEFAULT_IMPOSTOR_RUNTIME_FEATURES,
@@ -405,6 +475,7 @@ var NeedleImpostorLoaderPlugin = class {
405
475
  }
406
476
  /** @param {import('three/addons/loaders/GLTFLoader.js').GLTF} result */
407
477
  async afterRoot(result) {
478
+ await enableRendererNodeMaterials(this.options.renderer);
408
479
  const parser = (
409
480
  /** @type {{
410
481
  * json: {meshes?: Array<{primitives: Array<{extensions?: Record<string, unknown>}>}>},
@@ -420,7 +491,7 @@ var NeedleImpostorLoaderPlugin = class {
420
491
  for (const root of roots) {
421
492
  if (!root || visited.has(root)) continue;
422
493
  visited.add(root);
423
- const pending = [];
494
+ const pending2 = [];
424
495
  root.traverse((object) => {
425
496
  if (!("isMesh" in object) || object.isMesh !== true) return;
426
497
  const association = parser.associations.get(object);
@@ -439,7 +510,7 @@ var NeedleImpostorLoaderPlugin = class {
439
510
  if (!rawTextures || typeof rawTextures !== "object") {
440
511
  throw new Error("NEEDLE_mesh_impostor has no texture bindings.");
441
512
  }
442
- pending.push((async () => {
513
+ pending2.push((async () => {
443
514
  const maps = (
444
515
  /** @type {Record<string, import('three').Texture>} */
445
516
  {}
@@ -462,7 +533,7 @@ var NeedleImpostorLoaderPlugin = class {
462
533
  });
463
534
  })());
464
535
  });
465
- await Promise.all(pending);
536
+ await Promise.all(pending2);
466
537
  upgraded += upgradeImpostorScene(
467
538
  root,
468
539
  bindings,
@@ -773,14 +844,14 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
773
844
  const basisMember = (value, name) => value.get(name);
774
845
  const frameMember = (value, name) => value.get(name);
775
846
  const blendedMember = (value, name) => value.get(name);
776
- const nonZeroSign = Fn(([value]) => value.lessThan(0).select(float(-1), float(1)), "float");
847
+ const nonZeroSign = Fn2(([value]) => value.lessThan(0).select(float(-1), float(1)), "float");
777
848
  const buildFrameBasis = ([direction]) => {
778
849
  const referenceUp = abs(direction.y).greaterThan(0.999).select(vec3(0, 0, -1), vec3(0, 1, 0));
779
850
  const right = referenceUp.cross(direction).normalize();
780
851
  return FrameBasis(right, direction.cross(right).normalize());
781
852
  };
782
- const frameBasis = Fn(buildFrameBasis);
783
- const gridToDirection = Fn(([coordinate]) => {
853
+ const frameBasis = Fn2(buildFrameBasis);
854
+ const gridToDirection = Fn2(([coordinate]) => {
784
855
  const hemisphere = vec3(
785
856
  coordinate.x.sub(coordinate.y),
786
857
  float(1).sub(abs(coordinate.x.sub(coordinate.y))).sub(abs(float(-1).add(coordinate.x).add(coordinate.y))),
@@ -794,7 +865,7 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
794
865
  const full = fullY.lessThan(0).select(vec3(foldedX, fullY, foldedZ), vec3(fullX, fullY, fullZ)).normalize();
795
866
  return fullSphere ? full : hemisphere;
796
867
  }, "vec3");
797
- const directionToGrid = Fn(([inputDirection]) => {
868
+ const directionToGrid = Fn2(([inputDirection]) => {
798
869
  const direction = inputDirection.normalize().toVar();
799
870
  if (!fullSphere) {
800
871
  direction.y.assign(max(direction.y, 1e-6));
@@ -808,7 +879,7 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
808
879
  const full = direction.y.lessThan(0).select(folded, direction.xz);
809
880
  return (fullSphere ? full : hemisphere).mul(0.5).add(0.5).clamp(0, 1);
810
881
  }, "vec2");
811
- const atlasUv = Fn(([frame, frameUv]) => {
882
+ const atlasUv = Fn2(([frame, frameUv]) => {
812
883
  const interiorPixels = max(frameResolution.sub(padding.mul(2)), 1);
813
884
  const interiorScale = interiorPixels.div(frameResolution);
814
885
  const gutterUv = padding.div(interiorPixels);
@@ -818,7 +889,7 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
818
889
  const halfTexel = float(0.5001).div(frameResolution);
819
890
  return frame.add(insideCell.clamp(halfTexel, float(1).sub(halfTexel))).div(frames);
820
891
  }, "vec2");
821
- const decodeDepth16 = Fn(([packed]) => {
892
+ const decodeDepth16 = Fn2(([packed]) => {
822
893
  if (descriptor.compression?.depthEncoding === "lossless-geometry10-rgba") {
823
894
  const bytes2 = floor(packed.rg.mul(255).add(0.5));
824
895
  return bytes2.x.mul(4).add(floor(bytes2.y.div(85).add(0.5))).div(1023);
@@ -826,11 +897,11 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
826
897
  const bytes = floor(packed.ba.mul(255).add(0.5));
827
898
  return bytes.x.mul(256).add(bytes.y).div(65535);
828
899
  }, "float");
829
- const loadDepth16 = Fn(([texel]) => decodeDepth16(textureLoad(
900
+ const loadDepth16 = Fn2(([texel]) => decodeDepth16(textureLoad(
830
901
  geometryAtlas,
831
902
  ivec2(texel).clamp(ivec2(0), ivec2(atlasResolution.sub(1)))
832
903
  )), "float");
833
- const sampleDepth16 = Fn(([uvNode]) => {
904
+ const sampleDepth16 = Fn2(([uvNode]) => {
834
905
  const pixel = uvNode.mul(atlasResolution).sub(0.5);
835
906
  const base = floor(pixel);
836
907
  const fraction = fract(pixel);
@@ -846,7 +917,7 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
846
917
  );
847
918
  return mix(lower, upper, fraction.y);
848
919
  }, "float");
849
- const decodeOctahedral = Fn(([encoded]) => {
920
+ const decodeOctahedral = Fn2(([encoded]) => {
850
921
  const f = encoded.mul(2).sub(1).toVar();
851
922
  const value = vec3(f, float(1).sub(abs(f.x)).sub(abs(f.y))).toVar();
852
923
  const folded = vec2(
@@ -858,15 +929,15 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
858
929
  });
859
930
  return value.normalize();
860
931
  }, "vec3");
861
- const reconstructPosition = Fn(([frameUv, bounds, frameDirection, right, up, depthValue]) => {
932
+ const reconstructPosition = Fn2(([frameUv, bounds, frameDirection, right, up, depthValue]) => {
862
933
  const plane = mix(bounds.xy, bounds.zw, frameUv);
863
934
  return right.mul(plane.x).add(up.mul(plane.y)).add(frameDirection.mul(radius.sub(depthValue.mul(radius).mul(2))));
864
935
  }, "vec3");
865
- const cameraLocal = modelWorldMatrixInverse.mul(vec4(cameraPosition, 1)).xyz;
866
- const cameraRightLocal = modelWorldMatrixInverse.mul(vec4(cameraWorldMatrix[0].xyz, 0)).xyz.normalize();
867
- const cameraUpLocal = modelWorldMatrixInverse.mul(vec4(cameraWorldMatrix[1].xyz, 0)).xyz.normalize();
868
- const cameraOutLocal = modelWorldMatrixInverse.mul(vec4(cameraWorldMatrix[2].xyz, 0)).xyz.normalize();
869
- const projectionCameraDirection = Fn(([], builder) => builder.camera.isPerspectiveCamera ? cameraLocal.normalize() : cameraOutLocal, "vec3")();
936
+ const cameraLocal = modelWorldMatrixInverse.mul(vec43(cameraPosition, 1)).xyz;
937
+ const cameraRightLocal = modelWorldMatrixInverse.mul(vec43(cameraWorldMatrix[0].xyz, 0)).xyz.normalize();
938
+ const cameraUpLocal = modelWorldMatrixInverse.mul(vec43(cameraWorldMatrix[1].xyz, 0)).xyz.normalize();
939
+ const cameraOutLocal = modelWorldMatrixInverse.mul(vec43(cameraWorldMatrix[2].xyz, 0)).xyz.normalize();
940
+ const projectionCameraDirection = Fn2(([], builder) => builder.camera.isPerspectiveCamera ? cameraLocal.normalize() : cameraOutLocal, "vec3")();
870
941
  const horizontalCamera = vec3(
871
942
  projectionCameraDirection.x,
872
943
  0,
@@ -918,57 +989,161 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
918
989
  const rootFound = bool(false).toVar();
919
990
  const rootLower = float(0).toVar();
920
991
  const rootUpper = float(1).toVar();
921
- const previousHasSurface = bool(false).toVar();
922
- const previousSearchDepth = float(0).toVar();
923
- const previousSurfaceDepth = float(1).toVar();
924
- const coarseStep = float(1).div(coarseSearchSteps);
925
- Loop(coarseSearchSteps, ({ i }) => {
926
- const searchDepth = float(i).add(1).mul(coarseStep);
927
- const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));
928
- const searchRayPosition = planePosition.add(rayDirection.mul(
929
- searchPlaneDepth.sub(dot(planePosition, frameDirection)).div(safeRayPlaneDenominator)
930
- ));
931
- const searchUv = vec2(
932
- dot(searchRayPosition, right),
933
- dot(searchRayPosition, up)
934
- ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
935
- const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv))).or(any(searchUv.greaterThan(vec2(maximumFrameUv))));
936
- If(searchOutOfBounds, () => {
937
- previousHasSurface.assign(false);
992
+ const safeRay = vec3(
993
+ nonZeroSign(rayDirection.x),
994
+ nonZeroSign(rayDirection.y),
995
+ nonZeroSign(rayDirection.z)
996
+ ).mul(max(abs(rayDirection), vec3(1e-7)));
997
+ const boundsGuard = radius.mul(2).div(interiorResolution);
998
+ const boxT0 = vec3(...descriptor.boundsMin).sub(boundsGuard).sub(planePosition).div(safeRay);
999
+ const boxT1 = vec3(...descriptor.boundsMax).add(boundsGuard).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
+ const uvDepthSlope = vec2(dot(rayDirection, right), dot(rayDirection, up)).mul(radius.mul(-2).div(safeRayPlaneDenominator)).div(bounds.zw.sub(bounds.xy));
1009
+ const safeSlope = vec2(
1010
+ nonZeroSign(uvDepthSlope.x),
1011
+ nonZeroSign(uvDepthSlope.y)
1012
+ ).mul(max(abs(uvDepthSlope), vec2(1e-7)));
1013
+ const uvStart = projectedFrameUv.sub(uvDepthSlope.mul(0.5));
1014
+ const t0 = vec2(minimumFrameUv).sub(uvStart).div(safeSlope);
1015
+ const t1 = vec2(maximumFrameUv).sub(uvStart).div(safeSlope);
1016
+ const lower = min(t0, t1), upper = max(t0, t1);
1017
+ const searchStart = max(min(depth0, depth1), max(0, max(lower.x, lower.y)));
1018
+ const searchEnd = min(max(depth0, depth1), min(1, min(upper.x, upper.y)));
1019
+ const searchRange = max(searchEnd.sub(searchStart), 1e-6);
1020
+ const coarseStep = searchRange.div(coarseSearchSteps);
1021
+ const validateRoot = () => {
1022
+ If(rootSolved, () => {
1023
+ const at = atlasUv(frame, frameUv);
1024
+ const surface = reconstructPosition(frameUv, bounds, frameDirection, right, up, sampleDepth16(at));
1025
+ const closest = planePosition.add(rayDirection.mul(dot(surface.sub(planePosition), rayDirection)));
1026
+ const footprint2 = max(bounds.z.sub(bounds.x), bounds.w.sub(bounds.y)).div(interiorResolution);
1027
+ const nearestPixel = floor(at.mul(atlasResolution));
1028
+ const nearestDepth = loadDepth16(nearestPixel);
1029
+ const depthJump = abs(sampleDepth16(at).sub(nearestDepth)).mul(radius).mul(2);
1030
+ const discontinuity = bool(false).toVar();
1031
+ If(depthJump.greaterThan(footprint2.mul(4)), () => {
1032
+ const neighbor = (offset) => loadDepth16(nearestPixel.add(offset).clamp(
1033
+ frame.mul(frameResolution),
1034
+ frame.add(1).mul(frameResolution).sub(1)
1035
+ ));
1036
+ const curvature = max(
1037
+ abs(neighbor(vec2(-1, 0)).add(neighbor(vec2(1, 0))).sub(nearestDepth.mul(2))),
1038
+ abs(neighbor(vec2(0, -1)).add(neighbor(vec2(0, 1))).sub(nearestDepth.mul(2)))
1039
+ ).mul(radius).mul(2);
1040
+ discontinuity.assign(curvature.greaterThan(footprint2.mul(4)));
1041
+ });
1042
+ If(surface.sub(closest).length().greaterThan(footprint2.mul(4)).or(discontinuity).or(sampleCapturedAlpha(at).lessThan(reprojectionSurfaceCutoff)), () => {
1043
+ rootFound.assign(false);
1044
+ rootSolved.assign(false);
1045
+ strictRootSolved.assign(false);
1046
+ });
938
1047
  });
939
- If(searchOutOfBounds.not(), () => {
940
- const searchAtlasUv = atlasUv(frame, searchUv);
941
- const searchCoverage = sampleCapturedAlpha(searchAtlasUv);
942
- const searchSurfaceDepth = sampleDepth16(searchAtlasUv);
943
- const hasSurface = searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff);
944
- const depthDelta = searchDepth.sub(searchSurfaceDepth);
945
- const crossesDepth = previousHasSurface.and(previousSearchDepth.lessThan(previousSurfaceDepth)).and(depthDelta.greaterThanEqual(0));
946
- const continuousDepthStep = abs(searchSurfaceDepth.sub(previousSurfaceDepth)).lessThanEqual(coarseStep.mul(2));
947
- const crossesCoveredSurface = crossesDepth.and(continuousDepthStep);
948
- const entersAtSurface = previousHasSurface.not().and(depthDelta.greaterThanEqual(0)).and(depthDelta.lessThanEqual(coarseStep.mul(1.15)));
949
- const boundedRoot = crossesCoveredSurface.or(entersAtSurface);
950
- If(
951
- rootFound.not().and(hasSurface).and(features.boundedReprojection ? boundedRoot : depthDelta.greaterThanEqual(0)),
952
- () => {
953
- rootLower.assign(max(searchDepth.sub(coarseStep), 0));
1048
+ };
1049
+ const refineRoot = () => {
1050
+ If(rootFound, () => {
1051
+ Loop(profile.depthSamples, () => {
1052
+ const searchDepth = rootLower.add(rootUpper).mul(0.5);
1053
+ const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));
1054
+ const searchRayPosition = planePosition.add(rayDirection.mul(
1055
+ searchPlaneDepth.sub(dot(planePosition, frameDirection)).div(safeRayPlaneDenominator)
1056
+ ));
1057
+ const searchUv = vec2(
1058
+ dot(searchRayPosition, right),
1059
+ dot(searchRayPosition, up)
1060
+ ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
1061
+ const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv))).or(any(searchUv.greaterThan(vec2(maximumFrameUv))));
1062
+ const midpointIsUpper = bool(false).toVar();
1063
+ If(searchOutOfBounds.not(), () => {
1064
+ const searchAtlasUv = atlasUv(frame, searchUv);
1065
+ const searchCoverage = sampleCapturedAlpha(searchAtlasUv);
1066
+ const searchSurfaceDepth = sampleDepth16(searchAtlasUv);
1067
+ midpointIsUpper.assign(
1068
+ searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff).and(searchDepth.greaterThanEqual(searchSurfaceDepth))
1069
+ );
1070
+ });
1071
+ If(midpointIsUpper, () => {
954
1072
  rootUpper.assign(searchDepth);
955
- rootFound.assign(true);
956
- rootSolved.assign(true);
957
- strictRootSolved.assign(true);
958
- }
959
- );
960
- If(rootFound.not().and(hasSurface), () => {
961
- previousHasSurface.assign(true);
962
- previousSearchDepth.assign(searchDepth);
963
- previousSurfaceDepth.assign(searchSurfaceDepth);
1073
+ });
1074
+ If(midpointIsUpper.not(), () => {
1075
+ rootLower.assign(searchDepth);
1076
+ });
1077
+ });
1078
+ const residualAt = (depth) => {
1079
+ const planeDepth = radius.sub(depth.mul(radius).mul(2));
1080
+ const position = planePosition.add(rayDirection.mul(
1081
+ planeDepth.sub(dot(planePosition, frameDirection)).div(safeRayPlaneDenominator)
1082
+ ));
1083
+ const address = vec2(dot(position, right), dot(position, up)).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
1084
+ return depth.sub(sampleDepth16(atlasUv(frame, address)));
1085
+ };
1086
+ const lowResidual = residualAt(rootLower), highResidual = residualAt(rootUpper);
1087
+ const difference = lowResidual.sub(highResidual);
1088
+ const fraction = lowResidual.div(
1089
+ nonZeroSign(difference).mul(max(abs(difference), 1e-8))
1090
+ ).clamp(0, 1);
1091
+ const rootDepth = mix(rootLower, rootUpper, fraction);
1092
+ const rootPlaneDepth = radius.sub(rootDepth.mul(radius).mul(2));
1093
+ const rootRayPosition = planePosition.add(rayDirection.mul(
1094
+ rootPlaneDepth.sub(dot(planePosition, frameDirection)).div(safeRayPlaneDenominator)
1095
+ ));
1096
+ frameUv.assign(vec2(
1097
+ dot(rootRayPosition, right),
1098
+ dot(rootRayPosition, up)
1099
+ ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy)).clamp(
1100
+ minimumFrameUv,
1101
+ maximumFrameUv
1102
+ ));
1103
+ });
1104
+ };
1105
+ const traceInterval = (steps, start = searchStart, end = searchEnd) => {
1106
+ const coarseStep2 = max(end.sub(start), 1e-6).div(float(steps));
1107
+ Loop({ start: 0, end: steps, type: "int" }, ({ i }) => {
1108
+ If(rootFound.or(intersectsBounds.not()).or(end.lessThan(start)), () => {
1109
+ Break();
964
1110
  });
965
- If(hasSurface.not(), () => {
966
- previousHasSurface.assign(false);
1111
+ const searchDepth = start.add(float(i).add(1).mul(coarseStep2));
1112
+ const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));
1113
+ const searchRayPosition = planePosition.add(rayDirection.mul(
1114
+ searchPlaneDepth.sub(dot(planePosition, frameDirection)).div(safeRayPlaneDenominator)
1115
+ ));
1116
+ const searchUv = vec2(
1117
+ dot(searchRayPosition, right),
1118
+ dot(searchRayPosition, up)
1119
+ ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
1120
+ const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv))).or(any(searchUv.greaterThan(vec2(maximumFrameUv))));
1121
+ If(searchOutOfBounds.not(), () => {
1122
+ const searchAtlasUv = atlasUv(frame, searchUv);
1123
+ const searchCoverage = sampleCapturedAlpha(searchAtlasUv);
1124
+ const hasSurface = searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff);
1125
+ If(hasSurface, () => {
1126
+ const searchSurfaceDepth = sampleDepth16(searchAtlasUv);
1127
+ const depthDelta = searchDepth.sub(searchSurfaceDepth);
1128
+ If(
1129
+ rootFound.not().and(hasSurface).and(depthDelta.greaterThanEqual(0)),
1130
+ () => {
1131
+ rootLower.assign(max(searchDepth.sub(coarseStep2), 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
+ });
967
1141
  });
968
1142
  });
969
- });
970
- If(rootFound.not(), () => {
971
- const iterativeUv = frameUv.toVar();
1143
+ };
1144
+ traceInterval(int(coarseSearchSteps));
1145
+ If(rootFound.not().and(intersectsBounds), () => {
1146
+ const iterativeUv = projectedFrameUv.clamp(minimumFrameUv, maximumFrameUv).toVar();
972
1147
  const iterativeDepth = sampleDepth16(atlasUv(frame, iterativeUv)).toVar();
973
1148
  const iterationResidual = float(1).toVar();
974
1149
  const iterationValid = bool(true).toVar();
@@ -1004,50 +1179,10 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
1004
1179
  () => {
1005
1180
  frameUv.assign(iterativeUv);
1006
1181
  rootSolved.assign(true);
1182
+ if (features.boundedReprojection) validateRoot();
1007
1183
  }
1008
1184
  );
1009
1185
  });
1010
- If(rootFound, () => {
1011
- Loop(profile.depthSamples, () => {
1012
- const searchDepth = rootLower.add(rootUpper).mul(0.5);
1013
- const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));
1014
- const searchRayPosition = planePosition.add(rayDirection.mul(
1015
- searchPlaneDepth.sub(dot(planePosition, frameDirection)).div(safeRayPlaneDenominator)
1016
- ));
1017
- const searchUv = vec2(
1018
- dot(searchRayPosition, right),
1019
- dot(searchRayPosition, up)
1020
- ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
1021
- const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv))).or(any(searchUv.greaterThan(vec2(maximumFrameUv))));
1022
- const midpointIsUpper = bool(false).toVar();
1023
- If(searchOutOfBounds.not(), () => {
1024
- const searchAtlasUv = atlasUv(frame, searchUv);
1025
- const searchCoverage = sampleCapturedAlpha(searchAtlasUv);
1026
- const searchSurfaceDepth = sampleDepth16(searchAtlasUv);
1027
- midpointIsUpper.assign(
1028
- searchCoverage.greaterThanEqual(reprojectionSurfaceCutoff).and(searchDepth.greaterThanEqual(searchSurfaceDepth))
1029
- );
1030
- });
1031
- If(midpointIsUpper, () => {
1032
- rootUpper.assign(searchDepth);
1033
- });
1034
- If(midpointIsUpper.not(), () => {
1035
- rootLower.assign(searchDepth);
1036
- });
1037
- });
1038
- const rootDepth = rootLower.add(rootUpper).mul(0.5);
1039
- const rootPlaneDepth = radius.sub(rootDepth.mul(radius).mul(2));
1040
- const rootRayPosition = planePosition.add(rayDirection.mul(
1041
- rootPlaneDepth.sub(dot(planePosition, frameDirection)).div(safeRayPlaneDenominator)
1042
- ));
1043
- frameUv.assign(vec2(
1044
- dot(rootRayPosition, right),
1045
- dot(rootRayPosition, up)
1046
- ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy)).clamp(
1047
- minimumFrameUv,
1048
- maximumFrameUv
1049
- ));
1050
- });
1051
1186
  }
1052
1187
  const uvNode = atlasUv(frame, frameUv);
1053
1188
  reconstructed.assign(reconstructPosition(
@@ -1094,7 +1229,7 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
1094
1229
  const colorUv = colorAtlasUv(uvNode);
1095
1230
  const baseColor = sampleAtlas(baseColorAtlas, colorUv, mapLod(baseColorAtlas, colorUv), colorColumns);
1096
1231
  const capturedAlpha = sampleCapturedAlpha(uvNode);
1097
- const orm = compactLayout ? vec4(geometrySample.b, shadingSample.b, shadingSample.a, 1) : ormAtlas ? sampleAtlas(ormAtlas, uvNode, mapLod(ormAtlas, uvNode)) : vec4(
1232
+ const orm = compactLayout ? vec43(geometrySample.b, shadingSample.b, shadingSample.a, 1) : ormAtlas ? sampleAtlas(ormAtlas, uvNode, mapLod(ormAtlas, uvNode)) : vec43(
1098
1233
  descriptor.material.occlusion,
1099
1234
  descriptor.material.roughness,
1100
1235
  descriptor.material.metalness,
@@ -1107,7 +1242,7 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
1107
1242
  // sampled color/alpha here and the frame weight below applied crop
1108
1243
  // confidence twice; low-confidence crop-edge samples consequently
1109
1244
  // rendered as black outlines instead of fading away.
1110
- vec4(baseColor.rgb, coverage),
1245
+ vec43(baseColor.rgb, coverage),
1111
1246
  capturedAlpha,
1112
1247
  faceForwardNormal,
1113
1248
  reconstructed,
@@ -1120,7 +1255,7 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
1120
1255
  footprint
1121
1256
  );
1122
1257
  };
1123
- return Fn(buildFrameSample);
1258
+ return Fn2(buildFrameSample);
1124
1259
  };
1125
1260
  const samplePlanarFrame = createFrameSampler(false);
1126
1261
  const sampleReprojectedFrame = features.reprojection ? createFrameSampler(true) : null;
@@ -1304,15 +1439,10 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
1304
1439
  transition
1305
1440
  );
1306
1441
  };
1307
- const blendImpostor = Fn(buildBlendedSample);
1442
+ const blendImpostor = Fn2(buildBlendedSample);
1308
1443
  const sample = blendImpostor().toVar("impostorSample");
1309
- const reconstructedWorldPosition = modelWorldMatrix.mul(vec4(blendedMember(sample, "positionLocal"), 1)).xyz;
1310
- const reconstructedDepth = Fn(([localPosition], builder) => {
1311
- const viewZ = modelViewMatrix.mul(vec4(localPosition, 1)).z;
1312
- const resolvedDepth = builder.camera.isPerspectiveCamera ? viewZToPerspectiveDepth(viewZ, cameraNear, cameraFar) : viewZToOrthographicDepth(viewZ, cameraNear, cameraFar);
1313
- return builder.material.isShadowPassMaterial ? min(1, resolvedDepth.add(IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS)) : resolvedDepth;
1314
- }, "float");
1315
- const material = new MeshStandardNodeMaterial({
1444
+ const reconstructedWorldPosition = modelWorldMatrix2.mul(vec43(blendedMember(sample, "positionLocal"), 1)).xyz;
1445
+ const material = new CapturedSurfaceMaterial({
1316
1446
  name: "Needle PBR impostor TSL",
1317
1447
  side: DoubleSide,
1318
1448
  transparent: false,
@@ -1332,7 +1462,7 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
1332
1462
  const screenCoverage = screenDistanceCoverage.mul(mappingVisibility);
1333
1463
  material.positionNode = displayBillboardPosition;
1334
1464
  material.castShadowPositionNode = displayBillboardPosition;
1335
- material.colorNode = vec4(blendedMember(sample, "base").rgb, screenCoverage);
1465
+ material.colorNode = vec43(blendedMember(sample, "base").rgb, screenCoverage);
1336
1466
  material.normalNode = transformNormalToView(blendedMember(sample, "normalLocal"));
1337
1467
  material.aoNode = blendedMember(sample, "orm").r;
1338
1468
  material.roughnessNode = blendedMember(sample, "orm").g;
@@ -1344,7 +1474,8 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
1344
1474
  );
1345
1475
  material.maskShadowNode = distanceCoverage.mul(mappingVisibility).greaterThanEqual(0.5);
1346
1476
  material.alphaToCoverage = true;
1347
- material.depthNode = reconstructedDepth(blendedMember(sample, "positionLocal"));
1477
+ material.capturedPositionNode = blendedMember(sample, "positionLocal");
1478
+ material.depthNode = capturedSurfaceDepth(material.capturedPositionNode, IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS);
1348
1479
  material.receivedShadowPositionNode = reconstructedWorldPosition;
1349
1480
  material.toneMapped = true;
1350
1481
  material.userData.impostorShaderProfile = profile;