@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.
- package/CHANGELOG.md +7 -0
- package/README.md +14 -1
- package/build/box-impostor-runtime.js +321 -195
- package/build/box-impostor-runtime.js.map +4 -4
- package/build/impostor-runtime.js +944 -202
- package/build/impostor-runtime.js.map +4 -4
- package/build/index.js +7 -7
- package/build/index.js.map +2 -2
- package/build/internal/box-impostor/box-impostor-display.js +319 -193
- package/build/internal/box-impostor/box-impostor-display.js.map +4 -4
- package/build/internal/box-impostor/box-impostor-faces.js +8 -6
- package/build/internal/box-impostor/box-impostor-faces.js.map +2 -2
- package/build/internal/box-impostor/box-impostor-material.js +319 -193
- package/build/internal/box-impostor/box-impostor-material.js.map +4 -4
- package/build/internal/box-impostor/box-impostor-projection.js +8 -5
- package/build/internal/box-impostor/box-impostor-projection.js.map +2 -2
- package/build/internal/box-impostor/box-impostor-runtime.js +321 -195
- package/build/internal/box-impostor/box-impostor-runtime.js.map +4 -4
- package/build/internal/impostor/adaptive-impostor-renderer.js +434 -0
- package/build/internal/impostor/adaptive-impostor-renderer.js.map +7 -0
- package/build/internal/impostor/impostor-node-material.js +944 -202
- package/build/internal/impostor/impostor-node-material.js.map +4 -4
- package/build/internal/impostor/impostor-performance.js +136 -0
- package/build/internal/impostor/impostor-performance.js.map +7 -0
- package/build/internal/pixel-impostor/pixel-impostor-runtime.js +6 -1
- package/build/internal/pixel-impostor/pixel-impostor-runtime.js.map +2 -2
- package/build/internal/rendering/instance-space.js +110 -0
- package/build/internal/rendering/instance-space.js.map +7 -0
- package/build/internal/rendering/renderer-support.js +6 -1
- package/build/internal/rendering/renderer-support.js.map +2 -2
- package/build/pixel-impostor-runtime.js +6 -1
- package/build/pixel-impostor-runtime.js.map +2 -2
- package/build/types/box-impostor/box-impostor-faces.d.ts +3 -1
- package/build/types/box-impostor/box-impostor-projection.d.ts +3 -1
- package/build/types/impostor/adaptive-impostor-renderer.d.ts +74 -0
- package/build/types/impostor/adaptive-impostor-renderer.js +1 -0
- package/build/types/impostor/impostor-node-material.d.ts +5 -1
- package/build/types/impostor/impostor-performance.d.ts +90 -0
- package/build/types/impostor/impostor-performance.js +1 -0
- package/build/types/public/impostor-runtime.d.ts +2 -0
- package/build/types/public/index.d.ts +3 -0
- package/build/types/rendering/instance-space.d.ts +26 -0
- package/build/types/rendering/instance-space.js +1 -0
- package/build/types/rendering/renderer-support.d.ts +13 -0
- package/package.json +2 -2
- package/src/box-impostor/box-impostor-faces.js +7 -5
- package/src/box-impostor/box-impostor-material.js +34 -19
- package/src/box-impostor/box-impostor-projection.js +7 -4
- package/src/impostor/adaptive-impostor-renderer.js +423 -0
- package/src/impostor/impostor-node-material.js +347 -157
- package/src/impostor/impostor-performance.js +152 -0
- package/src/public/impostor-runtime.js +2 -0
- package/src/public/index.js +12 -9
- package/src/rendering/instance-space.js +121 -0
- package/src/rendering/renderer-support.js +9 -0
|
@@ -16,6 +16,10 @@ function rendererSupportsImpostorNodeMaterials(renderer) {
|
|
|
16
16
|
if (typeof Reflect.get(TSL, "struct") !== "function") return false;
|
|
17
17
|
return renderer?.isWebGPURenderer === true || renderer?.capabilities?.supportsNodeMaterials === true;
|
|
18
18
|
}
|
|
19
|
+
function rendererUsesMultisampleCoverage(renderer) {
|
|
20
|
+
const samples = renderer.currentSamples ?? renderer.getRenderTarget?.()?.samples;
|
|
21
|
+
return samples === void 0 ? renderer.getContextAttributes?.()?.antialias === true : samples > 1;
|
|
22
|
+
}
|
|
19
23
|
var pending = /* @__PURE__ */ new WeakMap();
|
|
20
24
|
async function enableRendererNodeMaterials(renderer) {
|
|
21
25
|
if (rendererSupportsImpostorNodeMaterials(renderer) || !renderer?.isWebGLRenderer || !renderer.setNodesHandler || typeof Reflect.get(TSL, "struct") !== "function") return;
|
|
@@ -93,6 +97,7 @@ function capturedSurfaceDepth(position, shadowBias = 0) {
|
|
|
93
97
|
|
|
94
98
|
// src/impostor/impostor-node-material.js
|
|
95
99
|
import {
|
|
100
|
+
Box3,
|
|
96
101
|
ClampToEdgeWrapping,
|
|
97
102
|
DoubleSide,
|
|
98
103
|
GLSL3,
|
|
@@ -102,8 +107,9 @@ import {
|
|
|
102
107
|
NoColorSpace,
|
|
103
108
|
SRGBColorSpace,
|
|
104
109
|
ShaderMaterial,
|
|
110
|
+
Sphere as Sphere2,
|
|
105
111
|
Vector3,
|
|
106
|
-
Vector4
|
|
112
|
+
Vector4 as Vector42
|
|
107
113
|
} from "three/webgpu";
|
|
108
114
|
import * as TSL2 from "three/tsl";
|
|
109
115
|
import {
|
|
@@ -116,15 +122,15 @@ import {
|
|
|
116
122
|
bool,
|
|
117
123
|
cameraPosition,
|
|
118
124
|
cameraWorldMatrix,
|
|
119
|
-
cross,
|
|
120
|
-
dot,
|
|
125
|
+
cross as cross2,
|
|
126
|
+
dot as dot2,
|
|
121
127
|
exp,
|
|
122
128
|
float,
|
|
123
129
|
floor,
|
|
124
130
|
fract,
|
|
125
131
|
fwidth,
|
|
126
|
-
int,
|
|
127
|
-
ivec2,
|
|
132
|
+
int as int2,
|
|
133
|
+
ivec2 as ivec22,
|
|
128
134
|
max,
|
|
129
135
|
min,
|
|
130
136
|
mix,
|
|
@@ -133,13 +139,14 @@ import {
|
|
|
133
139
|
positionGeometry,
|
|
134
140
|
smoothstep,
|
|
135
141
|
texture,
|
|
136
|
-
textureLoad,
|
|
142
|
+
textureLoad as textureLoad2,
|
|
137
143
|
textureSize,
|
|
138
144
|
transformNormalToView,
|
|
139
145
|
uniformArray,
|
|
146
|
+
varying as varying2,
|
|
140
147
|
vec2,
|
|
141
|
-
vec3,
|
|
142
|
-
vec4 as
|
|
148
|
+
vec3 as vec32,
|
|
149
|
+
vec4 as vec44
|
|
143
150
|
} from "three/tsl";
|
|
144
151
|
|
|
145
152
|
// src/impostor/impostor-metadata.js
|
|
@@ -213,6 +220,477 @@ function isBlendZone(value) {
|
|
|
213
220
|
value <= 1;
|
|
214
221
|
}
|
|
215
222
|
|
|
223
|
+
// src/impostor/adaptive-impostor-renderer.js
|
|
224
|
+
import {
|
|
225
|
+
DynamicDrawUsage,
|
|
226
|
+
InstancedBufferAttribute,
|
|
227
|
+
InstancedMesh,
|
|
228
|
+
Matrix4,
|
|
229
|
+
OrthographicCamera as OrthographicCamera2,
|
|
230
|
+
Sphere,
|
|
231
|
+
Vector2,
|
|
232
|
+
Vector4
|
|
233
|
+
} from "three";
|
|
234
|
+
|
|
235
|
+
// src/impostor/impostor-performance.js
|
|
236
|
+
import { OrthographicCamera } from "three";
|
|
237
|
+
var IMPOSTOR_PERFORMANCE_PRESETS = (
|
|
238
|
+
/** @type {const} */
|
|
239
|
+
{
|
|
240
|
+
fast: {
|
|
241
|
+
interpolation: true,
|
|
242
|
+
reprojection: false,
|
|
243
|
+
depthWeights: false,
|
|
244
|
+
perspectiveCorrection: true,
|
|
245
|
+
cellCorrection: false,
|
|
246
|
+
boundedReprojection: true,
|
|
247
|
+
raySamples: 0,
|
|
248
|
+
depthSamples: 0
|
|
249
|
+
},
|
|
250
|
+
medium: {
|
|
251
|
+
interpolation: true,
|
|
252
|
+
reprojection: true,
|
|
253
|
+
depthWeights: true,
|
|
254
|
+
perspectiveCorrection: true,
|
|
255
|
+
cellCorrection: false,
|
|
256
|
+
boundedReprojection: true,
|
|
257
|
+
raySamples: 8,
|
|
258
|
+
depthSamples: 2
|
|
259
|
+
},
|
|
260
|
+
high: {
|
|
261
|
+
interpolation: true,
|
|
262
|
+
reprojection: true,
|
|
263
|
+
depthWeights: true,
|
|
264
|
+
perspectiveCorrection: true,
|
|
265
|
+
cellCorrection: false,
|
|
266
|
+
boundedReprojection: true,
|
|
267
|
+
raySamples: 16,
|
|
268
|
+
depthSamples: 4
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
);
|
|
272
|
+
var IMPOSTOR_PERFORMANCE_TIERS = (
|
|
273
|
+
/** @type {const} */
|
|
274
|
+
["fast", "medium", "high"]
|
|
275
|
+
);
|
|
276
|
+
var DEFAULT_FRAME_BUDGET_MS = 1e3 / 60;
|
|
277
|
+
function resolveImpostorFrameBudget(performance2) {
|
|
278
|
+
const budget = typeof performance2 === "object" ? performance2.frameBudgetMs ?? DEFAULT_FRAME_BUDGET_MS : DEFAULT_FRAME_BUDGET_MS;
|
|
279
|
+
if (budget !== false && (!Number.isFinite(budget) || budget <= 0)) {
|
|
280
|
+
throw new RangeError("Impostor frameBudgetMs must be a positive finite number or false.");
|
|
281
|
+
}
|
|
282
|
+
return budget;
|
|
283
|
+
}
|
|
284
|
+
function selectImpostorTier(pixels, previous, pressure = 1, ceiling = 2) {
|
|
285
|
+
if (ceiling >= 2 && pixels >= pressure * (previous === 2 ? 160 : 208)) return 2;
|
|
286
|
+
return ceiling >= 1 && pixels >= pressure * (previous === 0 ? 96 : 72) ? 1 : 0;
|
|
287
|
+
}
|
|
288
|
+
function impostorPixelDiameter(radius, depth, scale, orthographic) {
|
|
289
|
+
if (orthographic) return radius * scale;
|
|
290
|
+
return depth <= -radius ? 0 : radius * scale / Math.max(radius, depth, 1e-4);
|
|
291
|
+
}
|
|
292
|
+
function createImpostorFrameBudget(budget = DEFAULT_FRAME_BUDGET_MS) {
|
|
293
|
+
const minimumInterval = Math.min(6, budget / 2);
|
|
294
|
+
const backlogThreshold = budget * (32 / DEFAULT_FRAME_BUDGET_MS);
|
|
295
|
+
let previous = -1, average = budget, pressure = 1;
|
|
296
|
+
let slow = 0, headroom = 0, ceiling = 2;
|
|
297
|
+
return {
|
|
298
|
+
get pressure() {
|
|
299
|
+
return pressure;
|
|
300
|
+
},
|
|
301
|
+
get ceiling() {
|
|
302
|
+
return ceiling;
|
|
303
|
+
},
|
|
304
|
+
/** @param {number} time @param {number=} gpuMilliseconds @param {number=} queueLag */
|
|
305
|
+
observe(time, gpuMilliseconds = 0, queueLag = 0) {
|
|
306
|
+
if (previous < 0) {
|
|
307
|
+
previous = time;
|
|
308
|
+
return pressure;
|
|
309
|
+
}
|
|
310
|
+
const elapsed = time - previous;
|
|
311
|
+
if (elapsed >= 0 && elapsed < minimumInterval) return pressure;
|
|
312
|
+
previous = time;
|
|
313
|
+
if (elapsed > 250 || elapsed <= 0) {
|
|
314
|
+
average = budget;
|
|
315
|
+
slow = headroom = 0;
|
|
316
|
+
return pressure;
|
|
317
|
+
}
|
|
318
|
+
average += (elapsed - average) * 0.14;
|
|
319
|
+
if (queueLag > backlogThreshold) gpuMilliseconds = Math.max(gpuMilliseconds, queueLag);
|
|
320
|
+
const slowFrame = elapsed > budget * 1.13 && average > budget * 1.13;
|
|
321
|
+
if (slowFrame || gpuMilliseconds > budget * 0.95) {
|
|
322
|
+
headroom = 0;
|
|
323
|
+
slow += Math.min(elapsed, 100);
|
|
324
|
+
if (slow >= 160) {
|
|
325
|
+
if (pressure >= 8) ceiling = Math.max(0, ceiling - 1);
|
|
326
|
+
else pressure = Math.min(8, pressure * Math.max(1.3, Math.min(2.5, average / budget)));
|
|
327
|
+
slow = 0;
|
|
328
|
+
}
|
|
329
|
+
} else if (average < budget * 1.06 && gpuMilliseconds < budget * 0.8) {
|
|
330
|
+
slow = 0;
|
|
331
|
+
if (++headroom >= 60) {
|
|
332
|
+
if (ceiling < 2) ceiling++;
|
|
333
|
+
else pressure = Math.max(1, pressure / 1.18);
|
|
334
|
+
headroom = 0;
|
|
335
|
+
}
|
|
336
|
+
} else {
|
|
337
|
+
slow = headroom = 0;
|
|
338
|
+
}
|
|
339
|
+
return pressure;
|
|
340
|
+
}
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// src/impostor/adaptive-impostor-renderer.js
|
|
345
|
+
var renderers = /* @__PURE__ */ new WeakMap();
|
|
346
|
+
function wrapRenderer(renderer) {
|
|
347
|
+
const original = renderer.render;
|
|
348
|
+
if (typeof original !== "function") return null;
|
|
349
|
+
const bindings = /* @__PURE__ */ new WeakMap();
|
|
350
|
+
const frameBudgets = /* @__PURE__ */ new Map();
|
|
351
|
+
const drawingSize = new Vector2(), viewport = new Vector4();
|
|
352
|
+
let rendering = false, active = 0, lastGpuTime = 0, lastFrame = -1;
|
|
353
|
+
let submittedAt = -1, lastProbe = -Infinity, queueLag = 0, completedAt = -Infinity;
|
|
354
|
+
function probeQueue(time) {
|
|
355
|
+
if (submittedAt >= 0 || time - lastProbe < 120) return;
|
|
356
|
+
const queue = renderer.backend?.device?.queue;
|
|
357
|
+
if (!queue?.onSubmittedWorkDone) return;
|
|
358
|
+
lastProbe = submittedAt = time;
|
|
359
|
+
void queue.onSubmittedWorkDone().then(() => {
|
|
360
|
+
completedAt = performance.now();
|
|
361
|
+
queueLag = completedAt - submittedAt;
|
|
362
|
+
submittedAt = -1;
|
|
363
|
+
}, () => {
|
|
364
|
+
submittedAt = -1;
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
const render = (scene, camera) => {
|
|
368
|
+
if (rendering || !active) return original.call(renderer, scene, camera);
|
|
369
|
+
const objects = [];
|
|
370
|
+
scene.traverseVisible((object) => {
|
|
371
|
+
const mesh = (
|
|
372
|
+
/** @type {Mesh} */
|
|
373
|
+
object
|
|
374
|
+
);
|
|
375
|
+
if (!mesh.isMesh || Array.isArray(mesh.material) || !camera.layers.test(mesh.layers)) return;
|
|
376
|
+
const entry = bindings.get(mesh.material);
|
|
377
|
+
if (entry) objects.push({ mesh, ...entry });
|
|
378
|
+
});
|
|
379
|
+
if (!objects.length) return original.call(renderer, scene, camera);
|
|
380
|
+
const target = renderer.getRenderTarget?.();
|
|
381
|
+
const height = target?.viewport.w ?? (renderer.getViewport ? renderer.getViewport(viewport).w * (renderer.getPixelRatio?.() ?? 1) : renderer.getDrawingBufferSize?.(drawingSize).y ?? 0);
|
|
382
|
+
if (height <= 0) return original.call(renderer, scene, camera);
|
|
383
|
+
const frame = renderer.info?.frame ?? 0;
|
|
384
|
+
const page = (
|
|
385
|
+
/** @type {typeof globalThis & { document?: { hidden: boolean } }} */
|
|
386
|
+
globalThis.document
|
|
387
|
+
);
|
|
388
|
+
const sampleFrame = frameBudgets.size > 0 && (frame > 0 ? frame !== lastFrame : !target) && page?.hidden === false;
|
|
389
|
+
if (sampleFrame) {
|
|
390
|
+
const time = performance.now();
|
|
391
|
+
const gpuTime = renderer.info?.render?.timestamp ?? 0;
|
|
392
|
+
const backlog = submittedAt >= 0 ? time - submittedAt : time - completedAt < 120 ? queueLag : 0;
|
|
393
|
+
for (const { state } of frameBudgets.values()) {
|
|
394
|
+
state.observe(time, gpuTime === lastGpuTime ? 0 : gpuTime, backlog);
|
|
395
|
+
}
|
|
396
|
+
lastGpuTime = gpuTime;
|
|
397
|
+
lastFrame = frame;
|
|
398
|
+
}
|
|
399
|
+
const scale = height * Math.abs(camera.projectionMatrix.elements[5]);
|
|
400
|
+
camera.updateWorldMatrix(true, false);
|
|
401
|
+
const restore = [];
|
|
402
|
+
rendering = true;
|
|
403
|
+
try {
|
|
404
|
+
for (const binding of new Set(objects.map((entry) => entry.binding))) binding.beginFrame();
|
|
405
|
+
for (const { mesh, binding, frameBudget } of objects) {
|
|
406
|
+
mesh.updateWorldMatrix(true, false);
|
|
407
|
+
const reset = binding.prepare(mesh, camera, scale, frameBudget?.pressure ?? 1, frameBudget?.ceiling ?? 2);
|
|
408
|
+
if (reset) restore.push(reset);
|
|
409
|
+
}
|
|
410
|
+
const result = original.call(renderer, scene, camera);
|
|
411
|
+
if (sampleFrame) probeQueue(performance.now());
|
|
412
|
+
return result;
|
|
413
|
+
} finally {
|
|
414
|
+
for (let index = restore.length - 1; index >= 0; index--) restore[index]();
|
|
415
|
+
rendering = false;
|
|
416
|
+
}
|
|
417
|
+
};
|
|
418
|
+
renderer.render = render;
|
|
419
|
+
return {
|
|
420
|
+
/** @param {Material} material @param {ReturnType<typeof createBinding>} binding @param {number | false} frameBudgetMs */
|
|
421
|
+
add(material, binding, frameBudgetMs) {
|
|
422
|
+
const budget = frameBudgetMs === false ? void 0 : frameBudgets.get(frameBudgetMs) ?? { state: createImpostorFrameBudget(frameBudgetMs), references: 0 };
|
|
423
|
+
if (frameBudgetMs !== false && budget) {
|
|
424
|
+
budget.references++;
|
|
425
|
+
frameBudgets.set(frameBudgetMs, budget);
|
|
426
|
+
}
|
|
427
|
+
const entry = { binding, frameBudget: budget?.state };
|
|
428
|
+
bindings.set(material, entry);
|
|
429
|
+
active++;
|
|
430
|
+
const dispose = () => {
|
|
431
|
+
if (bindings.get(material) !== entry) return;
|
|
432
|
+
material.removeEventListener("dispose", dispose);
|
|
433
|
+
bindings.delete(material);
|
|
434
|
+
binding.dispose();
|
|
435
|
+
if (frameBudgetMs !== false && budget && --budget.references === 0) frameBudgets.delete(frameBudgetMs);
|
|
436
|
+
if (--active === 0 && renderer.render === render) {
|
|
437
|
+
renderer.render = original;
|
|
438
|
+
renderers.delete(renderer);
|
|
439
|
+
}
|
|
440
|
+
};
|
|
441
|
+
material.addEventListener("dispose", dispose);
|
|
442
|
+
return dispose;
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
function registerAdaptiveImpostorMaterial(renderer, material, bounds, createVariant, frameBudgetMs) {
|
|
447
|
+
let hook = renderers.get(renderer);
|
|
448
|
+
if (!hook) {
|
|
449
|
+
const installed = wrapRenderer(renderer);
|
|
450
|
+
if (!installed) return;
|
|
451
|
+
hook = installed;
|
|
452
|
+
renderers.set(renderer, hook);
|
|
453
|
+
}
|
|
454
|
+
const binding = createBinding(material, bounds, createVariant, renderer.isWebGLRenderer === true);
|
|
455
|
+
const dispose = hook.add(material, binding, frameBudgetMs);
|
|
456
|
+
return { dispose, read: binding.read };
|
|
457
|
+
}
|
|
458
|
+
function createBinding(material, bounds, createVariant, classicWebGL) {
|
|
459
|
+
const single = /* @__PURE__ */ new WeakMap();
|
|
460
|
+
const instanced = /* @__PURE__ */ new WeakMap();
|
|
461
|
+
const ownedBins = /* @__PURE__ */ new Set();
|
|
462
|
+
const variants = [void 0, void 0, material];
|
|
463
|
+
const instanceVariants = [];
|
|
464
|
+
const sphere = new Sphere();
|
|
465
|
+
const viewFromMesh = new Matrix4();
|
|
466
|
+
const frameCounts = [0, 0, 0];
|
|
467
|
+
let frameInstanced = false;
|
|
468
|
+
let version = material.version;
|
|
469
|
+
function clearVariants() {
|
|
470
|
+
for (const variant2 of [...variants, ...instanceVariants]) {
|
|
471
|
+
if (variant2 && variant2 !== material) variant2.dispose();
|
|
472
|
+
}
|
|
473
|
+
variants[0] = variants[1] = void 0;
|
|
474
|
+
instanceVariants.length = 0;
|
|
475
|
+
}
|
|
476
|
+
const variant = (tier) => variants[tier] ??= createVariant(tier);
|
|
477
|
+
const instanceVariant = (tier) => classicWebGL ? instanceVariants[tier] ??= createVariant(tier) : variant(tier);
|
|
478
|
+
return {
|
|
479
|
+
beginFrame() {
|
|
480
|
+
frameCounts.fill(0);
|
|
481
|
+
frameInstanced = false;
|
|
482
|
+
},
|
|
483
|
+
/** @returns {AdaptiveImpostorPerformance | null} */
|
|
484
|
+
read() {
|
|
485
|
+
const [fast, medium, high] = frameCounts;
|
|
486
|
+
const active = [fast, medium, high].filter((count) => count > 0).length;
|
|
487
|
+
if (!active) return null;
|
|
488
|
+
const tier = fast ? 0 : medium ? 1 : 2;
|
|
489
|
+
return {
|
|
490
|
+
active: active > 1 ? "mixed" : IMPOSTOR_PERFORMANCE_TIERS[tier],
|
|
491
|
+
instances: frameInstanced ? { fast, medium, high } : null,
|
|
492
|
+
profile: active === 1 ? (frameInstanced ? instanceVariant(tier) : variant(tier)).userData.impostorShaderProfile : null
|
|
493
|
+
};
|
|
494
|
+
},
|
|
495
|
+
/** @param {Mesh} mesh @param {Camera} camera @param {number} scale @param {number} pressure @param {number} ceiling */
|
|
496
|
+
prepare(mesh, camera, scale, pressure, ceiling) {
|
|
497
|
+
if (version !== material.version) {
|
|
498
|
+
version = material.version;
|
|
499
|
+
clearVariants();
|
|
500
|
+
}
|
|
501
|
+
const ortho = camera instanceof OrthographicCamera2;
|
|
502
|
+
viewFromMesh.multiplyMatrices(camera.matrixWorldInverse, mesh.matrixWorld);
|
|
503
|
+
const worldScale = mesh.matrixWorld.getMaxScaleOnAxis();
|
|
504
|
+
if (
|
|
505
|
+
/** @type {InstancedMesh} */
|
|
506
|
+
mesh.isInstancedMesh
|
|
507
|
+
) {
|
|
508
|
+
const source = (
|
|
509
|
+
/** @type {InstancedMesh} */
|
|
510
|
+
mesh
|
|
511
|
+
);
|
|
512
|
+
if (!source.count || source.morphTexture) return;
|
|
513
|
+
let bins = instanced.get(source);
|
|
514
|
+
if (!bins) {
|
|
515
|
+
bins = createInstanceBins(bounds);
|
|
516
|
+
instanced.set(source, bins);
|
|
517
|
+
ownedBins.add(bins);
|
|
518
|
+
const owned = bins;
|
|
519
|
+
source.addEventListener("dispose", () => {
|
|
520
|
+
if (ownedBins.delete(owned)) owned.dispose();
|
|
521
|
+
instanced.delete(source);
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
const reset = bins.prepare(source, instanceVariant, viewFromMesh, worldScale, scale, ortho, pressure, ceiling);
|
|
525
|
+
frameInstanced = true;
|
|
526
|
+
for (let tier2 = 0; tier2 < 3; tier2++) frameCounts[tier2] += bins.counts[tier2];
|
|
527
|
+
return reset;
|
|
528
|
+
}
|
|
529
|
+
sphere.copy(bounds).applyMatrix4(viewFromMesh);
|
|
530
|
+
const pixels = impostorPixelDiameter(sphere.radius, -sphere.center.z, scale, ortho);
|
|
531
|
+
const tier = selectImpostorTier(pixels, single.get(mesh) ?? -1, pressure, ceiling);
|
|
532
|
+
single.set(mesh, tier);
|
|
533
|
+
frameCounts[tier]++;
|
|
534
|
+
return applyTier(mesh, variant(tier));
|
|
535
|
+
},
|
|
536
|
+
dispose() {
|
|
537
|
+
clearVariants();
|
|
538
|
+
for (const bins of ownedBins) bins.dispose();
|
|
539
|
+
ownedBins.clear();
|
|
540
|
+
}
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
function applyTier(mesh, material) {
|
|
544
|
+
const original = mesh.material;
|
|
545
|
+
if (material === original) return;
|
|
546
|
+
mesh.material = material;
|
|
547
|
+
return () => {
|
|
548
|
+
if (mesh.material === material) mesh.material = original;
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
function createInstanceBins(bounds) {
|
|
552
|
+
const meshes = [];
|
|
553
|
+
const matrix = new Matrix4(), previousView = new Matrix4();
|
|
554
|
+
const sphere = new Sphere();
|
|
555
|
+
const counts = [0, 0, 0];
|
|
556
|
+
let dirty = 0, count = -1, capacity = 0;
|
|
557
|
+
let assignments = new Uint8Array(), centers = new Float32Array();
|
|
558
|
+
let matrixAttribute = null;
|
|
559
|
+
let colorAttribute = null;
|
|
560
|
+
let matrixVersion = -1, colorVersion = -1, lastScale = 0, lastPressure = 0, lastCeiling = 2, lastOrtho = false;
|
|
561
|
+
function dispose() {
|
|
562
|
+
for (const mesh of meshes) mesh?.dispose();
|
|
563
|
+
meshes.length = 0;
|
|
564
|
+
}
|
|
565
|
+
return {
|
|
566
|
+
counts,
|
|
567
|
+
/**
|
|
568
|
+
* @param {InstancedMesh} source @param {(tier: number) => Material} variant
|
|
569
|
+
* @param {Matrix4} view @param {number} worldScale @param {number} scale
|
|
570
|
+
* @param {boolean} ortho @param {number} pressure @param {number} ceiling
|
|
571
|
+
*/
|
|
572
|
+
prepare(source, variant, view, worldScale, scale, ortho, pressure, ceiling) {
|
|
573
|
+
const sourceMatrices = source.instanceMatrix, colors = source.instanceColor;
|
|
574
|
+
if (capacity !== sourceMatrices.count) {
|
|
575
|
+
dispose();
|
|
576
|
+
capacity = sourceMatrices.count;
|
|
577
|
+
assignments = new Uint8Array(capacity).fill(3);
|
|
578
|
+
centers = new Float32Array(capacity * 4);
|
|
579
|
+
count = -1;
|
|
580
|
+
}
|
|
581
|
+
const transformed = count !== source.count || matrixAttribute !== sourceMatrices || matrixVersion !== sourceMatrices.version;
|
|
582
|
+
const recolored = colorAttribute !== colors || colorVersion !== (colors?.version ?? -1);
|
|
583
|
+
if (transformed) {
|
|
584
|
+
count = source.count;
|
|
585
|
+
matrixAttribute = sourceMatrices;
|
|
586
|
+
matrixVersion = sourceMatrices.version;
|
|
587
|
+
for (let index = 0; index < count; index++) {
|
|
588
|
+
source.getMatrixAt(index, matrix);
|
|
589
|
+
sphere.copy(bounds).applyMatrix4(matrix);
|
|
590
|
+
const offset = index * 4;
|
|
591
|
+
centers[offset] = sphere.center.x;
|
|
592
|
+
centers[offset + 1] = sphere.center.y;
|
|
593
|
+
centers[offset + 2] = sphere.center.z;
|
|
594
|
+
centers[offset + 3] = sphere.radius;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
if (recolored) {
|
|
598
|
+
colorAttribute = colors;
|
|
599
|
+
colorVersion = colors?.version ?? -1;
|
|
600
|
+
}
|
|
601
|
+
if (transformed || lastScale !== scale || lastPressure !== pressure || lastCeiling !== ceiling || lastOrtho !== ortho || !previousView.equals(view)) {
|
|
602
|
+
previousView.copy(view);
|
|
603
|
+
lastScale = scale;
|
|
604
|
+
lastPressure = pressure;
|
|
605
|
+
lastCeiling = ceiling;
|
|
606
|
+
lastOrtho = ortho;
|
|
607
|
+
counts.fill(0);
|
|
608
|
+
const e = view.elements;
|
|
609
|
+
for (let index = 0; index < count; index++) {
|
|
610
|
+
const offset = index * 4;
|
|
611
|
+
const depth = -(e[2] * centers[offset] + e[6] * centers[offset + 1] + e[10] * centers[offset + 2] + e[14]);
|
|
612
|
+
const pixels = impostorPixelDiameter(centers[offset + 3] * worldScale, depth, scale, ortho);
|
|
613
|
+
const previous = assignments[index];
|
|
614
|
+
const tier = selectImpostorTier(pixels, previous, pressure, ceiling);
|
|
615
|
+
counts[tier]++;
|
|
616
|
+
if (tier === previous) continue;
|
|
617
|
+
dirty |= 1 << previous | 1 << tier;
|
|
618
|
+
assignments[index] = tier;
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
const wholeTier = counts.indexOf(count);
|
|
622
|
+
if (wholeTier >= 0) return applyTier(source, variant(wholeTier));
|
|
623
|
+
const active = [];
|
|
624
|
+
for (let tier = 0; tier < counts.length; tier++) {
|
|
625
|
+
if (!counts[tier]) continue;
|
|
626
|
+
let mesh = meshes[tier];
|
|
627
|
+
if (!mesh) {
|
|
628
|
+
meshes[tier] = mesh = new InstancedMesh(source.geometry, variant(tier), capacity);
|
|
629
|
+
mesh.instanceMatrix.setUsage(DynamicDrawUsage);
|
|
630
|
+
dirty |= 1 << tier;
|
|
631
|
+
}
|
|
632
|
+
mesh.geometry = source.geometry;
|
|
633
|
+
mesh.material = variant(tier);
|
|
634
|
+
mesh.count = counts[tier];
|
|
635
|
+
mesh.castShadow = source.castShadow;
|
|
636
|
+
mesh.receiveShadow = source.receiveShadow;
|
|
637
|
+
mesh.renderOrder = source.renderOrder;
|
|
638
|
+
mesh.layers.mask = source.layers.mask;
|
|
639
|
+
mesh.frustumCulled = false;
|
|
640
|
+
mesh.customDepthMaterial = source.customDepthMaterial;
|
|
641
|
+
mesh.customDistanceMaterial = source.customDistanceMaterial;
|
|
642
|
+
if (colors && (!mesh.instanceColor || recolored && mesh.instanceColor.array.constructor !== colors.array.constructor)) {
|
|
643
|
+
mesh.instanceColor = new InstancedBufferAttribute(colors.array.slice(), colors.itemSize, colors.normalized);
|
|
644
|
+
mesh.instanceColor.setUsage(DynamicDrawUsage);
|
|
645
|
+
} else if (!colors) {
|
|
646
|
+
mesh.instanceColor = null;
|
|
647
|
+
}
|
|
648
|
+
if (transformed || recolored || dirty & 1 << tier) {
|
|
649
|
+
packInstances(source, mesh, assignments, tier);
|
|
650
|
+
}
|
|
651
|
+
mesh.onBeforeRender = (...args) => source.onBeforeRender(...args);
|
|
652
|
+
mesh.onAfterRender = (...args) => source.onAfterRender(...args);
|
|
653
|
+
active.push(mesh);
|
|
654
|
+
}
|
|
655
|
+
dirty = 0;
|
|
656
|
+
const mask = source.layers.mask;
|
|
657
|
+
source.add(...active);
|
|
658
|
+
source.layers.mask = 0;
|
|
659
|
+
return () => {
|
|
660
|
+
if (source.layers.mask === 0) source.layers.mask = mask;
|
|
661
|
+
source.remove(...active);
|
|
662
|
+
for (const mesh of active) {
|
|
663
|
+
mesh.onBeforeRender = Object3DPrototype.onBeforeRender;
|
|
664
|
+
mesh.onAfterRender = Object3DPrototype.onAfterRender;
|
|
665
|
+
}
|
|
666
|
+
};
|
|
667
|
+
},
|
|
668
|
+
dispose
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
var Object3DPrototype = InstancedMesh.prototype;
|
|
672
|
+
function packInstances(source, destination, assignments, tier) {
|
|
673
|
+
const matrices = source.instanceMatrix.array, packed = destination.instanceMatrix.array;
|
|
674
|
+
const sourceColors = source.instanceColor, targetColors = destination.instanceColor;
|
|
675
|
+
let next = 0;
|
|
676
|
+
for (let index = 0; index < source.count; index++) {
|
|
677
|
+
if (assignments[index] !== tier) continue;
|
|
678
|
+
for (let lane = 0; lane < 16; lane++) packed[next * 16 + lane] = matrices[index * 16 + lane];
|
|
679
|
+
if (sourceColors && targetColors) {
|
|
680
|
+
for (let lane = 0; lane < sourceColors.itemSize; lane++) {
|
|
681
|
+
targetColors.array[next * sourceColors.itemSize + lane] = sourceColors.array[index * sourceColors.itemSize + lane];
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
next++;
|
|
685
|
+
}
|
|
686
|
+
for (const attribute of [destination.instanceMatrix, destination.instanceColor]) {
|
|
687
|
+
if (!attribute) continue;
|
|
688
|
+
attribute.clearUpdateRanges();
|
|
689
|
+
attribute.addUpdateRange(0, next * attribute.itemSize);
|
|
690
|
+
attribute.needsUpdate = true;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
|
|
216
694
|
// src/rendering/texture-slot.js
|
|
217
695
|
function bindTextureSlot(material, slot, initial, nodes, onChange) {
|
|
218
696
|
let current = initial;
|
|
@@ -234,15 +712,120 @@ function bindTextureSlot(material, slot, initial, nodes, onChange) {
|
|
|
234
712
|
});
|
|
235
713
|
}
|
|
236
714
|
|
|
715
|
+
// src/rendering/instance-space.js
|
|
716
|
+
import { DataTexture, DynamicDrawUsage as DynamicDrawUsage2, FloatType, InstancedInterleavedBuffer, InterpolationSamplingType, NodeUpdateType, RGBAFormat } from "three/webgpu";
|
|
717
|
+
import { cross, dot, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, ivec2, textureLoad, varying, vec3, vec4 as vec43 } from "three/tsl";
|
|
718
|
+
var spaces = /* @__PURE__ */ new WeakMap();
|
|
719
|
+
var webglSpaces = /* @__PURE__ */ new WeakMap();
|
|
720
|
+
function instanceColumns(object, matrix, useTexture) {
|
|
721
|
+
const columns = [0, 1, 2, 3];
|
|
722
|
+
if (useTexture) {
|
|
723
|
+
const rowSize = Math.ceil(Math.sqrt(matrix.count) / 2);
|
|
724
|
+
const rows = Math.ceil(matrix.count / rowSize);
|
|
725
|
+
const data = new Float32Array(rowSize * rows * 16);
|
|
726
|
+
const texture2 = new DataTexture(data, rowSize * 4, rows, RGBAFormat, FloatType);
|
|
727
|
+
const upload = () => {
|
|
728
|
+
data.set(matrix.array);
|
|
729
|
+
texture2.needsUpdate = true;
|
|
730
|
+
};
|
|
731
|
+
upload();
|
|
732
|
+
const release = () => {
|
|
733
|
+
object.removeEventListener("dispose", release);
|
|
734
|
+
texture2.dispose();
|
|
735
|
+
webglSpaces.delete(matrix);
|
|
736
|
+
};
|
|
737
|
+
object.addEventListener("dispose", release);
|
|
738
|
+
const x = instanceIndex.mod(rowSize).mul(4);
|
|
739
|
+
const y = instanceIndex.div(rowSize);
|
|
740
|
+
return { nodes: columns.map((column) => textureLoad(texture2, ivec2(int(x.add(column)), int(y)))), upload };
|
|
741
|
+
}
|
|
742
|
+
const interleaved = new InstancedInterleavedBuffer(matrix.array, 16, 1);
|
|
743
|
+
const read = matrix.usage === DynamicDrawUsage2 ? instancedDynamicBufferAttribute : instancedBufferAttribute;
|
|
744
|
+
return {
|
|
745
|
+
nodes: columns.map((column) => read(
|
|
746
|
+
interleaved,
|
|
747
|
+
/** @type {const} */
|
|
748
|
+
"vec4",
|
|
749
|
+
16,
|
|
750
|
+
column * 4
|
|
751
|
+
)),
|
|
752
|
+
upload: () => {
|
|
753
|
+
interleaved.needsUpdate = true;
|
|
754
|
+
}
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
function instanceSpace(builder) {
|
|
758
|
+
const object = (
|
|
759
|
+
/** @type {InstancedMesh} */
|
|
760
|
+
builder.object
|
|
761
|
+
);
|
|
762
|
+
const matrix = object?.isInstancedMesh ? object.instanceMatrix : null;
|
|
763
|
+
if (!matrix) return null;
|
|
764
|
+
const backend = (
|
|
765
|
+
/** @type {{isWebGPUBackend?: boolean} | undefined} */
|
|
766
|
+
builder.renderer.backend
|
|
767
|
+
);
|
|
768
|
+
const useTexture = !backend?.isWebGPUBackend && matrix.count * 64 > (builder.getUniformBufferLimit?.() ?? 16384);
|
|
769
|
+
const cache = useTexture ? webglSpaces : spaces;
|
|
770
|
+
const cached = cache.get(matrix);
|
|
771
|
+
if (cached) return cached;
|
|
772
|
+
const { nodes, upload } = instanceColumns(object, matrix, useTexture);
|
|
773
|
+
let version = matrix.version;
|
|
774
|
+
nodes[0].updateBeforeType = NodeUpdateType.OBJECT;
|
|
775
|
+
nodes[0].updateBefore = () => {
|
|
776
|
+
if (matrix.version !== version) {
|
|
777
|
+
version = matrix.version;
|
|
778
|
+
upload();
|
|
779
|
+
}
|
|
780
|
+
return void 0;
|
|
781
|
+
};
|
|
782
|
+
const [a, b, c, d] = nodes.map((node) => node.xyz);
|
|
783
|
+
const determinant = dot(a, cross(b, c));
|
|
784
|
+
const rows = [cross(b, c), cross(c, a), cross(a, b)].map((row) => row.div(determinant));
|
|
785
|
+
const toLocalDirection = (v) => vec3(dot(rows[0], v), dot(rows[1], v), dot(rows[2], v));
|
|
786
|
+
const toMeshDirection = (v) => a.mul(v.x).add(b.mul(v.y)).add(c.mul(v.z));
|
|
787
|
+
const translation = [d.x, d.y, d.z];
|
|
788
|
+
const packed = [a, b, c].map(
|
|
789
|
+
(column, k) => varying(vec43(column, translation[k]), `instanceSpace${k}`).setInterpolation(InterpolationSamplingType.FLAT)
|
|
790
|
+
);
|
|
791
|
+
const [fa, fb, fc] = packed.map((column) => column.xyz);
|
|
792
|
+
const cofactors = () => [cross(fb, fc), cross(fc, fa), cross(fa, fb)];
|
|
793
|
+
const space = {
|
|
794
|
+
toLocalPoint: (p) => toLocalDirection(p.sub(d)),
|
|
795
|
+
toLocalDirection,
|
|
796
|
+
toMeshPoint: (p) => toMeshDirection(p).add(d),
|
|
797
|
+
toMeshDirection,
|
|
798
|
+
fragment: {
|
|
799
|
+
toMeshPoint: (p) => fa.mul(p.x).add(fb.mul(p.y)).add(fc.mul(p.z)).add(vec3(packed[0].w, packed[1].w, packed[2].w)),
|
|
800
|
+
toMeshDirection: (v) => fa.mul(v.x).add(fb.mul(v.y)).add(fc.mul(v.z)),
|
|
801
|
+
toMeshNormal: (n) => {
|
|
802
|
+
const [x, y, z] = cofactors();
|
|
803
|
+
return x.mul(n.x).add(y.mul(n.y)).add(z.mul(n.z)).mul(dot(fa, x).sign()).normalize();
|
|
804
|
+
},
|
|
805
|
+
toLocalDirection: (v) => {
|
|
806
|
+
const [x, y, z] = cofactors();
|
|
807
|
+
return vec3(dot(x, v), dot(y, v), dot(z, v)).div(dot(fa, x));
|
|
808
|
+
},
|
|
809
|
+
toLocalPoint: (p) => {
|
|
810
|
+
const [x, y, z] = cofactors();
|
|
811
|
+
const v = p.sub(vec3(packed[0].w, packed[1].w, packed[2].w));
|
|
812
|
+
return vec3(dot(x, v), dot(y, v), dot(z, v)).div(dot(fa, x));
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
};
|
|
816
|
+
cache.set(matrix, space);
|
|
817
|
+
return space;
|
|
818
|
+
}
|
|
819
|
+
|
|
237
820
|
// src/impostor/octahedral.js
|
|
238
821
|
var PERSPECTIVE_RAY_PLANE_SIGN = -1;
|
|
239
822
|
|
|
240
823
|
// src/impostor/impostor-runtime-support.js
|
|
241
824
|
import {
|
|
242
|
-
DataTexture,
|
|
243
|
-
FloatType,
|
|
825
|
+
DataTexture as DataTexture2,
|
|
826
|
+
FloatType as FloatType2,
|
|
244
827
|
NearestFilter,
|
|
245
|
-
RGBAFormat
|
|
828
|
+
RGBAFormat as RGBAFormat2
|
|
246
829
|
} from "three";
|
|
247
830
|
var REPROJECTION_CONFIDENCE_INNER_TEXELS = 0.25;
|
|
248
831
|
var REPROJECTION_CONFIDENCE_OUTER_TEXELS = 16;
|
|
@@ -253,12 +836,12 @@ function impostorContourUnionSharpness(frames) {
|
|
|
253
836
|
return Math.max(1, 16 / frames);
|
|
254
837
|
}
|
|
255
838
|
function createImpostorViewBoundsTexture(descriptor) {
|
|
256
|
-
const texture2 = new
|
|
839
|
+
const texture2 = new DataTexture2(
|
|
257
840
|
new Float32Array(descriptor.viewBounds),
|
|
258
841
|
descriptor.frames,
|
|
259
842
|
descriptor.frames,
|
|
260
|
-
|
|
261
|
-
|
|
843
|
+
RGBAFormat2,
|
|
844
|
+
FloatType2
|
|
262
845
|
);
|
|
263
846
|
texture2.name = "impostor view bounds";
|
|
264
847
|
texture2.minFilter = NearestFilter;
|
|
@@ -348,7 +931,8 @@ function clampRuntimeSamples(value, maximum) {
|
|
|
348
931
|
if (!Number.isFinite(numeric)) return 0;
|
|
349
932
|
return Math.min(maximum, Math.max(0, Math.round(numeric)));
|
|
350
933
|
}
|
|
351
|
-
function upgradeImpostorScene(root, bindings = /* @__PURE__ */ new Map(), inputFeatures = {}, renderer) {
|
|
934
|
+
function upgradeImpostorScene(root, bindings = /* @__PURE__ */ new Map(), inputFeatures = {}, renderer, performance2 = "fixed") {
|
|
935
|
+
const frameBudgetMs = resolveImpostorFrameBudget(performance2);
|
|
352
936
|
let upgraded = 0;
|
|
353
937
|
root.traverse((object) => {
|
|
354
938
|
const binding = bindings.get(object);
|
|
@@ -435,9 +1019,53 @@ function upgradeImpostorScene(root, bindings = /* @__PURE__ */ new Map(), inputF
|
|
|
435
1019
|
debugControls.raySamples = { value: descriptor.parallaxSteps * 4 };
|
|
436
1020
|
debugControls.depthSamples = { value: descriptor.parallaxSteps };
|
|
437
1021
|
debugControls.blendZone = { value: descriptor.blendZone };
|
|
438
|
-
|
|
1022
|
+
const variants = /* @__PURE__ */ new Map();
|
|
1023
|
+
let cachedAtlases = "";
|
|
1024
|
+
let adaptive;
|
|
1025
|
+
function stopAdaptivePerformance() {
|
|
1026
|
+
adaptive?.dispose();
|
|
1027
|
+
adaptive = void 0;
|
|
1028
|
+
}
|
|
1029
|
+
const releaseVariants = (keep) => {
|
|
1030
|
+
const retained = [...variants.values()];
|
|
1031
|
+
variants.clear();
|
|
1032
|
+
for (const material2 of retained) {
|
|
1033
|
+
material2.removeEventListener("dispose", onVariantDisposed);
|
|
1034
|
+
if (material2 !== keep) material2.dispose();
|
|
1035
|
+
}
|
|
1036
|
+
};
|
|
1037
|
+
const onVariantDisposed = (event) => releaseVariants(event.target);
|
|
1038
|
+
debugControls.setFeatures = (features, cacheVariants = false) => {
|
|
439
1039
|
const next = resolveImpostorRuntimeFeatures(descriptor, features);
|
|
440
|
-
|
|
1040
|
+
const previous = object.material;
|
|
1041
|
+
const atlasKey = cacheVariants ? Object.values(maps).map((texture2) => texture2?.uuid).join("/") : "";
|
|
1042
|
+
if (!cacheVariants || next.requested.blendZone !== requestedFeatures.blendZone || atlasKey !== cachedAtlases) {
|
|
1043
|
+
releaseVariants(previous);
|
|
1044
|
+
cachedAtlases = atlasKey;
|
|
1045
|
+
}
|
|
1046
|
+
const key = JSON.stringify(next.requested);
|
|
1047
|
+
const unchanged = key === JSON.stringify(requestedFeatures);
|
|
1048
|
+
if (unchanged && (!cacheVariants || variants.has(key))) return false;
|
|
1049
|
+
const wasRetained = [...variants.values()].includes(previous);
|
|
1050
|
+
const material2 = unchanged ? previous : variants.get(key) ?? createPbrImpostorNodeMaterial(
|
|
1051
|
+
descriptor,
|
|
1052
|
+
maps,
|
|
1053
|
+
next.requested,
|
|
1054
|
+
renderer
|
|
1055
|
+
);
|
|
1056
|
+
if (cacheVariants) {
|
|
1057
|
+
variants.delete(key);
|
|
1058
|
+
variants.set(key, material2);
|
|
1059
|
+
material2.addEventListener("dispose", onVariantDisposed);
|
|
1060
|
+
if (variants.size > 3) {
|
|
1061
|
+
const [oldKey, oldest] = variants.entries().next().value;
|
|
1062
|
+
variants.delete(oldKey);
|
|
1063
|
+
oldest.removeEventListener("dispose", onVariantDisposed);
|
|
1064
|
+
oldest.dispose();
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
if (unchanged) return false;
|
|
1068
|
+
stopAdaptivePerformance();
|
|
441
1069
|
Object.assign(requestedFeatures, next.requested);
|
|
442
1070
|
for (const name of RUNTIME_FEATURE_NAMES) {
|
|
443
1071
|
debugControls[name].value = requestedFeatures[name] ? 1 : 0;
|
|
@@ -445,25 +1073,41 @@ function upgradeImpostorScene(root, bindings = /* @__PURE__ */ new Map(), inputF
|
|
|
445
1073
|
debugControls.raySamples.value = requestedFeatures.raySamples;
|
|
446
1074
|
debugControls.depthSamples.value = requestedFeatures.depthSamples;
|
|
447
1075
|
debugControls.blendZone.value = requestedFeatures.blendZone;
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
renderer
|
|
454
|
-
);
|
|
455
|
-
replacement.userData.impostor = runtime;
|
|
456
|
-
replacement.userData.impostorDebug = debugControls;
|
|
457
|
-
debugControls.profile = replacement.userData.impostorShaderProfile;
|
|
458
|
-
object.material = replacement;
|
|
459
|
-
if (previous !== fallback) previous.dispose();
|
|
1076
|
+
material2.userData.impostor = runtime;
|
|
1077
|
+
material2.userData.impostorDebug = debugControls;
|
|
1078
|
+
debugControls.profile = material2.userData.impostorShaderProfile;
|
|
1079
|
+
object.material = material2;
|
|
1080
|
+
if (!wasRetained && previous !== fallback) previous.dispose();
|
|
460
1081
|
return true;
|
|
461
1082
|
};
|
|
462
1083
|
const material = createPbrImpostorNodeMaterial(descriptor, maps, requestedFeatures, renderer);
|
|
463
1084
|
material.userData.impostor = runtime;
|
|
464
1085
|
material.userData.impostorDebug = debugControls;
|
|
465
1086
|
debugControls.profile = material.userData.impostorShaderProfile;
|
|
1087
|
+
debugControls.getAdaptivePerformance = () => adaptive?.read() ?? null;
|
|
1088
|
+
debugControls.setPerformance = (mode) => {
|
|
1089
|
+
if (mode === "fixed") {
|
|
1090
|
+
stopAdaptivePerformance();
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
if (adaptive || !nodeMaterials || descriptor.mapping === "single") return;
|
|
1094
|
+
const bounds = new Box3(new Vector3(...descriptor.boundsMin), new Vector3(...descriptor.boundsMax)).getBoundingSphere(new Sphere2());
|
|
1095
|
+
const limits = { ...requestedFeatures };
|
|
1096
|
+
adaptive = registerAdaptiveImpostorMaterial(renderer, object.material, bounds, (tier) => {
|
|
1097
|
+
const preset = tier === 0 ? IMPOSTOR_PERFORMANCE_PRESETS.fast : tier === 1 ? IMPOSTOR_PERFORMANCE_PRESETS.medium : limits;
|
|
1098
|
+
const variant = createPbrImpostorNodeMaterial(descriptor, maps, {
|
|
1099
|
+
...limits,
|
|
1100
|
+
raySamples: Math.min(limits.raySamples, preset.raySamples),
|
|
1101
|
+
depthSamples: Math.min(limits.depthSamples, preset.depthSamples),
|
|
1102
|
+
reprojection: limits.reprojection && preset.reprojection,
|
|
1103
|
+
depthWeights: limits.depthWeights && preset.depthWeights
|
|
1104
|
+
}, renderer);
|
|
1105
|
+
variant.userData.impostor = runtime;
|
|
1106
|
+
return variant;
|
|
1107
|
+
}, frameBudgetMs);
|
|
1108
|
+
};
|
|
466
1109
|
object.material = material;
|
|
1110
|
+
debugControls.setPerformance(typeof performance2 === "object" ? "auto" : performance2);
|
|
467
1111
|
object.castShadow = descriptor.castShadow;
|
|
468
1112
|
object.receiveShadow = descriptor.receiveShadow;
|
|
469
1113
|
object.frustumCulled = false;
|
|
@@ -479,6 +1123,7 @@ var NeedleImpostorLoaderPlugin = class {
|
|
|
479
1123
|
* onUpgrade?: (count: number, result: import('three/addons/loaders/GLTFLoader.js').GLTF) => void,
|
|
480
1124
|
* features?: Partial<ImpostorRuntimeFeatures>,
|
|
481
1125
|
* renderer?: ImpostorRenderer,
|
|
1126
|
+
* performance?: import('./impostor-performance.js').ImpostorPerformance,
|
|
482
1127
|
* }=} options
|
|
483
1128
|
*/
|
|
484
1129
|
constructor(parser, options = {}) {
|
|
@@ -551,7 +1196,8 @@ var NeedleImpostorLoaderPlugin = class {
|
|
|
551
1196
|
root,
|
|
552
1197
|
bindings,
|
|
553
1198
|
this.options.features,
|
|
554
|
-
this.options.renderer
|
|
1199
|
+
this.options.renderer,
|
|
1200
|
+
this.options.performance ?? (this.options.features ? "fixed" : "auto")
|
|
555
1201
|
);
|
|
556
1202
|
}
|
|
557
1203
|
this.options.onUpgrade?.(upgraded, result);
|
|
@@ -577,7 +1223,7 @@ function createCompatibleImpostorNodeMaterial(descriptor, maps) {
|
|
|
577
1223
|
baseColorAtlas: { value: maps.baseColor },
|
|
578
1224
|
geometryAtlas: { value: maps.geometry ?? maps.normalDepth },
|
|
579
1225
|
viewBounds: {
|
|
580
|
-
value: Array.from({ length: boundsCount }, (_, index) => new
|
|
1226
|
+
value: Array.from({ length: boundsCount }, (_, index) => new Vector42(
|
|
581
1227
|
descriptor.viewBounds[index * 4],
|
|
582
1228
|
descriptor.viewBounds[index * 4 + 1],
|
|
583
1229
|
descriptor.viewBounds[index * 4 + 2],
|
|
@@ -602,13 +1248,27 @@ function createCompatibleImpostorNodeMaterial(descriptor, maps) {
|
|
|
602
1248
|
/* glsl */
|
|
603
1249
|
`
|
|
604
1250
|
out vec3 vPlaneLocal;
|
|
1251
|
+
#ifdef USE_INSTANCING
|
|
1252
|
+
flat out vec3 vCameraLocal;
|
|
1253
|
+
flat out mat4 vInstanceMatrix;
|
|
1254
|
+
#endif
|
|
605
1255
|
void main() {
|
|
606
|
-
|
|
1256
|
+
#ifdef USE_INSTANCING
|
|
1257
|
+
mat4 inverseModel = inverse(modelMatrix * instanceMatrix);
|
|
1258
|
+
vCameraLocal = (inverseModel * vec4(cameraPosition, 1.0)).xyz;
|
|
1259
|
+
vInstanceMatrix = instanceMatrix;
|
|
1260
|
+
#else
|
|
1261
|
+
mat4 inverseModel = inverse(modelMatrix);
|
|
1262
|
+
#endif
|
|
607
1263
|
mat4 cameraWorld = inverse(viewMatrix);
|
|
608
1264
|
vec3 rightLocal = normalize((inverseModel * vec4(cameraWorld[0].xyz, 0.0)).xyz);
|
|
609
1265
|
vec3 upLocal = normalize((inverseModel * vec4(cameraWorld[1].xyz, 0.0)).xyz);
|
|
610
1266
|
vPlaneLocal = rightLocal * position.x + upLocal * position.y;
|
|
611
|
-
|
|
1267
|
+
#ifdef USE_INSTANCING
|
|
1268
|
+
gl_Position = projectionMatrix * modelViewMatrix * instanceMatrix * vec4(vPlaneLocal, 1.0);
|
|
1269
|
+
#else
|
|
1270
|
+
gl_Position = projectionMatrix * modelViewMatrix * vec4(vPlaneLocal, 1.0);
|
|
1271
|
+
#endif
|
|
612
1272
|
}
|
|
613
1273
|
`
|
|
614
1274
|
),
|
|
@@ -627,6 +1287,10 @@ function createCompatibleImpostorNodeMaterial(descriptor, maps) {
|
|
|
627
1287
|
uniform mat4 modelViewMatrix;
|
|
628
1288
|
uniform mat4 projectionMatrix;
|
|
629
1289
|
in vec3 vPlaneLocal;
|
|
1290
|
+
#ifdef USE_INSTANCING
|
|
1291
|
+
flat in vec3 vCameraLocal;
|
|
1292
|
+
flat in mat4 vInstanceMatrix;
|
|
1293
|
+
#endif
|
|
630
1294
|
out vec4 fragColor;
|
|
631
1295
|
|
|
632
1296
|
float nonZeroSign(float value) { return value < 0.0 ? -1.0 : 1.0; }
|
|
@@ -691,7 +1355,11 @@ function createCompatibleImpostorNodeMaterial(descriptor, maps) {
|
|
|
691
1355
|
return textureLod(baseColorAtlas, safe, lod);
|
|
692
1356
|
}
|
|
693
1357
|
void main() {
|
|
694
|
-
|
|
1358
|
+
#ifdef USE_INSTANCING
|
|
1359
|
+
vec3 cameraLocal = vCameraLocal;
|
|
1360
|
+
#else
|
|
1361
|
+
vec3 cameraLocal = (inverse(modelMatrix) * vec4(cameraPosition, 1.0)).xyz;
|
|
1362
|
+
#endif
|
|
695
1363
|
vec3 cameraDirection = normalize(cameraLocal);
|
|
696
1364
|
#if SINGLE_VIEW
|
|
697
1365
|
vec2 frame = vec2(0.0);
|
|
@@ -742,7 +1410,11 @@ function createCompatibleImpostorNodeMaterial(descriptor, maps) {
|
|
|
742
1410
|
vec2 plane = mix(bounds.xy, bounds.zw, frameUv);
|
|
743
1411
|
vec3 reconstructedLocal = right * plane.x + up * plane.y
|
|
744
1412
|
+ frameDirection * (radius - depthValue * radius * 2.0);
|
|
745
|
-
|
|
1413
|
+
#ifdef USE_INSTANCING
|
|
1414
|
+
vec4 clip = projectionMatrix * modelViewMatrix * vInstanceMatrix * vec4(reconstructedLocal, 1.0);
|
|
1415
|
+
#else
|
|
1416
|
+
vec4 clip = projectionMatrix * modelViewMatrix * vec4(reconstructedLocal, 1.0);
|
|
1417
|
+
#endif
|
|
746
1418
|
gl_FragDepth = clip.z / clip.w * 0.5 + 0.5;
|
|
747
1419
|
fragColor = vec4(base.rgb, coverage);
|
|
748
1420
|
#if defined(TONE_MAPPING)
|
|
@@ -753,6 +1425,10 @@ function createCompatibleImpostorNodeMaterial(descriptor, maps) {
|
|
|
753
1425
|
`
|
|
754
1426
|
)
|
|
755
1427
|
});
|
|
1428
|
+
material.onBeforeCompile = (shader) => {
|
|
1429
|
+
if (shader.instancing) shader.fragmentShader = `#define USE_INSTANCING
|
|
1430
|
+
${shader.fragmentShader}`;
|
|
1431
|
+
};
|
|
756
1432
|
material.alphaToCoverage = true;
|
|
757
1433
|
material.toneMapped = true;
|
|
758
1434
|
material.userData.impostorShaderProfile = {
|
|
@@ -784,7 +1460,7 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
784
1460
|
const coarseSearchSteps = profile.raySamples;
|
|
785
1461
|
const fullSphere = descriptor.mapping === "full";
|
|
786
1462
|
const singleView = descriptor.mapping === "single";
|
|
787
|
-
const singleCaptureDirection =
|
|
1463
|
+
const singleCaptureDirection = vec32(...descriptor.captureDirection ?? [0, 1, 0]).normalize();
|
|
788
1464
|
const baseColorAtlas = texture(maps.baseColor);
|
|
789
1465
|
const normalDepthAtlas = texture(maps.normalDepth);
|
|
790
1466
|
const geometryAtlas = texture(maps.geometry ?? maps.normalDepth);
|
|
@@ -816,7 +1492,7 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
816
1492
|
const sampleCapturedAlpha = (uvNode) => compressedGeometry ? sampleAtlas(baseColorAtlas, colorAtlasUv(uvNode), float(0), colorColumns).a : sampleAtlas(baseColorAtlas, uvNode).a;
|
|
817
1493
|
const sampleContour = (uvNode) => compressedGeometry ? texture(geometryAtlas, uvNode).level(0).a : descriptor.coverageEncoding === "sdf-base-alpha" ? sampleAtlas(baseColorAtlas, uvNode).a : sampleAtlas(ormAtlas, uvNode).a;
|
|
818
1494
|
const viewBounds = uniformArray(
|
|
819
|
-
Array.from({ length: descriptor.frames * descriptor.frames }, (_, index) => new
|
|
1495
|
+
Array.from({ length: descriptor.frames * descriptor.frames }, (_, index) => new Vector42(
|
|
820
1496
|
descriptor.viewBounds[index * 4],
|
|
821
1497
|
descriptor.viewBounds[index * 4 + 1],
|
|
822
1498
|
descriptor.viewBounds[index * 4 + 2],
|
|
@@ -850,22 +1526,20 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
850
1526
|
emissive: "vec3",
|
|
851
1527
|
capturedCoverage: "float",
|
|
852
1528
|
distanceCoverage: "float",
|
|
853
|
-
cropSupport: "float"
|
|
854
|
-
coverageWidth: "float",
|
|
855
|
-
transition: "float"
|
|
1529
|
+
cropSupport: "float"
|
|
856
1530
|
}, "ImpostorBlendedSample");
|
|
857
1531
|
const basisMember = (value, name) => value.get(name);
|
|
858
1532
|
const frameMember = (value, name) => value.get(name);
|
|
859
1533
|
const blendedMember = (value, name) => value.get(name);
|
|
860
1534
|
const nonZeroSign = Fn2(([value]) => value.lessThan(0).select(float(-1), float(1)), "float");
|
|
861
1535
|
const buildFrameBasis = ([direction]) => {
|
|
862
|
-
const referenceUp = abs(direction.y).greaterThan(0.999).select(
|
|
1536
|
+
const referenceUp = abs(direction.y).greaterThan(0.999).select(vec32(0, 0, -1), vec32(0, 1, 0));
|
|
863
1537
|
const right = referenceUp.cross(direction).normalize();
|
|
864
1538
|
return FrameBasis(right, direction.cross(right).normalize());
|
|
865
1539
|
};
|
|
866
1540
|
const frameBasis = Fn2(buildFrameBasis);
|
|
867
1541
|
const gridToDirection = Fn2(([coordinate]) => {
|
|
868
|
-
const hemisphere =
|
|
1542
|
+
const hemisphere = vec32(
|
|
869
1543
|
coordinate.x.sub(coordinate.y),
|
|
870
1544
|
float(1).sub(abs(coordinate.x.sub(coordinate.y))).sub(abs(float(-1).add(coordinate.x).add(coordinate.y))),
|
|
871
1545
|
float(-1).add(coordinate.x).add(coordinate.y)
|
|
@@ -875,7 +1549,7 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
875
1549
|
const fullY = float(1).sub(abs(fullX)).sub(abs(fullZ)).toVar();
|
|
876
1550
|
const foldedX = nonZeroSign(fullX).mul(float(1).sub(abs(fullZ)));
|
|
877
1551
|
const foldedZ = nonZeroSign(fullZ).mul(float(1).sub(abs(fullX)));
|
|
878
|
-
const full = fullY.lessThan(0).select(
|
|
1552
|
+
const full = fullY.lessThan(0).select(vec32(foldedX, fullY, foldedZ), vec32(fullX, fullY, fullZ)).normalize();
|
|
879
1553
|
return fullSphere ? full : hemisphere;
|
|
880
1554
|
}, "vec3");
|
|
881
1555
|
const directionToGrid = Fn2(([inputDirection]) => {
|
|
@@ -910,9 +1584,9 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
910
1584
|
const bytes = floor(packed.ba.mul(255).add(0.5));
|
|
911
1585
|
return bytes.x.mul(256).add(bytes.y).div(65535);
|
|
912
1586
|
}, "float");
|
|
913
|
-
const loadDepth16 = Fn2(([texel]) => decodeDepth16(
|
|
1587
|
+
const loadDepth16 = Fn2(([texel]) => decodeDepth16(textureLoad2(
|
|
914
1588
|
geometryAtlas,
|
|
915
|
-
|
|
1589
|
+
ivec22(texel).clamp(ivec22(0), ivec22(atlasResolution.sub(1)))
|
|
916
1590
|
)), "float");
|
|
917
1591
|
const sampleDepth16 = Fn2(([uvNode]) => {
|
|
918
1592
|
const pixel = uvNode.mul(atlasResolution).sub(0.5);
|
|
@@ -932,7 +1606,7 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
932
1606
|
}, "float");
|
|
933
1607
|
const decodeOctahedral = Fn2(([encoded]) => {
|
|
934
1608
|
const f = encoded.mul(2).sub(1).toVar();
|
|
935
|
-
const value =
|
|
1609
|
+
const value = vec32(f, float(1).sub(abs(f.x)).sub(abs(f.y))).toVar();
|
|
936
1610
|
const folded = vec2(
|
|
937
1611
|
float(1).sub(abs(value.y)).mul(nonZeroSign(value.x)),
|
|
938
1612
|
float(1).sub(abs(value.x)).mul(nonZeroSign(value.y))
|
|
@@ -946,49 +1620,121 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
946
1620
|
const plane = mix(bounds.xy, bounds.zw, frameUv);
|
|
947
1621
|
return right.mul(plane.x).add(up.mul(plane.y)).add(frameDirection.mul(radius.sub(depthValue.mul(radius).mul(2))));
|
|
948
1622
|
}, "vec3");
|
|
949
|
-
const
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
1623
|
+
const local = (value, direction) => Fn2((_, builder) => {
|
|
1624
|
+
const space = instanceSpace(builder);
|
|
1625
|
+
if (!space) return value;
|
|
1626
|
+
return direction ? space.toLocalDirection(value) : space.toLocalPoint(value);
|
|
1627
|
+
})();
|
|
1628
|
+
const perInstance = (name, value) => Fn2((_, builder) => instanceSpace(builder) ? varying2(value, name) : value)();
|
|
1629
|
+
const cameraLocal = local(modelWorldMatrixInverse.mul(vec44(cameraPosition, 1)).xyz, false);
|
|
1630
|
+
const cameraRightLocal = local(modelWorldMatrixInverse.mul(vec44(cameraWorldMatrix[0].xyz, 0)).xyz, true).normalize();
|
|
1631
|
+
const cameraUpLocal = local(modelWorldMatrixInverse.mul(vec44(cameraWorldMatrix[1].xyz, 0)).xyz, true).normalize();
|
|
1632
|
+
const cameraOutLocal = local(modelWorldMatrixInverse.mul(vec44(cameraWorldMatrix[2].xyz, 0)).xyz, true).normalize();
|
|
953
1633
|
const projectionCameraDirection = Fn2(([], builder) => builder.camera.isPerspectiveCamera ? cameraLocal.normalize() : cameraOutLocal, "vec3")();
|
|
954
|
-
const horizontalCamera =
|
|
1634
|
+
const horizontalCamera = vec32(
|
|
955
1635
|
projectionCameraDirection.x,
|
|
956
1636
|
0,
|
|
957
1637
|
projectionCameraDirection.z
|
|
958
1638
|
);
|
|
959
|
-
const horizontalUp =
|
|
1639
|
+
const horizontalUp = vec32(cameraUpLocal.x, 0, cameraUpLocal.z);
|
|
960
1640
|
const horizonFromPosition = horizontalCamera.div(max(horizontalCamera.length(), 1e-6));
|
|
961
1641
|
const horizonFromCameraUp = horizontalUp.div(max(horizontalUp.length(), 1e-6));
|
|
962
1642
|
const horizonDirection = horizontalCamera.length().greaterThan(1e-4).select(horizonFromPosition, horizonFromCameraUp);
|
|
963
1643
|
const cameraDirection = projectionCameraDirection;
|
|
964
|
-
const mappingVisibility = fullSphere || singleView ? float(1) : smoothstep(-1, -0.9995, cameraDirection.y);
|
|
1644
|
+
const mappingVisibility = fullSphere || singleView ? float(1) : perInstance("vImpostorMappingVisibility", smoothstep(-1, -0.9995, cameraDirection.y));
|
|
965
1645
|
const horizonTransition = smoothstep(
|
|
966
1646
|
0,
|
|
967
1647
|
HEMISPHERE_HORIZON_TRANSITION_SINE,
|
|
968
1648
|
max(cameraDirection.y, 0)
|
|
969
1649
|
);
|
|
970
1650
|
const clampedCameraDirection = fullSphere || singleView ? cameraDirection : mix(horizonDirection, cameraDirection, horizonTransition).normalize();
|
|
971
|
-
const horizonBillboardUp =
|
|
1651
|
+
const horizonBillboardUp = cross2(horizonDirection, cameraRightLocal).normalize();
|
|
972
1652
|
const billboardUpLocal = fullSphere || singleView ? cameraUpLocal : mix(horizonBillboardUp, cameraUpLocal, horizonTransition).normalize();
|
|
973
|
-
const
|
|
1653
|
+
const samplingCameraPosition = clampedCameraDirection.mul(cameraLocal.length());
|
|
1654
|
+
const samplingCamera = perInstance("vImpostorSamplingCamera", samplingCameraPosition);
|
|
974
1655
|
const samplingBillboardPosition = cameraRightLocal.mul(positionGeometry.x).add(billboardUpLocal.mul(positionGeometry.y));
|
|
975
|
-
const displayBillboardPosition =
|
|
1656
|
+
const displayBillboardPosition = Fn2((_, builder) => {
|
|
1657
|
+
const card = cameraRightLocal.mul(positionGeometry.x).add(cameraUpLocal.mul(positionGeometry.y));
|
|
1658
|
+
return instanceSpace(builder)?.toMeshPoint(card) ?? card;
|
|
1659
|
+
})();
|
|
976
1660
|
const planeLocal = samplingBillboardPosition.toVarying("vImpostorPlaneLocal");
|
|
977
|
-
const
|
|
978
|
-
const
|
|
1661
|
+
const selectFrameTriangle = (centerGrid, orientation = null) => {
|
|
1662
|
+
const base = min(floor(centerGrid), vec2(frames.sub(2)));
|
|
1663
|
+
const centerFraction = centerGrid.sub(base);
|
|
1664
|
+
if (!orientation) {
|
|
1665
|
+
const foldCell = fullSphere ? bool(false) : base.x.add(base.y).equal(frames.sub(2));
|
|
1666
|
+
const baseDirection = gridToDirection(base.div(frames.sub(1)));
|
|
1667
|
+
const rightDirection = gridToDirection(base.add(vec2(1, 0)).div(frames.sub(1)));
|
|
1668
|
+
const upDirection = gridToDirection(base.add(vec2(0, 1)).div(frames.sub(1)));
|
|
1669
|
+
const diagonalDirection = gridToDirection(base.add(1).div(frames.sub(1)));
|
|
1670
|
+
const splitOnAntiDiagonal = foldCell.or(
|
|
1671
|
+
dot2(rightDirection, upDirection).greaterThan(dot2(baseDirection, diagonalDirection))
|
|
1672
|
+
);
|
|
1673
|
+
orientation = splitOnAntiDiagonal.select(
|
|
1674
|
+
centerFraction.x.add(centerFraction.y).lessThanEqual(1).select(float(2), float(3)),
|
|
1675
|
+
centerFraction.x.greaterThan(centerFraction.y).select(float(0), float(1))
|
|
1676
|
+
);
|
|
1677
|
+
}
|
|
1678
|
+
const horizontal = orientation.equal(0);
|
|
1679
|
+
const antiDiagonal = orientation.greaterThanEqual(2);
|
|
1680
|
+
const antiLower = orientation.equal(2);
|
|
1681
|
+
const right = base.add(vec2(1, 0));
|
|
1682
|
+
const up = base.add(vec2(0, 1));
|
|
1683
|
+
const diagonal = base.add(1);
|
|
1684
|
+
const frame0 = orientation.equal(3).select(diagonal, base);
|
|
1685
|
+
const frame1 = horizontal.or(antiLower).select(right, up);
|
|
1686
|
+
const frame2 = antiDiagonal.select(antiLower.select(up, right), diagonal);
|
|
1687
|
+
return { base, orientation, horizontal, antiDiagonal, antiLower, frame0, frame1, frame2 };
|
|
1688
|
+
};
|
|
1689
|
+
const vertexGrid = directionToGrid(samplingCameraPosition.normalize()).mul(frames.sub(1));
|
|
1690
|
+
const vertexTriangle = selectFrameTriangle(vertexGrid);
|
|
1691
|
+
const cardTriangle = varying2(
|
|
1692
|
+
vec32(vertexGrid, vertexTriangle.orientation),
|
|
1693
|
+
"vImpostorCardTriangle"
|
|
1694
|
+
).setInterpolation("flat");
|
|
1695
|
+
const elevationSine = clampedCameraDirection.y;
|
|
1696
|
+
const cardAnchorHeight = fullSphere ? float(0) : elevationSine.mul(elevationSine).mul(smoothstep(0.35, 0.8, elevationSine)).mul(descriptor.boundsMin[1] * 0.8);
|
|
1697
|
+
const cardAnchor = vec32(0, cardAnchorHeight, 0);
|
|
1698
|
+
const anchoredCardCorner = fullSphere ? samplingBillboardPosition : Fn2(() => {
|
|
1699
|
+
const planeNormal = cross2(cameraRightLocal, billboardUpLocal);
|
|
1700
|
+
const shift = cardAnchorHeight.mul(planeNormal.y).div(max(dot2(samplingCameraPosition, planeNormal), 1e-6));
|
|
1701
|
+
return mix(samplingBillboardPosition, samplingCameraPosition, shift);
|
|
1702
|
+
})();
|
|
1703
|
+
const projectCardCorner = Fn2(([frame, corner, eye, anchor]) => {
|
|
1704
|
+
const normal = gridToDirection(frame.div(frames.sub(1))).toVar();
|
|
1705
|
+
const basis = frameBasis(normal).toVar();
|
|
1706
|
+
const projectionEye = eye.add(normal.mul(eye.length())).toVar();
|
|
1707
|
+
const eyeDepth = dot2(projectionEye.sub(anchor), normal).toVar();
|
|
1708
|
+
const cornerDepth = dot2(corner.sub(anchor), normal).toVar();
|
|
1709
|
+
const projected = corner.mul(eyeDepth).sub(projectionEye.mul(cornerDepth)).toVar();
|
|
1710
|
+
return vec32(
|
|
1711
|
+
dot2(projected, basisMember(basis, "right")),
|
|
1712
|
+
dot2(projected, basisMember(basis, "up")),
|
|
1713
|
+
eyeDepth.sub(cornerDepth)
|
|
1714
|
+
);
|
|
1715
|
+
}).setLayout({
|
|
1716
|
+
name: "projectImpostorCardCorner",
|
|
1717
|
+
type: "vec3",
|
|
1718
|
+
inputs: [
|
|
1719
|
+
{ name: "frame", type: "vec2" },
|
|
1720
|
+
{ name: "corner", type: "vec3" },
|
|
1721
|
+
{ name: "eye", type: "vec3" },
|
|
1722
|
+
{ name: "anchor", type: "vec3" }
|
|
1723
|
+
]
|
|
1724
|
+
});
|
|
1725
|
+
const createFrameSampler = (withReprojection, withCardProjection = false) => {
|
|
1726
|
+
const buildFrameSample = ([frame, planePosition, rayDirection, bounds, cardProjection]) => {
|
|
979
1727
|
const frameDirection = singleView ? singleCaptureDirection : gridToDirection(frame.div(frames.sub(1)));
|
|
980
1728
|
const basis = frameBasis(frameDirection);
|
|
981
1729
|
const right = basisMember(basis, "right");
|
|
982
1730
|
const up = basisMember(basis, "up");
|
|
983
|
-
const rayPlaneDenominator =
|
|
1731
|
+
const rayPlaneDenominator = dot2(rayDirection, frameDirection);
|
|
984
1732
|
const safeRayPlaneDenominator = nonZeroSign(rayPlaneDenominator).mul(max(abs(rayPlaneDenominator), 0.05));
|
|
985
1733
|
const framePlanePosition = planePosition.sub(rayDirection.mul(
|
|
986
|
-
|
|
1734
|
+
dot2(planePosition, frameDirection).div(safeRayPlaneDenominator)
|
|
987
1735
|
));
|
|
988
|
-
const
|
|
989
|
-
|
|
990
|
-
dot(framePlanePosition, up)
|
|
991
|
-
).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
|
|
1736
|
+
const projectedPlane = withCardProjection ? cardProjection.xy.div(max(cardProjection.z, 1e-6)) : vec2(dot2(framePlanePosition, right), dot2(framePlanePosition, up));
|
|
1737
|
+
const projectedFrameUv = projectedPlane.sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
|
|
992
1738
|
const interiorResolution = max(frameResolution.sub(padding.mul(2)), 1);
|
|
993
1739
|
const gutterUv = padding.div(interiorResolution);
|
|
994
1740
|
const minimumFrameUv = gutterUv.negate();
|
|
@@ -1001,23 +1747,23 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1001
1747
|
const rootFound = bool(false).toVar();
|
|
1002
1748
|
const rootLower = float(0).toVar();
|
|
1003
1749
|
const rootUpper = float(1).toVar();
|
|
1004
|
-
const safeRay =
|
|
1750
|
+
const safeRay = vec32(
|
|
1005
1751
|
nonZeroSign(rayDirection.x),
|
|
1006
1752
|
nonZeroSign(rayDirection.y),
|
|
1007
1753
|
nonZeroSign(rayDirection.z)
|
|
1008
|
-
).mul(max(abs(rayDirection),
|
|
1754
|
+
).mul(max(abs(rayDirection), vec32(1e-7)));
|
|
1009
1755
|
const boundsGuard = radius.mul(2).div(interiorResolution);
|
|
1010
|
-
const boxT0 =
|
|
1011
|
-
const boxT1 =
|
|
1756
|
+
const boxT0 = vec32(...descriptor.boundsMin).sub(boundsGuard).sub(planePosition).div(safeRay);
|
|
1757
|
+
const boxT1 = vec32(...descriptor.boundsMax).add(boundsGuard).sub(planePosition).div(safeRay);
|
|
1012
1758
|
const boxLow = min(boxT0, boxT1), boxHigh = max(boxT0, boxT1);
|
|
1013
1759
|
const boxStart = max(boxLow.x, max(boxLow.y, boxLow.z));
|
|
1014
1760
|
const boxEnd = min(boxHigh.x, min(boxHigh.y, boxHigh.z));
|
|
1015
1761
|
const intersectsBounds = boxStart.lessThanEqual(boxEnd);
|
|
1016
1762
|
const captureDepthAt = (t) => radius.sub(
|
|
1017
|
-
|
|
1763
|
+
dot2(planePosition.add(rayDirection.mul(t)), frameDirection)
|
|
1018
1764
|
).div(radius.mul(2));
|
|
1019
1765
|
const depth0 = captureDepthAt(boxStart), depth1 = captureDepthAt(boxEnd);
|
|
1020
|
-
const uvDepthSlope = vec2(
|
|
1766
|
+
const uvDepthSlope = vec2(dot2(rayDirection, right), dot2(rayDirection, up)).mul(radius.mul(-2).div(safeRayPlaneDenominator)).div(bounds.zw.sub(bounds.xy));
|
|
1021
1767
|
const safeSlope = vec2(
|
|
1022
1768
|
nonZeroSign(uvDepthSlope.x),
|
|
1023
1769
|
nonZeroSign(uvDepthSlope.y)
|
|
@@ -1034,7 +1780,7 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1034
1780
|
If(rootSolved, () => {
|
|
1035
1781
|
const at = atlasUv(frame, frameUv);
|
|
1036
1782
|
const surface = reconstructPosition(frameUv, bounds, frameDirection, right, up, sampleDepth16(at));
|
|
1037
|
-
const closest = planePosition.add(rayDirection.mul(
|
|
1783
|
+
const closest = planePosition.add(rayDirection.mul(dot2(surface.sub(planePosition), rayDirection)));
|
|
1038
1784
|
const footprint2 = max(bounds.z.sub(bounds.x), bounds.w.sub(bounds.y)).div(interiorResolution);
|
|
1039
1785
|
const nearestPixel = floor(at.mul(atlasResolution));
|
|
1040
1786
|
const nearestDepth = loadDepth16(nearestPixel);
|
|
@@ -1064,11 +1810,11 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1064
1810
|
const searchDepth = rootLower.add(rootUpper).mul(0.5);
|
|
1065
1811
|
const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));
|
|
1066
1812
|
const searchRayPosition = planePosition.add(rayDirection.mul(
|
|
1067
|
-
searchPlaneDepth.sub(
|
|
1813
|
+
searchPlaneDepth.sub(dot2(planePosition, frameDirection)).div(safeRayPlaneDenominator)
|
|
1068
1814
|
));
|
|
1069
1815
|
const searchUv = vec2(
|
|
1070
|
-
|
|
1071
|
-
|
|
1816
|
+
dot2(searchRayPosition, right),
|
|
1817
|
+
dot2(searchRayPosition, up)
|
|
1072
1818
|
).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
|
|
1073
1819
|
const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv))).or(any(searchUv.greaterThan(vec2(maximumFrameUv))));
|
|
1074
1820
|
const midpointIsUpper = bool(false).toVar();
|
|
@@ -1090,9 +1836,9 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1090
1836
|
const residualAt = (depth) => {
|
|
1091
1837
|
const planeDepth = radius.sub(depth.mul(radius).mul(2));
|
|
1092
1838
|
const position = planePosition.add(rayDirection.mul(
|
|
1093
|
-
planeDepth.sub(
|
|
1839
|
+
planeDepth.sub(dot2(planePosition, frameDirection)).div(safeRayPlaneDenominator)
|
|
1094
1840
|
));
|
|
1095
|
-
const address = vec2(
|
|
1841
|
+
const address = vec2(dot2(position, right), dot2(position, up)).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
|
|
1096
1842
|
return depth.sub(sampleDepth16(atlasUv(frame, address)));
|
|
1097
1843
|
};
|
|
1098
1844
|
const lowResidual = residualAt(rootLower), highResidual = residualAt(rootUpper);
|
|
@@ -1103,11 +1849,11 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1103
1849
|
const rootDepth = mix(rootLower, rootUpper, fraction);
|
|
1104
1850
|
const rootPlaneDepth = radius.sub(rootDepth.mul(radius).mul(2));
|
|
1105
1851
|
const rootRayPosition = planePosition.add(rayDirection.mul(
|
|
1106
|
-
rootPlaneDepth.sub(
|
|
1852
|
+
rootPlaneDepth.sub(dot2(planePosition, frameDirection)).div(safeRayPlaneDenominator)
|
|
1107
1853
|
));
|
|
1108
1854
|
frameUv.assign(vec2(
|
|
1109
|
-
|
|
1110
|
-
|
|
1855
|
+
dot2(rootRayPosition, right),
|
|
1856
|
+
dot2(rootRayPosition, up)
|
|
1111
1857
|
).sub(bounds.xy).div(bounds.zw.sub(bounds.xy)).clamp(
|
|
1112
1858
|
minimumFrameUv,
|
|
1113
1859
|
maximumFrameUv
|
|
@@ -1123,11 +1869,11 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1123
1869
|
const searchDepth = start.add(float(i).add(1).mul(coarseStep2));
|
|
1124
1870
|
const searchPlaneDepth = radius.sub(searchDepth.mul(radius).mul(2));
|
|
1125
1871
|
const searchRayPosition = planePosition.add(rayDirection.mul(
|
|
1126
|
-
searchPlaneDepth.sub(
|
|
1872
|
+
searchPlaneDepth.sub(dot2(planePosition, frameDirection)).div(safeRayPlaneDenominator)
|
|
1127
1873
|
));
|
|
1128
1874
|
const searchUv = vec2(
|
|
1129
|
-
|
|
1130
|
-
|
|
1875
|
+
dot2(searchRayPosition, right),
|
|
1876
|
+
dot2(searchRayPosition, up)
|
|
1131
1877
|
).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
|
|
1132
1878
|
const searchOutOfBounds = any(searchUv.lessThan(vec2(minimumFrameUv))).or(any(searchUv.greaterThan(vec2(maximumFrameUv))));
|
|
1133
1879
|
If(searchOutOfBounds.not(), () => {
|
|
@@ -1153,7 +1899,7 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1153
1899
|
});
|
|
1154
1900
|
});
|
|
1155
1901
|
};
|
|
1156
|
-
traceInterval(
|
|
1902
|
+
traceInterval(int2(coarseSearchSteps));
|
|
1157
1903
|
If(rootFound.not().and(intersectsBounds), () => {
|
|
1158
1904
|
const iterativeUv = projectedFrameUv.clamp(minimumFrameUv, maximumFrameUv).toVar();
|
|
1159
1905
|
const iterativeDepth = sampleDepth16(atlasUv(frame, iterativeUv)).toVar();
|
|
@@ -1163,11 +1909,11 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1163
1909
|
If(iterationValid, () => {
|
|
1164
1910
|
const iterativePlaneDepth = radius.sub(iterativeDepth.mul(radius).mul(2));
|
|
1165
1911
|
const iterativeRayPosition = planePosition.add(rayDirection.mul(
|
|
1166
|
-
iterativePlaneDepth.sub(
|
|
1912
|
+
iterativePlaneDepth.sub(dot2(planePosition, frameDirection)).div(safeRayPlaneDenominator)
|
|
1167
1913
|
));
|
|
1168
1914
|
const nextUv = vec2(
|
|
1169
|
-
|
|
1170
|
-
|
|
1915
|
+
dot2(iterativeRayPosition, right),
|
|
1916
|
+
dot2(iterativeRayPosition, up)
|
|
1171
1917
|
).sub(bounds.xy).div(bounds.zw.sub(bounds.xy));
|
|
1172
1918
|
const nextOutOfBounds = any(nextUv.lessThan(vec2(minimumFrameUv))).or(any(nextUv.greaterThan(vec2(maximumFrameUv))));
|
|
1173
1919
|
If(nextOutOfBounds, () => {
|
|
@@ -1209,9 +1955,9 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1209
1955
|
const geometrySample = compressedGeometry ? texture(geometryAtlas, uvNode).level(0) : null;
|
|
1210
1956
|
const viewNormal = decodeOctahedral(shadingSample.rg);
|
|
1211
1957
|
const normal = right.mul(viewNormal.x).add(up.mul(viewNormal.y)).add(frameDirection.mul(viewNormal.z)).normalize();
|
|
1212
|
-
const faceForwardNormal =
|
|
1958
|
+
const faceForwardNormal = dot2(normal, rayDirection).lessThan(0).select(normal.negate(), normal);
|
|
1213
1959
|
const closestRayPoint = planePosition.add(
|
|
1214
|
-
rayDirection.mul(
|
|
1960
|
+
rayDirection.mul(dot2(reconstructed.sub(planePosition), rayDirection))
|
|
1215
1961
|
);
|
|
1216
1962
|
const footprint = max(
|
|
1217
1963
|
bounds.z.sub(bounds.x),
|
|
@@ -1241,7 +1987,7 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1241
1987
|
const colorUv = colorAtlasUv(uvNode);
|
|
1242
1988
|
const baseColor = sampleAtlas(baseColorAtlas, colorUv, mapLod(baseColorAtlas, colorUv), colorColumns);
|
|
1243
1989
|
const capturedAlpha = sampleCapturedAlpha(uvNode);
|
|
1244
|
-
const orm = compactLayout ?
|
|
1990
|
+
const orm = compactLayout ? vec44(geometrySample.b, shadingSample.b, shadingSample.a, 1) : ormAtlas ? sampleAtlas(ormAtlas, uvNode, mapLod(ormAtlas, uvNode)) : vec44(
|
|
1245
1991
|
descriptor.material.occlusion,
|
|
1246
1992
|
descriptor.material.roughness,
|
|
1247
1993
|
descriptor.material.metalness,
|
|
@@ -1254,12 +2000,12 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1254
2000
|
// sampled color/alpha here and the frame weight below applied crop
|
|
1255
2001
|
// confidence twice; low-confidence crop-edge samples consequently
|
|
1256
2002
|
// rendered as black outlines instead of fading away.
|
|
1257
|
-
|
|
2003
|
+
vec44(baseColor.rgb, coverage),
|
|
1258
2004
|
capturedAlpha,
|
|
1259
2005
|
faceForwardNormal,
|
|
1260
2006
|
reconstructed,
|
|
1261
2007
|
orm.rgb,
|
|
1262
|
-
emissiveAtlas ? sampleAtlas(emissiveAtlas, colorAtlasUv(uvNode, true), mapLod(emissiveAtlas, colorAtlasUv(uvNode, true)), colorColumns).rgb :
|
|
2008
|
+
emissiveAtlas ? sampleAtlas(emissiveAtlas, colorAtlasUv(uvNode, true), mapLod(emissiveAtlas, colorAtlasUv(uvNode, true)), colorColumns).rgb : vec32(0),
|
|
1263
2009
|
coverage,
|
|
1264
2010
|
resolvedValidity,
|
|
1265
2011
|
strictValidFloat,
|
|
@@ -1272,27 +2018,30 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1272
2018
|
let sampleFrame = functions.get(builder);
|
|
1273
2019
|
if (!sampleFrame) {
|
|
1274
2020
|
sampleFrame = Fn2(buildFrameSample).setLayout({
|
|
1275
|
-
name: withReprojection ? "sampleReprojectedImpostorFrame" : "samplePlanarImpostorFrame",
|
|
2021
|
+
name: withReprojection ? "sampleReprojectedImpostorFrame" : withCardProjection ? "sampleProjectedImpostorCard" : "samplePlanarImpostorFrame",
|
|
1276
2022
|
type: "ImpostorFrameSample",
|
|
1277
2023
|
inputs: [
|
|
1278
2024
|
{ name: "frame", type: "vec2" },
|
|
1279
2025
|
{ name: "planePosition", type: "vec3" },
|
|
1280
2026
|
{ name: "rayDirection", type: "vec3" },
|
|
1281
|
-
{ name: "bounds", type: "vec4" }
|
|
2027
|
+
{ name: "bounds", type: "vec4" },
|
|
2028
|
+
...withCardProjection ? [{ name: "cardProjection", type: "vec3" }] : []
|
|
1282
2029
|
]
|
|
1283
2030
|
});
|
|
1284
2031
|
functions.set(builder, sampleFrame);
|
|
1285
2032
|
}
|
|
1286
|
-
return (frame, planePosition, rayDirection) => sampleFrame(
|
|
2033
|
+
return (frame, planePosition, rayDirection, cardProjection) => sampleFrame(
|
|
1287
2034
|
frame,
|
|
1288
2035
|
planePosition,
|
|
1289
2036
|
rayDirection,
|
|
1290
|
-
viewBounds.element(
|
|
2037
|
+
viewBounds.element(int2(frame.y.mul(frames).add(frame.x))),
|
|
2038
|
+
...withCardProjection ? [cardProjection] : []
|
|
1291
2039
|
);
|
|
1292
2040
|
};
|
|
1293
2041
|
};
|
|
1294
2042
|
const planarFrameSamplers = createFrameSampler(false);
|
|
1295
2043
|
const reprojectedFrameSamplers = features.reprojection ? createFrameSampler(true) : null;
|
|
2044
|
+
const cardFrameSamplers = features.interpolation && features.perspectiveCorrection && !features.reprojection ? createFrameSampler(false, true) : null;
|
|
1296
2045
|
const buildBlendedSample = ([], builder) => {
|
|
1297
2046
|
const samplePlanarFrame = planarFrameSamplers(builder);
|
|
1298
2047
|
const sampleReprojectedFrame = reprojectedFrameSamplers ? reprojectedFrameSamplers(builder) : null;
|
|
@@ -1300,14 +2049,15 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1300
2049
|
const centerViewDirection = samplingCameraLocal.normalize();
|
|
1301
2050
|
const usePerspectiveCorrection = features.perspectiveCorrection && builder.camera.isPerspectiveCamera;
|
|
1302
2051
|
const rayDirection = usePerspectiveCorrection ? samplingCameraLocal.sub(planeLocal).normalize() : centerViewDirection;
|
|
2052
|
+
const sampleCardFrame = usePerspectiveCorrection && cardFrameSamplers ? cardFrameSamplers(builder) : null;
|
|
1303
2053
|
if (singleView) {
|
|
1304
2054
|
const singleFrame = vec2(0, 0);
|
|
1305
2055
|
const raw = features.reprojection ? sampleReprojectedFrame(singleFrame, planeLocal, rayDirection) : samplePlanarFrame(singleFrame, planeLocal, rayDirection);
|
|
1306
2056
|
const validity = frameMember(raw, "validity");
|
|
1307
|
-
const
|
|
2057
|
+
const capturedCoverage2 = frameMember(raw, "surfaceAlpha").mul(validity);
|
|
1308
2058
|
const distanceCoverage2 = min(
|
|
1309
2059
|
frameMember(raw, "contour"),
|
|
1310
|
-
|
|
2060
|
+
capturedCoverage2
|
|
1311
2061
|
);
|
|
1312
2062
|
return BlendedSample(
|
|
1313
2063
|
frameMember(raw, "base"),
|
|
@@ -1315,58 +2065,39 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1315
2065
|
frameMember(raw, "positionLocal"),
|
|
1316
2066
|
frameMember(raw, "orm"),
|
|
1317
2067
|
frameMember(raw, "emissive"),
|
|
1318
|
-
|
|
2068
|
+
capturedCoverage2,
|
|
1319
2069
|
distanceCoverage2,
|
|
1320
|
-
validity
|
|
1321
|
-
float(0),
|
|
1322
|
-
float(0)
|
|
2070
|
+
validity
|
|
1323
2071
|
);
|
|
1324
2072
|
}
|
|
1325
|
-
const centerGrid = directionToGrid(centerViewDirection).mul(frames.sub(1));
|
|
2073
|
+
const centerGrid = sampleCardFrame ? cardTriangle.xy : directionToGrid(centerViewDirection).mul(frames.sub(1));
|
|
1326
2074
|
const perspectiveGrid = usePerspectiveCorrection ? directionToGrid(
|
|
1327
2075
|
samplingCameraLocal.add(planeLocal.mul(PERSPECTIVE_RAY_PLANE_SIGN)).normalize()
|
|
1328
2076
|
).mul(frames.sub(1)) : centerGrid;
|
|
1329
|
-
const
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
const base = centerBase;
|
|
1333
|
-
const centerFraction = centerGrid.sub(base);
|
|
1334
|
-
const fraction = weightGrid.sub(base);
|
|
1335
|
-
const horizontal = centerFraction.x.greaterThan(centerFraction.y);
|
|
1336
|
-
const ordinaryFrame1 = base.add(horizontal.select(vec2(1, 0), vec2(0, 1)));
|
|
1337
|
-
const ordinaryWeights = horizontal.select(
|
|
1338
|
-
vec3(float(1).sub(fraction.x), fraction.x.sub(fraction.y), fraction.y),
|
|
1339
|
-
vec3(float(1).sub(fraction.y), fraction.y.sub(fraction.x), fraction.x)
|
|
2077
|
+
const { base, horizontal, antiDiagonal, antiLower, frame0, frame1, frame2 } = selectFrameTriangle(
|
|
2078
|
+
centerGrid,
|
|
2079
|
+
sampleCardFrame ? cardTriangle.z : null
|
|
1340
2080
|
);
|
|
1341
|
-
const
|
|
1342
|
-
const
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
const diagonalDirection = gridToDirection(base.add(1).div(frames.sub(1)));
|
|
1346
|
-
const antiDiagonal = foldCell.or(
|
|
1347
|
-
dot(rightDirection, upDirection).greaterThan(dot(baseDirection, diagonalDirection))
|
|
2081
|
+
const fraction = (features.cellCorrection ? perspectiveGrid : centerGrid).sub(base);
|
|
2082
|
+
const ordinaryWeights = horizontal.select(
|
|
2083
|
+
vec32(float(1).sub(fraction.x), fraction.x.sub(fraction.y), fraction.y),
|
|
2084
|
+
vec32(float(1).sub(fraction.y), fraction.y.sub(fraction.x), fraction.x)
|
|
1348
2085
|
);
|
|
1349
|
-
const antiLower = centerFraction.x.add(centerFraction.y).lessThanEqual(1);
|
|
1350
|
-
const antiFrame0 = antiLower.select(base, base.add(1));
|
|
1351
|
-
const antiFrame1 = antiLower.select(base.add(vec2(1, 0)), base.add(vec2(0, 1)));
|
|
1352
|
-
const antiFrame2 = antiLower.select(base.add(vec2(0, 1)), base.add(vec2(1, 0)));
|
|
1353
2086
|
const antiWeights = antiLower.select(
|
|
1354
|
-
|
|
1355
|
-
|
|
2087
|
+
vec32(float(1).sub(fraction.x).sub(fraction.y), fraction.x, fraction.y),
|
|
2088
|
+
vec32(fraction.x.add(fraction.y).sub(1), float(1).sub(fraction.x), float(1).sub(fraction.y))
|
|
1356
2089
|
);
|
|
1357
|
-
const
|
|
1358
|
-
|
|
1359
|
-
const
|
|
1360
|
-
|
|
1361
|
-
weights.divAssign(max(
|
|
1362
|
-
weights.assign(max(weights.sub(blendCutoff), vec3(0)));
|
|
1363
|
-
weights.divAssign(max(dot(weights, vec3(1)), 1e-4));
|
|
1364
|
-
const frame0Nearest = weights.x.greaterThanEqual(weights.y).and(weights.x.greaterThanEqual(weights.z));
|
|
1365
|
-
const nearestFrame = frame0Nearest.select(
|
|
1366
|
-
frame0,
|
|
1367
|
-
weights.y.greaterThanEqual(weights.z).select(frame1, frame2)
|
|
1368
|
-
).toVar("impostorNearestFrame");
|
|
2090
|
+
const weights = max(antiDiagonal.select(antiWeights, ordinaryWeights), vec32(0)).toVar();
|
|
2091
|
+
weights.divAssign(max(dot2(weights, vec32(1)), 1e-4));
|
|
2092
|
+
const angularCutoff = features.reprojection ? blendCutoff : blendCutoff.mul(0.35);
|
|
2093
|
+
weights.assign(max(weights.sub(angularCutoff), vec32(0)));
|
|
2094
|
+
weights.divAssign(max(dot2(weights, vec32(1)), 1e-4));
|
|
1369
2095
|
if (!features.interpolation) {
|
|
2096
|
+
const frame0Nearest = weights.x.greaterThanEqual(weights.y).and(weights.x.greaterThanEqual(weights.z));
|
|
2097
|
+
const nearestFrame = frame0Nearest.select(
|
|
2098
|
+
frame0,
|
|
2099
|
+
weights.y.greaterThanEqual(weights.z).select(frame1, frame2)
|
|
2100
|
+
);
|
|
1370
2101
|
const raw = samplePlanarFrame(nearestFrame, planeLocal, rayDirection);
|
|
1371
2102
|
return BlendedSample(
|
|
1372
2103
|
frameMember(raw, "base"),
|
|
@@ -1376,40 +2107,50 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1376
2107
|
frameMember(raw, "emissive"),
|
|
1377
2108
|
frameMember(raw, "surfaceAlpha"),
|
|
1378
2109
|
frameMember(raw, "surfaceAlpha"),
|
|
1379
|
-
frameMember(raw, "validity")
|
|
1380
|
-
float(0),
|
|
1381
|
-
float(0)
|
|
2110
|
+
frameMember(raw, "validity")
|
|
1382
2111
|
);
|
|
1383
2112
|
}
|
|
1384
|
-
const
|
|
1385
|
-
|
|
1386
|
-
|
|
2113
|
+
const resolveFrame = (frame, key) => {
|
|
2114
|
+
if (sampleCardFrame) {
|
|
2115
|
+
const corner = projectCardCorner(
|
|
2116
|
+
vertexTriangle[key],
|
|
2117
|
+
anchoredCardCorner,
|
|
2118
|
+
samplingCameraPosition,
|
|
2119
|
+
cardAnchor
|
|
2120
|
+
);
|
|
2121
|
+
return sampleCardFrame(frame, planeLocal, rayDirection, varying2(corner, "vImpostorCard_" + key));
|
|
2122
|
+
}
|
|
2123
|
+
return (sampleReprojectedFrame ?? samplePlanarFrame)(frame, planeLocal, rayDirection);
|
|
2124
|
+
};
|
|
2125
|
+
const a = resolveFrame(frame0, "frame0");
|
|
2126
|
+
const b = resolveFrame(frame1, "frame1");
|
|
2127
|
+
const c = resolveFrame(frame2, "frame2");
|
|
1387
2128
|
const angularWeights = weights.toVar("impostorAngularWeights");
|
|
1388
2129
|
if (features.depthWeights) {
|
|
1389
|
-
const residual =
|
|
2130
|
+
const residual = vec32(
|
|
1390
2131
|
frameMember(a, "rayError").div(frameMember(a, "footprint")),
|
|
1391
2132
|
frameMember(b, "rayError").div(frameMember(b, "footprint")),
|
|
1392
2133
|
frameMember(c, "rayError").div(frameMember(c, "footprint"))
|
|
1393
2134
|
).div(0.5);
|
|
1394
|
-
weights.mulAssign(max(exp(residual.mul(residual).mul(-0.5)),
|
|
2135
|
+
weights.mulAssign(max(exp(residual.mul(residual).mul(-0.5)), vec32(0.05)));
|
|
1395
2136
|
}
|
|
1396
|
-
weights.divAssign(max(
|
|
2137
|
+
weights.divAssign(max(dot2(weights, vec32(1)), 1e-4));
|
|
1397
2138
|
const visibilityWeights = weights.toVar("impostorVisibilityWeights");
|
|
1398
|
-
const resolvedSampleValidity =
|
|
2139
|
+
const resolvedSampleValidity = vec32(
|
|
1399
2140
|
frameMember(a, "validity"),
|
|
1400
2141
|
frameMember(b, "validity"),
|
|
1401
2142
|
frameMember(c, "validity")
|
|
1402
2143
|
);
|
|
1403
|
-
const strictSampleValidity =
|
|
2144
|
+
const strictSampleValidity = vec32(
|
|
1404
2145
|
frameMember(a, "strictValidity"),
|
|
1405
2146
|
frameMember(b, "strictValidity"),
|
|
1406
2147
|
frameMember(c, "strictValidity")
|
|
1407
2148
|
);
|
|
1408
|
-
const strictSupport =
|
|
1409
|
-
const seedValidity = max(resolvedSampleValidity.sub(strictSampleValidity),
|
|
2149
|
+
const strictSupport = dot2(angularWeights, strictSampleValidity);
|
|
2150
|
+
const seedValidity = max(resolvedSampleValidity.sub(strictSampleValidity), vec32(0));
|
|
1410
2151
|
const seedWeight = float(1).sub(smoothstep(0, 0.01, strictSupport));
|
|
1411
2152
|
const sampleValidity = strictSampleValidity.add(seedValidity.mul(seedWeight));
|
|
1412
|
-
const surfaceAlpha =
|
|
2153
|
+
const surfaceAlpha = vec32(
|
|
1413
2154
|
frameMember(a, "surfaceAlpha"),
|
|
1414
2155
|
frameMember(b, "surfaceAlpha"),
|
|
1415
2156
|
frameMember(c, "surfaceAlpha")
|
|
@@ -1424,60 +2165,58 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1424
2165
|
float(1).sub(largestAngularWeight)
|
|
1425
2166
|
).toVar("impostorCoverageTransition");
|
|
1426
2167
|
weights.mulAssign(surfaceAlpha).mulAssign(sampleValidity);
|
|
1427
|
-
|
|
1428
|
-
const
|
|
1429
|
-
|
|
1430
|
-
|
|
2168
|
+
const capturedCoverage = dot2(weights, vec32(1)).toVar();
|
|
2169
|
+
const textureWeights = weights.mul(weights).toVar();
|
|
2170
|
+
textureWeights.divAssign(max(dot2(textureWeights, vec32(1)), 1e-8));
|
|
2171
|
+
weights.divAssign(max(capturedCoverage, 1e-4));
|
|
2172
|
+
const weighted = (field, blend = weights) => frameMember(a, field).mul(blend.x).add(frameMember(b, field).mul(blend.y)).add(frameMember(c, field).mul(blend.z));
|
|
2173
|
+
const contourSharpness = impostorContourUnionSharpness(descriptor.frames) * (features.reprojection ? 1 : 0.5);
|
|
1431
2174
|
const effectiveContourSharpness = mix(
|
|
1432
2175
|
float(0.01),
|
|
1433
2176
|
float(contourSharpness),
|
|
1434
2177
|
transition
|
|
1435
2178
|
);
|
|
1436
2179
|
const coverageContributions = visibilityWeights.mul(sampleValidity).toVar("impostorCoverageContributions");
|
|
1437
|
-
const coverageSupport =
|
|
1438
|
-
const
|
|
1439
|
-
const perspectiveCapturedCoverage = dot(
|
|
1440
|
-
coverageContributions,
|
|
1441
|
-
surfaceAlpha
|
|
1442
|
-
);
|
|
1443
|
-
const coverageDistanceSamples = vec3(
|
|
2180
|
+
const coverageSupport = dot2(coverageContributions, vec32(1)).toVar("impostorCoverageSupport");
|
|
2181
|
+
const coverageDistanceSamples = vec32(
|
|
1444
2182
|
frameMember(a, "contour"),
|
|
1445
2183
|
frameMember(b, "contour"),
|
|
1446
2184
|
frameMember(c, "contour")
|
|
1447
2185
|
);
|
|
1448
|
-
const
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
);
|
|
2186
|
+
const signedDistances = coverageDistanceSamples.sub(0.5);
|
|
2187
|
+
let edgeDistance;
|
|
2188
|
+
if (features.reprojection) {
|
|
2189
|
+
edgeDistance = dot2(
|
|
2190
|
+
coverageContributions,
|
|
2191
|
+
exp(signedDistances.mul(effectiveContourSharpness)).sub(1)
|
|
2192
|
+
).div(max(coverageSupport, 1e-4).mul(effectiveContourSharpness));
|
|
2193
|
+
} else {
|
|
2194
|
+
const cropDistances = mix(vec32(-0.5), signedDistances, sampleValidity).toVar();
|
|
2195
|
+
const unionBias = min(effectiveContourSharpness.mul(0.4), 1);
|
|
2196
|
+
edgeDistance = dot2(visibilityWeights, cropDistances.add(cropDistances.mul(cropDistances).mul(unionBias)));
|
|
2197
|
+
}
|
|
1461
2198
|
return BlendedSample(
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
coverageSupport
|
|
1470
|
-
// View-domain antialiasing complements screen-space fwidth. It widens
|
|
1471
|
-
// only where the contributing captures disagree about occupancy, so a
|
|
1472
|
-
// moving contour crosses pixels over an angular interval rather than in
|
|
1473
|
-
// one frame while stable interiors remain sharp.
|
|
1474
|
-
coverageDistanceDeviation.mul(0.2).mul(transition),
|
|
1475
|
-
transition
|
|
2199
|
+
weighted("base", textureWeights),
|
|
2200
|
+
weighted("normalLocal").normalize(),
|
|
2201
|
+
weighted("positionLocal"),
|
|
2202
|
+
weighted("orm"),
|
|
2203
|
+
weighted("emissive", textureWeights),
|
|
2204
|
+
capturedCoverage,
|
|
2205
|
+
edgeDistance.add(0.5),
|
|
2206
|
+
coverageSupport
|
|
1476
2207
|
);
|
|
1477
2208
|
};
|
|
1478
2209
|
const blendImpostor = Fn2(buildBlendedSample);
|
|
1479
2210
|
const sample = blendImpostor().toVar("impostorSample");
|
|
1480
|
-
const
|
|
2211
|
+
const capturedPosition = Fn2((_, builder) => {
|
|
2212
|
+
const position = blendedMember(sample, "positionLocal");
|
|
2213
|
+
return instanceSpace(builder)?.fragment.toMeshPoint(position) ?? position;
|
|
2214
|
+
})().toVar("impostorCapturedPosition");
|
|
2215
|
+
const capturedNormal = Fn2((_, builder) => {
|
|
2216
|
+
const normal = blendedMember(sample, "normalLocal");
|
|
2217
|
+
return instanceSpace(builder)?.fragment.toMeshNormal(normal) ?? normal;
|
|
2218
|
+
})();
|
|
2219
|
+
const reconstructedWorldPosition = modelWorldMatrix2.mul(vec44(capturedPosition, 1)).xyz;
|
|
1481
2220
|
const material = new CapturedSurfaceMaterial({
|
|
1482
2221
|
name: "Needle PBR impostor TSL",
|
|
1483
2222
|
side: DoubleSide,
|
|
@@ -1486,10 +2225,7 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1486
2225
|
depthWrite: true
|
|
1487
2226
|
});
|
|
1488
2227
|
const distanceCoverage = blendedMember(sample, "distanceCoverage");
|
|
1489
|
-
const coverageWidth = max(
|
|
1490
|
-
max(fwidth(distanceCoverage), blendedMember(sample, "coverageWidth")),
|
|
1491
|
-
1 / 255
|
|
1492
|
-
);
|
|
2228
|
+
const coverageWidth = max(fwidth(distanceCoverage), 1 / 255);
|
|
1493
2229
|
const screenDistanceCoverage = smoothstep(
|
|
1494
2230
|
float(0.5).sub(coverageWidth),
|
|
1495
2231
|
float(0.5).add(coverageWidth),
|
|
@@ -1498,19 +2234,25 @@ function createPbrImpostorNodeMaterial(descriptor, maps, inputFeatures = {}, ren
|
|
|
1498
2234
|
const screenCoverage = screenDistanceCoverage.mul(mappingVisibility);
|
|
1499
2235
|
material.positionNode = displayBillboardPosition;
|
|
1500
2236
|
material.castShadowPositionNode = displayBillboardPosition;
|
|
1501
|
-
|
|
1502
|
-
material.
|
|
2237
|
+
const multisampleCoverage = Fn2(([], builder) => rendererUsesMultisampleCoverage(builder.renderer) ? screenCoverage : float(1))();
|
|
2238
|
+
material.colorNode = vec44(blendedMember(sample, "base").rgb, multisampleCoverage);
|
|
2239
|
+
material.normalNode = transformNormalToView(capturedNormal);
|
|
1503
2240
|
material.aoNode = blendedMember(sample, "orm").r;
|
|
1504
2241
|
material.roughnessNode = blendedMember(sample, "orm").g;
|
|
1505
2242
|
material.metalnessNode = blendedMember(sample, "orm").b;
|
|
1506
2243
|
material.emissiveNode = blendedMember(sample, "emissive");
|
|
1507
2244
|
const cropSupported = blendedMember(sample, "cropSupport").greaterThanEqual(0.25);
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
)
|
|
1511
|
-
|
|
2245
|
+
const captured = blendedMember(sample, "capturedCoverage").greaterThanEqual(features.reprojection ? 0.25 : 1e-4);
|
|
2246
|
+
const solidContour = distanceCoverage.mul(mappingVisibility).greaterThanEqual(0.5);
|
|
2247
|
+
material.maskNode = Fn2(([], builder) => {
|
|
2248
|
+
if (!rendererUsesMultisampleCoverage(builder.renderer)) return solidContour.and(captured);
|
|
2249
|
+
return screenCoverage.greaterThanEqual(0.25).and(
|
|
2250
|
+
screenCoverage.greaterThanEqual(0.5).or(cropSupported)
|
|
2251
|
+
).and(captured);
|
|
2252
|
+
})();
|
|
2253
|
+
material.maskShadowNode = solidContour.and(captured);
|
|
1512
2254
|
material.alphaToCoverage = true;
|
|
1513
|
-
material.capturedPositionNode =
|
|
2255
|
+
material.capturedPositionNode = capturedPosition;
|
|
1514
2256
|
material.depthNode = capturedSurfaceDepth(material.capturedPositionNode, IMPOSTOR_SHADOW_CASTER_DEPTH_BIAS);
|
|
1515
2257
|
material.receivedShadowPositionNode = reconstructedWorldPosition;
|
|
1516
2258
|
material.toneMapped = true;
|