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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +14 -1
  3. package/build/box-impostor-runtime.js +321 -195
  4. package/build/box-impostor-runtime.js.map +4 -4
  5. package/build/impostor-runtime.js +944 -202
  6. package/build/impostor-runtime.js.map +4 -4
  7. package/build/index.js +7 -7
  8. package/build/index.js.map +2 -2
  9. package/build/internal/box-impostor/box-impostor-display.js +319 -193
  10. package/build/internal/box-impostor/box-impostor-display.js.map +4 -4
  11. package/build/internal/box-impostor/box-impostor-faces.js +8 -6
  12. package/build/internal/box-impostor/box-impostor-faces.js.map +2 -2
  13. package/build/internal/box-impostor/box-impostor-material.js +319 -193
  14. package/build/internal/box-impostor/box-impostor-material.js.map +4 -4
  15. package/build/internal/box-impostor/box-impostor-projection.js +8 -5
  16. package/build/internal/box-impostor/box-impostor-projection.js.map +2 -2
  17. package/build/internal/box-impostor/box-impostor-runtime.js +321 -195
  18. package/build/internal/box-impostor/box-impostor-runtime.js.map +4 -4
  19. package/build/internal/impostor/adaptive-impostor-renderer.js +434 -0
  20. package/build/internal/impostor/adaptive-impostor-renderer.js.map +7 -0
  21. package/build/internal/impostor/impostor-node-material.js +944 -202
  22. package/build/internal/impostor/impostor-node-material.js.map +4 -4
  23. package/build/internal/impostor/impostor-performance.js +136 -0
  24. package/build/internal/impostor/impostor-performance.js.map +7 -0
  25. package/build/internal/pixel-impostor/pixel-impostor-runtime.js +6 -1
  26. package/build/internal/pixel-impostor/pixel-impostor-runtime.js.map +2 -2
  27. package/build/internal/rendering/instance-space.js +110 -0
  28. package/build/internal/rendering/instance-space.js.map +7 -0
  29. package/build/internal/rendering/renderer-support.js +6 -1
  30. package/build/internal/rendering/renderer-support.js.map +2 -2
  31. package/build/pixel-impostor-runtime.js +6 -1
  32. package/build/pixel-impostor-runtime.js.map +2 -2
  33. package/build/types/box-impostor/box-impostor-faces.d.ts +3 -1
  34. package/build/types/box-impostor/box-impostor-projection.d.ts +3 -1
  35. package/build/types/impostor/adaptive-impostor-renderer.d.ts +74 -0
  36. package/build/types/impostor/adaptive-impostor-renderer.js +1 -0
  37. package/build/types/impostor/impostor-node-material.d.ts +5 -1
  38. package/build/types/impostor/impostor-performance.d.ts +90 -0
  39. package/build/types/impostor/impostor-performance.js +1 -0
  40. package/build/types/public/impostor-runtime.d.ts +2 -0
  41. package/build/types/public/index.d.ts +3 -0
  42. package/build/types/rendering/instance-space.d.ts +26 -0
  43. package/build/types/rendering/instance-space.js +1 -0
  44. package/build/types/rendering/renderer-support.d.ts +13 -0
  45. package/package.json +2 -2
  46. package/src/box-impostor/box-impostor-faces.js +7 -5
  47. package/src/box-impostor/box-impostor-material.js +34 -19
  48. package/src/box-impostor/box-impostor-projection.js +7 -4
  49. package/src/impostor/adaptive-impostor-renderer.js +423 -0
  50. package/src/impostor/impostor-node-material.js +347 -157
  51. package/src/impostor/impostor-performance.js +152 -0
  52. package/src/public/impostor-runtime.js +2 -0
  53. package/src/public/index.js +12 -9
  54. package/src/rendering/instance-space.js +121 -0
  55. package/src/rendering/renderer-support.js +9 -0
@@ -4,12 +4,13 @@
4
4
  // their declared member layout.
5
5
  // @ts-nocheck
6
6
 
7
- import { enableRendererNodeMaterials, rendererSupportsImpostorNodeMaterials } from '../rendering/renderer-support.js';
7
+ import { enableRendererNodeMaterials, rendererSupportsImpostorNodeMaterials, rendererUsesMultisampleCoverage } from '../rendering/renderer-support.js';
8
8
  export { rendererSupportsImpostorNodeMaterials } from '../rendering/renderer-support.js';
9
9
 
10
10
  import { CapturedSurfaceMaterial } from '../rendering/captured-surface-material.js';
11
11
  import { capturedSurfaceDepth } from '../rendering/captured-surface-depth.js';
12
12
  import {
13
+ Box3,
13
14
  ClampToEdgeWrapping,
14
15
  DoubleSide,
15
16
  GLSL3,
@@ -19,6 +20,7 @@ import {
19
20
  NoColorSpace,
20
21
  SRGBColorSpace,
21
22
  ShaderMaterial,
23
+ Sphere,
22
24
  Vector3,
23
25
  Vector4,
24
26
  } from 'three/webgpu';
@@ -54,12 +56,16 @@ import {
54
56
  textureSize,
55
57
  transformNormalToView,
56
58
  uniformArray,
59
+ varying,
57
60
  vec2,
58
61
  vec3,
59
62
  vec4,
60
63
  } from 'three/tsl';
61
64
  import { NEEDLE_MESH_IMPOSTOR } from './impostor-metadata.js';
65
+ import { registerAdaptiveImpostorMaterial } from './adaptive-impostor-renderer.js';
66
+ import { IMPOSTOR_PERFORMANCE_PRESETS, resolveImpostorFrameBudget } from './impostor-performance.js';
62
67
  import { bindTextureSlot } from '../rendering/texture-slot.js';
68
+ import { instanceSpace } from '../rendering/instance-space.js';
63
69
  import { PERSPECTIVE_RAY_PLANE_SIGN } from './octahedral.js';
64
70
  import {
65
71
  REPROJECTION_CONFIDENCE_INNER_TEXELS,
@@ -195,8 +201,10 @@ function clampRuntimeSamples(value, maximum) {
195
201
  * }}>} bindings
196
202
  * @param {Partial<ImpostorRuntimeFeatures>=} inputFeatures
197
203
  * @param {ImpostorRenderer=} renderer
204
+ * @param {import('./impostor-performance.js').ImpostorPerformance=} performance
198
205
  */
199
- export function upgradeImpostorScene(root, bindings = new Map(), inputFeatures = {}, renderer) {
206
+ export function upgradeImpostorScene(root, bindings = new Map(), inputFeatures = {}, renderer, performance = 'fixed') {
207
+ const frameBudgetMs = resolveImpostorFrameBudget(performance);
200
208
  let upgraded = 0;
201
209
  root.traverse((object) => {
202
210
  const binding = bindings.get(object);
@@ -297,9 +305,54 @@ export function upgradeImpostorScene(root, bindings = new Map(), inputFeatures =
297
305
  debugControls.raySamples = { value: descriptor.parallaxSteps * 4 };
298
306
  debugControls.depthSamples = { value: descriptor.parallaxSteps };
299
307
  debugControls.blendZone = { value: descriptor.blendZone };
300
- debugControls.setFeatures = (features) => {
308
+ // Auto cycles through three profiles. Retain their programs while the
309
+ // preview owns them, and release the variants when its active material is
310
+ // disposed. Manual edits keep the normal replace-and-dispose lifecycle.
311
+ const variants = new Map();
312
+ let cachedAtlases = '';
313
+ let adaptive;
314
+ function stopAdaptivePerformance() {
315
+ adaptive?.dispose();
316
+ adaptive = undefined;
317
+ }
318
+ const releaseVariants = (keep) => {
319
+ const retained = [...variants.values()];
320
+ variants.clear();
321
+ for (const material of retained) {
322
+ material.removeEventListener('dispose', onVariantDisposed);
323
+ if (material !== keep) material.dispose();
324
+ }
325
+ };
326
+ const onVariantDisposed = (event) => releaseVariants(event.target);
327
+ debugControls.setFeatures = (features, cacheVariants = false) => {
301
328
  const next = resolveImpostorRuntimeFeatures(descriptor, features);
302
- if (JSON.stringify(next.requested) === JSON.stringify(requestedFeatures)) return false;
329
+ const previous = object.material;
330
+ // An atlas can be replaced on the active material after loading.
331
+ const atlasKey = cacheVariants ? Object.values(maps).map(texture => texture?.uuid).join('/') : '';
332
+ if (!cacheVariants || next.requested.blendZone !== requestedFeatures.blendZone || atlasKey !== cachedAtlases) {
333
+ releaseVariants(previous);
334
+ cachedAtlases = atlasKey;
335
+ }
336
+ const key = JSON.stringify(next.requested);
337
+ const unchanged = key === JSON.stringify(requestedFeatures);
338
+ if (unchanged && (!cacheVariants || variants.has(key))) return false;
339
+ const wasRetained = [...variants.values()].includes(previous);
340
+ const material = unchanged ? previous : variants.get(key) ?? createPbrImpostorNodeMaterial(
341
+ descriptor, maps, next.requested, renderer,
342
+ );
343
+ if (cacheVariants) {
344
+ variants.delete(key);
345
+ variants.set(key, material);
346
+ material.addEventListener('dispose', onVariantDisposed);
347
+ if (variants.size > 3) {
348
+ const [oldKey, oldest] = variants.entries().next().value;
349
+ variants.delete(oldKey);
350
+ oldest.removeEventListener('dispose', onVariantDisposed);
351
+ oldest.dispose();
352
+ }
353
+ }
354
+ if (unchanged) return false;
355
+ stopAdaptivePerformance();
303
356
  Object.assign(requestedFeatures, next.requested);
304
357
  for (const name of RUNTIME_FEATURE_NAMES) {
305
358
  debugControls[name].value = requestedFeatures[name] ? 1 : 0;
@@ -307,25 +360,43 @@ export function upgradeImpostorScene(root, bindings = new Map(), inputFeatures =
307
360
  debugControls.raySamples.value = requestedFeatures.raySamples;
308
361
  debugControls.depthSamples.value = requestedFeatures.depthSamples;
309
362
  debugControls.blendZone.value = requestedFeatures.blendZone;
310
- const previous = object.material;
311
- const replacement = createPbrImpostorNodeMaterial(
312
- descriptor,
313
- maps,
314
- requestedFeatures,
315
- renderer,
316
- );
317
- replacement.userData.impostor = runtime;
318
- replacement.userData.impostorDebug = debugControls;
319
- debugControls.profile = replacement.userData.impostorShaderProfile;
320
- object.material = replacement;
321
- if (previous !== fallback) previous.dispose();
363
+ material.userData.impostor = runtime;
364
+ material.userData.impostorDebug = debugControls;
365
+ debugControls.profile = material.userData.impostorShaderProfile;
366
+ object.material = material;
367
+ if (!wasRetained && previous !== fallback) previous.dispose();
322
368
  return true;
323
369
  };
324
370
  const material = createPbrImpostorNodeMaterial(descriptor, maps, requestedFeatures, renderer);
325
371
  material.userData.impostor = runtime;
326
372
  material.userData.impostorDebug = debugControls;
327
373
  debugControls.profile = material.userData.impostorShaderProfile;
374
+ debugControls.getAdaptivePerformance = () => adaptive?.read() ?? null;
375
+ debugControls.setPerformance = (mode) => {
376
+ if (mode === 'fixed') {
377
+ stopAdaptivePerformance();
378
+ return;
379
+ }
380
+ if (adaptive || !nodeMaterials || descriptor.mapping === 'single') return;
381
+ const bounds = new Box3(new Vector3(...descriptor.boundsMin), new Vector3(...descriptor.boundsMax))
382
+ .getBoundingSphere(new Sphere());
383
+ const limits = { ...requestedFeatures };
384
+ adaptive = registerAdaptiveImpostorMaterial(renderer, object.material, bounds, tier => {
385
+ const preset = tier === 0 ? IMPOSTOR_PERFORMANCE_PRESETS.fast
386
+ : tier === 1 ? IMPOSTOR_PERFORMANCE_PRESETS.medium : limits;
387
+ const variant = createPbrImpostorNodeMaterial(descriptor, maps, {
388
+ ...limits,
389
+ raySamples: Math.min(limits.raySamples, preset.raySamples),
390
+ depthSamples: Math.min(limits.depthSamples, preset.depthSamples),
391
+ reprojection: limits.reprojection && preset.reprojection,
392
+ depthWeights: limits.depthWeights && preset.depthWeights,
393
+ }, renderer);
394
+ variant.userData.impostor = runtime;
395
+ return variant;
396
+ }, frameBudgetMs);
397
+ };
328
398
  object.material = material;
399
+ debugControls.setPerformance(typeof performance === 'object' ? 'auto' : performance);
329
400
  object.castShadow = descriptor.castShadow;
330
401
  object.receiveShadow = descriptor.receiveShadow;
331
402
  object.frustumCulled = false;
@@ -347,6 +418,7 @@ export class NeedleImpostorLoaderPlugin {
347
418
  * onUpgrade?: (count: number, result: import('three/addons/loaders/GLTFLoader.js').GLTF) => void,
348
419
  * features?: Partial<ImpostorRuntimeFeatures>,
349
420
  * renderer?: ImpostorRenderer,
421
+ * performance?: import('./impostor-performance.js').ImpostorPerformance,
350
422
  * }=} options
351
423
  */
352
424
  constructor(parser, options = {}) {
@@ -410,6 +482,7 @@ export class NeedleImpostorLoaderPlugin {
410
482
  bindings,
411
483
  this.options.features,
412
484
  this.options.renderer,
485
+ this.options.performance ?? (this.options.features ? 'fixed' : 'auto'),
413
486
  );
414
487
  }
415
488
  this.options.onUpgrade?.(upgraded, result);
@@ -476,13 +549,27 @@ function createCompatibleImpostorNodeMaterial(descriptor, maps) {
476
549
  },
477
550
  vertexShader: /* glsl */ `
478
551
  out vec3 vPlaneLocal;
552
+ #ifdef USE_INSTANCING
553
+ flat out vec3 vCameraLocal;
554
+ flat out mat4 vInstanceMatrix;
555
+ #endif
479
556
  void main() {
480
- mat4 inverseModel = inverse(modelMatrix);
557
+ #ifdef USE_INSTANCING
558
+ mat4 inverseModel = inverse(modelMatrix * instanceMatrix);
559
+ vCameraLocal = (inverseModel * vec4(cameraPosition, 1.0)).xyz;
560
+ vInstanceMatrix = instanceMatrix;
561
+ #else
562
+ mat4 inverseModel = inverse(modelMatrix);
563
+ #endif
481
564
  mat4 cameraWorld = inverse(viewMatrix);
482
565
  vec3 rightLocal = normalize((inverseModel * vec4(cameraWorld[0].xyz, 0.0)).xyz);
483
566
  vec3 upLocal = normalize((inverseModel * vec4(cameraWorld[1].xyz, 0.0)).xyz);
484
567
  vPlaneLocal = rightLocal * position.x + upLocal * position.y;
485
- gl_Position = projectionMatrix * modelViewMatrix * vec4(vPlaneLocal, 1.0);
568
+ #ifdef USE_INSTANCING
569
+ gl_Position = projectionMatrix * modelViewMatrix * instanceMatrix * vec4(vPlaneLocal, 1.0);
570
+ #else
571
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(vPlaneLocal, 1.0);
572
+ #endif
486
573
  }
487
574
  `,
488
575
  fragmentShader: /* glsl */ `
@@ -498,6 +585,10 @@ function createCompatibleImpostorNodeMaterial(descriptor, maps) {
498
585
  uniform mat4 modelViewMatrix;
499
586
  uniform mat4 projectionMatrix;
500
587
  in vec3 vPlaneLocal;
588
+ #ifdef USE_INSTANCING
589
+ flat in vec3 vCameraLocal;
590
+ flat in mat4 vInstanceMatrix;
591
+ #endif
501
592
  out vec4 fragColor;
502
593
 
503
594
  float nonZeroSign(float value) { return value < 0.0 ? -1.0 : 1.0; }
@@ -562,7 +653,11 @@ function createCompatibleImpostorNodeMaterial(descriptor, maps) {
562
653
  return textureLod(baseColorAtlas, safe, lod);
563
654
  }
564
655
  void main() {
565
- vec3 cameraLocal = (inverse(modelMatrix) * vec4(cameraPosition, 1.0)).xyz;
656
+ #ifdef USE_INSTANCING
657
+ vec3 cameraLocal = vCameraLocal;
658
+ #else
659
+ vec3 cameraLocal = (inverse(modelMatrix) * vec4(cameraPosition, 1.0)).xyz;
660
+ #endif
566
661
  vec3 cameraDirection = normalize(cameraLocal);
567
662
  #if SINGLE_VIEW
568
663
  vec2 frame = vec2(0.0);
@@ -613,7 +708,11 @@ function createCompatibleImpostorNodeMaterial(descriptor, maps) {
613
708
  vec2 plane = mix(bounds.xy, bounds.zw, frameUv);
614
709
  vec3 reconstructedLocal = right * plane.x + up * plane.y
615
710
  + frameDirection * (radius - depthValue * radius * 2.0);
616
- vec4 clip = projectionMatrix * modelViewMatrix * vec4(reconstructedLocal, 1.0);
711
+ #ifdef USE_INSTANCING
712
+ vec4 clip = projectionMatrix * modelViewMatrix * vInstanceMatrix * vec4(reconstructedLocal, 1.0);
713
+ #else
714
+ vec4 clip = projectionMatrix * modelViewMatrix * vec4(reconstructedLocal, 1.0);
715
+ #endif
617
716
  gl_FragDepth = clip.z / clip.w * 0.5 + 0.5;
618
717
  fragColor = vec4(base.rgb, coverage);
619
718
  #if defined(TONE_MAPPING)
@@ -623,6 +722,10 @@ function createCompatibleImpostorNodeMaterial(descriptor, maps) {
623
722
  }
624
723
  `,
625
724
  });
725
+ // Three defines USE_INSTANCING for the vertex stage only.
726
+ material.onBeforeCompile = (shader) => {
727
+ if (shader.instancing) shader.fragmentShader = `#define USE_INSTANCING\n${shader.fragmentShader}`;
728
+ };
626
729
  material.alphaToCoverage = true;
627
730
  material.toneMapped = true;
628
731
  material.userData.impostorShaderProfile = {
@@ -754,8 +857,6 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
754
857
  capturedCoverage: 'float',
755
858
  distanceCoverage: 'float',
756
859
  cropSupport: 'float',
757
- coverageWidth: 'float',
758
- transition: 'float',
759
860
  }, 'ImpostorBlendedSample');
760
861
  const basisMember = (value, name) => value.get(name);
761
862
  const frameMember = (value, name) => value.get(name);
@@ -866,18 +967,28 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
866
967
  .add(up.mul(plane.y))
867
968
  .add(frameDirection.mul(radius.sub(depthValue.mul(radius).mul(2))));
868
969
  }, 'vec3');
869
- const cameraLocal = modelWorldMatrixInverse.mul(vec4(cameraPosition, 1)).xyz;
970
+ // Each instance of an InstancedMesh holds the capture in its own space, so
971
+ // the camera is brought there per instance, in the vertex stage.
972
+ const local = (value, direction) => Fn((_, builder) => {
973
+ const space = instanceSpace(builder);
974
+ if (!space) return value;
975
+ return direction ? space.toLocalDirection(value) : space.toLocalPoint(value);
976
+ })();
977
+ const perInstance = (name, value) => Fn((_, builder) => (
978
+ instanceSpace(builder) ? varying(value, name) : value
979
+ ))();
980
+ const cameraLocal = local(modelWorldMatrixInverse.mul(vec4(cameraPosition, 1)).xyz, false);
870
981
  // Match the physical card basis produced by Three's billboard helper. A
871
982
  // direction-derived world-up frame is equivalent away from the poles, but
872
983
  // becomes undefined at zenith/nadir and falls back to a fixed orientation.
873
984
  // The camera still has a valid screen-space roll there, so using its actual
874
985
  // right/up axes keeps sampling coordinates rotating with the source view.
875
- const cameraRightLocal = modelWorldMatrixInverse
876
- .mul(vec4(cameraWorldMatrix[0].xyz, 0)).xyz.normalize();
877
- const cameraUpLocal = modelWorldMatrixInverse
878
- .mul(vec4(cameraWorldMatrix[1].xyz, 0)).xyz.normalize();
879
- const cameraOutLocal = modelWorldMatrixInverse
880
- .mul(vec4(cameraWorldMatrix[2].xyz, 0)).xyz.normalize();
986
+ const cameraRightLocal = local(modelWorldMatrixInverse
987
+ .mul(vec4(cameraWorldMatrix[0].xyz, 0)).xyz, true).normalize();
988
+ const cameraUpLocal = local(modelWorldMatrixInverse
989
+ .mul(vec4(cameraWorldMatrix[1].xyz, 0)).xyz, true).normalize();
990
+ const cameraOutLocal = local(modelWorldMatrixInverse
991
+ .mul(vec4(cameraWorldMatrix[2].xyz, 0)).xyz, true).normalize();
881
992
  const projectionCameraDirection = Fn(([], builder) => (
882
993
  builder.camera.isPerspectiveCamera ? cameraLocal.normalize() : cameraOutLocal
883
994
  ), 'vec3')();
@@ -903,7 +1014,7 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
903
1014
  // arbitrary pole orientation as an opaque rectangle.
904
1015
  const mappingVisibility = (fullSphere || singleView)
905
1016
  ? float(1)
906
- : smoothstep(-1, -0.9995, cameraDirection.y);
1017
+ : perInstance('vImpostorMappingVisibility', smoothstep(-1, -0.9995, cameraDirection.y));
907
1018
  // Ease into the authored hemisphere over its first degree. Although the
908
1019
  // directions on either side of zero are mathematically close, switching the
909
1020
  // billboard basis exactly at zero moves rasterized edges by a pixel and
@@ -920,14 +1031,101 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
920
1031
  const billboardUpLocal = (fullSphere || singleView)
921
1032
  ? cameraUpLocal
922
1033
  : mix(horizonBillboardUp, cameraUpLocal, horizonTransition).normalize();
923
- const samplingCamera = clampedCameraDirection.mul(cameraLocal.length());
1034
+ const samplingCameraPosition = clampedCameraDirection.mul(cameraLocal.length());
1035
+ const samplingCamera = perInstance('vImpostorSamplingCamera', samplingCameraPosition);
924
1036
  const samplingBillboardPosition = cameraRightLocal.mul(positionGeometry.x)
925
1037
  .add(billboardUpLocal.mul(positionGeometry.y));
926
- const displayBillboardPosition = cameraRightLocal.mul(positionGeometry.x)
927
- .add(cameraUpLocal.mul(positionGeometry.y));
1038
+ // A position node replaces the instanced position, so place the card here.
1039
+ const displayBillboardPosition = Fn((_, builder) => {
1040
+ const card = cameraRightLocal.mul(positionGeometry.x)
1041
+ .add(cameraUpLocal.mul(positionGeometry.y));
1042
+ return instanceSpace(builder)?.toMeshPoint(card) ?? card;
1043
+ })();
928
1044
  const planeLocal = samplingBillboardPosition.toVarying('vImpostorPlaneLocal');
929
- const createFrameSampler = (withReprojection) => {
930
- const buildFrameSample = ([frame, planePosition, rayDirection, bounds]) => {
1045
+ // Use the same triangle in both shader stages. Per-pixel perspective
1046
+ // correction may change its weights, never which captures it addresses.
1047
+ const selectFrameTriangle = (centerGrid, orientation = null) => {
1048
+ const base = min(floor(centerGrid), vec2(frames.sub(2)));
1049
+ const centerFraction = centerGrid.sub(base);
1050
+ if (!orientation) {
1051
+ const foldCell = fullSphere
1052
+ ? bool(false)
1053
+ : base.x.add(base.y).equal(frames.sub(2));
1054
+ const baseDirection = gridToDirection(base.div(frames.sub(1)));
1055
+ const rightDirection = gridToDirection(base.add(vec2(1, 0)).div(frames.sub(1)));
1056
+ const upDirection = gridToDirection(base.add(vec2(0, 1)).div(frames.sub(1)));
1057
+ const diagonalDirection = gridToDirection(base.add(1).div(frames.sub(1)));
1058
+ const splitOnAntiDiagonal = foldCell.or(
1059
+ dot(rightDirection, upDirection).greaterThan(dot(baseDirection, diagonalDirection)),
1060
+ );
1061
+ orientation = splitOnAntiDiagonal.select(
1062
+ centerFraction.x.add(centerFraction.y).lessThanEqual(1).select(float(2), float(3)),
1063
+ centerFraction.x.greaterThan(centerFraction.y).select(float(0), float(1)),
1064
+ );
1065
+ }
1066
+ const horizontal = orientation.equal(0);
1067
+ const antiDiagonal = orientation.greaterThanEqual(2);
1068
+ const antiLower = orientation.equal(2);
1069
+ const right = base.add(vec2(1, 0));
1070
+ const up = base.add(vec2(0, 1));
1071
+ const diagonal = base.add(1);
1072
+ const frame0 = orientation.equal(3).select(diagonal, base);
1073
+ const frame1 = horizontal.or(antiLower).select(right, up);
1074
+ const frame2 = antiDiagonal.select(antiLower.select(up, right), diagonal);
1075
+ return { base, orientation, horizontal, antiDiagonal, antiLower, frame0, frame1, frame2 };
1076
+ };
1077
+ const vertexGrid = directionToGrid(samplingCameraPosition.normalize()).mul(frames.sub(1));
1078
+ const vertexTriangle = selectFrameTriangle(vertexGrid);
1079
+ // Carry the selected triangle across intact. Re-selecting it in the
1080
+ // fragment could pair a corner projection with the wrong atlas cell at a tie.
1081
+ const cardTriangle = varying(
1082
+ vec3(vertexGrid, vertexTriangle.orientation),
1083
+ 'vImpostorCardTriangle',
1084
+ ).setInterpolation('flat');
1085
+ // For steep views of an upper-hemisphere capture, align the sampled
1086
+ // planes nearer the bottom of the object. A center-plane rotation can
1087
+ // project the base of a tall asset to different places in adjacent views.
1088
+ const elevationSine = clampedCameraDirection.y;
1089
+ const cardAnchorHeight = fullSphere
1090
+ ? float(0)
1091
+ : elevationSine.mul(elevationSine)
1092
+ .mul(smoothstep(0.35, 0.8, elevationSine))
1093
+ .mul(descriptor.boundsMin[1] * 0.8);
1094
+ const cardAnchor = vec3(0, cardAnchorHeight, 0);
1095
+ const anchoredCardCorner = fullSphere ? samplingBillboardPosition : Fn(() => {
1096
+ const planeNormal = cross(cameraRightLocal, billboardUpLocal);
1097
+ // Move along the live camera ray so the rasterized card stays unchanged.
1098
+ const shift = cardAnchorHeight.mul(planeNormal.y)
1099
+ .div(max(dot(samplingCameraPosition, planeNormal), 0.000001));
1100
+ return mix(samplingBillboardPosition, samplingCameraPosition, shift);
1101
+ })();
1102
+ const projectCardCorner = Fn(([frame, corner, eye, anchor]) => {
1103
+ const normal = gridToDirection(frame.div(frames.sub(1))).toVar();
1104
+ const basis = frameBasis(normal).toVar();
1105
+ // Aim between the live and captured views. In the orthographic limit,
1106
+ // this rotates the card into the capture plane without stretching it.
1107
+ // Projecting directly along the live view makes oblique captures stretch
1108
+ // as they come into the blend.
1109
+ const projectionEye = eye.add(normal.mul(eye.length())).toVar();
1110
+ const eyeDepth = dot(projectionEye.sub(anchor), normal).toVar();
1111
+ const cornerDepth = dot(corner.sub(anchor), normal).toVar();
1112
+ const projected = corner.mul(eyeDepth).sub(projectionEye.mul(cornerDepth)).toVar();
1113
+ // Interpolate the homogeneous position, then divide in the fragment.
1114
+ // Dividing at the corners would skew the projective mapping diagonally.
1115
+ return vec3(dot(projected, basisMember(basis, 'right')),
1116
+ dot(projected, basisMember(basis, 'up')), eyeDepth.sub(cornerDepth));
1117
+ }).setLayout({
1118
+ name: 'projectImpostorCardCorner',
1119
+ type: 'vec3',
1120
+ inputs: [
1121
+ { name: 'frame', type: 'vec2' },
1122
+ { name: 'corner', type: 'vec3' },
1123
+ { name: 'eye', type: 'vec3' },
1124
+ { name: 'anchor', type: 'vec3' },
1125
+ ],
1126
+ });
1127
+ const createFrameSampler = (withReprojection, withCardProjection = false) => {
1128
+ const buildFrameSample = ([frame, planePosition, rayDirection, bounds, cardProjection]) => {
931
1129
  const frameDirection = singleView
932
1130
  ? singleCaptureDirection
933
1131
  : gridToDirection(frame.div(frames.sub(1)));
@@ -946,10 +1144,10 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
946
1144
  const framePlanePosition = planePosition.sub(rayDirection.mul(
947
1145
  dot(planePosition, frameDirection).div(safeRayPlaneDenominator),
948
1146
  ));
949
- const projectedFrameUv = vec2(
950
- dot(framePlanePosition, right),
951
- dot(framePlanePosition, up),
952
- ).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
1147
+ const projectedPlane = withCardProjection
1148
+ ? cardProjection.xy.div(max(cardProjection.z, 0.000001))
1149
+ : vec2(dot(framePlanePosition, right), dot(framePlanePosition, up));
1150
+ const projectedFrameUv = projectedPlane.sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
953
1151
  const interiorResolution = max(frameResolution.sub(padding.mul(2)), 1);
954
1152
  const gutterUv = padding.div(interiorResolution);
955
1153
  const minimumFrameUv = gutterUv.negate();
@@ -1305,23 +1503,31 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1305
1503
  let sampleFrame = functions.get(builder);
1306
1504
  if (!sampleFrame) {
1307
1505
  sampleFrame = Fn(buildFrameSample).setLayout({
1308
- name: withReprojection ? 'sampleReprojectedImpostorFrame' : 'samplePlanarImpostorFrame',
1506
+ name: withReprojection ? 'sampleReprojectedImpostorFrame' : withCardProjection
1507
+ ? 'sampleProjectedImpostorCard' : 'samplePlanarImpostorFrame',
1309
1508
  type: 'ImpostorFrameSample',
1310
1509
  inputs: [
1311
1510
  { name: 'frame', type: 'vec2' },
1312
1511
  { name: 'planePosition', type: 'vec3' },
1313
1512
  { name: 'rayDirection', type: 'vec3' },
1314
1513
  { name: 'bounds', type: 'vec4' },
1514
+ ...(withCardProjection ? [{ name: 'cardProjection', type: 'vec3' }] : []),
1315
1515
  ],
1316
1516
  });
1317
1517
  functions.set(builder, sampleFrame);
1318
1518
  }
1319
- return (frame, planePosition, rayDirection) => sampleFrame(frame, planePosition, rayDirection,
1320
- viewBounds.element(int(frame.y.mul(frames).add(frame.x))));
1519
+ return (frame, planePosition, rayDirection, cardProjection) => sampleFrame(
1520
+ frame, planePosition, rayDirection,
1521
+ viewBounds.element(int(frame.y.mul(frames).add(frame.x))),
1522
+ ...(withCardProjection ? [cardProjection] : []),
1523
+ );
1321
1524
  };
1322
1525
  };
1323
1526
  const planarFrameSamplers = createFrameSampler(false);
1324
1527
  const reprojectedFrameSamplers = features.reprojection ? createFrameSampler(true) : null;
1528
+ const cardFrameSamplers = features.interpolation && features.perspectiveCorrection && !features.reprojection
1529
+ ? createFrameSampler(false, true)
1530
+ : null;
1325
1531
  const buildBlendedSample = ([], builder) => {
1326
1532
  const samplePlanarFrame = planarFrameSamplers(builder);
1327
1533
  const sampleReprojectedFrame = reprojectedFrameSamplers ? reprojectedFrameSamplers(builder) : null;
@@ -1336,6 +1542,9 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1336
1542
  const rayDirection = usePerspectiveCorrection
1337
1543
  ? samplingCameraLocal.sub(planeLocal).normalize()
1338
1544
  : centerViewDirection;
1545
+ const sampleCardFrame = usePerspectiveCorrection && cardFrameSamplers
1546
+ ? cardFrameSamplers(builder)
1547
+ : null;
1339
1548
  if (singleView) {
1340
1549
  const singleFrame = vec2(0, 0);
1341
1550
  const raw = features.reprojection
@@ -1361,11 +1570,11 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1361
1570
  capturedCoverage,
1362
1571
  distanceCoverage,
1363
1572
  validity,
1364
- float(0),
1365
- float(0),
1366
1573
  );
1367
1574
  }
1368
- const centerGrid = directionToGrid(centerViewDirection).mul(frames.sub(1));
1575
+ const centerGrid = sampleCardFrame
1576
+ ? cardTriangle.xy
1577
+ : directionToGrid(centerViewDirection).mul(frames.sub(1));
1369
1578
  // Match every card point to a capture along its physical point-to-camera
1370
1579
  // ray. Adding the card offset instead mirrors this correction: a shallow
1371
1580
  // box makes that inversion visible immediately on its near/far corners.
@@ -1374,63 +1583,35 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1374
1583
  samplingCameraLocal.add(planeLocal.mul(PERSPECTIVE_RAY_PLANE_SIGN)).normalize(),
1375
1584
  ).mul(frames.sub(1))
1376
1585
  : centerGrid;
1377
- const maximumBase = vec2(frames.sub(2));
1378
- const centerBase = min(floor(centerGrid), maximumBase);
1379
- // Keep one frame triangle for the whole card. Switching discrete atlas
1380
- // cells per fragment creates visible vertical bands even with perfectly
1381
- // valid source frames. Perspective correction instead adjusts the three
1382
- // weights inside the center-selected triangle and clamps to its simplex.
1383
- const weightGrid = features.cellCorrection
1384
- ? perspectiveGrid
1385
- : centerGrid;
1386
- const base = centerBase;
1387
- const centerFraction = centerGrid.sub(base);
1388
- const fraction = weightGrid.sub(base);
1389
- const horizontal = centerFraction.x.greaterThan(centerFraction.y);
1390
- const ordinaryFrame1 = base.add(horizontal.select(vec2(1, 0), vec2(0, 1)));
1586
+ const { base, horizontal, antiDiagonal, antiLower, frame0, frame1, frame2 } = selectFrameTriangle(
1587
+ centerGrid, sampleCardFrame ? cardTriangle.z : null,
1588
+ );
1589
+ const fraction = (features.cellCorrection ? perspectiveGrid : centerGrid).sub(base);
1391
1590
  const ordinaryWeights = horizontal.select(
1392
1591
  vec3(float(1).sub(fraction.x), fraction.x.sub(fraction.y), fraction.y),
1393
1592
  vec3(float(1).sub(fraction.y), fraction.y.sub(fraction.x), fraction.x),
1394
1593
  );
1395
- const foldCell = fullSphere
1396
- ? bool(false)
1397
- : base.x.add(base.y).equal(frames.sub(2));
1398
- const baseDirection = gridToDirection(base.div(frames.sub(1)));
1399
- const rightDirection = gridToDirection(base.add(vec2(1, 0)).div(frames.sub(1)));
1400
- const upDirection = gridToDirection(base.add(vec2(0, 1)).div(frames.sub(1)));
1401
- const diagonalDirection = gridToDirection(base.add(1).div(frames.sub(1)));
1402
- const antiDiagonal = foldCell.or(
1403
- dot(rightDirection, upDirection).greaterThan(dot(baseDirection, diagonalDirection)),
1404
- );
1405
- const antiLower = centerFraction.x.add(centerFraction.y).lessThanEqual(1);
1406
- const antiFrame0 = antiLower.select(base, base.add(1));
1407
- const antiFrame1 = antiLower.select(base.add(vec2(1, 0)), base.add(vec2(0, 1)));
1408
- const antiFrame2 = antiLower.select(base.add(vec2(0, 1)), base.add(vec2(1, 0)));
1409
1594
  const antiWeights = antiLower.select(
1410
1595
  vec3(float(1).sub(fraction.x).sub(fraction.y), fraction.x, fraction.y),
1411
1596
  vec3(fraction.x.add(fraction.y).sub(1), float(1).sub(fraction.x), float(1).sub(fraction.y)),
1412
1597
  );
1413
- const frame0 = antiDiagonal.select(antiFrame0, base);
1414
- const frame1 = antiDiagonal.select(antiFrame1, ordinaryFrame1);
1415
- const frame2 = antiDiagonal.select(antiFrame2, base.add(1));
1416
1598
  const weights = max(antiDiagonal.select(antiWeights, ordinaryWeights), vec3(0)).toVar();
1417
1599
  weights.divAssign(max(dot(weights, vec3(1)), 0.0001));
1418
1600
  // Compact angular support: on each triangle edge, `blendZone` is the
1419
1601
  // fraction over which both endpoint captures contribute. Unlike exponent
1420
1602
  // sharpening, this gives capture vertices a real single-view neighborhood
1421
1603
  // instead of letting tiny contributors affect virtually the whole cell.
1422
- weights.assign(max(weights.sub(blendCutoff), vec3(0)));
1604
+ // Planar captures need more overlap to move between offset contours.
1605
+ const angularCutoff = features.reprojection ? blendCutoff : blendCutoff.mul(0.35);
1606
+ weights.assign(max(weights.sub(angularCutoff), vec3(0)));
1423
1607
  weights.divAssign(max(dot(weights, vec3(1)), 0.0001));
1424
- const frame0Nearest = weights.x.greaterThanEqual(weights.y)
1425
- .and(weights.x.greaterThanEqual(weights.z));
1426
- // TSL expressions are lazy. Snapshot the winner before raw mode mutates
1427
- // `weights` to [1, 0, 0], otherwise the expression is re-evaluated later
1428
- // and silently falls back to frame0 instead of the reported nearest frame.
1429
- const nearestFrame = frame0Nearest.select(
1430
- frame0,
1431
- weights.y.greaterThanEqual(weights.z).select(frame1, frame2),
1432
- ).toVar('impostorNearestFrame');
1433
1608
  if (!features.interpolation) {
1609
+ const frame0Nearest = weights.x.greaterThanEqual(weights.y)
1610
+ .and(weights.x.greaterThanEqual(weights.z));
1611
+ const nearestFrame = frame0Nearest.select(
1612
+ frame0,
1613
+ weights.y.greaterThanEqual(weights.z).select(frame1, frame2),
1614
+ );
1434
1615
  const raw = samplePlanarFrame(nearestFrame, planeLocal, rayDirection);
1435
1616
  return BlendedSample(
1436
1617
  frameMember(raw, 'base'),
@@ -1441,19 +1622,20 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1441
1622
  frameMember(raw, 'surfaceAlpha'),
1442
1623
  frameMember(raw, 'surfaceAlpha'),
1443
1624
  frameMember(raw, 'validity'),
1444
- float(0),
1445
- float(0),
1446
1625
  );
1447
1626
  }
1448
- const a = features.reprojection
1449
- ? sampleReprojectedFrame(frame0, planeLocal, rayDirection)
1450
- : samplePlanarFrame(frame0, planeLocal, rayDirection);
1451
- const b = features.reprojection
1452
- ? sampleReprojectedFrame(frame1, planeLocal, rayDirection)
1453
- : samplePlanarFrame(frame1, planeLocal, rayDirection);
1454
- const c = features.reprojection
1455
- ? sampleReprojectedFrame(frame2, planeLocal, rayDirection)
1456
- : samplePlanarFrame(frame2, planeLocal, rayDirection);
1627
+ const resolveFrame = (frame, key) => {
1628
+ if (sampleCardFrame) {
1629
+ const corner = projectCardCorner(
1630
+ vertexTriangle[key], anchoredCardCorner, samplingCameraPosition, cardAnchor,
1631
+ );
1632
+ return sampleCardFrame(frame, planeLocal, rayDirection, varying(corner, 'vImpostorCard_' + key));
1633
+ }
1634
+ return (sampleReprojectedFrame ?? samplePlanarFrame)(frame, planeLocal, rayDirection);
1635
+ };
1636
+ const a = resolveFrame(frame0, 'frame0');
1637
+ const b = resolveFrame(frame1, 'frame1');
1638
+ const c = resolveFrame(frame2, 'frame2');
1457
1639
  const angularWeights = weights.toVar('impostorAngularWeights');
1458
1640
  if (features.depthWeights) {
1459
1641
  // A reprojected frame sample only represents this camera ray while its
@@ -1512,13 +1694,15 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1512
1694
  float(1).sub(largestAngularWeight),
1513
1695
  ).toVar('impostorCoverageTransition');
1514
1696
  weights.mulAssign(surfaceAlpha).mulAssign(sampleValidity);
1515
- weights.divAssign(max(dot(weights, vec3(1)), 0.0001));
1516
- const weighted3 = (field) => frameMember(a, field).mul(weights.x)
1517
- .add(frameMember(b, field).mul(weights.y))
1518
- .add(frameMember(c, field).mul(weights.z));
1519
- const weighted4 = (field) => frameMember(a, field).mul(weights.x)
1520
- .add(frameMember(b, field).mul(weights.y))
1521
- .add(frameMember(c, field).mul(weights.z));
1697
+ const capturedCoverage = dot(weights, vec3(1)).toVar();
1698
+ // Prefer the better-aligned texture sooner. Keeping these weights out of
1699
+ // the contour, lighting normals and depth lets those transition smoothly.
1700
+ const textureWeights = weights.mul(weights).toVar();
1701
+ textureWeights.divAssign(max(dot(textureWeights, vec3(1)), 0.00000001));
1702
+ weights.divAssign(max(capturedCoverage, 0.0001));
1703
+ const weighted = (field, blend = weights) => frameMember(a, field).mul(blend.x)
1704
+ .add(frameMember(b, field).mul(blend.y))
1705
+ .add(frameMember(c, field).mul(blend.z));
1522
1706
  // A weighted average of inside/outside SDFs makes whole features cross the
1523
1707
  // 0.5 contour together near a frame bisector. Normalized log-sum-exp acts
1524
1708
  // as a smooth union: it preserves thin features and equals the authored
@@ -1528,7 +1712,10 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1528
1712
  // retain disoccluded thin parts; dense grids can use a near-linear blend,
1529
1713
  // preventing a tiny-weight frame from popping in a whole feature. This is
1530
1714
  // derived only from sampling density, never from asset classification.
1531
- const contourSharpness = impostorContourUnionSharpness(descriptor.frames);
1715
+ // The planar warp can leave nearby features slightly misaligned. A
1716
+ // gentler union keeps those contours from briefly reproducing both views.
1717
+ const contourSharpness = impostorContourUnionSharpness(descriptor.frames)
1718
+ * (features.reprojection ? 1 : 0.5);
1532
1719
  // A contour from a newly entering capture must begin as an ordinary
1533
1720
  // weighted SDF contribution. Applying the full smooth-union temperature
1534
1721
  // at an infinitesimal angular weight makes an entire disoccluded feature
@@ -1544,59 +1731,52 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1544
1731
  .toVar('impostorCoverageContributions');
1545
1732
  const coverageSupport = dot(coverageContributions, vec3(1))
1546
1733
  .toVar('impostorCoverageSupport');
1547
- const coverageWeights = coverageContributions
1548
- .div(max(coverageSupport, 0.0001))
1549
- .toVar('impostorCoverageWeights');
1550
- // Do not normalize occupancy. If only a low-weight capture claims a pixel,
1551
- // that claim remains low confidence instead of becoming a second opaque
1552
- // silhouette. Normalization is retained solely for blending attributes of
1553
- // samples that have already passed this coverage test.
1554
- const perspectiveCapturedCoverage = dot(
1555
- coverageContributions,
1556
- surfaceAlpha,
1557
- );
1558
1734
  const coverageDistanceSamples = vec3(
1559
1735
  frameMember(a, 'contour'),
1560
1736
  frameMember(b, 'contour'),
1561
1737
  frameMember(c, 'contour'),
1562
1738
  );
1563
- const unionDistanceCoverage = max(
1564
- dot(coverageWeights, exp(coverageDistanceSamples.mul(effectiveContourSharpness))),
1565
- 0.0001,
1566
- ).log().div(effectiveContourSharpness);
1567
- // The SDF provides a stable subpixel contour, but it may not expand beyond
1568
- // actual captured occupancy. This cap removes disjoint depth layers that a
1569
- // smooth union would otherwise preserve from multiple camera frames.
1570
- const perspectiveDistanceCoverage = min(
1571
- unionDistanceCoverage,
1572
- perspectiveCapturedCoverage,
1573
- );
1574
- const coverageDistanceMean = dot(coverageWeights, coverageDistanceSamples);
1575
- const coverageDistanceDeviation = dot(
1576
- coverageWeights,
1577
- abs(coverageDistanceSamples.sub(coverageDistanceMean)),
1578
- );
1739
+ const signedDistances = coverageDistanceSamples.sub(0.5);
1740
+ let edgeDistance;
1741
+ if (features.reprojection) {
1742
+ // Fold the threshold into the smooth union so it has the same zero
1743
+ // crossing as log-sum-exp without taking a logarithm.
1744
+ edgeDistance = dot(
1745
+ coverageContributions, exp(signedDistances.mul(effectiveContourSharpness)).sub(1),
1746
+ ).div(max(coverageSupport, 0.0001).mul(effectiveContourSharpness));
1747
+ } else {
1748
+ // Missing planar crops vote outside. Renormalizing their weights away
1749
+ // lets a barely active view reveal a whole disconnected silhouette.
1750
+ const cropDistances = mix(vec3(-0.5), signedDistances, sampleValidity).toVar();
1751
+ // A mild quadratic bias retains fine silhouettes without bringing
1752
+ // whole regions across the threshold together in sparse view blends.
1753
+ const unionBias = min(effectiveContourSharpness.mul(0.4), 1);
1754
+ edgeDistance = dot(visibilityWeights, cropDistances.add(cropDistances.mul(cropDistances).mul(unionBias)));
1755
+ }
1579
1756
  return BlendedSample(
1580
- weighted4('base'),
1581
- weighted3('normalLocal').normalize(),
1582
- weighted3('positionLocal'),
1583
- weighted3('orm'),
1584
- weighted3('emissive'),
1585
- perspectiveCapturedCoverage,
1586
- perspectiveDistanceCoverage,
1757
+ weighted('base', textureWeights),
1758
+ weighted('normalLocal').normalize(),
1759
+ weighted('positionLocal'),
1760
+ weighted('orm'),
1761
+ weighted('emissive', textureWeights),
1762
+ capturedCoverage,
1763
+ edgeDistance.add(0.5),
1587
1764
  coverageSupport,
1588
- // View-domain antialiasing complements screen-space fwidth. It widens
1589
- // only where the contributing captures disagree about occupancy, so a
1590
- // moving contour crosses pixels over an angular interval rather than in
1591
- // one frame while stable interiors remain sharp.
1592
- coverageDistanceDeviation.mul(0.2).mul(transition),
1593
- transition,
1594
1765
  );
1595
1766
  };
1596
1767
  const blendImpostor = Fn(buildBlendedSample);
1597
1768
 
1598
1769
  const sample = blendImpostor().toVar('impostorSample');
1599
- const reconstructedWorldPosition = modelWorldMatrix.mul(vec4(blendedMember(sample, 'positionLocal'), 1)).xyz;
1770
+ // Lighting, depth and shadows work in the mesh's space.
1771
+ const capturedPosition = Fn((_, builder) => {
1772
+ const position = blendedMember(sample, 'positionLocal');
1773
+ return instanceSpace(builder)?.fragment.toMeshPoint(position) ?? position;
1774
+ })().toVar('impostorCapturedPosition');
1775
+ const capturedNormal = Fn((_, builder) => {
1776
+ const normal = blendedMember(sample, 'normalLocal');
1777
+ return instanceSpace(builder)?.fragment.toMeshNormal(normal) ?? normal;
1778
+ })();
1779
+ const reconstructedWorldPosition = modelWorldMatrix.mul(vec4(capturedPosition, 1)).xyz;
1600
1780
  const material = new CapturedSurfaceMaterial({
1601
1781
  name: 'Needle PBR impostor TSL',
1602
1782
  side: DoubleSide,
@@ -1605,10 +1785,7 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1605
1785
  depthWrite: true,
1606
1786
  });
1607
1787
  const distanceCoverage = blendedMember(sample, 'distanceCoverage');
1608
- const coverageWidth = max(
1609
- max(fwidth(distanceCoverage), blendedMember(sample, 'coverageWidth')),
1610
- 1 / 255,
1611
- );
1788
+ const coverageWidth = max(fwidth(distanceCoverage), 1 / 255);
1612
1789
  const screenDistanceCoverage = smoothstep(
1613
1790
  float(0.5).sub(coverageWidth),
1614
1791
  float(0.5).add(coverageWidth),
@@ -1623,8 +1800,11 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1623
1800
  // the same camera-facing geometry (the shadow camera during a shadow pass).
1624
1801
  material.positionNode = displayBillboardPosition;
1625
1802
  material.castShadowPositionNode = displayBillboardPosition;
1626
- material.colorNode = vec4(blendedMember(sample, 'base').rgb, screenCoverage);
1627
- material.normalNode = transformNormalToView(blendedMember(sample, 'normalLocal'));
1803
+ const multisampleCoverage = Fn(([], builder) => (
1804
+ rendererUsesMultisampleCoverage(builder.renderer) ? screenCoverage : float(1)
1805
+ ))();
1806
+ material.colorNode = vec4(blendedMember(sample, 'base').rgb, multisampleCoverage);
1807
+ material.normalNode = transformNormalToView(capturedNormal);
1628
1808
  material.aoNode = blendedMember(sample, 'orm').r;
1629
1809
  material.roughnessNode = blendedMember(sample, 'orm').g;
1630
1810
  material.metalnessNode = blendedMember(sample, 'orm').b;
@@ -1635,12 +1815,22 @@ export function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures =
1635
1815
  // frame is promoted to a faint rectangular card outline. Opaque contour
1636
1816
  // samples bypass that gate so real thin features retain silhouette quality.
1637
1817
  const cropSupported = blendedMember(sample, 'cropSupport').greaterThanEqual(0.25);
1638
- material.maskNode = screenCoverage.greaterThanEqual(0.25).and(
1639
- screenCoverage.greaterThanEqual(0.5).or(cropSupported),
1640
- );
1641
- material.maskShadowNode = distanceCoverage.mul(mappingVisibility).greaterThanEqual(0.5);
1818
+ // A filter footprint can reach past every contributing capture. Such
1819
+ // fragments have no captured color and would leave a dark outline.
1820
+ // Depth reconstruction also needs enough occupancy to reject a stray root
1821
+ // from a low-weight capture. Make that a mask so it cannot fade solid pixels.
1822
+ const captured = blendedMember(sample, 'capturedCoverage')
1823
+ .greaterThanEqual(features.reprojection ? 0.25 : 0.0001);
1824
+ const solidContour = distanceCoverage.mul(mappingVisibility).greaterThanEqual(0.5);
1825
+ material.maskNode = Fn(([], builder) => {
1826
+ if (!rendererUsesMultisampleCoverage(builder.renderer)) return solidContour.and(captured);
1827
+ return screenCoverage.greaterThanEqual(0.25).and(
1828
+ screenCoverage.greaterThanEqual(0.5).or(cropSupported),
1829
+ ).and(captured);
1830
+ })();
1831
+ material.maskShadowNode = solidContour.and(captured);
1642
1832
  material.alphaToCoverage = true;
1643
- material.capturedPositionNode = blendedMember(sample, 'positionLocal');
1833
+ material.capturedPositionNode = capturedPosition;
1644
1834
  // Offset only the shadow writer: different capture views can disagree slightly.
1645
1835
  material.depthNode = capturedSurfaceDepth(material.capturedPositionNode, IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS);
1646
1836
  material.receivedShadowPositionNode = reconstructedWorldPosition;