@needle-tools/three-mesh-effects 0.3.4 → 0.3.6
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 +32 -27
- package/README.md +63 -231
- package/SKILL.md +11 -68
- package/build/box-impostor-runtime.js +14 -2
- package/build/box-impostor-runtime.js.map +2 -2
- package/build/deformation-runtime.js +1 -1
- package/build/deformation-runtime.js.map +1 -1
- package/build/hull-effects.js.map +1 -1
- package/build/impostor-runtime.js +2 -2
- package/build/impostor-runtime.js.map +2 -2
- package/build/index.js +2 -2
- package/build/index.js.map +2 -2
- package/build/internal/box-impostor/box-impostor-display.js +10 -2
- package/build/internal/box-impostor/box-impostor-display.js.map +2 -2
- package/build/internal/box-impostor/box-impostor-faces.js.map +1 -1
- package/build/internal/box-impostor/box-impostor-geometry.js +4 -0
- package/build/internal/box-impostor/box-impostor-geometry.js.map +2 -2
- package/build/internal/box-impostor/box-impostor-material.js +10 -2
- package/build/internal/box-impostor/box-impostor-material.js.map +2 -2
- package/build/internal/box-impostor/box-impostor-metadata.js +4 -0
- package/build/internal/box-impostor/box-impostor-metadata.js.map +2 -2
- package/build/internal/box-impostor/box-impostor-projection.js.map +1 -1
- package/build/internal/box-impostor/box-impostor-runtime.js +14 -2
- package/build/internal/box-impostor/box-impostor-runtime.js.map +2 -2
- package/build/internal/deformation/rig-runtime.js +1 -1
- package/build/internal/deformation/rig-runtime.js.map +1 -1
- package/build/internal/impostor/impostor-node-material.js +2 -2
- package/build/internal/impostor/impostor-node-material.js.map +2 -2
- package/build/internal/impostor/octahedral.js.map +1 -1
- package/build/internal/pixel-impostor/pixel-impostor-display.js +39 -16
- package/build/internal/pixel-impostor/pixel-impostor-display.js.map +2 -2
- package/build/internal/pixel-impostor/pixel-impostor-metadata.js +61 -6
- package/build/internal/pixel-impostor/pixel-impostor-metadata.js.map +2 -2
- package/build/internal/pixel-impostor/pixel-impostor-runtime.js +980 -26
- package/build/internal/pixel-impostor/pixel-impostor-runtime.js.map +4 -4
- package/build/internal/rendering/hull-effect-runtime.js.map +1 -1
- package/build/internal/rendering/renderer-support.js.map +1 -1
- package/build/internal/rendering/skin-projection.js.map +1 -1
- package/build/internal/rendering/surface-query.js.map +1 -1
- package/build/internal/rendering/wrap-preview.js.map +1 -1
- package/build/internal/rendering/wrap-skin.js.map +1 -1
- package/build/pixel-impostor-runtime.js +362 -172
- package/build/pixel-impostor-runtime.js.map +4 -4
- package/build/types/box-impostor/box-impostor-metadata.d.ts +3 -1
- package/build/types/deformation/rig-runtime.d.ts +1 -1
- package/build/types/impostor/octahedral.d.ts +1 -1
- package/build/types/pixel-impostor/pixel-impostor-display.d.ts +3 -3
- package/build/types/pixel-impostor/pixel-impostor-metadata.d.ts +76 -5
- package/build/types/pixel-impostor/pixel-impostor-runtime.d.ts +19 -7
- package/build/types/public/pixel-impostor-runtime.d.ts +1 -1
- package/build/types/rendering/renderer-support.d.ts +1 -1
- package/build/types/rendering/surface-query.d.ts +2 -2
- package/package.json +2 -2
- package/src/box-impostor/box-impostor-material.js +10 -2
- package/src/box-impostor/box-impostor-metadata.js +5 -1
- package/src/deformation/rig-runtime.ts +1 -1
- package/src/impostor/impostor-node-material.js +2 -2
- package/src/impostor/octahedral.js +1 -1
- package/src/pixel-impostor/pixel-impostor-display.js +32 -18
- package/src/pixel-impostor/pixel-impostor-metadata.js +69 -9
- package/src/pixel-impostor/pixel-impostor-runtime.js +32 -9
- package/src/public/index.js +2 -2
- package/src/public/pixel-impostor-runtime.js +1 -1
- package/src/rendering/renderer-support.js +1 -1
- package/src/rendering/surface-query.js +2 -2
|
@@ -1,17 +1,932 @@
|
|
|
1
1
|
// @ts-nocheck
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __esm = (fn, res) => function __init() {
|
|
5
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
6
|
+
};
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
// src/rendering/classic-webgl-support.js
|
|
13
|
+
function classicWebGLSupportsNodeMaterials(revision) {
|
|
14
|
+
const fork = /^186\.2-alpha\.(\d+)$/.exec(revision);
|
|
15
|
+
if (fork) return Number(fork[1]) >= 2;
|
|
16
|
+
return Number.parseInt(revision, 10) >= 187;
|
|
17
|
+
}
|
|
18
|
+
var init_classic_webgl_support = __esm({
|
|
19
|
+
"src/rendering/classic-webgl-support.js"() {
|
|
20
|
+
"use strict";
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
// src/rendering/renderer-support.js
|
|
25
|
+
var renderer_support_exports = {};
|
|
26
|
+
__export(renderer_support_exports, {
|
|
27
|
+
enableRendererNodeMaterials: () => enableRendererNodeMaterials,
|
|
28
|
+
rendererSupportsImpostorNodeMaterials: () => rendererSupportsImpostorNodeMaterials
|
|
29
|
+
});
|
|
30
|
+
import { REVISION } from "three";
|
|
31
|
+
import * as TSL from "three/tsl";
|
|
32
|
+
function rendererSupportsImpostorNodeMaterials(renderer) {
|
|
33
|
+
if (typeof Reflect.get(TSL, "struct") !== "function") return false;
|
|
34
|
+
return renderer?.isWebGPURenderer === true || renderer?.capabilities?.supportsNodeMaterials === true;
|
|
35
|
+
}
|
|
36
|
+
async function enableRendererNodeMaterials(renderer) {
|
|
37
|
+
if (rendererSupportsImpostorNodeMaterials(renderer) || !renderer?.isWebGLRenderer || !renderer.setNodesHandler || typeof Reflect.get(TSL, "struct") !== "function") return;
|
|
38
|
+
let setup = pending.get(renderer);
|
|
39
|
+
if (!setup) {
|
|
40
|
+
setup = import("three/addons/tsl/WebGLNodesHandler.js").then(({ WebGLNodesHandler }) => {
|
|
41
|
+
if (rendererSupportsImpostorNodeMaterials(renderer)) return;
|
|
42
|
+
if (!classicWebGLSupportsNodeMaterials(REVISION)) {
|
|
43
|
+
console.warn(`Mesh Effects: WebGLRenderer from three r${REVISION} stops drawing node materials after about a dozen are in use. Use three r187 or later, or WebGPURenderer.`);
|
|
44
|
+
}
|
|
45
|
+
renderer.setNodesHandler?.(new WebGLNodesHandler());
|
|
46
|
+
renderer.capabilities ??= {};
|
|
47
|
+
renderer.capabilities.supportsNodeMaterials = true;
|
|
48
|
+
}).catch((error) => {
|
|
49
|
+
pending.delete(renderer);
|
|
50
|
+
throw error;
|
|
51
|
+
});
|
|
52
|
+
pending.set(renderer, setup);
|
|
53
|
+
}
|
|
54
|
+
await setup;
|
|
55
|
+
}
|
|
56
|
+
var pending;
|
|
57
|
+
var init_renderer_support = __esm({
|
|
58
|
+
"src/rendering/renderer-support.js"() {
|
|
59
|
+
"use strict";
|
|
60
|
+
init_classic_webgl_support();
|
|
61
|
+
pending = /* @__PURE__ */ new WeakMap();
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
// src/rendering/captured-surface-material.js
|
|
66
|
+
import { MeshStandardNodeMaterial } from "three/webgpu";
|
|
67
|
+
import { context, modelViewMatrix, modelWorldMatrix, vec4 } from "three/tsl";
|
|
68
|
+
var CapturedSurfaceMaterial;
|
|
69
|
+
var init_captured_surface_material = __esm({
|
|
70
|
+
"src/rendering/captured-surface-material.js"() {
|
|
71
|
+
"use strict";
|
|
72
|
+
CapturedSurfaceMaterial = class extends MeshStandardNodeMaterial {
|
|
73
|
+
/** @type {import('three/webgpu').Node<'vec3'> | null} */
|
|
74
|
+
capturedPositionNode = null;
|
|
75
|
+
/**
|
|
76
|
+
* @override
|
|
77
|
+
* @param {import('three/webgpu').NodeBuilder} builder
|
|
78
|
+
*/
|
|
79
|
+
setupLighting(builder) {
|
|
80
|
+
const lighting = super.setupLighting(builder);
|
|
81
|
+
if (!this.capturedPositionNode) return lighting;
|
|
82
|
+
const world = modelWorldMatrix.mul(vec4(this.capturedPositionNode, 1)).xyz;
|
|
83
|
+
const view = modelViewMatrix.mul(vec4(this.capturedPositionNode, 1)).xyz;
|
|
84
|
+
return context(lighting, {
|
|
85
|
+
positionView: view,
|
|
86
|
+
positionWorld: world,
|
|
87
|
+
shadowPositionWorld: world
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
// src/rendering/captured-surface-depth.js
|
|
95
|
+
import {
|
|
96
|
+
Fn,
|
|
97
|
+
cameraFar,
|
|
98
|
+
cameraNear,
|
|
99
|
+
cameraProjectionMatrix,
|
|
100
|
+
modelViewMatrix as modelViewMatrix2,
|
|
101
|
+
vec4 as vec42,
|
|
102
|
+
viewZToLogarithmicDepth,
|
|
103
|
+
viewZToOrthographicDepth,
|
|
104
|
+
viewZToPerspectiveDepth,
|
|
105
|
+
viewZToReversedOrthographicDepth,
|
|
106
|
+
viewZToReversedPerspectiveDepth
|
|
107
|
+
} from "three/tsl";
|
|
108
|
+
function capturedSurfaceDepth(position, shadowBias = 0) {
|
|
109
|
+
return Fn(
|
|
110
|
+
(_, builder) => {
|
|
111
|
+
const z = modelViewMatrix2.mul(vec42(position, 1)).z.toVar("capturedSurfaceViewZ");
|
|
112
|
+
const reversed = builder.renderer.reversedDepthBuffer === true;
|
|
113
|
+
const perspective = cameraProjectionMatrix.mul(vec42(0, 0, 0, 1)).w.equal(0);
|
|
114
|
+
const perspectiveDepth = builder.renderer.logarithmicDepthBuffer === true ? viewZToLogarithmicDepth(z, cameraNear, cameraFar) : (reversed ? viewZToReversedPerspectiveDepth : viewZToPerspectiveDepth)(z, cameraNear, cameraFar);
|
|
115
|
+
const result = perspective.select(
|
|
116
|
+
perspectiveDepth,
|
|
117
|
+
(reversed ? viewZToReversedOrthographicDepth : viewZToOrthographicDepth)(z, cameraNear, cameraFar)
|
|
118
|
+
);
|
|
119
|
+
return shadowBias && "isShadowPassMaterial" in builder.material && builder.material.isShadowPassMaterial ? result.add(reversed ? -shadowBias : shadowBias).clamp(0, 1) : result;
|
|
120
|
+
}
|
|
121
|
+
)();
|
|
122
|
+
}
|
|
123
|
+
var init_captured_surface_depth = __esm({
|
|
124
|
+
"src/rendering/captured-surface-depth.js"() {
|
|
125
|
+
"use strict";
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
// src/pixel-impostor/pixel-impostor-display.js
|
|
130
|
+
var pixel_impostor_display_exports = {};
|
|
131
|
+
__export(pixel_impostor_display_exports, {
|
|
132
|
+
createPixelImpostorDisplay: () => createPixelImpostorDisplay,
|
|
133
|
+
createPixelImpostorRaycastPreview: () => createPixelImpostorRaycastPreview
|
|
134
|
+
});
|
|
135
|
+
import * as THREE from "three";
|
|
136
|
+
import { MeshBasicNodeMaterial, MeshStandardNodeMaterial as MeshStandardNodeMaterial2 } from "three/webgpu";
|
|
137
|
+
import {
|
|
138
|
+
Break,
|
|
139
|
+
Fn as Fn2,
|
|
140
|
+
If,
|
|
141
|
+
Loop,
|
|
142
|
+
abs,
|
|
143
|
+
attribute,
|
|
144
|
+
cameraProjectionMatrix as cameraProjectionMatrix2,
|
|
145
|
+
cameraProjectionMatrixInverse,
|
|
146
|
+
cameraPosition,
|
|
147
|
+
cameraWorldMatrix,
|
|
148
|
+
ceil,
|
|
149
|
+
clamp,
|
|
150
|
+
countOneBits,
|
|
151
|
+
float,
|
|
152
|
+
fwidth,
|
|
153
|
+
getViewPosition,
|
|
154
|
+
max,
|
|
155
|
+
min,
|
|
156
|
+
mix,
|
|
157
|
+
modelViewMatrix as modelViewMatrix3,
|
|
158
|
+
modelWorldMatrix as modelWorldMatrix2,
|
|
159
|
+
modelWorldMatrixInverse,
|
|
160
|
+
mod,
|
|
161
|
+
normalMap as normalMapNode,
|
|
162
|
+
normalView,
|
|
163
|
+
smoothstep,
|
|
164
|
+
step,
|
|
165
|
+
sRGBTransferEOTF,
|
|
166
|
+
positionLocal,
|
|
167
|
+
screenCoordinate,
|
|
168
|
+
screenSize,
|
|
169
|
+
texture,
|
|
170
|
+
transformNormalToView,
|
|
171
|
+
uint,
|
|
172
|
+
uniform,
|
|
173
|
+
uvec2,
|
|
174
|
+
uvec4,
|
|
175
|
+
uv,
|
|
176
|
+
vec2,
|
|
177
|
+
vec3,
|
|
178
|
+
vec4 as vec43,
|
|
179
|
+
vertexColor
|
|
180
|
+
} from "three/tsl";
|
|
181
|
+
function createPixelImpostorRaycastPreview(asset, bounds, descriptor) {
|
|
182
|
+
const binding = descriptor;
|
|
183
|
+
descriptor = binding.descriptor && typeof binding.descriptor === "object" ? (
|
|
184
|
+
/** @type {Record<string, unknown>} */
|
|
185
|
+
binding.descriptor
|
|
186
|
+
) : descriptor;
|
|
187
|
+
const dimensions = Array.isArray(descriptor.dimensions) ? descriptor.dimensions.map(Number) : [];
|
|
188
|
+
const planar = Math.round(dimensions[0] ?? 0);
|
|
189
|
+
const layers = Math.round(dimensions[1] ?? 0);
|
|
190
|
+
if (!(planar > 0) || !(layers > 0) || Math.round(dimensions[2] ?? 0) !== planar) return null;
|
|
191
|
+
const atlasTextures = (
|
|
192
|
+
/** @type {THREE.Texture[]} */
|
|
193
|
+
[]
|
|
194
|
+
);
|
|
195
|
+
if (binding.atlas instanceof THREE.Texture) atlasTextures.push(binding.atlas);
|
|
196
|
+
asset.traverse((object) => {
|
|
197
|
+
if (atlasTextures.length > 0 || !(object instanceof THREE.Mesh)) return;
|
|
198
|
+
const materials = Array.isArray(object.material) ? object.material : [object.material];
|
|
199
|
+
for (const material of materials) {
|
|
200
|
+
const map = (
|
|
201
|
+
/** @type {THREE.MeshBasicMaterial} */
|
|
202
|
+
material.map
|
|
203
|
+
);
|
|
204
|
+
if (map) {
|
|
205
|
+
atlasTextures.push(map);
|
|
206
|
+
break;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
const atlas = atlasTextures[0];
|
|
211
|
+
if (!atlas) return null;
|
|
212
|
+
atlas.magFilter = THREE.NearestFilter;
|
|
213
|
+
atlas.minFilter = THREE.NearestFilter;
|
|
214
|
+
atlas.generateMipmaps = false;
|
|
215
|
+
atlas.needsUpdate = true;
|
|
216
|
+
const normalAtlas = binding.normalAtlas instanceof THREE.Texture ? binding.normalAtlas : null;
|
|
217
|
+
const ormAtlas = binding.ormAtlas instanceof THREE.Texture ? binding.ormAtlas : null;
|
|
218
|
+
const indexAtlas = binding.indexAtlas instanceof THREE.Texture ? binding.indexAtlas : null;
|
|
219
|
+
const sparse = descriptor.storage === "sparse";
|
|
220
|
+
if (sparse && !indexAtlas) return null;
|
|
221
|
+
for (const map of [normalAtlas, ormAtlas, indexAtlas]) {
|
|
222
|
+
if (!map) continue;
|
|
223
|
+
map.colorSpace = THREE.NoColorSpace;
|
|
224
|
+
map.magFilter = THREE.NearestFilter;
|
|
225
|
+
map.minFilter = THREE.NearestFilter;
|
|
226
|
+
map.generateMipmaps = false;
|
|
227
|
+
map.needsUpdate = true;
|
|
228
|
+
}
|
|
229
|
+
const authoredMin = Array.isArray(descriptor.volumeMin) ? descriptor.volumeMin.map(Number) : null;
|
|
230
|
+
const authoredSize = Array.isArray(descriptor.volumeSize) ? descriptor.volumeSize.map(Number) : null;
|
|
231
|
+
const size = authoredSize?.length === 3 && authoredSize.every((value) => value > 0) ? new THREE.Vector3().fromArray(authoredSize) : bounds.getSize(new THREE.Vector3());
|
|
232
|
+
const center = authoredMin?.length === 3 ? new THREE.Vector3().fromArray(authoredMin).addScaledVector(size, 0.5) : bounds.getCenter(new THREE.Vector3());
|
|
233
|
+
const authoredOccupiedMin = Array.isArray(descriptor.occupiedMin) ? descriptor.occupiedMin.map(Number) : null;
|
|
234
|
+
const authoredOccupiedSize = Array.isArray(descriptor.occupiedSize) ? descriptor.occupiedSize.map(Number) : null;
|
|
235
|
+
const raycastSize = authoredOccupiedSize?.length === 3 && authoredOccupiedSize.every((value) => value > 0) ? new THREE.Vector3().fromArray(authoredOccupiedSize) : size.clone();
|
|
236
|
+
const raycastCenter = authoredOccupiedMin?.length === 3 ? new THREE.Vector3().fromArray(authoredOccupiedMin).addScaledVector(raycastSize, 0.5) : center.clone();
|
|
237
|
+
const raycastOffset = raycastCenter.clone().sub(center);
|
|
238
|
+
const atlasColumns = Math.max(1, Math.round(Number(descriptor.atlasColumns) || Math.ceil(Math.sqrt(layers))));
|
|
239
|
+
const atlasRows = Math.max(1, Math.round(Number(descriptor.atlasRows) || Math.ceil(layers / atlasColumns)));
|
|
240
|
+
const surfaceAtlasSize = Array.isArray(descriptor.surfaceAtlasSize) ? descriptor.surfaceAtlasSize.map(Number) : [atlas.image.width, atlas.image.height];
|
|
241
|
+
const indexAtlasSize = Array.isArray(descriptor.indexAtlasSize) ? descriptor.indexAtlasSize.map(Number) : [1, 1];
|
|
242
|
+
const sizeNode = uniform(size.clone());
|
|
243
|
+
const raycastHalfSize = uniform(raycastSize.clone().multiplyScalar(0.5));
|
|
244
|
+
const raycastOffsetNode = uniform(raycastOffset);
|
|
245
|
+
const screenPixelSize = uniform(1);
|
|
246
|
+
const splatPixelSize = uniform(5);
|
|
247
|
+
const splatScale = uniform(1);
|
|
248
|
+
const projectedNormalMix = uniform(1);
|
|
249
|
+
const unlitMix = uniform(0);
|
|
250
|
+
const snapMode = uniform(0);
|
|
251
|
+
const viewportSize = uniform(new THREE.Vector2(1, 1));
|
|
252
|
+
const dpr = uniform(1);
|
|
253
|
+
const volumeDimensions = vec3(planar, layers, planar);
|
|
254
|
+
const voxelHalfExtents = vec3(
|
|
255
|
+
size.x / planar * 0.5,
|
|
256
|
+
size.y / layers * 0.5,
|
|
257
|
+
size.z / planar * 0.5
|
|
258
|
+
);
|
|
259
|
+
const minimumCellSize = Math.min(size.x / planar, size.y / layers, size.z / planar);
|
|
260
|
+
const maximumSteps = planar * 2 + layers + 3;
|
|
261
|
+
const linearTextureUv = (index, dimensions2) => vec2(
|
|
262
|
+
mod(index, dimensions2[0]).add(0.5).div(dimensions2[0]),
|
|
263
|
+
index.div(dimensions2[0]).floor().add(0.5).div(dimensions2[1])
|
|
264
|
+
);
|
|
265
|
+
const loadTexel = (map, atlasUv) => texture(map).load(uvec2(atlasUv.mul(vec2(Number(map.image.width), Number(map.image.height))).floor()));
|
|
266
|
+
const sparseUint = (texel) => {
|
|
267
|
+
if (!indexAtlas) throw new Error("Sparse pixel impostor requires an index atlas");
|
|
268
|
+
const bytes = uvec4(loadTexel(indexAtlas, linearTextureUv(texel, indexAtlasSize)).mul(255).round());
|
|
269
|
+
return bytes.x.bitOr(bytes.y.shiftLeft(8)).bitOr(bytes.z.shiftLeft(16)).bitOr(bytes.w.shiftLeft(24));
|
|
270
|
+
};
|
|
271
|
+
const traceVolumeNode = Fn2(([sampleOffset]) => {
|
|
272
|
+
const rasterPixelSize = screenPixelSize.mul(dpr);
|
|
273
|
+
const sampleCoordinate = screenCoordinate.div(rasterPixelSize).floor().mul(rasterPixelSize).add(
|
|
274
|
+
rasterPixelSize.mul(vec2(0.5).add(sampleOffset))
|
|
275
|
+
);
|
|
276
|
+
const sampleUv = sampleCoordinate.div(screenSize);
|
|
277
|
+
const nearView = getViewPosition(sampleUv, float(0), cameraProjectionMatrixInverse);
|
|
278
|
+
const farView = getViewPosition(sampleUv, float(1), cameraProjectionMatrixInverse);
|
|
279
|
+
const nearWorld = cameraWorldMatrix.mul(vec43(nearView, 1));
|
|
280
|
+
const farWorld = cameraWorldMatrix.mul(vec43(farView, 1));
|
|
281
|
+
const rayOrigin = modelWorldMatrixInverse.mul(nearWorld).xyz;
|
|
282
|
+
const rayFar = modelWorldMatrixInverse.mul(farWorld).xyz;
|
|
283
|
+
const rayDirection = rayFar.sub(rayOrigin).normalize();
|
|
284
|
+
const distanceA = raycastHalfSize.negate().sub(rayOrigin).div(rayDirection);
|
|
285
|
+
const distanceB = raycastHalfSize.sub(rayOrigin).div(rayDirection);
|
|
286
|
+
const nearestDistance = max(
|
|
287
|
+
max(min(distanceA.x, distanceB.x), min(distanceA.y, distanceB.y)),
|
|
288
|
+
min(distanceA.z, distanceB.z)
|
|
289
|
+
).max(0);
|
|
290
|
+
const exitDistance = min(
|
|
291
|
+
min(max(distanceA.x, distanceB.x), max(distanceA.y, distanceB.y)),
|
|
292
|
+
max(distanceA.z, distanceB.z)
|
|
293
|
+
);
|
|
294
|
+
const entry = rayOrigin.add(rayDirection.mul(nearestDistance));
|
|
295
|
+
const gridVelocity = rayDirection.div(sizeNode).mul(volumeDimensions);
|
|
296
|
+
const gridPoint = entry.add(raycastOffsetNode).div(sizeNode).add(0.5).mul(volumeDimensions).add(gridVelocity.mul(minimumCellSize * 1e-3));
|
|
297
|
+
const cell = exitDistance.greaterThanEqual(nearestDistance).select(gridPoint.floor(), vec3(-1)).toVar();
|
|
298
|
+
const directionStep = step(0, gridVelocity).mul(2).sub(1).toVar();
|
|
299
|
+
const absoluteVelocity = abs(gridVelocity).max(1e-6);
|
|
300
|
+
const cellFraction = gridPoint.sub(cell);
|
|
301
|
+
const positiveAxis = step(0, gridVelocity);
|
|
302
|
+
const nextDistance = cellFraction.mul(vec3(1).sub(positiveAxis)).add(vec3(1).sub(cellFraction).mul(positiveAxis));
|
|
303
|
+
const nextCrossing = nextDistance.div(absoluteVelocity).toVar();
|
|
304
|
+
const crossingDelta = vec3(1).div(absoluteVelocity).toVar();
|
|
305
|
+
const result = vec43(0, 0, 0, 0).toVar();
|
|
306
|
+
const travelled = nearestDistance.toVar();
|
|
307
|
+
Loop(maximumSteps, () => {
|
|
308
|
+
const outside = cell.x.lessThan(0).or(cell.y.lessThan(0)).or(cell.z.lessThan(0)).or(cell.x.greaterThanEqual(planar)).or(cell.y.greaterThanEqual(layers)).or(cell.z.greaterThanEqual(planar));
|
|
309
|
+
If(outside, () => {
|
|
310
|
+
Break();
|
|
311
|
+
});
|
|
312
|
+
const linearCell = cell.x.add(cell.z.add(cell.y.mul(planar)).mul(planar));
|
|
313
|
+
let cellOccupied;
|
|
314
|
+
if (sparse) {
|
|
315
|
+
const wordIndex = linearCell.div(32).floor();
|
|
316
|
+
const word = sparseUint(wordIndex.mul(2));
|
|
317
|
+
const bit = uint(mod(linearCell, 32));
|
|
318
|
+
cellOccupied = word.shiftRight(bit).bitAnd(1).equal(1);
|
|
319
|
+
} else {
|
|
320
|
+
const atlasColumn = mod(cell.y, atlasColumns);
|
|
321
|
+
const atlasRow = cell.y.div(atlasColumns).floor();
|
|
322
|
+
const atlasUv = vec2(
|
|
323
|
+
atlasColumn.mul(planar).add(cell.x).add(0.5).div(atlasColumns * planar),
|
|
324
|
+
atlasRow.mul(planar).add(cell.z).add(0.5).div(atlasRows * planar)
|
|
325
|
+
);
|
|
326
|
+
cellOccupied = loadTexel(atlas, atlasUv).a.greaterThan(0.5);
|
|
327
|
+
}
|
|
328
|
+
If(cellOccupied, () => {
|
|
329
|
+
result.assign(vec43(
|
|
330
|
+
rayOrigin.add(rayDirection.mul(travelled)),
|
|
331
|
+
linearCell.add(1)
|
|
332
|
+
));
|
|
333
|
+
Break();
|
|
334
|
+
});
|
|
335
|
+
const nearestCrossing = min(nextCrossing.x, min(nextCrossing.y, nextCrossing.z));
|
|
336
|
+
travelled.assign(nearestDistance.add(nearestCrossing));
|
|
337
|
+
If(nextCrossing.x.lessThanEqual(nearestCrossing.add(1e-6)), () => {
|
|
338
|
+
cell.x.addAssign(directionStep.x);
|
|
339
|
+
nextCrossing.x.addAssign(crossingDelta.x);
|
|
340
|
+
});
|
|
341
|
+
If(nextCrossing.y.lessThanEqual(nearestCrossing.add(1e-6)), () => {
|
|
342
|
+
cell.y.addAssign(directionStep.y);
|
|
343
|
+
nextCrossing.y.addAssign(crossingDelta.y);
|
|
344
|
+
});
|
|
345
|
+
If(nextCrossing.z.lessThanEqual(nearestCrossing.add(1e-6)), () => {
|
|
346
|
+
cell.z.addAssign(directionStep.z);
|
|
347
|
+
nextCrossing.z.addAssign(crossingDelta.z);
|
|
348
|
+
});
|
|
349
|
+
});
|
|
350
|
+
return result;
|
|
351
|
+
});
|
|
352
|
+
const traceVolume = (
|
|
353
|
+
/** @type {(sampleOffset: import('three/webgpu').Node<'vec2'>) => import('three/webgpu').Node<'vec4'>} */
|
|
354
|
+
/** @type {unknown} */
|
|
355
|
+
traceVolumeNode
|
|
356
|
+
);
|
|
357
|
+
const createRaycastMaterial = (antialias, pbr) => {
|
|
358
|
+
const centerHit = traceVolume(vec2(0));
|
|
359
|
+
const occupied = centerHit.w.greaterThan(0);
|
|
360
|
+
let coverage = float(1);
|
|
361
|
+
if (antialias) {
|
|
362
|
+
const sampleHits = [
|
|
363
|
+
traceVolume(vec2(-0.125, -0.375)),
|
|
364
|
+
traceVolume(vec2(0.375, -0.125)),
|
|
365
|
+
traceVolume(vec2(-0.375, 0.125)),
|
|
366
|
+
traceVolume(vec2(0.125, 0.375))
|
|
367
|
+
];
|
|
368
|
+
const sampleOccupancy = sampleHits.map((sampleHit) => sampleHit.w.greaterThan(0));
|
|
369
|
+
coverage = sampleOccupancy[0].select(1, 0).add(sampleOccupancy[1].select(1, 0)).add(sampleOccupancy[2].select(1, 0)).add(sampleOccupancy[3].select(1, 0)).mul(0.25).mul(occupied.select(1, 0));
|
|
370
|
+
}
|
|
371
|
+
const hit = centerHit.toVar(antialias ? "pixelImpostorAaHit" : "pixelImpostorFastHit");
|
|
372
|
+
const linearHitCell = hit.w.sub(1).max(0);
|
|
373
|
+
const hitLayer = linearHitCell.div(planar * planar).floor();
|
|
374
|
+
const hitSliceCell = mod(linearHitCell, planar * planar);
|
|
375
|
+
const hitCell = vec3(mod(hitSliceCell, planar), hitLayer, hitSliceCell.div(planar).floor());
|
|
376
|
+
let hitAtlasUv;
|
|
377
|
+
if (sparse) {
|
|
378
|
+
const wordIndex = linearHitCell.div(32).floor();
|
|
379
|
+
const word = sparseUint(wordIndex.mul(2));
|
|
380
|
+
const prefixRank = sparseUint(wordIndex.mul(2).add(1));
|
|
381
|
+
const bit = uint(mod(linearHitCell, 32));
|
|
382
|
+
const precedingMask = uint(1).shiftLeft(bit).sub(1);
|
|
383
|
+
const precedingCount = (
|
|
384
|
+
/** @type {ReturnType<typeof countOneBits> & import('three/webgpu').Node<'uint'>} */
|
|
385
|
+
countOneBits(word.bitAnd(precedingMask))
|
|
386
|
+
);
|
|
387
|
+
const record = prefixRank.add(precedingCount);
|
|
388
|
+
hitAtlasUv = linearTextureUv(float(record), surfaceAtlasSize);
|
|
389
|
+
} else {
|
|
390
|
+
const hitAtlasColumn = mod(hitCell.y, atlasColumns);
|
|
391
|
+
const hitAtlasRow = hitCell.y.div(atlasColumns).floor();
|
|
392
|
+
hitAtlasUv = vec2(
|
|
393
|
+
hitAtlasColumn.mul(planar).add(hitCell.x).add(0.5).div(atlasColumns * planar),
|
|
394
|
+
hitAtlasRow.mul(planar).add(hitCell.z).add(0.5).div(atlasRows * planar)
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
const baseSample = loadTexel(atlas, hitAtlasUv);
|
|
398
|
+
const ormSample = ormAtlas ? loadTexel(ormAtlas, hitAtlasUv) : vec43(1, 1, 0, 1);
|
|
399
|
+
const hitPosition = hit.xyz;
|
|
400
|
+
const hitToCamera = modelWorldMatrixInverse.mul(vec43(cameraPosition, 1)).xyz.sub(hitPosition);
|
|
401
|
+
const faceSign = step(0, hitToCamera).mul(2).sub(1);
|
|
402
|
+
const hitCellCenter = hitCell.add(0.5).div(volumeDimensions).sub(0.5).mul(sizeNode).sub(raycastOffsetNode);
|
|
403
|
+
const cellDelta = hitPosition.sub(hitCellCenter).div(sizeNode).mul(volumeDimensions);
|
|
404
|
+
const absoluteCellDelta = cellDelta.abs();
|
|
405
|
+
const boundaryDistance = max(
|
|
406
|
+
absoluteCellDelta.x,
|
|
407
|
+
max(absoluteCellDelta.y, absoluteCellDelta.z)
|
|
408
|
+
);
|
|
409
|
+
const faceDirection = hitToCamera.abs().normalize();
|
|
410
|
+
const xFaceScore = absoluteCellDelta.x.greaterThanEqual(boundaryDistance.sub(1e-4)).select(faceDirection.x, -1);
|
|
411
|
+
const yFaceScore = absoluteCellDelta.y.greaterThanEqual(boundaryDistance.sub(1e-4)).select(faceDirection.y, -1);
|
|
412
|
+
const zFaceScore = absoluteCellDelta.z.greaterThanEqual(boundaryDistance.sub(1e-4)).select(faceDirection.z, -1);
|
|
413
|
+
const geometricNormal = xFaceScore.greaterThanEqual(yFaceScore).and(xFaceScore.greaterThanEqual(zFaceScore)).select(vec3(faceSign.x, 0, 0), yFaceScore.greaterThanEqual(zFaceScore).select(vec3(0, faceSign.y, 0), vec3(0, 0, faceSign.z)));
|
|
414
|
+
const sampledNormal = normalAtlas ? loadTexel(normalAtlas, hitAtlasUv).xyz.mul(2).sub(1) : geometricNormal;
|
|
415
|
+
const bakedNormal = sampledNormal.dot(sampledNormal).greaterThan(1e-8).select(sampledNormal.normalize(), geometricNormal);
|
|
416
|
+
const projectedNormal = bakedNormal.dot(geometricNormal).lessThan(0).select(bakedNormal.negate(), bakedNormal);
|
|
417
|
+
const shadingNormal = mix(geometricNormal, projectedNormal, projectedNormalMix).normalize();
|
|
418
|
+
const materialName = `Pixel impostor \xB7 volume raycast \xB7 ${antialias ? "AA" : "fast"} \xB7 ${pbr ? "PBR maps" : "plain lit"}`;
|
|
419
|
+
const material = new CapturedSurfaceMaterial({
|
|
420
|
+
name: materialName,
|
|
421
|
+
side: THREE.FrontSide,
|
|
422
|
+
depthTest: true,
|
|
423
|
+
depthWrite: true
|
|
424
|
+
});
|
|
425
|
+
material.colorNode = vec43(
|
|
426
|
+
baseSample.rgb.mul(float(1).sub(unlitMix)),
|
|
427
|
+
antialias ? baseSample.a.mul(coverage) : baseSample.a
|
|
428
|
+
);
|
|
429
|
+
material.emissiveNode = baseSample.rgb.mul(pbr ? ormSample.r : 1).mul(unlitMix);
|
|
430
|
+
material.normalNode = transformNormalToView(shadingNormal);
|
|
431
|
+
if (pbr) {
|
|
432
|
+
material.aoNode = ormSample.r;
|
|
433
|
+
material.roughnessNode = ormSample.g.max(0.04);
|
|
434
|
+
material.metalnessNode = ormSample.b;
|
|
435
|
+
}
|
|
436
|
+
material.receivedShadowPositionNode = modelWorldMatrix2.mul(vec43(hitPosition, 1)).xyz;
|
|
437
|
+
material.maskNode = occupied.and(
|
|
438
|
+
baseSample.a.greaterThan(Number(descriptor.alphaCutoff) || 0.5)
|
|
439
|
+
);
|
|
440
|
+
material.maskShadowNode = antialias ? coverage.greaterThanEqual(0.5) : occupied;
|
|
441
|
+
material.alphaToCoverage = antialias;
|
|
442
|
+
material.capturedPositionNode = hitPosition;
|
|
443
|
+
material.depthNode = capturedSurfaceDepth(hitPosition);
|
|
444
|
+
material.toneMapped = true;
|
|
445
|
+
material.userData.screenPixelSize = screenPixelSize;
|
|
446
|
+
material.userData.pixelImpostorRaycastAntialias = antialias;
|
|
447
|
+
material.userData.pixelImpostorRaySamples = antialias ? 5 : 1;
|
|
448
|
+
material.userData.pixelImpostorPbr = pbr;
|
|
449
|
+
return material;
|
|
450
|
+
};
|
|
451
|
+
const raycastMaterials = {
|
|
452
|
+
mapped: {
|
|
453
|
+
fast: createRaycastMaterial(false, true),
|
|
454
|
+
antialias: createRaycastMaterial(true, true)
|
|
455
|
+
},
|
|
456
|
+
plain: {
|
|
457
|
+
fast: createRaycastMaterial(false, false),
|
|
458
|
+
antialias: createRaycastMaterial(true, false)
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
const raycast = new THREE.Mesh(new THREE.BoxGeometry(
|
|
462
|
+
raycastSize.x,
|
|
463
|
+
raycastSize.y,
|
|
464
|
+
raycastSize.z
|
|
465
|
+
), raycastMaterials.mapped.antialias);
|
|
466
|
+
raycast.name = "Pixel impostor \xB7 volume raycast";
|
|
467
|
+
raycast.position.copy(raycastCenter);
|
|
468
|
+
raycast.castShadow = true;
|
|
469
|
+
raycast.receiveShadow = true;
|
|
470
|
+
raycast.userData.previewPixelImpostor = true;
|
|
471
|
+
raycast.userData.pixelImpostorDisplayMode = "raycast";
|
|
472
|
+
raycast.userData.pixelImpostorAlternateMaterials = [
|
|
473
|
+
...Object.values(raycastMaterials.mapped),
|
|
474
|
+
...Object.values(raycastMaterials.plain)
|
|
475
|
+
];
|
|
476
|
+
const surfacePoints = binding.surfacePoints instanceof THREE.BufferAttribute || binding.surfacePoints instanceof THREE.InterleavedBufferAttribute ? binding.surfacePoints : null;
|
|
477
|
+
const shellless = descriptor.voxelShell === false;
|
|
478
|
+
let shell = null;
|
|
479
|
+
if (!shellless) asset.traverse((object) => {
|
|
480
|
+
if (!shell && object instanceof THREE.Mesh && (object.geometry.getAttribute("_voxel_center") || surfacePoints)) {
|
|
481
|
+
shell = object;
|
|
482
|
+
}
|
|
483
|
+
});
|
|
484
|
+
if (!shell && !shellless) return null;
|
|
485
|
+
const voxelShell = (
|
|
486
|
+
/** @type {THREE.Mesh | null} */
|
|
487
|
+
shell
|
|
488
|
+
);
|
|
489
|
+
const geometryBaseSample = texture(atlas, uv());
|
|
490
|
+
const geometryOrmSample = ormAtlas ? texture(ormAtlas, uv()) : vec43(1, 1, 0, 1);
|
|
491
|
+
const geometryNormal = attribute(
|
|
492
|
+
"normal",
|
|
493
|
+
/** @type {const} */
|
|
494
|
+
"vec3"
|
|
495
|
+
).normalize();
|
|
496
|
+
const geometryProjectedNormal = normalAtlas ? texture(normalAtlas, uv()).xyz.mul(2).sub(1).normalize() : geometryNormal;
|
|
497
|
+
const geometryAlignedNormal = geometryProjectedNormal.dot(geometryNormal).lessThan(0).select(geometryProjectedNormal.negate(), geometryProjectedNormal);
|
|
498
|
+
const createGeometryMaterial = (pbr) => {
|
|
499
|
+
const material = new MeshStandardNodeMaterial2({
|
|
500
|
+
name: `Pixel impostor \xB7 voxel geometry \xB7 ${pbr ? "mapped" : "plain"}`,
|
|
501
|
+
side: THREE.FrontSide,
|
|
502
|
+
depthTest: true,
|
|
503
|
+
depthWrite: true
|
|
504
|
+
});
|
|
505
|
+
material.colorNode = vec43(
|
|
506
|
+
geometryBaseSample.rgb.mul(float(1).sub(unlitMix)),
|
|
507
|
+
geometryBaseSample.a
|
|
508
|
+
);
|
|
509
|
+
material.emissiveNode = geometryBaseSample.rgb.mul(pbr ? geometryOrmSample.r : 1).mul(unlitMix);
|
|
510
|
+
material.normalNode = transformNormalToView(
|
|
511
|
+
mix(geometryNormal, geometryAlignedNormal, projectedNormalMix).normalize()
|
|
512
|
+
);
|
|
513
|
+
if (pbr) {
|
|
514
|
+
material.aoNode = geometryOrmSample.r;
|
|
515
|
+
material.roughnessNode = geometryOrmSample.g.max(0.04);
|
|
516
|
+
material.metalnessNode = geometryOrmSample.b;
|
|
517
|
+
}
|
|
518
|
+
material.maskNode = geometryBaseSample.a.greaterThan(
|
|
519
|
+
Number(descriptor.alphaCutoff) || 0.5
|
|
520
|
+
);
|
|
521
|
+
material.toneMapped = true;
|
|
522
|
+
material.userData.pixelImpostorPbr = pbr;
|
|
523
|
+
return material;
|
|
524
|
+
};
|
|
525
|
+
const geometryMaterials = {
|
|
526
|
+
mapped: createGeometryMaterial(true),
|
|
527
|
+
plain: createGeometryMaterial(false)
|
|
528
|
+
};
|
|
529
|
+
const previousGeometryMaterial = voxelShell?.material ?? null;
|
|
530
|
+
if (voxelShell) {
|
|
531
|
+
voxelShell.material = geometryMaterials.mapped;
|
|
532
|
+
voxelShell.userData.pixelImpostorAlternateMaterials = Object.values(geometryMaterials);
|
|
533
|
+
}
|
|
534
|
+
const skinnedSplats = voxelShell instanceof THREE.SkinnedMesh;
|
|
535
|
+
const useSurfacePoints = surfacePoints && !skinnedSplats;
|
|
536
|
+
const splatsAvailable = Boolean(voxelShell || useSurfacePoints);
|
|
537
|
+
let splatGeometry = skinnedSplats ? (
|
|
538
|
+
/** @type {THREE.Mesh} */
|
|
539
|
+
voxelShell.geometry.clone()
|
|
540
|
+
) : voxelShell?.geometry ?? new THREE.BufferGeometry();
|
|
541
|
+
if (skinnedSplats) {
|
|
542
|
+
const centers = (
|
|
543
|
+
/** @type {THREE.Mesh} */
|
|
544
|
+
voxelShell.geometry.getAttribute("_voxel_center")
|
|
545
|
+
);
|
|
546
|
+
if (!centers) throw new Error("Animated voxel splats require retained voxel centers.");
|
|
547
|
+
splatGeometry.setAttribute("position", centers.clone());
|
|
548
|
+
}
|
|
549
|
+
if (useSurfacePoints) {
|
|
550
|
+
const count = surfacePoints.count;
|
|
551
|
+
const coordinates = new Float32Array(count * 3);
|
|
552
|
+
const records = new Float32Array(count);
|
|
553
|
+
for (let index = 0; index < count; index++) {
|
|
554
|
+
coordinates[index * 3] = surfacePoints.getX(index);
|
|
555
|
+
coordinates[index * 3 + 1] = surfacePoints.getY(index);
|
|
556
|
+
coordinates[index * 3 + 2] = surfacePoints.getZ(index);
|
|
557
|
+
records[index] = index;
|
|
558
|
+
}
|
|
559
|
+
const instancedGeometry = new THREE.InstancedBufferGeometry();
|
|
560
|
+
instancedGeometry.instanceCount = count;
|
|
561
|
+
splatGeometry = instancedGeometry;
|
|
562
|
+
splatGeometry.setAttribute("position", new THREE.BufferAttribute(new Float32Array(12), 3));
|
|
563
|
+
splatGeometry.setAttribute("_voxel_corner", new THREE.BufferAttribute(new Float32Array([
|
|
564
|
+
-1,
|
|
565
|
+
-1,
|
|
566
|
+
1,
|
|
567
|
+
-1,
|
|
568
|
+
1,
|
|
569
|
+
1,
|
|
570
|
+
-1,
|
|
571
|
+
1
|
|
572
|
+
]), 2));
|
|
573
|
+
splatGeometry.setAttribute("_voxel_coord", new THREE.InstancedBufferAttribute(coordinates, 3));
|
|
574
|
+
splatGeometry.setAttribute("_voxel_record", new THREE.InstancedBufferAttribute(records, 1));
|
|
575
|
+
splatGeometry.setIndex([0, 1, 2, 0, 2, 3]);
|
|
576
|
+
splatGeometry.boundingBox = voxelShell?.geometry.boundingBox?.clone() ?? bounds.clone();
|
|
577
|
+
splatGeometry.boundingSphere = voxelShell?.geometry.boundingSphere?.clone() ?? splatGeometry.boundingBox.getBoundingSphere(new THREE.Sphere());
|
|
578
|
+
}
|
|
579
|
+
const voxelCoordinate = attribute(
|
|
580
|
+
"_voxel_coord",
|
|
581
|
+
/** @type {const} */
|
|
582
|
+
"vec3"
|
|
583
|
+
);
|
|
584
|
+
const voxelCenter = skinnedSplats ? positionLocal : useSurfacePoints ? voxelCoordinate.add(0.5).div(volumeDimensions).sub(0.5).mul(sizeNode).add(uniform(center.clone())) : attribute(
|
|
585
|
+
"_voxel_center",
|
|
586
|
+
/** @type {const} */
|
|
587
|
+
"vec3"
|
|
588
|
+
);
|
|
589
|
+
const voxelCorner = attribute(
|
|
590
|
+
"_voxel_corner",
|
|
591
|
+
/** @type {const} */
|
|
592
|
+
"vec2"
|
|
593
|
+
);
|
|
594
|
+
const centerView = modelViewMatrix3.mul(vec43(voxelCenter, 1));
|
|
595
|
+
const centerClip = cameraProjectionMatrix2.mul(centerView);
|
|
596
|
+
const centerNdc = centerClip.xy.div(centerClip.w);
|
|
597
|
+
const cssViewport = viewportSize;
|
|
598
|
+
const centerCss = centerNdc.mul(0.5).add(0.5).mul(cssViewport);
|
|
599
|
+
const projectVoxelPoint = (point) => {
|
|
600
|
+
const projected = cameraProjectionMatrix2.mul(modelViewMatrix3.mul(vec43(point, 1)));
|
|
601
|
+
return projected.xy.div(projected.w).mul(0.5).add(0.5).mul(cssViewport);
|
|
602
|
+
};
|
|
603
|
+
const projectedX = projectVoxelPoint(voxelCenter.add(vec3(voxelHalfExtents.x, 0, 0)));
|
|
604
|
+
const projectedY = projectVoxelPoint(voxelCenter.add(vec3(0, voxelHalfExtents.y, 0)));
|
|
605
|
+
const projectedZ = projectVoxelPoint(voxelCenter.add(vec3(0, 0, voxelHalfExtents.z)));
|
|
606
|
+
const projectedHalfFootprint = projectedX.sub(centerCss).abs().add(projectedY.sub(centerCss).abs()).add(projectedZ.sub(centerCss).abs());
|
|
607
|
+
const projectedVoxelSize = max(projectedHalfFootprint.x, projectedHalfFootprint.y).mul(2);
|
|
608
|
+
const projectedCellSpan = projectedVoxelSize.div(splatPixelSize);
|
|
609
|
+
const nearestCellSpan = ceil(projectedCellSpan.sub(0.5)).max(1);
|
|
610
|
+
const singleCell = snapMode.equal(1);
|
|
611
|
+
const centerOnly = snapMode.equal(2);
|
|
612
|
+
const cellSpan = singleCell.select(1, nearestCellSpan);
|
|
613
|
+
const cellCenter = centerCss.div(splatPixelSize).floor().mul(splatPixelSize).add(splatPixelSize.mul(0.5));
|
|
614
|
+
const gridIntersection = centerCss.div(splatPixelSize).add(0.5).floor().mul(splatPixelSize);
|
|
615
|
+
const oddCellSpan = mod(cellSpan, 2);
|
|
616
|
+
const parityAlignedCenter = oddCellSpan.greaterThan(0.5).select(cellCenter, gridIntersection);
|
|
617
|
+
const snappedCss = centerOnly.select(cellCenter, parityAlignedCenter);
|
|
618
|
+
const splatSize = cellSpan.mul(splatPixelSize).mul(splatScale);
|
|
619
|
+
const quadCss = snappedCss.add(voxelCorner.mul(splatSize.mul(0.52)));
|
|
620
|
+
const quadNdc = quadCss.div(cssViewport).mul(2).sub(1);
|
|
621
|
+
const quadClip = vec43(quadNdc.mul(centerClip.w), centerClip.z, centerClip.w);
|
|
622
|
+
const quadViewHomogeneous = cameraProjectionMatrixInverse.mul(quadClip);
|
|
623
|
+
const quadView = quadViewHomogeneous.xyz.div(quadViewHomogeneous.w);
|
|
624
|
+
const quadWorld = cameraWorldMatrix.mul(vec43(quadView, 1));
|
|
625
|
+
const quadLocalHomogeneous = modelWorldMatrixInverse.mul(quadWorld);
|
|
626
|
+
const quadLocal = quadLocalHomogeneous.xyz.div(quadLocalHomogeneous.w);
|
|
627
|
+
const splatUv = useSurfacePoints ? linearTextureUv(attribute(
|
|
628
|
+
"_voxel_record",
|
|
629
|
+
/** @type {const} */
|
|
630
|
+
"float"
|
|
631
|
+
), surfaceAtlasSize) : uv();
|
|
632
|
+
const splatColor = texture(atlas, splatUv);
|
|
633
|
+
const splatOrm = ormAtlas ? texture(ormAtlas, splatUv) : vec43(1, 1, 0, 1);
|
|
634
|
+
const cameraLocal = modelWorldMatrixInverse.mul(vec43(cameraPosition, 1)).xyz;
|
|
635
|
+
const viewDirection = cameraLocal.sub(voxelCenter).normalize();
|
|
636
|
+
const splatBakedNormal = normalAtlas ? texture(normalAtlas, splatUv).xyz.mul(2).sub(1).normalize() : viewDirection;
|
|
637
|
+
const splatProjectedNormal = splatBakedNormal.dot(viewDirection).lessThan(0).select(splatBakedNormal.negate(), splatBakedNormal);
|
|
638
|
+
const splatShadingNormal = mix(
|
|
639
|
+
viewDirection,
|
|
640
|
+
splatProjectedNormal,
|
|
641
|
+
projectedNormalMix
|
|
642
|
+
).normalize();
|
|
643
|
+
let splatMask;
|
|
644
|
+
if (useSurfacePoints) {
|
|
645
|
+
splatMask = splatColor.a.greaterThan(0.5);
|
|
646
|
+
} else {
|
|
647
|
+
const voxelFaceMask = float(attribute(
|
|
648
|
+
"_voxel_face_mask",
|
|
649
|
+
/** @type {const} */
|
|
650
|
+
"float"
|
|
651
|
+
));
|
|
652
|
+
const faceScores = [
|
|
653
|
+
viewDirection.x.negate(),
|
|
654
|
+
viewDirection.x,
|
|
655
|
+
viewDirection.z.negate(),
|
|
656
|
+
viewDirection.z,
|
|
657
|
+
viewDirection.y.negate(),
|
|
658
|
+
viewDirection.y
|
|
659
|
+
];
|
|
660
|
+
const exposedScore = (face) => {
|
|
661
|
+
const exposed = mod(voxelFaceMask.div(2 ** face).floor(), 2);
|
|
662
|
+
return mix(-2, faceScores[face], exposed);
|
|
663
|
+
};
|
|
664
|
+
const bestFaceScore = max(
|
|
665
|
+
max(max(exposedScore(0), exposedScore(1)), max(exposedScore(2), exposedScore(3))),
|
|
666
|
+
max(exposedScore(4), exposedScore(5))
|
|
667
|
+
);
|
|
668
|
+
const sourceFaceNormal = attribute(
|
|
669
|
+
"normal",
|
|
670
|
+
/** @type {const} */
|
|
671
|
+
"vec3"
|
|
672
|
+
);
|
|
673
|
+
splatMask = sourceFaceNormal.dot(viewDirection).greaterThanEqual(bestFaceScore.sub(1e-5)).and(splatColor.a.greaterThan(0.5));
|
|
674
|
+
}
|
|
675
|
+
const createSnappedMaterial = (pbr) => {
|
|
676
|
+
const material = new MeshStandardNodeMaterial2({
|
|
677
|
+
name: `Pixel impostor \xB7 vertex-snapped shell \xB7 ${pbr ? "mapped" : "plain"}`,
|
|
678
|
+
side: THREE.FrontSide,
|
|
679
|
+
depthTest: true,
|
|
680
|
+
depthWrite: true
|
|
681
|
+
});
|
|
682
|
+
material.positionNode = quadLocal;
|
|
683
|
+
material.colorNode = vec43(splatColor.rgb.mul(float(1).sub(unlitMix)), splatColor.a);
|
|
684
|
+
material.emissiveNode = splatColor.rgb.mul(pbr ? splatOrm.r : 1).mul(unlitMix);
|
|
685
|
+
material.normalNode = transformNormalToView(splatShadingNormal);
|
|
686
|
+
if (pbr) {
|
|
687
|
+
material.aoNode = splatOrm.r;
|
|
688
|
+
material.roughnessNode = splatOrm.g.max(0.04);
|
|
689
|
+
material.metalnessNode = splatOrm.b;
|
|
690
|
+
}
|
|
691
|
+
material.maskNode = splatMask;
|
|
692
|
+
material.toneMapped = true;
|
|
693
|
+
material.userData.pixelImpostorPbr = pbr;
|
|
694
|
+
return material;
|
|
695
|
+
};
|
|
696
|
+
const snappedMaterials = {
|
|
697
|
+
mapped: createSnappedMaterial(true),
|
|
698
|
+
plain: createSnappedMaterial(false)
|
|
699
|
+
};
|
|
700
|
+
const snappedShell = skinnedSplats ? new THREE.SkinnedMesh(splatGeometry, snappedMaterials.mapped) : new THREE.Mesh(splatGeometry, snappedMaterials.mapped);
|
|
701
|
+
if (snappedShell instanceof THREE.SkinnedMesh && voxelShell instanceof THREE.SkinnedMesh) {
|
|
702
|
+
snappedShell.bindMode = voxelShell.bindMode;
|
|
703
|
+
snappedShell.bind(voxelShell.skeleton, voxelShell.bindMatrix);
|
|
704
|
+
snappedShell.bindMatrixInverse.copy(voxelShell.bindMatrixInverse);
|
|
705
|
+
}
|
|
706
|
+
asset.updateWorldMatrix(true, true);
|
|
707
|
+
voxelShell?.updateWorldMatrix(true, false);
|
|
708
|
+
if (!useSurfacePoints && voxelShell) {
|
|
709
|
+
snappedShell.matrix.copy(asset.matrixWorld).invert().multiply(voxelShell.matrixWorld);
|
|
710
|
+
snappedShell.matrixAutoUpdate = false;
|
|
711
|
+
}
|
|
712
|
+
snappedShell.name = "Pixel impostor \xB7 vertex-snapped shell";
|
|
713
|
+
snappedShell.castShadow = false;
|
|
714
|
+
snappedShell.receiveShadow = false;
|
|
715
|
+
snappedShell.userData.previewPixelImpostor = true;
|
|
716
|
+
snappedShell.userData.pixelImpostorDisplayMode = "vertex-snap";
|
|
717
|
+
snappedShell.userData.pixelImpostorAlternateMaterials = Object.values(snappedMaterials);
|
|
718
|
+
const preview = new THREE.Group();
|
|
719
|
+
preview.name = "Pixel impostor shader previews";
|
|
720
|
+
preview.visible = false;
|
|
721
|
+
preview.userData.screenPixelSize = screenPixelSize;
|
|
722
|
+
preview.userData.splatPixelSize = splatPixelSize;
|
|
723
|
+
preview.userData.splatScale = splatScale;
|
|
724
|
+
preview.userData.projectedNormalMix = projectedNormalMix;
|
|
725
|
+
preview.userData.projectedNormalMixValue = 1;
|
|
726
|
+
preview.userData.unlitMix = unlitMix;
|
|
727
|
+
preview.userData.raycastMesh = raycast;
|
|
728
|
+
preview.userData.raycastMaterials = raycastMaterials;
|
|
729
|
+
preview.userData.geometryMesh = voxelShell;
|
|
730
|
+
preview.userData.previousGeometryMaterial = previousGeometryMaterial;
|
|
731
|
+
preview.userData.geometryMaterials = geometryMaterials;
|
|
732
|
+
preview.userData.snappedMesh = snappedShell;
|
|
733
|
+
preview.userData.snappedMaterials = snappedMaterials;
|
|
734
|
+
preview.userData.raycastAntialiasEnabled = true;
|
|
735
|
+
preview.userData.snapMode = snapMode;
|
|
736
|
+
preview.userData.viewportSize = viewportSize;
|
|
737
|
+
preview.userData.dpr = dpr;
|
|
738
|
+
preview.userData.pixelSizeValue = 5;
|
|
739
|
+
preview.add(raycast, snappedShell);
|
|
740
|
+
const textureBytes = textureFootprintBytes(atlas) + (normalAtlas ? textureFootprintBytes(normalAtlas) : 0) + (ormAtlas ? textureFootprintBytes(ormAtlas) : 0) + (indexAtlas ? textureFootprintBytes(indexAtlas) : 0);
|
|
741
|
+
const shellStats = voxelShell ? pixelDisplayMeshStats(voxelShell, textureBytes) : null;
|
|
742
|
+
const splatStats = splatsAvailable ? pixelDisplayMeshStats(snappedShell, textureFootprintBytes(atlas)) : null;
|
|
743
|
+
preview.userData.availableModes = [
|
|
744
|
+
...voxelShell ? ["geometry"] : [],
|
|
745
|
+
...splatsAvailable ? ["vertex-snap"] : [],
|
|
746
|
+
"raycast",
|
|
747
|
+
"screen-pixels"
|
|
748
|
+
];
|
|
749
|
+
const raycastStats = pixelDisplayMeshStats(raycast, textureBytes);
|
|
750
|
+
preview.userData.displayStats = {
|
|
751
|
+
geometry: shellStats,
|
|
752
|
+
"vertex-snap": splatStats,
|
|
753
|
+
raycast: raycastStats,
|
|
754
|
+
"screen-pixels": raycastStats
|
|
755
|
+
};
|
|
756
|
+
return preview;
|
|
757
|
+
}
|
|
758
|
+
function pixelDisplayMeshStats(mesh, textureBytes) {
|
|
759
|
+
const position = mesh.geometry.getAttribute("position");
|
|
760
|
+
const geometryBytes = bufferGeometryFootprintBytes(mesh.geometry);
|
|
761
|
+
const instances = mesh.geometry instanceof THREE.InstancedBufferGeometry ? mesh.geometry.instanceCount : 1;
|
|
762
|
+
return {
|
|
763
|
+
triangles: (mesh.geometry.getIndex()?.count ?? position?.count ?? 0) / 3 * instances,
|
|
764
|
+
vertices: (position?.count ?? 0) * instances,
|
|
765
|
+
drawCalls: 1,
|
|
766
|
+
geometryBytes,
|
|
767
|
+
textureBytes,
|
|
768
|
+
gpuBytes: geometryBytes + textureBytes
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
function bufferGeometryFootprintBytes(geometry) {
|
|
772
|
+
const buffers = /* @__PURE__ */ new Set();
|
|
773
|
+
let bytes = 0;
|
|
774
|
+
const add = (attribute2) => {
|
|
775
|
+
if (!attribute2) return;
|
|
776
|
+
const storage = attribute2 instanceof THREE.InterleavedBufferAttribute ? attribute2.data : attribute2;
|
|
777
|
+
if (buffers.has(storage)) return;
|
|
778
|
+
buffers.add(storage);
|
|
779
|
+
bytes += storage.array?.byteLength ?? 0;
|
|
780
|
+
};
|
|
781
|
+
add(geometry.getIndex());
|
|
782
|
+
for (const attribute2 of Object.values(geometry.attributes)) add(attribute2);
|
|
783
|
+
return bytes;
|
|
784
|
+
}
|
|
785
|
+
function textureFootprintBytes(atlas) {
|
|
786
|
+
const image = (
|
|
787
|
+
/** @type {{width?:number,height?:number,data?:{byteLength?:number}} | null} */
|
|
788
|
+
atlas.image
|
|
789
|
+
);
|
|
790
|
+
if (image?.data?.byteLength !== void 0) return image.data.byteLength;
|
|
791
|
+
const width = Number(image?.width ?? 0);
|
|
792
|
+
const height = Number(image?.height ?? 0);
|
|
793
|
+
return Number.isFinite(width) && Number.isFinite(height) ? width * height * 4 : 0;
|
|
794
|
+
}
|
|
795
|
+
function createPixelImpostorDisplay(asset, options = {}) {
|
|
796
|
+
let binding = options.binding ?? null;
|
|
797
|
+
asset.traverse((object) => {
|
|
798
|
+
if (!binding && object.userData.pixelImpostor) binding = object.userData.pixelImpostor;
|
|
799
|
+
});
|
|
800
|
+
if (!binding) throw new Error("Load a NEEDLE_pixel_impostor GLB with registerNeedlePixelImpostorLoader first.");
|
|
801
|
+
const preview = createPixelImpostorRaycastPreview(asset, new THREE.Box3().setFromObject(asset), binding);
|
|
802
|
+
if (!preview) throw new Error("The pixel impostor has no supported shader atlas.");
|
|
803
|
+
const originals = /* @__PURE__ */ new Map();
|
|
804
|
+
asset.traverse((object) => {
|
|
805
|
+
if (object instanceof THREE.Mesh) originals.set(object, object.visible);
|
|
806
|
+
});
|
|
807
|
+
if (options.attach !== false) asset.add(preview);
|
|
808
|
+
const stored = (
|
|
809
|
+
/** @type {Partial<import('./pixel-impostor-metadata.js').PixelImpostorDisplay>} */
|
|
810
|
+
/** @type {{display?: object}} */
|
|
811
|
+
(binding.descriptor ?? {}).display ?? {}
|
|
812
|
+
);
|
|
813
|
+
options = { ...stored, ...Object.fromEntries(Object.entries(options).filter(([, value]) => value !== void 0)) };
|
|
814
|
+
let mode = options.mode ?? (preview.userData.availableModes.includes("geometry") ? "geometry" : "screen-pixels");
|
|
815
|
+
let pbr = options.pbr ?? true;
|
|
816
|
+
let antialias = options.antialias ?? true;
|
|
817
|
+
const setMode = (next) => {
|
|
818
|
+
if (!["geometry", "vertex-snap", "raycast", "screen-pixels"].includes(next)) throw new Error(`Unknown pixel display mode: ${next}`);
|
|
819
|
+
if (!preview.userData.availableModes.includes(next)) throw new Error(`This pixel impostor has no voxel shell, so it cannot use the ${next} display mode.`);
|
|
820
|
+
mode = next;
|
|
821
|
+
preview.userData.displayMode = next;
|
|
822
|
+
for (const [mesh, visible] of originals) mesh.visible = next === "geometry" && visible;
|
|
823
|
+
preview.visible = next !== "geometry";
|
|
824
|
+
for (const child of preview.children) child.visible = child.userData.pixelImpostorDisplayMode === next || next === "screen-pixels" && child.userData.pixelImpostorDisplayMode === "raycast";
|
|
825
|
+
preview.userData.screenPixelSize.value = next === "screen-pixels" ? options.pixelSize ?? 5 : 1;
|
|
826
|
+
const raycast = preview.userData.raycastMesh;
|
|
827
|
+
const raycastMaterials = preview.userData.raycastMaterials;
|
|
828
|
+
if (raycast instanceof THREE.Mesh) raycast.material = raycastMaterials[pbr ? "mapped" : "plain"][next === "raycast" && antialias ? "antialias" : "fast"];
|
|
829
|
+
const snapped = preview.userData.snappedMesh;
|
|
830
|
+
if (snapped instanceof THREE.Mesh) snapped.material = preview.userData.snappedMaterials[pbr ? "mapped" : "plain"];
|
|
831
|
+
const shell = preview.userData.geometryMesh;
|
|
832
|
+
if (shell instanceof THREE.Mesh) shell.material = preview.userData.geometryMaterials[pbr ? "mapped" : "plain"];
|
|
833
|
+
return preview.userData.displayStats?.[next] ?? null;
|
|
834
|
+
};
|
|
835
|
+
const updateViewport = () => {
|
|
836
|
+
const canvas = options.renderer?.domElement;
|
|
837
|
+
const viewport = preview.userData.viewportSize.value;
|
|
838
|
+
if (viewport instanceof THREE.Vector2) viewport.set(Math.max(1, canvas?.clientWidth ?? 1), Math.max(1, canvas?.clientHeight ?? 1));
|
|
839
|
+
preview.userData.dpr.value = options.renderer?.getPixelRatio?.() ?? 1;
|
|
840
|
+
};
|
|
841
|
+
preview.userData.splatPixelSize.value = options.pixelSize ?? 5;
|
|
842
|
+
preview.userData.splatScale.value = options.splatScale ?? 1;
|
|
843
|
+
preview.userData.projectedNormalMix.value = options.projectedNormalMix ?? 1;
|
|
844
|
+
preview.userData.snapMode.value = options.snapMode === "single-cell" ? 1 : options.snapMode === "center-only" ? 2 : 0;
|
|
845
|
+
setMode(mode);
|
|
846
|
+
updateViewport();
|
|
847
|
+
return {
|
|
848
|
+
preview,
|
|
849
|
+
setMode,
|
|
850
|
+
updateViewport,
|
|
851
|
+
/** @param {boolean} enabled */
|
|
852
|
+
setPbr(enabled) {
|
|
853
|
+
pbr = Boolean(enabled);
|
|
854
|
+
setMode(mode);
|
|
855
|
+
},
|
|
856
|
+
/** @param {boolean} enabled */
|
|
857
|
+
setAntialias(enabled) {
|
|
858
|
+
antialias = Boolean(enabled);
|
|
859
|
+
setMode(mode);
|
|
860
|
+
},
|
|
861
|
+
dispose() {
|
|
862
|
+
preview.removeFromParent();
|
|
863
|
+
for (const [mesh, visible] of originals) mesh.visible = visible;
|
|
864
|
+
const shell = preview.userData.geometryMesh;
|
|
865
|
+
if (shell instanceof THREE.Mesh) shell.material = preview.userData.previousGeometryMaterial;
|
|
866
|
+
for (const child of preview.children) if (child instanceof THREE.Mesh && child.geometry !== preview.userData.geometryMesh?.geometry) child.geometry.dispose();
|
|
867
|
+
for (const materials of [preview.userData.raycastMaterials?.mapped, preview.userData.raycastMaterials?.plain, preview.userData.snappedMaterials, preview.userData.geometryMaterials]) {
|
|
868
|
+
if (materials) for (const material of Object.values(materials)) material.dispose();
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
};
|
|
872
|
+
}
|
|
873
|
+
var init_pixel_impostor_display = __esm({
|
|
874
|
+
"src/pixel-impostor/pixel-impostor-display.js"() {
|
|
875
|
+
"use strict";
|
|
876
|
+
init_captured_surface_material();
|
|
877
|
+
init_captured_surface_depth();
|
|
878
|
+
}
|
|
879
|
+
});
|
|
2
880
|
|
|
3
881
|
// src/pixel-impostor/pixel-impostor-runtime.js
|
|
4
|
-
import { ClampToEdgeWrapping, NearestFilter, NoColorSpace, SRGBColorSpace } from "three";
|
|
882
|
+
import { ClampToEdgeWrapping, NearestFilter as NearestFilter2, NoColorSpace as NoColorSpace2, SRGBColorSpace } from "three";
|
|
5
883
|
|
|
6
884
|
// src/pixel-impostor/pixel-impostor-metadata.js
|
|
7
885
|
var NEEDLE_PIXEL_IMPOSTOR = "NEEDLE_pixel_impostor";
|
|
886
|
+
var DEFAULT_PIXEL_IMPOSTOR_DISPLAY = Object.freeze({
|
|
887
|
+
mode: (
|
|
888
|
+
/** @type {PixelImpostorDisplay['mode']} */
|
|
889
|
+
"geometry"
|
|
890
|
+
),
|
|
891
|
+
pixelSize: 5,
|
|
892
|
+
splatScale: 1,
|
|
893
|
+
snapMode: (
|
|
894
|
+
/** @type {PixelImpostorDisplay['snapMode']} */
|
|
895
|
+
"nearest-grid"
|
|
896
|
+
),
|
|
897
|
+
antialias: true,
|
|
898
|
+
pbr: true,
|
|
899
|
+
projectedNormalMix: 1
|
|
900
|
+
});
|
|
901
|
+
var PIXEL_IMPOSTOR_VOLUME_MODES = Object.freeze(
|
|
902
|
+
/** @type {const} */
|
|
903
|
+
["raycast", "screen-pixels"]
|
|
904
|
+
);
|
|
905
|
+
function normalizePixelImpostorDisplay(input = {}) {
|
|
906
|
+
const value = { ...DEFAULT_PIXEL_IMPOSTOR_DISPLAY, ...input };
|
|
907
|
+
if (!["geometry", "vertex-snap", "raycast", "screen-pixels"].includes(value.mode) || !Number.isInteger(value.pixelSize) || value.pixelSize < 1 || value.pixelSize > 64 || !Number.isFinite(value.splatScale) || value.splatScale <= 0 || value.splatScale > 4 || !["nearest-grid", "single-cell", "center-only"].includes(value.snapMode) || typeof value.antialias !== "boolean" || typeof value.pbr !== "boolean" || !Number.isFinite(value.projectedNormalMix) || value.projectedNormalMix < 0 || value.projectedNormalMix > 1)
|
|
908
|
+
throw new Error("Invalid pixel impostor display settings.");
|
|
909
|
+
return {
|
|
910
|
+
mode: value.mode,
|
|
911
|
+
pixelSize: value.pixelSize,
|
|
912
|
+
splatScale: value.splatScale,
|
|
913
|
+
snapMode: value.snapMode,
|
|
914
|
+
antialias: value.antialias,
|
|
915
|
+
pbr: value.pbr,
|
|
916
|
+
projectedNormalMix: value.projectedNormalMix
|
|
917
|
+
};
|
|
918
|
+
}
|
|
8
919
|
function parsePixelImpostorDescriptor(value) {
|
|
9
920
|
if (!value || typeof value !== "object") return null;
|
|
10
921
|
const raw = (
|
|
11
922
|
/** @type {Record<string, unknown>} */
|
|
12
923
|
value
|
|
13
924
|
);
|
|
14
|
-
|
|
925
|
+
const v4 = typeof raw.version === "string" && /^4\.(?:0|[1-9][0-9]*)$/.test(raw.version);
|
|
926
|
+
if (![1, 2, 3].includes(
|
|
927
|
+
/** @type {number} */
|
|
928
|
+
raw.version
|
|
929
|
+
) && !v4 || !triplet(raw.dimensions) || !triplet(raw.volumeMin) || !triplet(raw.volumeSize)) return null;
|
|
15
930
|
const dimensions = (
|
|
16
931
|
/** @type {number[]} */
|
|
17
932
|
raw.dimensions
|
|
@@ -31,14 +946,24 @@ function parsePixelImpostorDescriptor(value) {
|
|
|
31
946
|
/** @type {number[]} */
|
|
32
947
|
raw.occupiedSize
|
|
33
948
|
) : volumeSize;
|
|
34
|
-
if (!dimensions.every((item) => Number.isInteger(item) && item > 0) || !volumeSize.every((item) => Number.isFinite(item) && item > 0) || !occupiedSize.every((item) => Number.isFinite(item) && item > 0) ||
|
|
35
|
-
|
|
36
|
-
|
|
949
|
+
if (!dimensions.every((item) => Number.isInteger(item) && item > 0) || !volumeSize.every((item) => Number.isFinite(item) && item > 0) || !occupiedSize.every((item) => Number.isFinite(item) && item > 0) || v4 && raw.storage !== "sparse" && raw.storage !== "dense") return null;
|
|
950
|
+
if (!((raw.version === 3 || v4) && raw.storage === "sparse") && (!Number.isInteger(raw.atlasColumns) || Number(raw.atlasColumns) < 1 || !Number.isInteger(raw.atlasRows) || Number(raw.atlasRows) < 1)) return null;
|
|
951
|
+
const sparse = (raw.version === 3 || v4) && raw.storage === "sparse";
|
|
952
|
+
let display = null;
|
|
953
|
+
try {
|
|
954
|
+
display = raw.display && typeof raw.display === "object" ? normalizePixelImpostorDisplay(
|
|
955
|
+
/** @type {Partial<PixelImpostorDisplay>} */
|
|
956
|
+
raw.display
|
|
957
|
+
) : null;
|
|
958
|
+
} catch {
|
|
959
|
+
display = null;
|
|
960
|
+
}
|
|
961
|
+
if (raw.version === 3 && !sparse || sparse && (!Number.isInteger(raw.surfaceCount) || Number(raw.surfaceCount) < 1 || !pair(raw.surfaceAtlasSize) || !pair(raw.indexAtlasSize))) return null;
|
|
37
962
|
return (
|
|
38
963
|
/** @type {PixelImpostorDescriptor} */
|
|
39
964
|
{
|
|
40
965
|
version: (
|
|
41
|
-
/** @type {1 | 2 | 3} */
|
|
966
|
+
/** @type {1 | 2 | 3 | string} */
|
|
42
967
|
raw.version
|
|
43
968
|
),
|
|
44
969
|
dimensions: [...dimensions],
|
|
@@ -57,7 +982,12 @@ function parsePixelImpostorDescriptor(value) {
|
|
|
57
982
|
raw.surfaceAtlasSize],
|
|
58
983
|
indexAtlasSize: [.../** @type {number[]} */
|
|
59
984
|
raw.indexAtlasSize]
|
|
60
|
-
} : {}
|
|
985
|
+
} : {},
|
|
986
|
+
...display ? { display } : {},
|
|
987
|
+
...v4 && raw.voxelShell === false ? { voxelShell: (
|
|
988
|
+
/** @type {const} */
|
|
989
|
+
false
|
|
990
|
+
) } : {}
|
|
61
991
|
}
|
|
62
992
|
);
|
|
63
993
|
}
|
|
@@ -70,10 +1000,11 @@ function pair(value) {
|
|
|
70
1000
|
|
|
71
1001
|
// src/pixel-impostor/pixel-impostor-runtime.js
|
|
72
1002
|
var NeedlePixelImpostorLoaderPlugin = class {
|
|
73
|
-
/** @param {unknown} parser */
|
|
74
|
-
constructor(parser) {
|
|
1003
|
+
/** @param {unknown} parser @param {{renderer?: import('../rendering/renderer-support.js').ImpostorRenderer}} [options] */
|
|
1004
|
+
constructor(parser, options = {}) {
|
|
75
1005
|
this.name = NEEDLE_PIXEL_IMPOSTOR;
|
|
76
1006
|
this.parser = parser;
|
|
1007
|
+
this.options = options;
|
|
77
1008
|
}
|
|
78
1009
|
/** @param {import('three/addons/loaders/GLTFLoader.js').GLTF} result */
|
|
79
1010
|
async afterRoot(result) {
|
|
@@ -81,7 +1012,7 @@ var NeedlePixelImpostorLoaderPlugin = class {
|
|
|
81
1012
|
/** @type {{json:{meshes?:Array<{primitives:Array<{extensions?:Record<string,unknown>}>}>},associations:Map<import('three').Object3D,{meshes?:number,primitives?:number}>,getDependency(type:'texture',index:number):Promise<import('three').Texture>,getDependency(type:'accessor',index:number):Promise<import('three').BufferAttribute>}} */
|
|
82
1013
|
this.parser
|
|
83
1014
|
);
|
|
84
|
-
const
|
|
1015
|
+
const pending2 = (
|
|
85
1016
|
/** @type {Promise<void>[]} */
|
|
86
1017
|
[]
|
|
87
1018
|
);
|
|
@@ -106,23 +1037,23 @@ var NeedlePixelImpostorLoaderPlugin = class {
|
|
|
106
1037
|
if (required) throw new Error(`NEEDLE_pixel_impostor has no ${role} binding.`);
|
|
107
1038
|
return null;
|
|
108
1039
|
}
|
|
109
|
-
const
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
return
|
|
1040
|
+
const texture2 = await parser.getDependency("texture", Number(index));
|
|
1041
|
+
texture2.colorSpace = colorSpace;
|
|
1042
|
+
texture2.magFilter = NearestFilter2;
|
|
1043
|
+
texture2.minFilter = NearestFilter2;
|
|
1044
|
+
texture2.wrapS = ClampToEdgeWrapping;
|
|
1045
|
+
texture2.wrapT = ClampToEdgeWrapping;
|
|
1046
|
+
texture2.generateMipmaps = false;
|
|
1047
|
+
texture2.needsUpdate = true;
|
|
1048
|
+
return texture2;
|
|
118
1049
|
};
|
|
119
1050
|
const surfacePointsIndex = record.surfacePoints;
|
|
120
1051
|
const surfacePointsPromise = Number.isInteger(surfacePointsIndex) ? parser.getDependency("accessor", Number(surfacePointsIndex)) : Promise.resolve(null);
|
|
121
|
-
|
|
1052
|
+
pending2.push(Promise.all([
|
|
122
1053
|
loadTexture("atlas", SRGBColorSpace, true),
|
|
123
|
-
loadTexture("normalAtlas",
|
|
124
|
-
loadTexture("ormAtlas",
|
|
125
|
-
loadTexture("indexAtlas",
|
|
1054
|
+
loadTexture("normalAtlas", NoColorSpace2),
|
|
1055
|
+
loadTexture("ormAtlas", NoColorSpace2),
|
|
1056
|
+
loadTexture("indexAtlas", NoColorSpace2, descriptor.storage === "sparse"),
|
|
126
1057
|
surfacePointsPromise
|
|
127
1058
|
]).then(([atlas, normalAtlas, ormAtlas, indexAtlas, surfacePoints]) => {
|
|
128
1059
|
if (!atlas) throw new Error("NEEDLE_pixel_impostor atlas is unavailable.");
|
|
@@ -136,11 +1067,34 @@ var NeedlePixelImpostorLoaderPlugin = class {
|
|
|
136
1067
|
};
|
|
137
1068
|
}));
|
|
138
1069
|
});
|
|
139
|
-
await Promise.all(
|
|
1070
|
+
await Promise.all(pending2);
|
|
1071
|
+
await this.applyStoredDisplay(result);
|
|
1072
|
+
}
|
|
1073
|
+
/** @param {import('three/addons/loaders/GLTFLoader.js').GLTF} result */
|
|
1074
|
+
async applyStoredDisplay(result) {
|
|
1075
|
+
const renderer = this.options.renderer, scene = result.scene;
|
|
1076
|
+
if (!renderer || !scene) return;
|
|
1077
|
+
let binding = null;
|
|
1078
|
+
scene.traverse((object) => {
|
|
1079
|
+
if (!binding && object.userData.pixelImpostor?.descriptor?.display) binding = object.userData.pixelImpostor;
|
|
1080
|
+
});
|
|
1081
|
+
if (!binding) return;
|
|
1082
|
+
const { rendererSupportsImpostorNodeMaterials: rendererSupportsImpostorNodeMaterials2 } = await Promise.resolve().then(() => (init_renderer_support(), renderer_support_exports));
|
|
1083
|
+
if (!rendererSupportsImpostorNodeMaterials2(renderer)) {
|
|
1084
|
+
console.warn("[three-mesh-effects] NEEDLE_pixel_impostor displays need WebGPURenderer or a renderer with node-material support; drawing the file's mesh.");
|
|
1085
|
+
return;
|
|
1086
|
+
}
|
|
1087
|
+
const { createPixelImpostorDisplay: createPixelImpostorDisplay2 } = await Promise.resolve().then(() => (init_pixel_impostor_display(), pixel_impostor_display_exports));
|
|
1088
|
+
const display = createPixelImpostorDisplay2(scene, { binding, renderer: (
|
|
1089
|
+
/** @type {any} */
|
|
1090
|
+
renderer
|
|
1091
|
+
) });
|
|
1092
|
+
for (const child of display.preview.children) child.onBeforeRender = () => display.updateViewport();
|
|
1093
|
+
scene.userData.pixelImpostorDisplay = display;
|
|
140
1094
|
}
|
|
141
1095
|
};
|
|
142
|
-
function registerNeedlePixelImpostorLoader(loader) {
|
|
143
|
-
loader.register((parser) => new NeedlePixelImpostorLoaderPlugin(parser));
|
|
1096
|
+
function registerNeedlePixelImpostorLoader(loader, options = {}) {
|
|
1097
|
+
loader.register((parser) => new NeedlePixelImpostorLoaderPlugin(parser, options));
|
|
144
1098
|
return loader;
|
|
145
1099
|
}
|
|
146
1100
|
export {
|