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

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.
@@ -0,0 +1,452 @@
1
+ // @ts-nocheck
2
+ import { Matrix4, NodeUpdateType, StorageBufferAttribute, Vector3 } from 'three/webgpu';
3
+ import {
4
+ Fn,
5
+ If,
6
+ Loop,
7
+ atomicMin,
8
+ atomicStore,
9
+ clamp,
10
+ float,
11
+ floor,
12
+ instanceIndex,
13
+ int,
14
+ ivec2,
15
+ max,
16
+ min,
17
+ storage,
18
+ textureLoad,
19
+ uint,
20
+ vec2,
21
+ vec3,
22
+ vec4,
23
+ } from 'three/tsl';
24
+ import { BOX_FACE_AXES } from './box-impostor-face-axes.js';
25
+
26
+ const MIN_TILE_SIZE = 3;
27
+ const MAX_CAPTURE_TILES = 512 * 1024;
28
+ // The angle only schedules a refresh. Reprojecting the entire ray segment below
29
+ // also works between refreshes and when a shadow camera uses a different view.
30
+ const REFRESH_ANGLE_SQUARED = Math.tan(Math.PI / 360) ** 2;
31
+ const DEPTH_MAX = 65535;
32
+ const MAX_VIEW_BYTES = 16 * 1024 * 1024;
33
+ const MAX_CACHED_VIEW_BYTES = 64 * 1024 * 1024;
34
+
35
+ function buffer(length, components = 1, Type = Float32Array) {
36
+ return new StorageBufferAttribute(length, components, Type);
37
+ }
38
+
39
+ function captureTiles(descriptor) {
40
+ const faces = descriptor.boxes.flatMap((box, id) =>
41
+ BOX_FACE_AXES.map((axes, face) => {
42
+ const [, , width, height] = box.views[face];
43
+ const w = width - 2 * descriptor.padding,
44
+ h = height - 2 * descriptor.padding;
45
+ const right = axes.right.findIndex(Boolean),
46
+ up = axes.up.findIndex(Boolean);
47
+ const tolerance =
48
+ (4 * Math.max(box.halfSize[right] / w, box.halfSize[up] / h)) / box.halfSize[face >> 1] +
49
+ 5 / DEPTH_MAX;
50
+ return { key: id * 6 + face, w, h, tolerance };
51
+ }),
52
+ );
53
+ // Include the first gutter texel on each side. At the positive carrier edge
54
+ // the nearest-texel test can address exactly the end of the inner rectangle.
55
+ const countFor = (size) =>
56
+ faces.reduce((n, f) => n + Math.ceil((f.w + 2) / size) * Math.ceil((f.h + 2) / size), 0);
57
+ let size = MIN_TILE_SIZE;
58
+ while (countFor(size) > MAX_CAPTURE_TILES) size *= 2;
59
+ const tiles = buffer(countFor(size), 4);
60
+ let offset = 0;
61
+ for (const { key, w, h, tolerance } of faces) {
62
+ for (let y = -1; y <= h; y += size) {
63
+ for (let x = -1; x <= w; x += size) {
64
+ tiles.array[offset] = key;
65
+ tiles.array[offset + 1] = x;
66
+ tiles.array[offset + 2] = y;
67
+ tiles.array[offset + 3] = tolerance;
68
+ offset += 4;
69
+ }
70
+ }
71
+ }
72
+ return { tiles, size };
73
+ }
74
+
75
+ // A tile may cross a silhouette or see a second surface through a hole. Keep
76
+ // the two depth ranges separate, with the full footprint of every supported texel.
77
+ function buildPatches(descriptor, maps, rects, tiles, size, output) {
78
+ const descriptions = storage(tiles, 'vec4', tiles.count).toReadOnly();
79
+ const patches = storage(output, 'vec4', output.count);
80
+ return Fn(() => {
81
+ const meta = descriptions.element(instanceIndex).toVar();
82
+ const key = int(meta.x),
83
+ face = key.mod(6),
84
+ axis = face.div(2);
85
+ const rect = textureLoad(rects, ivec2(face, key.div(6)))
86
+ .mul(descriptor.atlasResolution)
87
+ .round()
88
+ .toVar();
89
+ const extent = ivec2(rect.zw.add(1).sub(meta.yz)).min(ivec2(size));
90
+ const origin = ivec2(rect.xy.add(meta.yz));
91
+ const near = float(1).toVar(),
92
+ far = float(0).toVar();
93
+ function visit(process) {
94
+ Loop({ start: int(0), end: extent.y, type: 'int', name: 'row' }, ({ row }) => {
95
+ Loop({ start: int(0), end: extent.x, type: 'int', name: 'column' }, ({ column }) => {
96
+ const pixel = origin.add(ivec2(column, row));
97
+ If(textureLoad(maps.orm, pixel).a.greaterThan(0.5), () => {
98
+ const packed = textureLoad(maps.normalDepth, pixel);
99
+ const depth = packed.b.mul(65280).add(packed.a.mul(255)).div(DEPTH_MAX).toVar();
100
+ process(column, row, depth);
101
+ });
102
+ });
103
+ });
104
+ }
105
+ visit((x, y, depth) => {
106
+ near.assign(min(near, depth));
107
+ far.assign(max(far, depth));
108
+ });
109
+ const middle = near.add(far).mul(0.5).toVar();
110
+ const low = [vec3(2).toVar(), vec3(2).toVar()],
111
+ high = [vec3(-2).toVar(), vec3(-2).toVar()];
112
+ visit((x, y, depth) => {
113
+ const uv = meta.yz.add(vec2(x, y)).div(rect.zw).mul(2).sub(1);
114
+ const lo = vec3(uv.clamp(-1, 1), float(1).sub(depth.mul(2)).sub(meta.w).max(-1)).toVar();
115
+ const hi = vec3(
116
+ uv.add(vec2(2).div(rect.zw)).clamp(-1, 1),
117
+ float(1).sub(depth.mul(2)).add(meta.w).min(1),
118
+ ).toVar();
119
+ // Both branches need these extrema. TSL otherwise emits shared
120
+ // temporaries inside the first branch that references them.
121
+ lo.toStack();
122
+ hi.toStack();
123
+ const extend = (group) => {
124
+ low[group].assign(min(low[group], lo));
125
+ high[group].assign(max(high[group], hi));
126
+ };
127
+ If(depth.lessThanEqual(middle), () => {
128
+ extend(0);
129
+ }).Else(() => {
130
+ extend(1);
131
+ });
132
+ });
133
+ const facing = face.mod(2).equal(0).select(1, -1);
134
+ const right = axis
135
+ .equal(0)
136
+ .select(vec3(0, 0, facing.negate()), axis.equal(1).select(vec3(1, 0, 0), vec3(facing, 0, 0)));
137
+ const up = axis.equal(1).select(vec3(0, 0, facing.negate()), vec3(0, 1, 0));
138
+ const normal = right.cross(up);
139
+ const rotate = (p) => right.mul(p.x).add(up.mul(p.y)).add(normal.mul(p.z));
140
+ for (let group = 0; group < 2; group++) {
141
+ const a = rotate(low[group]),
142
+ b = rotate(high[group]),
143
+ slot = instanceIndex.mul(4).add(group * 2);
144
+ const valid = low[group].x.lessThanEqual(high[group].x);
145
+ patches.element(slot).assign(vec4(min(a, b), valid.select(meta.x, -1)));
146
+ patches.element(slot.add(1)).assign(vec4(max(a, b), 0));
147
+ }
148
+ })().compute(tiles.count);
149
+ }
150
+
151
+ function makeViewPasses(patchBuffer, views, ranges, count, resolution) {
152
+ const table = storage(ranges, 'uint', count).toAtomic();
153
+ const reset = Fn(() => {
154
+ atomicStore(table.element(instanceIndex), uint(DEPTH_MAX));
155
+ })().compute(count);
156
+ const patches = storage(patchBuffer, 'vec4', patchBuffer.count).toReadOnly();
157
+ const scatter = Fn(() => {
158
+ const a = patches.element(instanceIndex.mul(2)).toVar(),
159
+ b = patches.element(instanceIndex.mul(2).add(1)).toVar();
160
+ If(a.w.greaterThanEqual(0), () => {
161
+ const key = int(a.w),
162
+ box = key.div(6);
163
+ const mapping = views.element(box.mul(2)),
164
+ reference = views.element(box.mul(2).add(1));
165
+ If(reference.w.greaterThanEqual(0), () => {
166
+ const axis = int(reference.w).mod(3),
167
+ x = axis.add(1).mod(3),
168
+ y = axis.add(2).mod(3);
169
+ const e = vec2(reference.element(x), reference.element(y)),
170
+ ez = reference.element(axis);
171
+ const za = a.element(axis),
172
+ zb = b.element(axis);
173
+ const weight = reference.w.lessThan(3).select(1, 0).toVar();
174
+ const eyeSlope = e.div(ez).toVar(),
175
+ inverseDistance = weight.div(ez).toVar();
176
+ const project = (v, z) => v.sub(eyeSlope.mul(z)).div(float(1).sub(inverseDistance.mul(z)));
177
+ const l = vec2(a.element(x), a.element(y)),
178
+ h = vec2(b.element(x), b.element(y));
179
+ const cell = (v, bias) =>
180
+ ivec2(floor(v.sub(mapping.xy).mul(mapping.zw).add(bias)).clamp(0, resolution - 1));
181
+ const lo = cell(min(project(l, za), project(l, zb)), -0.005);
182
+ const hi = cell(max(project(h, za), project(h, zb)), 0.005);
183
+ // At each depth, all rays in a cell lie within this distance of its
184
+ // centre ray. Intersect that beam with the patch before marking a range.
185
+ const padding = vec2(0.506).div(mapping.zw).mul(inverseDistance.abs().add(1)).add(2e-6);
186
+ Loop({ start: lo.y, end: hi.y.add(1), type: 'int', name: 'row' }, ({ row }) => {
187
+ Loop({ start: lo.x, end: hi.x.add(1), type: 'int', name: 'column' }, ({ column }) => {
188
+ const uv = vec2(column, row).add(0.5).div(mapping.zw).add(mapping.xy);
189
+ const slope = eyeSlope.sub(uv.mul(inverseDistance)).toVar();
190
+ const safe = slope.add(1e-30).sign().mul(slope.abs().max(1e-12));
191
+ const ta = l.sub(padding).sub(uv).div(safe).toVar(),
192
+ tb = h.add(padding).sub(uv).div(safe).toVar();
193
+ const begin = max(za, max(min(ta.x, tb.x), min(ta.y, tb.y))),
194
+ end = min(zb, min(max(ta.x, tb.x), max(ta.y, tb.y)));
195
+ If(begin.lessThanEqual(end), () => {
196
+ const depths = floor(
197
+ vec2(begin.add(1), float(1).sub(end))
198
+ .mul(DEPTH_MAX / 2)
199
+ .sub(0.02),
200
+ ).max(0);
201
+ const i = key.mul(resolution).add(row).mul(resolution).add(column).mul(2);
202
+ atomicMin(table.element(i), uint(depths.x));
203
+ atomicMin(table.element(i.add(1)), uint(depths.y));
204
+ });
205
+ });
206
+ });
207
+ });
208
+ });
209
+ })().compute(patchBuffer.count / 2);
210
+ return { reset, scatter, table };
211
+ }
212
+
213
+ function setProjection(data, descriptor, reference, orthographic, resolution) {
214
+ for (const [id, box] of descriptor.boxes.entries()) {
215
+ const p = box.axes.map(
216
+ (axis, i) =>
217
+ axis.reduce(
218
+ (sum, v, k) => sum + v * (orthographic ? reference[k] : reference[k] - box.center[k]),
219
+ 0,
220
+ ) / box.halfSize[i],
221
+ );
222
+ const axis = p.map(Math.abs).indexOf(Math.max(...p.map(Math.abs)));
223
+ const ez = p[axis],
224
+ offset = id * 8;
225
+ if (orthographic ? Math.abs(ez) < 1e-12 : Math.abs(ez) <= 1.01) {
226
+ data[offset + 7] = -1;
227
+ continue;
228
+ }
229
+ for (let j = 0; j < 2; j++) {
230
+ const e = p[(axis + 1 + j) % 3];
231
+ const project = (v, z) => (orthographic ? v - (z * e) / ez : (v * ez - z * e) / (ez - z));
232
+ const low = Math.min(project(-1, -1), project(-1, 1));
233
+ const high = Math.max(project(1, -1), project(1, 1));
234
+ data[offset + j] = low;
235
+ data[offset + j + 2] = resolution / (high - low);
236
+ }
237
+ data.set(p, offset + 4);
238
+ data[offset + 7] = axis + (orthographic ? 3 : 0);
239
+ }
240
+ }
241
+
242
+ /** Restrict the existing full-resolution search to intervals containing supported
243
+ * capture texels. All preparation stays on the GPU, including for compressed maps. */
244
+ export function createBoxRayBounds(descriptor, maps, rects, material) {
245
+ const boxes = descriptor.boxes.length;
246
+ const resolution = Math.min(128, Math.floor(Math.sqrt(MAX_VIEW_BYTES / (48 * boxes))));
247
+ if (
248
+ resolution < 32 ||
249
+ descriptor.atlasResolution < 512 ||
250
+ [maps.normalDepth, maps.orm].some((map) => map.isRenderTargetTexture || map.isVideoTexture)
251
+ )
252
+ return null;
253
+ const count = boxes * 6 * resolution ** 2 * 2;
254
+ const maxViews = Math.max(1, Math.floor(MAX_CACHED_VIEW_BYTES / (count * 4 + boxes * 32)));
255
+ const inactiveView = buffer(boxes * 2, 4);
256
+ for (let i = 0; i < boxes; i++) inactiveView.array.set([0, 0, 1, 1, 2, 0, 0, -1], i * 8);
257
+ const inactiveRanges = buffer(1, 1, Uint32Array);
258
+ const views = storage(inactiveView, 'vec4', boxes * 2).toReadOnly();
259
+ // Unsized arrays allow a one-word binding when this draw uses the full search.
260
+ const ranges = storage(inactiveRanges, 'uint').toReadOnly();
261
+ const inverse = new Matrix4(),
262
+ eye = new Vector3(),
263
+ center = new Vector3();
264
+ const states = new Map();
265
+ let tiles, patches, reduce, passes;
266
+
267
+ function prepare({ renderer, camera, object }) {
268
+ views.value = inactiveView;
269
+ ranges.value = inactiveRanges;
270
+ if (
271
+ !renderer.backend?.isWebGPUBackend ||
272
+ renderer.xr?.isPresenting ||
273
+ object.isInstancedMesh ||
274
+ (!camera.isPerspectiveCamera && !camera.isOrthographicCamera) ||
275
+ camera.isArrayCamera
276
+ )
277
+ return;
278
+ inverse.copy(object.matrixWorld).invert();
279
+ const ortho = camera.isOrthographicCamera === true;
280
+ if (ortho) camera.getWorldDirection(eye).transformDirection(inverse);
281
+ else eye.setFromMatrixPosition(camera.matrixWorld).applyMatrix4(inverse);
282
+ if (!Number.isFinite(eye.lengthSq())) return;
283
+ let state = states.get(renderer);
284
+ if (!state) {
285
+ state = { slots: [], initialized: false };
286
+ states.set(renderer, state);
287
+ }
288
+ if (!tiles) {
289
+ const capture = captureTiles(descriptor);
290
+ tiles = capture.tiles;
291
+ patches = buffer(tiles.count * 4, 4);
292
+ reduce = buildPatches(descriptor, maps, rects, tiles, capture.size, patches);
293
+ const computeViews = storage(inactiveView, 'vec4', boxes * 2).toReadOnly();
294
+ passes = {
295
+ ...makeViewPasses(patches, computeViews, inactiveRanges, count, resolution),
296
+ views: computeViews,
297
+ };
298
+ }
299
+ if (
300
+ !state.initialized ||
301
+ state.depthVersion !== maps.normalDepth.version ||
302
+ state.coverageVersion !== maps.orm.version
303
+ ) {
304
+ renderer.compute(reduce);
305
+ for (const slot of state.slots) slot.ready = false;
306
+ state.depthVersion = maps.normalDepth.version;
307
+ state.coverageVersion = maps.orm.version;
308
+ state.initialized = true;
309
+ }
310
+ const frame = renderer.info.render.calls;
311
+ const compatible = (v) => v.ready && v.ortho === ortho && v.eye.distanceToSquared(eye) <= v.radiusSq;
312
+ let slot = state.slots.find((v) => v.object.deref() === object && v.camera.deref() === camera);
313
+ if (!slot || !compatible(slot)) {
314
+ const shared = state.slots.find(compatible);
315
+ if (shared) {
316
+ shared.frame = frame;
317
+ views.value = shared.view;
318
+ ranges.value = shared.ranges;
319
+ return;
320
+ }
321
+ if (slot?.frame === frame) slot = undefined;
322
+ }
323
+ if (!slot) {
324
+ if (state.slots.length < maxViews) {
325
+ slot = { view: buffer(boxes * 2, 4), ranges: buffer(count, 1, Uint32Array), eye: new Vector3() };
326
+ state.slots.push(slot);
327
+ } else {
328
+ slot = state.slots.reduce((oldest, v) => (v.frame < oldest.frame ? v : oldest));
329
+ // All buffers may still be referenced by the same unsubmitted render
330
+ // pass. Reproject into the closest available view without rewriting it.
331
+ if (slot.frame === frame) {
332
+ let nearest = Infinity;
333
+ for (const v of state.slots) {
334
+ if (!v.ready || v.ortho !== ortho) continue;
335
+ const distance = v.eye.distanceToSquared(eye);
336
+ if (distance < nearest) {
337
+ nearest = distance;
338
+ views.value = v.view;
339
+ ranges.value = v.ranges;
340
+ }
341
+ }
342
+ return;
343
+ }
344
+ }
345
+ slot.object = new WeakRef(object);
346
+ slot.camera = new WeakRef(camera);
347
+ slot.ready = false;
348
+ }
349
+ slot.frame = frame;
350
+ views.value = slot.view;
351
+ ranges.value = slot.ranges;
352
+ if (compatible(slot)) return;
353
+ setProjection(slot.view.array, descriptor, eye.toArray(), ortho, resolution);
354
+ slot.view.needsUpdate = true;
355
+ passes.views.value = slot.view;
356
+ passes.table.value = slot.ranges;
357
+ renderer.compute([passes.reset, passes.scatter]);
358
+ const distanceSquared = ortho
359
+ ? 1
360
+ : Math.min(...descriptor.boxes.map((box) => eye.distanceToSquared(center.fromArray(box.center))));
361
+ slot.radiusSq = distanceSquared * REFRESH_ANGLE_SQUARED;
362
+ slot.eye.copy(eye);
363
+ slot.ortho = ortho;
364
+ slot.ready = true;
365
+ }
366
+ // Participate in the renderer's node lifecycle even when the host supplies
367
+ // its own material hooks or renders the hit graph through an override.
368
+ views.updateBeforeType = NodeUpdateType.OBJECT;
369
+ views.updateBefore = prepare;
370
+ material.addEventListener('dispose', () => {
371
+ for (const state of states.values()) {
372
+ for (const slot of state.slots) {
373
+ slot.view.dispose();
374
+ slot.ranges.dispose();
375
+ }
376
+ }
377
+ states.clear();
378
+ reduce?.dispose();
379
+ passes?.reset.dispose();
380
+ passes?.scatter.dispose();
381
+ tiles?.dispose();
382
+ patches?.dispose();
383
+ inactiveView.dispose();
384
+ inactiveRanges.dispose();
385
+ });
386
+
387
+ return (builder, id, o, r, enter, exit) => {
388
+ if (!builder.renderer.backend?.isWebGPUBackend) return null;
389
+ const mapping = views.element(id.mul(2)).toVar();
390
+ const ref = views.element(id.mul(2).add(1)).toVar();
391
+ const axis = int(max(ref.w, 0)).mod(3),
392
+ x = axis.add(1).mod(3),
393
+ y = axis.add(2).mod(3);
394
+ const rz = r.element(axis).toVar(),
395
+ oz = o.element(axis).toVar();
396
+ // A segment projects to a line in the reference view, even when another
397
+ // camera, object or shadow pass borrows this view. Check every crossed
398
+ // cell, or use the full search when their bounding rectangle is too wide.
399
+ const ez = ref.element(axis),
400
+ e = vec2(ref.element(x), ref.element(y));
401
+ const eyeSlope = e.div(ez),
402
+ inverseDistance = ref.w.lessThan(3).select(1, 0).div(ez);
403
+ const project = (t) => {
404
+ const point = o.add(r.mul(t)),
405
+ v = vec2(point.element(x), point.element(y)),
406
+ z = point.element(axis);
407
+ const p = v.sub(eyeSlope.mul(z)).div(float(1).sub(inverseDistance.mul(z)));
408
+ return p.sub(mapping.xy).mul(mapping.zw);
409
+ };
410
+ const a = project(enter).toVar(),
411
+ b = project(exit).toVar();
412
+ const cellLo = ivec2(floor(min(a, b).sub(0.001)).clamp(0, resolution - 1)).toVar();
413
+ const cellHi = ivec2(floor(max(a, b).add(0.001)).clamp(0, resolution - 1)).toVar();
414
+ const valid = ref.w
415
+ .greaterThanEqual(0)
416
+ .and(rz.abs().greaterThan(1e-12))
417
+ .and(cellHi.sub(cellLo).lessThanEqual(ivec2(2)).all())
418
+ .toVar();
419
+ return (face, enter, exit) => {
420
+ const start = enter.toVar(),
421
+ end = exit.toVar();
422
+ If(valid, () => {
423
+ const base = id
424
+ .mul(6)
425
+ .add(face)
426
+ .mul(resolution ** 2);
427
+ const at = (u, v) => base.add(v.mul(resolution)).add(u).mul(2);
428
+ const idx = at(cellLo.x, cellLo.y).toVar();
429
+ const lower = ranges.element(idx).toVar(),
430
+ upper = ranges.element(idx.add(1)).toVar();
431
+ If(cellHi.notEqual(cellLo).any(), () => {
432
+ Loop({ start: cellLo.y, end: cellHi.y.add(1), type: 'int', name: 'by' }, ({ by }) => {
433
+ Loop({ start: cellLo.x, end: cellHi.x.add(1), type: 'int', name: 'bx' }, ({ bx }) => {
434
+ const p = at(bx, by);
435
+ lower.assign(min(lower, ranges.element(p)));
436
+ upper.assign(min(upper, ranges.element(p.add(1))));
437
+ });
438
+ });
439
+ });
440
+ const lo = float(lower)
441
+ .mul(2 / DEPTH_MAX)
442
+ .sub(1),
443
+ hi = float(1).sub(float(upper).mul(2 / DEPTH_MAX));
444
+ const a = lo.sub(oz).div(rz),
445
+ b = hi.sub(oz).div(rz);
446
+ start.assign(min(a, b));
447
+ end.assign(lo.lessThanEqual(hi).select(max(a, b), enter.sub(1)));
448
+ });
449
+ return { start, end };
450
+ };
451
+ };
452
+ }