@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
@@ -0,0 +1,771 @@
1
+ // TSL's struct declarations erase members; GPU rendering tests cover this graph.
2
+ // @ts-nocheck
3
+ import { capturedSurfaceDepth } from '../rendering/captured-surface-depth.js';
4
+ import {
5
+ DataTexture,
6
+ FloatType,
7
+ RGBAFormat,
8
+ RedIntegerFormat,
9
+ UnsignedIntType,
10
+ NearestFilter,
11
+ LinearFilter,
12
+ DoubleSide,
13
+ BackSide,
14
+ FrontSide,
15
+ } from "three/webgpu";
16
+ import {
17
+ Fn,
18
+ If,
19
+ Loop,
20
+ Break,
21
+ attribute,
22
+ varying,
23
+ positionLocal,
24
+ modelWorldMatrixInverse,
25
+ cameraPosition,
26
+ cameraWorldMatrix,
27
+ cameraProjectionMatrix,
28
+ vec2,
29
+ vec3,
30
+ vec4,
31
+ float,
32
+ int,
33
+ uint,
34
+ dot,
35
+ abs,
36
+ max,
37
+ min,
38
+ sign,
39
+ texture,
40
+ textureLoad,
41
+ ivec2,
42
+ normalize,
43
+ floor,
44
+ fract,
45
+ modelWorldMatrix,
46
+ cameraNear,
47
+ transformNormalToView,
48
+ struct,
49
+ uniform,
50
+ } from "three/tsl";
51
+ import {CapturedSurfaceMaterial} from '../rendering/captured-surface-material.js';
52
+ import {refineSurfaceCrossing} from './box-impostor-surface-search.js';
53
+ import { applyBoxFaces } from "./box-impostor-faces.js";
54
+ import { applyBoxProjection } from "./box-impostor-projection.js";
55
+ import {
56
+ normalizeBoxImpostorDisplay,
57
+ boxTransparency,
58
+ boxDepthMode,
59
+ } from "./box-impostor-display-settings.js";
60
+ import {
61
+ BOX_FACE_AXES,
62
+ BOX_OCCUPANCY_RESOLUTION,
63
+ } from "./box-impostor-metadata.js";
64
+
65
+ /** Six orthographic depth fields, one compiled ray budget and one shared PBR
66
+ * material. The same graph runs on native WebGPU and Three's WebGL2 backend.
67
+ * @param {import('./box-impostor-metadata.js').BoxImpostorDescriptor} descriptor
68
+ * @param {{baseColor:import('three').Texture,normalDepth:import('three').Texture,orm:import('three').Texture,emissive:import('three').Texture}} maps */
69
+ export function createBoxImpostorMaterial(descriptor, maps) {
70
+ return createBoxImpostorMaterialVariant(descriptor, maps, {filtering:true});
71
+ }
72
+
73
+ /** Internal compile-time variants for matched quality and cost measurements. */
74
+ export function createBoxImpostorMaterialVariant(descriptor, maps, {filtering = false} = {}) {
75
+ const settings = normalizeBoxImpostorDisplay(descriptor);
76
+ const alphaCutoff = uniform(settings.alphaCutoff);
77
+ const transparency = boxTransparency(descriptor, settings);
78
+ const minimumAlpha = transparency === "cutout" ? alphaCutoff : float(1 / 255);
79
+ // Opaque/masked captures store geometric coverage in base alpha as well.
80
+ // This also supports older MRT captures whose unused ORM alpha was opaque.
81
+ const surfaceCoverage = (ormAlpha,baseAlpha) => filtering && descriptor.alphaMode !== 'blend' ? min(ormAlpha,baseAlpha) : ormAlpha;
82
+ const decodeNormal = encoded => {
83
+ const packed=encoded.mul(2).sub(1);
84
+ const normal=vec3(packed,float(1).sub(abs(packed.x)).sub(abs(packed.y))).toVar();
85
+ If(normal.z.lessThan(0),()=>{normal.xy.assign(vec2(1).sub(abs(normal.yx)).mul(sign(normal.xy.add(1e-20))));});
86
+ return normal.normalize();
87
+ };
88
+ const filteredNormal = (uv,depth,tolerance,nearest,alpha,sampled=texture(maps.normalDepth,uv).level(0),ormAlpha=texture(maps.orm,uv).level(0).a) => {
89
+ sampled=sampled.toVar();
90
+ const coverage=max(descriptor.alphaMode==='blend'?ormAlpha:alpha,1e-10);
91
+ const nearestNormal=decodeNormal(nearest.rg),result=decodeNormal(sampled.rg.div(coverage)).toVar();
92
+ const sampledDepth=sampled.b.mul(65280).add(sampled.a.mul(255)).div(65535);
93
+ const nearestDepth=nearest.b.mul(65280).add(nearest.a.mul(255)).div(65535);
94
+ // Bilinear oct coordinates suffice on smooth interiors. Decode individual
95
+ // taps only at a wrap, coverage edge or depth-layer discontinuity.
96
+ If(nearestNormal.z.lessThan(0).or(dot(result,nearestNormal).lessThan(.75)).or(coverage.lessThan(.9999)).or(abs(sampledDepth.sub(nearestDepth)).greaterThan(tolerance)),()=>{
97
+ const p=uv.mul(descriptor.atlasResolution).sub(.5),lo=floor(p),f=fract(p);
98
+ const normal=vec3(0).toVar(),weights=float(0).toVar();
99
+ for(const [x,y] of [[0,0],[1,0],[0,1],[1,1]]) {
100
+ const texel=ivec2(lo.add(vec2(x,y)).clamp(0,descriptor.atlasResolution-1));
101
+ const packed=textureLoad(maps.normalDepth,texel).toVar();
102
+ const alpha=textureLoad(maps.baseColor,texel).a;
103
+ const coverage=descriptor.alphaMode==='blend'?textureLoad(maps.orm,texel).a:alpha;
104
+ const capturedDepth=packed.b.mul(65280).add(packed.a.mul(255)).div(65535);
105
+ const supported=coverage.greaterThan(1e-4).and(alpha.greaterThanEqual(minimumAlpha.mul(coverage))).and(abs(capturedDepth.sub(depth)).lessThanEqual(tolerance));
106
+ If(supported,()=>{
107
+ const weight=(x?f.x:float(1).sub(f.x)).mul(y?f.y:float(1).sub(f.y)).mul(coverage);
108
+ normal.addAssign(decodeNormal(packed.rg.div(max(coverage,1e-10))).mul(weight));weights.addAssign(weight);
109
+ });
110
+ }
111
+ // Decode before filtering: octahedral coordinates wrap at the back pole.
112
+ result.assign(weights.greaterThan(1e-10).select(normal.normalize(),nearestNormal));
113
+ });
114
+ return result;
115
+ };
116
+ for (const map of Object.values(maps)) {
117
+ if (map.minFilter !== LinearFilter || map.magFilter !== LinearFilter) {
118
+ map.minFilter = map.magFilter = LinearFilter;
119
+ map.generateMipmaps = false;
120
+ map.needsUpdate = true;
121
+ }
122
+ }
123
+ const material = new CapturedSurfaceMaterial({
124
+ name: "Box impostor",
125
+ side: descriptor.mode !== "fitted" ? DoubleSide : BackSide,
126
+ alphaHash: transparency === "dithered",
127
+ transparent: transparency === "blended",
128
+ depthWrite: transparency !== "blended",
129
+ forceSinglePass: true,
130
+ });
131
+ const rectData = new Float32Array(descriptor.boxes.length * 6 * 4);
132
+ descriptor.boxes.forEach((b, i) =>
133
+ b.views.forEach((r, j) =>
134
+ rectData.set(
135
+ [
136
+ (r[0] + descriptor.padding) / descriptor.atlasResolution,
137
+ (r[1] + descriptor.padding) / descriptor.atlasResolution,
138
+ (r[2] - 2 * descriptor.padding) / descriptor.atlasResolution,
139
+ (r[3] - 2 * descriptor.padding) / descriptor.atlasResolution,
140
+ ],
141
+ (i * 6 + j) * 4,
142
+ ),
143
+ ),
144
+ );
145
+ const rects = new DataTexture(
146
+ rectData,
147
+ 6,
148
+ descriptor.boxes.length,
149
+ RGBAFormat,
150
+ FloatType,
151
+ );
152
+ rects.needsUpdate = true;
153
+ rects.magFilter = rects.minFilter = NearestFilter;
154
+ material.addEventListener("dispose", () => rects.dispose());
155
+ const center = attribute("boxCenter", "vec3"),
156
+ half = attribute("boxHalfSize", "vec3");
157
+ const ax = attribute("boxAxisX", "vec3"),
158
+ ay = attribute("boxAxisY", "vec3"),
159
+ az = attribute("boxAxisZ", "vec3");
160
+ const toBox = (p) => vec3(dot(p, ax), dot(p, ay), dot(p, az));
161
+ const fromBox = (p) => ax.mul(p.x).add(ay.mul(p.y)).add(az.mul(p.z));
162
+ const eye = modelWorldMatrixInverse.mul(vec4(cameraPosition, 1)).xyz;
163
+ const viewAxis = modelWorldMatrixInverse
164
+ .mul(cameraWorldMatrix.mul(vec4(0, 0, 1, 0)))
165
+ .xyz.normalize();
166
+ const perspective = cameraProjectionMatrix.element(3).w.equal(0);
167
+ let proxy = positionLocal;
168
+ if (descriptor.mode !== "fitted") {
169
+ proxy = Fn((_, builder) => {
170
+ const delta = eye.sub(center);
171
+ const forward = perspective.and(delta.length().greaterThan(1e-6)).select(normalize(delta), viewAxis);
172
+ const right = modelWorldMatrixInverse
173
+ .mul(cameraWorldMatrix.mul(vec4(0, 1, 0, 0)))
174
+ .xyz.cross(forward)
175
+ .normalize();
176
+ const up = forward.cross(right).normalize();
177
+ // Project all box corners onto the nearest eye-facing plane. This is a
178
+ // conservative perspective bound, including views close to a thin box.
179
+ const radius = half.length();
180
+ const distance = dot(eye.sub(center), forward);
181
+ const planeOffset = perspective.select(min(radius, distance.sub(cameraNear.mul(2))), radius);
182
+ const plane = center.add(forward.mul(planeOffset));
183
+ const lo = vec2(1e20).toVar(),
184
+ hi = vec2(-1e20).toVar();
185
+ for (const x of [-1, 1])
186
+ for (const y of [-1, 1])
187
+ for (const z of [-1, 1]) {
188
+ const corner = fromBox(half.mul(vec3(x, y, z)));
189
+ const scale = perspective.select(
190
+ max(distance.sub(planeOffset), 0.00001).div(
191
+ max(distance.sub(dot(corner, forward)), 0.00001),
192
+ ),
193
+ float(1),
194
+ );
195
+ const p = vec2(dot(corner, right), dot(corner, up)).mul(scale);
196
+ lo.assign(min(lo, p));
197
+ hi.assign(max(hi, p));
198
+ }
199
+ const corner = attribute("cardCorner", "vec2").add(1).mul(0.5);
200
+ const xy = lo.add(hi.sub(lo).mul(corner));
201
+ return plane.add(right.mul(xy.x)).add(up.mul(xy.y));
202
+ })();
203
+ material.positionNode = proxy;
204
+ material.castShadowPositionNode = proxy;
205
+ }
206
+ const raster = varying(proxy, "boxRasterPosition");
207
+ if (
208
+ boxDepthMode(descriptor, settings) === "projection" &&
209
+ descriptor.mode === "fitted" &&
210
+ settings.interpolation === "none"
211
+ ) {
212
+ material.side = FrontSide;
213
+ return applyBoxFaces({
214
+ material,
215
+ descriptor,
216
+ maps,
217
+ alphaCutoff,
218
+ transparency,
219
+ half,
220
+ toBox,
221
+ fromBox,
222
+ });
223
+ }
224
+ if (boxDepthMode(descriptor, settings) === "projection")
225
+ return applyBoxProjection({
226
+ material,
227
+ descriptor,
228
+ maps,
229
+ settings,
230
+ transparency,
231
+ alphaCutoff,
232
+ rects,
233
+ center,
234
+ half,
235
+ toBox,
236
+ fromBox,
237
+ eye,
238
+ viewAxis,
239
+ perspective,
240
+ raster,
241
+ });
242
+ const accelerated = descriptor.boxes.every((b) => b.depthBounds);
243
+ const gridSize = BOX_OCCUPANCY_RESOLUTION;
244
+ let occupancy;
245
+ if (
246
+ descriptor.boxes.every((b) => b.occupancy) &&
247
+ descriptor.boxes.some((b) =>
248
+ b.occupancy.some((word) => word !== 0xffffffff),
249
+ )
250
+ ) {
251
+ const wordsPerBox = gridSize ** 3 / 32;
252
+ const words = new Uint32Array(wordsPerBox * descriptor.boxes.length);
253
+ descriptor.boxes.forEach((box, index) =>
254
+ words.set(box.occupancy, index * wordsPerBox),
255
+ );
256
+ occupancy = new DataTexture(
257
+ words,
258
+ wordsPerBox,
259
+ descriptor.boxes.length,
260
+ RedIntegerFormat,
261
+ UnsignedIntType,
262
+ );
263
+ occupancy.needsUpdate = true;
264
+ material.addEventListener("dispose", () => occupancy.dispose());
265
+ }
266
+ const Result = struct(
267
+ { uv: "vec2", position: "vec3", normal: "vec3", valid: "float" },
268
+ "BoxImpostorHit",
269
+ );
270
+ const raycast = Fn((_, builder) => {
271
+ const ray = perspective.select(
272
+ normalize(raster.sub(eye)),
273
+ viewAxis.negate(),
274
+ );
275
+ const origin = perspective.select(
276
+ eye,
277
+ raster.sub(ray.mul(half.length().mul(4))),
278
+ );
279
+ const o = toBox(origin.sub(center)).div(half),
280
+ r = toBox(ray).div(half);
281
+ const safe = sign(r.add(1e-20)).mul(max(abs(r), 1e-10));
282
+ const a = vec3(-1).sub(o).div(safe),
283
+ b = vec3(1).sub(o).div(safe);
284
+ const enter = max(max(min(a, b).x, min(a, b).y), min(a, b).z).max(0);
285
+ const exit = min(min(max(a, b).x, max(a, b).y), max(a, b).z);
286
+ const occupiedStart = enter.toVar();
287
+ // This cover contains whole source voxel cubes. Only the empty space is
288
+ // skipped; the depth fields still determine the full-resolution surface.
289
+ if (occupancy) {
290
+ const gridOrigin = o.add(1).mul(gridSize / 2);
291
+ const gridRay = r.mul(gridSize / 2);
292
+ const step = sign(gridRay.add(1e-20));
293
+ const cell = floor(gridOrigin.add(gridRay.mul(enter)))
294
+ .clamp(0, gridSize - 1)
295
+ .toVar();
296
+ const inverse = vec3(1).div(safe.mul(gridSize / 2));
297
+ const delta = abs(inverse);
298
+ const next = cell
299
+ .add(step.add(1).mul(0.5))
300
+ .sub(gridOrigin)
301
+ .mul(inverse)
302
+ .toVar();
303
+ const t = enter.toVar();
304
+ occupiedStart.assign(exit.add(1));
305
+ Loop(gridSize * 3 + 1, () => {
306
+ If(t.greaterThan(exit), () => {
307
+ Break();
308
+ });
309
+ const cellIndex = uint(
310
+ cell.x.add(cell.y.mul(gridSize)).add(cell.z.mul(gridSize ** 2)),
311
+ ).toVar();
312
+ const word = textureLoad(
313
+ occupancy,
314
+ ivec2(int(cellIndex.shiftRight(5)), int(attribute("boxId", "float"))),
315
+ ).r;
316
+ const support = word.shiftRight(cellIndex.bitAnd(31)).bitAnd(1);
317
+ If(support.notEqual(uint(0)), () => {
318
+ occupiedStart.assign(t);
319
+ Break();
320
+ });
321
+ const edge = min(min(next.x, next.y), next.z).toVar();
322
+ const advance = vec3(
323
+ next.x.lessThanEqual(edge).select(1, 0),
324
+ next.y.lessThanEqual(edge).select(1, 0),
325
+ next.z.lessThanEqual(edge).select(1, 0),
326
+ );
327
+ cell.addAssign(advance.mul(step));
328
+ next.addAssign(advance.mul(delta));
329
+ t.assign(edge);
330
+ If(
331
+ cell.x
332
+ .lessThan(0)
333
+ .or(cell.x.greaterThan(gridSize - 1))
334
+ .or(cell.y.lessThan(0))
335
+ .or(cell.y.greaterThan(gridSize - 1))
336
+ .or(cell.z.lessThan(0))
337
+ .or(cell.z.greaterThan(gridSize - 1)),
338
+ () => {
339
+ Break();
340
+ },
341
+ );
342
+ });
343
+ }
344
+ const look = toBox(ray).negate();
345
+ const bestT = exit.add(1).toVar(),
346
+ bestUv = vec2(0).toVar(),
347
+ bestNormal = vec3(0, 0, 1).toVar(),
348
+ valid = float(0).toVar(),
349
+ found = float(0).toVar();
350
+ // A face-on capture can miss a nearer surface visible from another axis.
351
+ // Resolve each supported field and retain the closest validated surface.
352
+ const angles = abs(look).toVar();
353
+ const major = angles.x
354
+ .greaterThanEqual(angles.y)
355
+ .and(angles.x.greaterThanEqual(angles.z))
356
+ .select(
357
+ int(0),
358
+ angles.y.greaterThanEqual(angles.z).select(int(1), int(2)),
359
+ )
360
+ .toVar();
361
+ const nextAxis = major.add(1).mod(3),
362
+ lastAxis = major.add(2).mod(3);
363
+ const second = angles
364
+ .element(nextAxis)
365
+ .greaterThanEqual(angles.element(lastAxis))
366
+ .select(nextAxis, lastAxis)
367
+ .toVar();
368
+ const third = int(3).sub(major).sub(second).toVar();
369
+ Loop(
370
+ { start: 0, end: 6, type: "int", name: "viewIndex" },
371
+ ({ viewIndex: i }) => {
372
+ If(occupiedStart.greaterThan(exit), () => {
373
+ Break();
374
+ });
375
+ valid.assign(0);
376
+ const rank = i.mod(3);
377
+ const axis = rank
378
+ .equal(0)
379
+ .select(major, rank.equal(1).select(second, third))
380
+ .toVar();
381
+ const positive = i
382
+ .lessThan(3)
383
+ .select(
384
+ look.element(axis).greaterThanEqual(0),
385
+ look.element(axis).lessThan(0),
386
+ );
387
+ const face = axis.mul(2).add(positive.select(int(0), int(1)));
388
+ const facing = positive.select(1, -1);
389
+ const n = vec3(
390
+ axis.equal(0).select(facing, 0),
391
+ axis.equal(1).select(facing, 0),
392
+ axis.equal(2).select(facing, 0),
393
+ ).toVar();
394
+ const right = axis
395
+ .equal(0)
396
+ .select(
397
+ vec3(0, 0, facing.negate()),
398
+ axis.equal(1).select(vec3(1, 0, 0), vec3(facing, 0, 0)),
399
+ )
400
+ .toVar();
401
+ const up = axis
402
+ .equal(1)
403
+ .select(vec3(0, 0, facing.negate()), vec3(0, 1, 0))
404
+ .toVar();
405
+ const direction = i.lessThan(3).select(1, -1);
406
+ const rect = textureLoad(
407
+ rects,
408
+ ivec2(face, int(attribute("boxId", "float"))),
409
+ ).toVar();
410
+ const sampleUv = (p) =>
411
+ rect.xy.add(
412
+ vec2(dot(p, right), dot(p, up))
413
+ .mul(0.5)
414
+ .add(0.5)
415
+ .clamp(0, 1)
416
+ .mul(rect.zw),
417
+ );
418
+ const decode = (d) => d.b.mul(65280).add(d.a.mul(255)).div(65535);
419
+ const depthAt = (uv) => decode(texture(maps.normalDepth, uv).level(0));
420
+ const distance = (t) => {
421
+ const p = o.add(r.mul(t));
422
+ return dot(p, n)
423
+ .sub(float(1).sub(depthAt(sampleUv(p)).mul(2)))
424
+ .mul(direction);
425
+ };
426
+ const acceptHit = (hitT) => {
427
+ const point = o.add(r.mul(hitT)),
428
+ uv = sampleUv(point);
429
+ // Filtering may move a hit within a texel footprint. A depth
430
+ // jump beyond that footprint must not become a connecting wall.
431
+ const texel = ivec2(uv.mul(descriptor.atlasResolution));
432
+ const nearest = textureLoad(maps.normalDepth, texel);
433
+ // Depth padding supports filtering; every hit still requires an
434
+ // occupied nearest texel, including at box entry.
435
+ const capturedBase = texture(maps.baseColor,uv).level(0);
436
+ const occupied = textureLoad(maps.orm, texel).a.greaterThan(0.5);
437
+ const residual = abs(
438
+ dot(point, n).sub(float(1).sub(decode(nearest).mul(2))),
439
+ );
440
+ const tolerance = max(
441
+ dot(abs(right), half).div(rect.z.mul(descriptor.atlasResolution)),
442
+ dot(abs(up), half).div(rect.w.mul(descriptor.atlasResolution)),
443
+ )
444
+ .div(dot(abs(n), half))
445
+ .mul(4)
446
+ .add(4 / 65535);
447
+ If(
448
+ residual
449
+ .lessThanEqual(tolerance)
450
+ .and(occupied)
451
+ .and(
452
+ capturedBase.a.greaterThanEqual(minimumAlpha),
453
+ ),
454
+ () => {
455
+ valid.assign(1);
456
+ If(hitT.lessThan(bestT), () => {
457
+ bestT.assign(hitT);
458
+ bestUv.assign(uv);
459
+ found.assign(1);
460
+ const packed = texture(maps.normalDepth, uv)
461
+ .level(0)
462
+ .rg.div(max(surfaceCoverage(texture(maps.orm, uv).level(0).a,capturedBase.a), 1e-10))
463
+ .mul(2)
464
+ .sub(1);
465
+ const normal = vec3(
466
+ packed.x,
467
+ packed.y,
468
+ float(1).sub(abs(packed.x)).sub(abs(packed.y)),
469
+ ).toVar();
470
+ If(normal.z.lessThan(0), () => {
471
+ normal.xy.assign(
472
+ vec2(1)
473
+ .sub(abs(normal.yx))
474
+ .mul(sign(normal.xy.add(1e-20))),
475
+ );
476
+ });
477
+ bestNormal.assign(
478
+ fromBox(
479
+ right
480
+ .mul(normal.x)
481
+ .add(up.mul(normal.y))
482
+ .add(n.mul(normal.z)),
483
+ ).normalize(),
484
+ );
485
+ bestNormal.mulAssign(
486
+ dot(bestNormal, ray).greaterThan(0).select(-1, 1),
487
+ );
488
+ });
489
+ },
490
+ );
491
+ };
492
+ const traceInterval = (
493
+ start,
494
+ end,
495
+ steps,
496
+ ) => {
497
+ // Sample every crossed texel; a fixed interval budget skips thin
498
+ // surfaces when an oblique ray spans hundreds of capture pixels.
499
+ const footprint = vec2(dot(r, right), dot(r, up)).abs().mul(rect.zw).mul(descriptor.atlasResolution / 2).mul(end.sub(start));
500
+ const samples = max(float(steps), max(footprint.x,footprint.y).mul(steps/8)).div(2).ceil().mul(2).toVar();
501
+ const step=end.sub(start).div(samples);
502
+ const previous = start.toVar(),
503
+ previousD = distance(start).toVar();
504
+ // At interval entry the refinement bracket has zero width. Resolve it
505
+ // once rather than resampling the same depth through every bisection.
506
+ If(previousD.lessThanEqual(0), () => {
507
+ acceptHit(start);
508
+ });
509
+ Loop({ start: int(0), end: int(samples.div(2)), type: "int" }, ({ i }) => {
510
+ If(valid.greaterThan(0.5), () => {
511
+ Break();
512
+ });
513
+ // Issue independent depth reads together, then resolve crossings in
514
+ // their original order before refining either crossing direction.
515
+ const samples = [1, 2].map((offset) => {
516
+ const t = start.add(step.mul(float(i.mul(2).add(offset)))).toVar();
517
+ return { t, d: distance(t).toVar() };
518
+ });
519
+ for (const { t, d } of samples) {
520
+ If(valid.greaterThan(0.5).or(t.sub(step).greaterThan(bestT)), () => {
521
+ Break();
522
+ });
523
+ If(valid.lessThan(.5).and(d.mul(previousD).lessThanEqual(0)), () => {
524
+ const crossing=refineSurfaceCrossing({float,If,Loop},{lo:previous,hi:t,loValue:previousD,hiValue:d,height:distance,steps:3,secant:true});
525
+ acceptHit(crossing);
526
+ If(bestT.lessThanEqual(t), () => {
527
+ Break();
528
+ });
529
+ });
530
+ previous.assign(t);
531
+ previousD.assign(d);
532
+ }
533
+ });
534
+ };
535
+ If(
536
+ exit
537
+ .greaterThanEqual(enter)
538
+ .and(abs(look.element(axis)).greaterThan(0.001)),
539
+ () => {
540
+ if (!accelerated) {
541
+ traceInterval(enter, exit, descriptor.raySteps);
542
+ } else {
543
+ const depths = axis
544
+ .equal(0)
545
+ .select(
546
+ attribute("boxDepthX", "vec4"),
547
+ axis
548
+ .equal(1)
549
+ .select(
550
+ attribute("boxDepthY", "vec4"),
551
+ attribute("boxDepthZ", "vec4"),
552
+ ),
553
+ );
554
+ const interval = positive.select(depths.xy, depths.zw);
555
+ const initialDepth = float(1).sub(dot(o, n)).mul(0.5);
556
+ const depthSlope = dot(r, n).negate().mul(0.5);
557
+ const da = interval.x
558
+ .sub(2 / 65535)
559
+ .sub(initialDepth)
560
+ .div(depthSlope);
561
+ const db = interval.y
562
+ .add(2 / 65535)
563
+ .sub(initialDepth)
564
+ .div(depthSlope);
565
+ const start = max(occupiedStart, min(da, db));
566
+ const end = min(min(exit, bestT), max(da, db));
567
+ If(
568
+ interval.x
569
+ .lessThanEqual(interval.y)
570
+ .and(end.greaterThanEqual(start)),
571
+ () => {
572
+ const search = () =>
573
+ traceInterval(start, end, descriptor.raySteps);
574
+ const hasFlatView = descriptor.boxes.some((box) =>
575
+ [0, 2, 4, 6, 8, 10].some(
576
+ (i) =>
577
+ box.depthBounds[i + 1] >= box.depthBounds[i] &&
578
+ box.depthBounds[i + 1] - box.depthBounds[i] <= 1,
579
+ ),
580
+ );
581
+ if (hasFlatView) {
582
+ If(
583
+ interval.y.sub(interval.x).lessThanEqual(1 / 65535),
584
+ () => {
585
+ const t = interval.x
586
+ .add(interval.y)
587
+ .mul(0.5)
588
+ .sub(initialDepth)
589
+ .div(depthSlope);
590
+ If(
591
+ t
592
+ .greaterThanEqual(enter)
593
+ .and(t.lessThanEqual(min(exit, bestT))),
594
+ () => {
595
+ acceptHit(t);
596
+ },
597
+ );
598
+ },
599
+ ).Else(search);
600
+ } else search();
601
+ },
602
+ );
603
+ }
604
+ },
605
+ );
606
+ },
607
+ );
608
+ valid.assign(found);
609
+ const point = o.add(r.mul(bestT));
610
+ return Result(
611
+ bestUv,
612
+ center.add(fromBox(point.mul(half))),
613
+ bestNormal,
614
+ valid,
615
+ );
616
+ });
617
+ const hit = raycast().toVar("boxHit");
618
+ hit.toStack();
619
+ const base = texture(maps.baseColor, hit.get("uv")).level(0),
620
+ orm = texture(maps.orm, hit.get("uv")).level(0);
621
+ // Capture backgrounds are zero in every map. Normalize all filtered surface
622
+ // attributes by geometric coverage; an
623
+ // empty neighbor must not turn a rough edge into a glossy highlight.
624
+ const coverage = max(surfaceCoverage(orm.a,base.a), 1e-10);
625
+ let color = base.div(coverage),
626
+ surfaceOrm = orm.rgb.div(coverage),
627
+ emission = texture(maps.emissive, hit.get("uv")).level(0).rgb.div(coverage),
628
+ normal = hit.get("normal");
629
+ if (settings.interpolation !== "none") {
630
+ const fallbackColor = color,
631
+ fallbackOrm = surfaceOrm,
632
+ fallbackEmission = emission,
633
+ fallbackNormal = normal;
634
+ const Surface = struct(
635
+ { color: "vec4", orm: "vec3", emission: "vec3", normal: "vec3" },
636
+ "BoxSurfaceBlend",
637
+ );
638
+ const blended = Fn(() => {
639
+ const point = toBox(hit.get("position").sub(center)).div(half);
640
+ const look = toBox(
641
+ perspective.select(normalize(eye.sub(hit.get("position"))), viewAxis),
642
+ );
643
+ const colors = vec4(0).toVar(),
644
+ materials = vec3(0).toVar(),
645
+ emissions = vec3(0).toVar(),
646
+ normals = vec3(0).toVar(),
647
+ weights = float(0).toVar();
648
+ for (let axis = 0; axis < 3; axis++) {
649
+ const positive = look.element(axis).greaterThanEqual(0);
650
+ const front = BOX_FACE_AXES[axis * 2],
651
+ back = BOX_FACE_AXES[axis * 2 + 1];
652
+ const n = positive.select(vec3(...front.normal), vec3(...back.normal));
653
+ const right = positive.select(
654
+ vec3(...front.right),
655
+ vec3(...back.right),
656
+ );
657
+ const up = positive.select(vec3(...front.up), vec3(...back.up));
658
+ const face = positive.select(int(axis * 2), int(axis * 2 + 1));
659
+ const rect = textureLoad(
660
+ rects,
661
+ ivec2(face, int(attribute("boxId", "float"))),
662
+ );
663
+ const uv = rect.xy.add(
664
+ vec2(dot(point, right), dot(point, up))
665
+ .mul(0.5)
666
+ .add(0.5)
667
+ .clamp(0, 1)
668
+ .mul(rect.zw),
669
+ );
670
+ const texel = ivec2(uv.mul(descriptor.atlasResolution));
671
+ const captured = textureLoad(maps.normalDepth, texel);
672
+ const sampled = texture(maps.baseColor, uv).level(0);
673
+ const sampledOrm = texture(maps.orm, uv).level(0);
674
+ const occupied = textureLoad(maps.orm, texel).a.greaterThan(0.5);
675
+ const depth = captured.b.mul(65280).add(captured.a.mul(255)).div(65535);
676
+ const tolerance = max(
677
+ dot(abs(right), half).div(rect.z.mul(descriptor.atlasResolution)),
678
+ dot(abs(up), half).div(rect.w.mul(descriptor.atlasResolution)),
679
+ )
680
+ .div(dot(abs(n), half))
681
+ .mul(4)
682
+ .add(4 / 65535);
683
+ // Only blend captures that see this same surface. A hidden layer or
684
+ // background texel must not bleed across an occlusion boundary.
685
+ If(
686
+ occupied
687
+ .and(sampled.a.greaterThanEqual(minimumAlpha))
688
+ .and(
689
+ abs(dot(point, n).sub(float(1).sub(depth.mul(2)))).lessThanEqual(
690
+ tolerance,
691
+ ),
692
+ ),
693
+ () => {
694
+ const angle = abs(look.element(axis));
695
+ const filtered = filtering ? texture(maps.normalDepth,uv).level(0).toVar() : captured;
696
+ let weight =
697
+ settings.interpolation === "smooth" ? angle.mul(angle) : angle;
698
+ if (filtering) {
699
+ const error = abs(dot(point,n).sub(float(1).sub(
700
+ filtered.b.mul(65280).add(filtered.a.mul(255)).div(65535).mul(2)
701
+ )));
702
+ weight = weight.mul(float(1).sub(error.div(tolerance)).clamp(0,1));
703
+ }
704
+ const coverage = max(surfaceCoverage(sampledOrm.a,sampled.a), 1e-10);
705
+ colors.addAssign(sampled.div(coverage).mul(weight));
706
+ materials.addAssign(sampledOrm.rgb.div(coverage).mul(weight));
707
+ emissions.addAssign(
708
+ texture(maps.emissive, uv).level(0).rgb.div(coverage).mul(weight),
709
+ );
710
+ let shadingNormal;
711
+ if (filtering) shadingNormal = filteredNormal(uv,float(1).sub(dot(point,n)).mul(.5),tolerance.mul(.5),captured,sampled.a,filtered,sampledOrm.a);
712
+ else {
713
+ const packed = captured.rg.mul(2).sub(1);
714
+ const decoded = vec3(
715
+ packed,
716
+ float(1).sub(abs(packed.x)).sub(abs(packed.y)),
717
+ ).toVar();
718
+ If(decoded.z.lessThan(0), () => {
719
+ decoded.xy.assign(
720
+ vec2(1)
721
+ .sub(abs(decoded.yx))
722
+ .mul(sign(decoded.xy.add(1e-20))),
723
+ );
724
+ });
725
+ shadingNormal = decoded;
726
+ }
727
+ normals.addAssign(
728
+ fromBox(
729
+ right
730
+ .mul(shadingNormal.x)
731
+ .add(up.mul(shadingNormal.y))
732
+ .add(n.mul(shadingNormal.z)),
733
+ )
734
+ .normalize()
735
+ .mul(weight),
736
+ );
737
+ weights.addAssign(weight);
738
+ },
739
+ );
740
+ }
741
+ const divisor = max(weights, 1e-10),
742
+ valid = weights.greaterThan(1e-10);
743
+ return Surface(
744
+ valid.select(colors.div(divisor), fallbackColor),
745
+ valid.select(materials.div(divisor), fallbackOrm),
746
+ valid.select(emissions.div(divisor), fallbackEmission),
747
+ valid.select(normals.normalize(), fallbackNormal),
748
+ );
749
+ })().toVar("boxBlendedSurface");
750
+ color = blended.get("color");
751
+ surfaceOrm = blended.get("orm");
752
+ emission = blended.get("emission");
753
+ normal = blended.get("normal");
754
+ }
755
+ material.capturedPositionNode = hit.get("position");
756
+ material.colorNode = color.rgb;
757
+ material.normalNode = transformNormalToView(normal);
758
+ material.roughnessNode = surfaceOrm.g;
759
+ material.metalnessNode = surfaceOrm.b;
760
+ material.aoNode = surfaceOrm.r;
761
+ material.emissiveNode = emission;
762
+ if (transparency !== "cutout") material.opacityNode = color.a.clamp(0, 1);
763
+ material.maskNode = hit.get("valid").greaterThan(0.5);
764
+ material.maskShadowNode = material.maskNode;
765
+ material.depthNode = capturedSurfaceDepth(hit.get("position"));
766
+ material.receivedShadowPositionNode = modelWorldMatrix.mul(
767
+ vec4(hit.get("position"), 1),
768
+ ).xyz;
769
+ material.userData.boxImpostor = { descriptor, maps, alphaCutoff };
770
+ return material;
771
+ }