three-vat 4.1.0 → 4.2.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/dist/index.js CHANGED
@@ -1,984 +1,158 @@
1
- import { LoopMode, MAX_TEXTURE_SIZE, vertexLayoutFor, makeVATNormalTexture, makeVATTexture, RIG_TEXELS_PER_SLOT, LIBRARY_PLAYBACK_DEFAULTS, FORWARD_ONLY_REASON, INFINITE_REPETITIONS, HALF_FLOAT_MAX, RIG_TEXELS } from './chunk-OEKKEHRQ.js';
2
- export { EndMode, INFINITE_REPETITIONS, LoopMode, MAX_TEXTURE_SIZE, createVATPlaybackTexture, endsAt, makeVATNormalTexture, makeVATTexture, resolveVATFrame, setVATInstance } from './chunk-OEKKEHRQ.js';
3
- import { LoopRepeat, LoopOnce, LoopPingPong, DataUtils, Quaternion, Matrix4, Box3, Vector4, Vector3, Sphere, HalfFloatType, BufferGeometry, BufferAttribute, AdditiveAnimationBlendMode, AnimationMixer, PropertyBinding, FloatType, Material, InterleavedBuffer, SkinnedMesh, Mesh, Bone, Object3D, Skeleton, AnimationClip, Color, InterleavedBufferAttribute, VectorKeyframeTrack, StringKeyframeTrack, QuaternionKeyframeTrack, NumberKeyframeTrack, ColorKeyframeTrack, BooleanKeyframeTrack, Float16BufferAttribute, Interpolant } from 'three';
1
+ import { BAKED_FILE_EXTENSION, BAKED_FILE_VERSION, BAKED_LAYER_FORMATS, positionDigest, bakeVATWith, flatFacts, mergedFlatMaterial, keepRestSlots, restSlotsOf } from './chunk-P6AFXEBT.js';
2
+ export { bakeVAT, decodeOctahedral, encodeOctahedral } from './chunk-P6AFXEBT.js';
3
+ import { makeVATTexture, makeVATNormalTexture } from './chunk-4IKOXUSX.js';
4
+ export { EndMode, INFINITE_REPETITIONS, LoopMode, MAX_TEXTURE_SIZE, createVATPlaybackTexture, endsAt, makeVATNormalTexture, makeVATTexture, resolveVATFrame, setVATInstance, turnVATInstance } from './chunk-4IKOXUSX.js';
5
+ import { Quaternion, Box3, Vector3, Sphere, BufferAttribute, BufferGeometry, FloatType, HalfFloatType, Material, InterleavedBuffer, SkinnedMesh, Mesh, Bone, Object3D, Skeleton, Matrix4, AnimationClip, AnimationMixer, VectorKeyframeTrack, StringKeyframeTrack, QuaternionKeyframeTrack, NumberKeyframeTrack, ColorKeyframeTrack, BooleanKeyframeTrack, InterleavedBufferAttribute, Float16BufferAttribute, PropertyBinding, Interpolant } from 'three';
6
+ import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
4
7
 
5
- var IGNORED = ["uuid", "name", "color", "userData", "metadata"];
6
- function flatFacts(material) {
7
- const m = material;
8
- if (!m.color?.isColor || m.vertexColors || m.isShadowMaterial) return null;
9
- const own = (key) => Object.prototype.hasOwnProperty.call(m, key);
10
- if (own("onBeforeCompile") || own("customProgramCacheKey")) return null;
11
- for (const value of Object.values(m)) {
12
- const v = value;
13
- if (v?.isTexture || v?.isNode) return null;
8
+ async function loadVAT(url, { loader = new GLTFLoader(), materials } = {}) {
9
+ if (!withPlugin.has(loader)) {
10
+ loader.register((parser) => new VATPlugin(parser));
11
+ withPlugin.add(loader);
14
12
  }
15
- const json = m.toJSON();
16
- for (const key of IGNORED) delete json[key];
17
- return { key: JSON.stringify(json), color: [m.color.r, m.color.g, m.color.b] };
18
- }
19
- function mergedFlatMaterial(members) {
20
- const merged = members[0].clone();
21
- merged.color.setRGB(1, 1, 1);
22
- merged.vertexColors = true;
23
- merged.name = members.map((m) => m.name).filter(Boolean).join(" + ");
24
- return merged;
25
- }
26
- var FLAT_MERGE = { facts: flatFacts, merge: mergedFlatMaterial };
27
- function planFlatMerge(materials, hooks) {
28
- const facts = /* @__PURE__ */ new Map();
29
- const groups = /* @__PURE__ */ new Map();
30
- for (const material of materials) {
31
- if (facts.has(material)) continue;
32
- const f = hooks.facts(material);
33
- if (!f) continue;
34
- facts.set(material, f);
35
- groups.set(f.key, [...groups.get(f.key) ?? [], material]);
36
- }
37
- const targets = /* @__PURE__ */ new Map();
38
- for (const members of groups.values()) {
39
- if (members.length < 2) continue;
40
- const merged = hooks.merge(members);
41
- for (const m of members) targets.set(m, { material: merged, tint: new Color().fromArray(facts.get(m).color) });
42
- }
43
- return { targetOf: (material) => targets.get(material) };
44
- }
45
-
46
- // src/octahedral.ts
47
- var signNotZero = (v) => v >= 0 ? 1 : -1;
48
- var toByte = (v) => Math.max(0, Math.min(255, Math.round((v * 0.5 + 0.5) * 255)));
49
- function encodeOctahedral(x, y, z, out, offset) {
50
- const l1 = Math.abs(x) + Math.abs(y) + Math.abs(z);
51
- if (l1 === 0) {
52
- out[offset] = toByte(0);
53
- out[offset + 1] = toByte(0);
54
- return;
55
- }
56
- const px = x / l1;
57
- const py = y / l1;
58
- const fold = z <= 0;
59
- out[offset] = toByte(fold ? (1 - Math.abs(py)) * signNotZero(px) : px);
60
- out[offset + 1] = toByte(fold ? (1 - Math.abs(px)) * signNotZero(py) : py);
61
- }
62
- function decodeOctahedral(u, v, out = { x: 0, y: 0, z: 0 }) {
63
- const ex = u / 255 * 2 - 1;
64
- const ey = v / 255 * 2 - 1;
65
- const z = 1 - Math.abs(ex) - Math.abs(ey);
66
- const t = Math.max(-z, 0);
67
- const x = ex - signNotZero(ex) * t;
68
- const y = ey - signNotZero(ey) * t;
69
- const length = Math.hypot(x, y, z) || 1;
70
- out.x = x / length;
71
- out.y = y / length;
72
- out.z = z / length;
73
- return out;
74
- }
75
-
76
- // src/bake.ts
77
- var LOOP_MODES = /* @__PURE__ */ new Map([
78
- [LoopRepeat, LoopMode.Repeat],
79
- [LoopOnce, LoopMode.Once],
80
- [LoopPingPong, LoopMode.PingPong]
81
- ]);
82
- function isAction(input) {
83
- return typeof input.getClip === "function";
84
- }
85
- function resolveAnimation(input) {
86
- if (!isAction(input)) return { clip: input, defaults: { ...LIBRARY_PLAYBACK_DEFAULTS } };
87
- const clip = input.getClip();
88
- const name = clip.name || "(unnamed)";
89
- const cannotBlend = (field, value) => new Error(
90
- `three-vat: action for clip "${name}" has ${field} ${value}; that blends several actions at once, which a single baked band cannot represent \u2014 bake the clips separately and crossfade between them (three-vat#30), or reset the action before baking`
91
- );
92
- if (input.weight !== 1) throw cannotBlend("weight", String(input.weight));
93
- if (input.blendMode === AdditiveAnimationBlendMode) throw cannotBlend("blendMode", "additive");
94
- if (input.timeScale < 0) {
95
- throw new Error(
96
- `three-vat: action for clip "${name}" has timeScale ${input.timeScale}; ${FORWARD_ONLY_REASON}.`
97
- );
98
- }
99
- const loopMode = LOOP_MODES.get(input.loop);
100
- if (loopMode === void 0) {
101
- throw new Error(
102
- `three-vat: action for clip "${name}" has an unrecognised loop mode ${input.loop}; expected THREE.LoopRepeat, LoopOnce or LoopPingPong`
103
- );
104
- }
105
- return {
106
- clip,
107
- defaults: {
108
- loopMode,
109
- // three's `repetitions` defaults to Infinity and `LoopOnce` ignores it
110
- // outright — so a one-shot is one play whatever the field says, and an
111
- // endless count becomes the sentinel a Float32Array can carry.
112
- repetitions: loopMode === LoopMode.Once ? 1 : Number.isFinite(input.repetitions) ? input.repetitions : INFINITE_REPETITIONS,
113
- // Not read off the action (see the rule above), so a bake clamps whichever
114
- // input it was handed. Uniform across loop modes on purpose: an instance
115
- // may override a repeating clip's `loopMode` to `Once` and inherit this
116
- // field, so there is no mode whose end mode is safely unreachable and
117
- // could hold a different answer. Rewind is per instance:
118
- // `{ ..., endMode: EndMode.Rewind }` (#43, ADR-0017).
119
- endMode: LIBRARY_PLAYBACK_DEFAULTS.endMode,
120
- speed: input.timeScale
121
- }
122
- };
123
- }
124
- function morphCountOf({ mesh, morphPos, morphNrm }) {
125
- const influences = mesh.morphTargetInfluences;
126
- return influences ? Math.min(influences.length, Math.max(morphPos?.length ?? 0, morphNrm?.length ?? 0)) : 0;
127
- }
128
- var _mt = /* @__PURE__ */ new Vector3();
129
- var _mb = /* @__PURE__ */ new Vector3();
130
- var _mbn = /* @__PURE__ */ new Vector3();
131
- function morphVertex(part, v, weights, count, p, n) {
132
- const { basePos, baseNrm, morphPos, morphNrm, morphRelative } = part;
133
- if (!morphRelative) {
134
- _mb.fromBufferAttribute(basePos, v);
135
- if (n) _mbn.fromBufferAttribute(baseNrm, v);
136
- }
137
- for (let t = 0; t < count; t++) {
138
- const w = weights[t];
139
- if (w === 0) continue;
140
- const targetPos = morphPos?.[t];
141
- if (targetPos) {
142
- _mt.fromBufferAttribute(targetPos, v);
143
- if (!morphRelative) _mt.sub(_mb);
144
- p.addScaledVector(_mt, w);
145
- }
146
- const targetNrm = n ? morphNrm?.[t] : void 0;
147
- if (n && targetNrm) {
148
- _mt.fromBufferAttribute(targetNrm, v);
149
- if (!morphRelative) _mt.sub(_mbn);
150
- n.addScaledVector(_mt, w);
151
- }
152
- }
153
- }
154
- function asAttribute(value, mesh, name) {
155
- if (!(value instanceof BufferAttribute)) {
156
- throw new Error(
157
- `three-vat: mesh "${mesh.name || "(unnamed)"}" has an interleaved or unsupported "${name}" attribute; VAT bakes plain BufferAttributes`
158
- );
159
- }
160
- return value;
161
- }
162
- function deriveNormals(position, index) {
163
- const scratch = new BufferGeometry();
164
- scratch.setAttribute("position", position);
165
- scratch.setIndex(index);
166
- scratch.computeVertexNormals();
167
- return scratch.attributes.normal;
168
- }
169
- function collectParts(root, hooks) {
170
- const found = [];
171
- root.traverse((o) => {
172
- const mesh = o;
173
- if (mesh.isMesh && mesh.geometry) found.push(mesh);
174
- });
175
- if (found.length === 0) {
176
- throw new Error("three-vat: no Mesh found under root; nothing to bake");
177
- }
178
- const flat = hooks ? planFlatMerge(
179
- found.flatMap((mesh) => Array.isArray(mesh.material) ? [] : [mesh.material]),
180
- hooks
181
- ) : null;
182
- const materials = [];
183
- const parts = [];
184
- for (const mesh of found) {
185
- if (Array.isArray(mesh.material)) {
186
- throw new Error(
187
- `three-vat: mesh "${mesh.name || "(unnamed)"}" uses a material array; split it into one mesh per material before baking`
188
- );
189
- }
190
- const geometry = mesh.geometry;
191
- const source = mesh.material;
192
- const merged = flat?.targetOf(source);
193
- const material = merged?.material ?? source;
194
- let materialIndex = materials.indexOf(material);
195
- if (materialIndex === -1) materialIndex = materials.push(material) - 1;
196
- const skinned = mesh;
197
- const basePos = asAttribute(geometry.attributes.position, mesh, "position");
198
- parts.push({
199
- mesh,
200
- material,
201
- materialIndex,
202
- vertexStart: 0,
203
- // assigned below, after material sorting
204
- vertexCount: geometry.attributes.position.count,
205
- basePos,
206
- baseNrm: geometry.attributes.normal ? asAttribute(geometry.attributes.normal, mesh, "normal") : deriveNormals(basePos, geometry.index),
207
- isSkinned: !!geometry.attributes.skinWeight && !!skinned.skeleton,
208
- skeleton: skinned.skeleton,
209
- pose: void 0,
210
- // assigned below, once the distinct rigs are known
211
- skinIndex: geometry.attributes.skinIndex,
212
- skinWeight: geometry.attributes.skinWeight,
213
- morphPos: geometry.morphAttributes.position,
214
- morphNrm: geometry.morphAttributes.normal,
215
- morphRelative: geometry.morphTargetsRelative,
216
- tint: merged?.tint ?? null
217
- });
218
- }
219
- parts.sort((a, b) => a.materialIndex - b.materialIndex);
220
- let offset = 0;
221
- for (const part of parts) {
222
- part.vertexStart = offset;
223
- offset += part.vertexCount;
224
- }
225
- return parts;
226
- }
227
- function mergeGeometry(parts, restMatrices, total) {
228
- const position = new Float32Array(total * 3);
229
- const normal = new Float32Array(total * 3);
230
- const _v = new Vector3();
231
- const _n = new Vector3();
232
- parts.forEach((part, pi) => {
233
- const m = restMatrices[pi];
234
- for (let v = 0; v < part.vertexCount; v++) {
235
- _v.fromBufferAttribute(part.basePos, v).applyMatrix4(m);
236
- _n.fromBufferAttribute(part.baseNrm, v).transformDirection(m);
237
- _v.toArray(position, (part.vertexStart + v) * 3);
238
- _n.toArray(normal, (part.vertexStart + v) * 3);
239
- }
240
- });
241
- const merged = new BufferGeometry();
242
- merged.setAttribute("position", new BufferAttribute(position, 3));
243
- merged.setAttribute("normal", new BufferAttribute(normal, 3));
244
- mergeSurface(merged, parts, total, restMatrices);
245
- return merged;
246
- }
247
- function mergeSurface(merged, parts, total, restMatrices) {
248
- const merging = parts.some((p) => p.tint);
249
- const want = optionalAttributes(parts, merging);
250
- const uv = want.uv ? new Float32Array(total * 2) : null;
251
- const color = want.color ? new Float32Array(total * 3) : null;
252
- const tangent = want.tangent ? new Float32Array(total * 4) : null;
253
- const _t = new Vector3();
254
- parts.forEach((part, pi) => {
255
- const geometry = part.mesh.geometry;
256
- const start = part.vertexStart;
257
- const srcUV = uv ? asAttribute(geometry.attributes.uv, part.mesh, "uv") : null;
258
- const srcColor = color ? colorSource(part, merging) : null;
259
- const srcTangent = tangent ? geometry.attributes.tangent : null;
260
- const m = restMatrices?.[pi];
261
- for (let v = 0; v < part.vertexCount; v++) {
262
- const vi = start + v;
263
- if (uv && srcUV) {
264
- uv[vi * 2] = srcUV.getX(v);
265
- uv[vi * 2 + 1] = srcUV.getY(v);
266
- }
267
- if (color) writeColor(color, vi * 3, part, srcColor, v);
268
- if (tangent && srcTangent) {
269
- _t.fromBufferAttribute(srcTangent, v);
270
- if (m) _t.transformDirection(m);
271
- const o4 = vi * 4;
272
- tangent[o4] = _t.x;
273
- tangent[o4 + 1] = _t.y;
274
- tangent[o4 + 2] = _t.z;
275
- tangent[o4 + 3] = srcTangent.getW(v);
276
- }
277
- }
278
- });
279
- if (uv) merged.setAttribute("uv", new BufferAttribute(uv, 2));
280
- if (color) merged.setAttribute("color", new BufferAttribute(color, 3));
281
- if (tangent) merged.setAttribute("tangent", new BufferAttribute(tangent, 4));
282
- indexParts(merged, parts);
283
- }
284
- function colorSource(part, merging) {
285
- const source = part.mesh.geometry.attributes.color;
286
- if (part.tint || !source) return null;
287
- if (merging && source instanceof InterleavedBufferAttribute) return source;
288
- return asAttribute(source, part.mesh, "color");
289
- }
290
- function writeColor(out, o3, part, source, v) {
291
- if (part.tint) {
292
- out[o3] = part.tint.r;
293
- out[o3 + 1] = part.tint.g;
294
- out[o3 + 2] = part.tint.b;
295
- } else if (source) {
296
- out[o3] = source.getX(v);
297
- out[o3 + 1] = source.getY(v);
298
- out[o3 + 2] = source.getZ(v);
299
- } else {
300
- out[o3] = out[o3 + 1] = out[o3 + 2] = 1;
301
- }
302
- }
303
- function optionalAttributes(parts, merging) {
304
- return {
305
- uv: parts.every((p) => !!p.mesh.geometry.attributes.uv),
306
- // A merge writes a colour for every part it touched, so the attribute is
307
- // there whenever one happened; a part it did not touch keeps its own, or
308
- // white, which leaves an untinted material's shading as it was.
309
- color: merging || parts.every((p) => !!p.mesh.geometry.attributes.color),
310
- tangent: parts.every((p) => {
311
- const t = p.mesh.geometry.attributes.tangent;
312
- return t instanceof BufferAttribute && t.itemSize === 4;
313
- })
314
- };
315
- }
316
- function indexParts(merged, parts) {
317
- const indices = [];
318
- const groups = [];
319
- for (const part of parts) {
320
- const start = part.vertexStart;
321
- const groupStart = indices.length;
322
- const index = part.mesh.geometry.index;
323
- if (index) {
324
- for (let i = 0; i < index.count; i++) indices.push(start + index.getX(i));
325
- } else {
326
- for (let v = 0; v < part.vertexCount; v++) indices.push(start + v);
327
- }
328
- const last = groups[groups.length - 1];
329
- if (last && last.materialIndex === part.materialIndex) {
330
- last.count += indices.length - groupStart;
331
- } else {
332
- groups.push({
333
- start: groupStart,
334
- count: indices.length - groupStart,
335
- materialIndex: part.materialIndex
336
- });
337
- }
338
- }
339
- merged.setIndex(indices);
340
- for (const g of groups) merged.addGroup(g.start, g.count, g.materialIndex);
341
- }
342
- function frameCountsFor(clips, fps, maxTextureSize) {
343
- const frameCounts = clips.map((c) => Math.max(2, Math.round(c.duration * fps)));
344
- const totalFrames = frameCounts.reduce((a, b) => a + b, 0);
345
- if (totalFrames > maxTextureSize) {
346
- throw new Error(
347
- `three-vat: totalFrames ${totalFrames} exceeds maxTextureSize ${maxTextureSize}; lower fps or bake fewer clips`
348
- );
349
- }
350
- return { frameCounts, totalFrames };
351
- }
352
- function bakeVAT(root, animations, options = {}) {
353
- return bakeVATWith(root, animations, options, FLAT_MERGE);
354
- }
355
- function bakeVATWith(root, animations, options, hooks) {
356
- const {
357
- fps = 30,
358
- maxTextureSize = MAX_TEXTURE_SIZE,
359
- bakeNormals = true,
360
- encoding = "auto",
361
- mergeFlatMaterials = false
362
- } = options;
363
- const resolved = animations.map(resolveAnimation);
364
- root.updateMatrixWorld(true);
365
- const parts = collectParts(root, mergeFlatMaterials ? hooks : null);
366
- if (encoding === "rig") return bakeRig(root, parts, resolved, { fps, maxTextureSize });
367
- if (encoding === "delta") {
368
- return { ...bakeVertices(root, parts, resolved, { fps, maxTextureSize, bakeNormals }), fallback: null };
369
- }
370
- let refusal;
13
+ let gltf;
371
14
  try {
372
- return bakeRig(root, parts, resolved, { fps, maxTextureSize });
15
+ gltf = await loader.loadAsync(url);
373
16
  } catch (error) {
374
- if (!(error instanceof RigRefusal)) throw error;
375
- refusal = error;
17
+ if (error instanceof Refusal) throw new Error(`three-vat: ${url} ${error.message}`);
18
+ throw error;
376
19
  }
377
- try {
378
- return { ...bakeVertices(root, parts, resolved, { fps, maxTextureSize, bakeNormals }), fallback: refusal.message };
379
- } catch (error) {
380
- if (!(error instanceof Error)) throw error;
20
+ const vat = loaded.get(gltf);
21
+ if (vat === void 0) {
381
22
  throw new Error(
382
- `three-vat: neither encoding can bake this subtree. The vertex encoding: ${unprefixed(error)}. The rig encoding, tried first: ${unprefixed(refusal)}`,
383
- { cause: refusal }
23
+ `three-vat: ${url} is not a baked file: it carries no ${BAKED_FILE_EXTENSION} extension. Write one with \`npx three-vat bake <input> --out <file>\``
384
24
  );
385
25
  }
386
- }
387
- function unprefixed(error) {
388
- return error.message.replace(/^three-vat: /, "");
389
- }
390
- function sampleClips(root, resolved, frameCounts, poses, writeFrame) {
391
- const mixer = new AnimationMixer(root);
392
- const clipTable = [];
393
- let rowOffset = 0;
394
- try {
395
- for (let ci = 0; ci < resolved.length; ci++) {
396
- const { clip, defaults } = resolved[ci];
397
- const frames = frameCounts[ci];
398
- const action = mixer.clipAction(clip);
399
- action.play();
400
- let maxDeltaSq = 0;
401
- for (let f = 0; f < frames; f++) {
402
- mixer.setTime(f / frames * clip.duration);
403
- root.updateMatrixWorld(true);
404
- poseSkeletons(poses);
405
- maxDeltaSq = Math.max(maxDeltaSq, writeFrame(clip, f, rowOffset + f));
406
- }
407
- action.stop();
408
- clipTable.push({
409
- name: clip.name,
410
- startFrame: rowOffset,
411
- frames,
412
- fps: frames / clip.duration,
413
- duration: clip.duration,
414
- maxDelta: Math.sqrt(maxDeltaSq),
415
- // Declared once, here, rather than repeated at every instance that plays
416
- // this band. An instance overrides any of them, field by field.
417
- ...defaults
418
- });
419
- rowOffset += frames;
420
- }
421
- } finally {
422
- mixer.stopAllAction();
423
- mixer.setTime(0);
424
- root.updateMatrixWorld(true);
425
- }
426
- return clipTable;
427
- }
428
- function bakeVertices(root, parts, resolved, { fps, maxTextureSize, bakeNormals }) {
429
- const clips = resolved.map((a) => a.clip);
430
- const vertexCount = parts.reduce((n, p) => n + p.vertexCount, 0);
431
- const { frameCounts, totalFrames } = frameCountsFor(clips, fps, maxTextureSize);
432
- const { rowsPerFrame, width, height, frameStride } = vertexLayoutFor(vertexCount, totalFrames, maxTextureSize);
433
- const rootInverse = root.matrixWorld.clone().invert();
434
- const restMatrices = parts.map(
435
- (p) => new Matrix4().multiplyMatrices(rootInverse, p.mesh.matrixWorld)
436
- );
437
- const geometry = mergeGeometry(parts, restMatrices, vertexCount);
438
- const mergedBase = geometry.attributes.position;
439
- const posData = new Uint16Array(frameStride * totalFrames * 4);
440
- const nrmData = bakeNormals ? new Uint8Array(frameStride * totalFrames * 2) : null;
441
- const bakeNormal = nrmData !== null;
442
- const bounds = new Box3();
443
- const _si = new Vector4();
444
- const _sw = new Vector4();
445
- const _acc = new Matrix4();
446
- const _skin = new Matrix4();
447
- const _partMatrix = new Matrix4();
448
- const _p = new Vector3();
449
- const _bp = new Vector3();
450
- const _n = new Vector3();
451
- const poses = attachPoseBuffers(parts);
452
- const influencers = bakeNormals ? parts.filter((p) => p.pose).map(influencedBones) : [];
453
- let warnedNonUniformScale = false;
454
- const writeFrame = (clip, f, row) => {
455
- let maxDeltaSq = 0;
456
- if (!warnedNonUniformScale) {
457
- warnedNonUniformScale = warnOnNonUniformBoneScale(influencers);
458
- }
459
- for (const part of parts) {
460
- _partMatrix.multiplyMatrices(rootInverse, part.mesh.matrixWorld);
461
- const influences = part.mesh.morphTargetInfluences;
462
- const { isSkinned, skinIndex, skinWeight } = part;
463
- const boneMatrices = part.pose?.matrices;
464
- const morphCount = morphCountOf(part);
465
- for (let v = 0; v < part.vertexCount; v++) {
466
- const vi = part.vertexStart + v;
467
- _p.fromBufferAttribute(part.basePos, v);
468
- if (bakeNormal) _n.fromBufferAttribute(part.baseNrm, v);
469
- if (influences && morphCount > 0) morphVertex(part, v, influences, morphCount, _p, bakeNormal ? _n : null);
470
- if (isSkinned && boneMatrices) {
471
- const skinned = part.mesh;
472
- _si.fromBufferAttribute(skinIndex, v);
473
- _sw.fromBufferAttribute(skinWeight, v);
474
- const ae = _acc.elements;
475
- for (let e = 0; e < 16; e++) ae[e] = 0;
476
- for (let i = 0; i < 4; i++) {
477
- const w = _sw.getComponent(i);
478
- if (w === 0) continue;
479
- const b = _si.getComponent(i) * BONE_STRIDE;
480
- for (let e = 0; e < 16; e++) ae[e] += boneMatrices[b + e] * w;
481
- }
482
- _skin.multiplyMatrices(_acc, skinned.bindMatrix).premultiply(skinned.bindMatrixInverse);
483
- _p.applyMatrix4(_skin);
484
- if (bakeNormal) _n.transformDirection(_skin);
485
- }
486
- _p.applyMatrix4(_partMatrix);
487
- if (bakeNormal) _n.transformDirection(_partMatrix);
488
- bounds.expandByPoint(_p);
489
- _bp.fromBufferAttribute(mergedBase, vi);
490
- const texel = row * frameStride + vi;
491
- const o = texel * 4;
492
- const dx = _p.x - _bp.x;
493
- const dy = _p.y - _bp.y;
494
- const dz = _p.z - _bp.z;
495
- maxDeltaSq = Math.max(maxDeltaSq, dx * dx + dy * dy + dz * dz);
496
- const largest = Math.max(Math.abs(dx), Math.abs(dy), Math.abs(dz));
497
- if (largest > HALF_FLOAT_MAX) {
498
- throw new Error(
499
- `three-vat: position delta component ${largest} (clip "${clip.name}", frame ${f}, vertex ${vi}) exceeds the half-float limit of ${HALF_FLOAT_MAX} the position texture stores; a unit smaller than the metre is the usual cause`
500
- );
501
- }
502
- posData[o] = toHalfFloat(dx);
503
- posData[o + 1] = toHalfFloat(dy);
504
- posData[o + 2] = toHalfFloat(dz);
505
- posData[o + 3] = HALF_ONE;
506
- if (bakeNormal) encodeOctahedral(_n.x, _n.y, _n.z, nrmData, texel * 2);
507
- }
508
- }
509
- return maxDeltaSq;
510
- };
511
- const clipTable = sampleClips(root, resolved, frameCounts, poses, writeFrame);
512
- geometry.boundingBox = bounds.clone();
513
- geometry.boundingSphere = bounds.getBoundingSphere(new Sphere());
514
- const materials = [];
515
- for (const part of parts) materials[part.materialIndex] = part.material;
516
- return {
517
- positionTexture: makeVATTexture(posData, width, height, HalfFloatType),
518
- normalTexture: nrmData ? makeVATNormalTexture(nrmData, width, height) : null,
519
- clips: clipTable,
520
- bounds,
521
- vertexCount,
522
- totalFrames,
523
- rowsPerFrame,
524
- encoding: "delta",
525
- geometry,
526
- materials
527
- };
528
- }
529
- var toHalfFloat = DataUtils.toHalfFloat;
530
- var HALF_ONE = /* @__PURE__ */ toHalfFloat(1);
531
- var BONE_STRIDE = 16;
532
- var IDENTITY = /* @__PURE__ */ new Matrix4();
533
- function attachPoseBuffers(parts) {
534
- const byRig = /* @__PURE__ */ new Map();
535
- for (const part of parts) {
536
- if (!part.isSkinned || !part.skeleton) continue;
537
- let pose = byRig.get(part.skeleton);
538
- if (!pose) {
539
- const matrices = new Float64Array(part.skeleton.bones.length * BONE_STRIDE);
540
- pose = { skeleton: part.skeleton, matrices };
541
- byRig.set(part.skeleton, pose);
542
- }
543
- part.pose = pose;
544
- }
545
- return [...byRig.values()];
546
- }
547
- function poseSkeletons(poses) {
548
- const scratch = new Matrix4();
549
- for (const { skeleton, matrices } of poses) {
550
- const { bones, boneInverses } = skeleton;
551
- for (let b = 0; b < bones.length; b++) {
552
- scratch.multiplyMatrices(bones[b]?.matrixWorld ?? IDENTITY, boneInverses[b]);
553
- matrices.set(scratch.elements, b * BONE_STRIDE);
554
- }
555
- }
556
- }
557
- function influencedBones(part) {
558
- const used = /* @__PURE__ */ new Set();
559
- const index = part.skinIndex;
560
- const weight = part.skinWeight;
561
- for (let v = 0; v < part.vertexCount; v++) {
562
- for (let i = 0; i < 4; i++) {
563
- if (weight.getComponent(v, i) !== 0) used.add(index.getComponent(v, i));
564
- }
565
- }
566
- return { pose: part.pose, bones: [...used] };
567
- }
568
- var SCALE_UNIFORMITY_EPSILON = 1e-4;
569
- var MATRIX_BASIS = [0, 1, 2, 4, 5, 6, 8, 9, 10];
570
- function hasNonUniformScale(matrices, b) {
571
- const o = b * BONE_STRIDE;
572
- return unevenSquares(
573
- matrices[o] ** 2 + matrices[o + 1] ** 2 + matrices[o + 2] ** 2,
574
- matrices[o + 4] ** 2 + matrices[o + 5] ** 2 + matrices[o + 6] ** 2,
575
- matrices[o + 8] ** 2 + matrices[o + 9] ** 2 + matrices[o + 10] ** 2
576
- );
577
- }
578
- function hasShear(matrices, b) {
579
- const m = (i) => matrices[b * BONE_STRIDE + i];
580
- const lengthSq = (a) => m(a) ** 2 + m(a + 1) ** 2 + m(a + 2) ** 2;
581
- const dot = (a, c) => m(a) * m(c) + m(a + 1) * m(c + 1) + m(a + 2) * m(c + 2);
582
- const square = (a, c) => dot(a, c) ** 2 <= SCALE_UNIFORMITY_EPSILON ** 2 * lengthSq(a) * lengthSq(c);
583
- return !(square(0, 4) && square(0, 8) && square(4, 8));
584
- }
585
- function unevenSquares(x, y, z) {
586
- const max = Math.max(x, y, z);
587
- return max - Math.min(x, y, z) > SCALE_UNIFORMITY_EPSILON * max;
588
- }
589
- function warnOnNonUniformBoneScale(influencers) {
590
- for (const { pose, bones } of influencers) {
591
- for (const b of bones) {
592
- if (!hasNonUniformScale(pose.matrices, b)) continue;
593
- console.warn(
594
- `three-vat: bone "${pose.skeleton.bones[b].name || "(unnamed)"}" animates with non-uniform scale; baked normals under it are approximate, because linear-blend skinning transforms a normal by the skin matrix rather than its inverse-transpose \u2014 the same shortcut three's own skinning shader takes. Positions are exact.`
26
+ if (materials !== void 0) {
27
+ const plural = (n) => `${n} material${n === 1 ? "" : "s"}`;
28
+ if (materials.length !== vat.materials.length) {
29
+ throw new Error(
30
+ `three-vat: loadVAT's \`materials\` holds ${plural(materials.length)}, and ${url} has ${plural(vat.materials.length)}, one for each materialIndex; pass one for each, in that order`
595
31
  );
596
- return true;
597
32
  }
33
+ vat.materials = [...materials];
598
34
  }
599
- return false;
35
+ return vat;
600
36
  }
601
- var VERTEX_ENCODING_STORES_IT = "the vertex encoding (`encoding: 'delta'`) stores what a rig cannot";
602
- var RigRefusal = class extends Error {
37
+ var withPlugin = /* @__PURE__ */ new WeakSet();
38
+ var loaded = /* @__PURE__ */ new WeakMap();
39
+ var Refusal = class extends Error {
603
40
  };
604
- function placementOf(part, rootInverse, out) {
605
- out.multiplyMatrices(rootInverse, part.mesh.matrixWorld);
606
- if (part.pose) out.multiply(part.mesh.bindMatrixInverse);
607
- return out;
608
- }
609
- var MATRIX_EPSILON = 1e-6;
610
- function matricesClose(a, b) {
611
- const ae = a.elements;
612
- const be = b.elements;
613
- for (let e = 0; e < 16; e++) if (Math.abs(ae[e] - be[e]) > MATRIX_EPSILON) return false;
614
- return true;
615
- }
616
- function slotLabel(slot) {
617
- const parts = slot.parts.map(partName).join(", ");
618
- if (!slot.rig) return `rigid part ${parts}`;
619
- const { pose, bone } = slot.rig;
620
- return `bone "${pose.skeleton.bones[bone]?.name || `bone ${bone}`}" of ${parts}`;
621
- }
622
- function partName(part) {
623
- return `"${part.mesh.name || "(unnamed)"}"`;
624
- }
625
- function slotReads(slot, bone, boneInverse, bindMatrix, placement) {
626
- const { rig } = slot;
627
- return rig !== void 0 && rig.pose.skeleton.bones[rig.bone] === bone && matricesClose(rig.pose.skeleton.boneInverses[rig.bone], boneInverse) && matricesClose(rig.bindMatrix, bindMatrix) && matricesClose(slot.restPlacement, placement);
628
- }
629
- function layoutSlots(parts, rootInverse) {
630
- const slots = [];
631
- const slotMaps = /* @__PURE__ */ new Map();
632
- for (const part of parts) {
633
- const restPlacement = placementOf(part, rootInverse, new Matrix4());
634
- if (part.pose) {
635
- const { pose } = part;
636
- const { bones, boneInverses } = pose.skeleton;
637
- const bindMatrix = part.mesh.bindMatrix.clone();
638
- const map = [];
639
- for (let b = 0; b < bones.length; b++) {
640
- const bone = bones[b];
641
- const shared = bone ? slots.findIndex((s) => slotReads(s, bone, boneInverses[b], bindMatrix, restPlacement)) : -1;
642
- if (shared >= 0) {
643
- const slot = slots[shared];
644
- if (!slot.parts.includes(part)) slot.parts.push(part);
645
- map.push(shared);
646
- } else {
647
- map.push(slots.length);
648
- slots.push({ rig: { pose, bone: b, bindMatrix }, parts: [part], restPlacement });
649
- }
650
- }
651
- slotMaps.set(part, map);
652
- } else {
653
- slotMaps.set(part, [slots.length]);
654
- slots.push({ rig: void 0, parts: [part], restPlacement });
41
+ var VATPlugin = class {
42
+ constructor(parser) {
43
+ this.parser = parser;
44
+ this.name = BAKED_FILE_EXTENSION;
45
+ }
46
+ get extension() {
47
+ return this.parser.json.extensions?.[BAKED_FILE_EXTENSION];
48
+ }
49
+ beforeRoot() {
50
+ const extension = this.extension;
51
+ if (extension !== void 0 && extension.version !== BAKED_FILE_VERSION) {
52
+ throw new Refusal(
53
+ `is a baked file of format version ${extension.version}, and this three-vat reads version ${BAKED_FILE_VERSION} only; bake it again with this version of \`three-vat bake\``
54
+ );
655
55
  }
656
- }
657
- return { slots, slotMaps };
658
- }
659
- function morphTracksOn(mesh, clip, root) {
660
- const driven = /* @__PURE__ */ new Map();
661
- for (const track of clip.tracks) {
662
- const parsed = PropertyBinding.parseTrackName(track.name);
663
- if (parsed.propertyName !== "morphTargetInfluences") continue;
664
- if (PropertyBinding.findNode(root, parsed.nodeName) !== mesh) continue;
665
- const size = track.getValueSize();
666
- const keys = track.times.length;
667
- const values = track.values;
668
- const add = (t, read) => {
669
- const list = driven.get(t) ?? [];
670
- for (let k = 0; k < keys; k++) list.push(read(k));
671
- driven.set(t, list);
56
+ return null;
57
+ }
58
+ async afterRoot(result) {
59
+ const extension = this.extension;
60
+ if (extension !== void 0) loaded.set(result, await this.build(extension));
61
+ }
62
+ async build(extension) {
63
+ const node = await this.parser.getDependency("mesh", extension.mesh);
64
+ const primitives = node.isMesh ? [node] : node.children;
65
+ const geometry = mergedGeometry(primitives, extension);
66
+ const materials = [];
67
+ extension.groups.forEach((group, i) => materials[group.materialIndex] = primitives[i].material);
68
+ const bounds = new Box3(new Vector3().fromArray(extension.bounds.min), new Vector3().fromArray(extension.bounds.max));
69
+ geometry.boundingBox = bounds.clone();
70
+ geometry.boundingSphere = bounds.getBoundingSphere(new Sphere());
71
+ const shared = {
72
+ geometry,
73
+ materials,
74
+ clips: extension.clips.map((clip) => ({ ...clip })),
75
+ bounds,
76
+ vertexCount: extension.vertexCount,
77
+ totalFrames: extension.totalFrames
672
78
  };
673
- if (parsed.propertyIndex === void 0) {
674
- for (let t = 0; t < size; t++) add(t, (k) => values[k * size + t]);
675
- } else {
676
- const byIndex = Number(parsed.propertyIndex);
677
- const t = Number.isInteger(byIndex) ? byIndex : mesh.morphTargetDictionary?.[parsed.propertyIndex];
678
- if (t !== void 0) add(t, (k) => values[k]);
679
- }
680
- }
681
- return driven;
682
- }
683
- function morphInfluences(part, clips, root) {
684
- const { mesh } = part;
685
- const influences = mesh.morphTargetInfluences;
686
- const count = morphCountOf(part);
687
- if (!influences || count === 0) return { statics: [], animated: [] };
688
- const driven = clips.map((clip) => morphTracksOn(mesh, clip, root));
689
- const statics = [];
690
- const animated = [];
691
- for (let t = 0; t < count; t++) {
692
- const seen = /* @__PURE__ */ new Set();
693
- const offending = [];
694
- driven.forEach((tracks, ci) => {
695
- const values = tracks.get(t);
696
- if (!values) {
697
- seen.add(influences[t]);
698
- return;
699
- }
700
- offending.push(`"${clips[ci].name}"`);
701
- for (const value of values) seen.add(value);
702
- });
703
- if (seen.size > 1) {
704
- const name = Object.entries(mesh.morphTargetDictionary ?? {}).find(([, i]) => i === t)?.[0];
705
- animated.push({ part, target: name ? `"${name}"` : String(t), clips: offending });
79
+ if (extension.encoding === "rig") {
80
+ geometry.setAttribute("skinWeight", await this.writtenWeights(extension.mesh));
81
+ return {
82
+ encoding: "rig",
83
+ rigTexture: await this.texture(extension.layers.rig),
84
+ slotCount: extension.slotCount,
85
+ ...shared
86
+ };
706
87
  }
707
- statics.push(seen.values().next().value);
88
+ const { position, normal } = extension.layers;
89
+ return {
90
+ encoding: "delta",
91
+ positionTexture: await this.texture(position),
92
+ normalTexture: normal ? await this.texture(normal) : null,
93
+ rowsPerFrame: extension.rowsPerFrame,
94
+ fallback: extension.fallback,
95
+ ...shared
96
+ };
708
97
  }
709
- return { statics, animated };
710
- }
711
- function refuseAnimatedMorphs(animated) {
712
- const byDriver = /* @__PURE__ */ new Map();
713
- for (const { part, target, clips } of animated) {
714
- const key = `${target}
715
- ${clips.join("\n")}`;
716
- const entry = byDriver.get(key) ?? { target, clips, parts: [] };
717
- if (!entry.parts.includes(part)) entry.parts.push(part);
718
- byDriver.set(key, entry);
98
+ /**
99
+ * The skin weights of the mesh's primitives as the file holds them, four
100
+ * floats a vertex, read from the file rather than taken from the geometry:
101
+ * `GLTFLoader` normalizes a skinned primitive's weights in place, and the
102
+ * bake's are the source's, unrounded. That geometry is a view over the loaded buffer view,
103
+ * so the bytes are read from the buffer beneath it, which nothing writes to.
104
+ * The primitives share the attribute, so the first one's is read.
105
+ */
106
+ async writtenWeights(mesh) {
107
+ const json = this.parser.json;
108
+ const accessor = json.accessors[json.meshes[mesh].primitives[0].attributes["WEIGHTS_0"]];
109
+ const view = json.bufferViews[accessor.bufferView];
110
+ if (accessor.componentType !== 5126 || (view.byteStride ?? 16) !== 16) {
111
+ throw rewritten("its skin weights are no longer the floats the bake wrote");
112
+ }
113
+ const buffer = await this.parser.getDependency("buffer", view.buffer);
114
+ const start = (view.byteOffset ?? 0) + (accessor.byteOffset ?? 0);
115
+ return new BufferAttribute(new Float32Array(buffer.slice(start, start + accessor.count * 16)), 4);
116
+ }
117
+ /** A layer's texels, handed to the builder the bake used for that layer. */
118
+ async texture({ bufferView, width, height, format }) {
119
+ if (!Object.prototype.hasOwnProperty.call(BAKED_LAYER_FORMATS, format)) {
120
+ throw new Refusal(`holds a texture layer of unknown format "${format}"`);
121
+ }
122
+ const { bytesPerTexel, build } = BAKED_LAYER_FORMATS[format];
123
+ const buffer = await this.parser.getDependency("bufferView", bufferView);
124
+ return build(buffer.slice(0, width * height * bytesPerTexel), width, height);
719
125
  }
720
- const offences = [...byDriver.values()].map(({ target, clips, parts }) => {
721
- const one = clips.length === 1;
722
- const its = parts.length === 1 ? "its" : "their";
723
- return `clip${one ? "" : "s"} ${clips.join(", ")} animate${one ? "s" : ""} morph target ${target} of part${parts.length === 1 ? "" : "s"} ${parts.map(partName).join(", ")}, ${its} vertices moving where no bone does`;
724
- });
725
- return new RigRefusal(
726
- `three-vat: the rig encoding cannot bake this subtree: ${offences.join("; ")}. A slot stores a rotation, a translation and one scale, not a per-vertex delta, and ${VERTEX_ENCODING_STORES_IT}`
727
- );
728
- }
729
- function foldMorphs(part, statics) {
730
- const { vertexCount, basePos, baseNrm } = part;
731
- const position = new Float32Array(vertexCount * 3);
732
- const normal = new Float32Array(vertexCount * 3);
733
- const active = statics.some((w) => w !== 0);
734
- const _p = new Vector3();
735
- const _n = new Vector3();
736
- for (let v = 0; v < vertexCount; v++) {
737
- _p.fromBufferAttribute(basePos, v);
738
- _n.fromBufferAttribute(baseNrm, v);
739
- if (active) {
740
- morphVertex(part, v, statics, statics.length, _p, _n);
741
- _n.normalize();
742
- }
743
- _p.toArray(position, v * 3);
744
- _n.toArray(normal, v * 3);
745
- }
746
- return { position, normal };
747
- }
748
- function scaleSensitiveNodes(slots, root, influenced) {
749
- const sensitive = /* @__PURE__ */ new Map();
750
- slots.forEach((slot, i) => {
751
- if (!influenced[i]) return;
752
- if (slot.rig) {
753
- const { bones } = slot.rig.pose.skeleton;
754
- for (let node = bones[slot.rig.bone] ?? null; node && bones.includes(node); node = node.parent) {
755
- sensitive.set(node, slot);
756
- }
757
- } else {
758
- for (let node = slot.parts[0].mesh; node && node !== root; node = node.parent) {
759
- sensitive.set(node, slot);
760
- }
761
- }
126
+ };
127
+ var rewritten = (what) => new Refusal(
128
+ `holds a geometry rewritten after the bake: ${what}. Its texels are addressed by the vertex order the bake wrote, so an optimizer that reorders, welds or simplifies vertices (a gltfpack or gltf-transform pass) is the likely cause; bake it again, and keep the baked file out of that step`
129
+ );
130
+ function mergedGeometry(primitives, extension) {
131
+ if (primitives.length !== extension.groups.length) {
132
+ throw rewritten(`${primitives.length} primitives where ${extension.groups.length} were written`);
133
+ }
134
+ const shared = primitives[0].geometry;
135
+ const position = shared.attributes.position;
136
+ if (position.count !== extension.vertexCount) {
137
+ throw rewritten(`${position.count} vertices where ${extension.vertexCount} were written`);
138
+ }
139
+ if (positionDigest(position) !== extension.digest) throw rewritten("its rest positions no longer match");
140
+ const geometry = new BufferGeometry();
141
+ for (const [name, attribute] of Object.entries(shared.attributes)) geometry.setAttribute(name, attribute);
142
+ const runs = primitives.map((mesh, i) => {
143
+ const index = mesh.geometry.index;
144
+ const group = extension.groups[i];
145
+ if (mesh.geometry.attributes.position !== position || index === null || index.count !== group.count) {
146
+ throw rewritten(`primitive ${i} no longer draws the run of vertices it was written with`);
147
+ }
148
+ return index.array;
762
149
  });
763
- return sensitive;
764
- }
765
- function refuseAnimatedNonUniformScale(slots, clips, root, influenced) {
766
- const sensitive = scaleSensitiveNodes(slots, root, influenced);
767
- for (const clip of clips) {
768
- for (const track of clip.tracks) {
769
- const parsed = PropertyBinding.parseTrackName(track.name);
770
- if (parsed.propertyName !== "scale" || track.getValueSize() !== 3) continue;
771
- const node = PropertyBinding.findNode(root, parsed.nodeName);
772
- const reached = node && sensitive.get(node);
773
- if (!reached) continue;
774
- const values = track.values;
775
- for (let k = 0; k < track.times.length; k++) {
776
- const o = k * 3;
777
- if (unevenSquares(values[o] ** 2, values[o + 1] ** 2, values[o + 2] ** 2)) {
778
- throw nonUniformScale(slotLabel(reached), clip);
779
- }
780
- }
781
- }
782
- }
783
- }
784
- function nonUniformScale(label, clip) {
785
- return new RigRefusal(
786
- `three-vat: ${label} animates with non-uniform scale in clip "${clip.name}", which the rig encoding cannot store \u2014 a slot is a rotation, a translation and one scale, and ${VERTEX_ENCODING_STORES_IT}. Authored with a uniform scale, it bakes as a rig`
787
- );
788
- }
789
- function bakeRig(root, parts, resolved, { fps, maxTextureSize }) {
790
- const clips = resolved.map((a) => a.clip);
791
- const rootInverse = root.matrixWorld.clone().invert();
792
- const poses = attachPoseBuffers(parts);
793
- const { slots, slotMaps } = layoutSlots(parts, rootInverse);
794
- const slotCount = slots.length;
795
- const morphs = parts.map((part) => morphInfluences(part, clips, root));
796
- const animated = morphs.flatMap((m) => m.animated);
797
- if (animated.length > 0) throw refuseAnimatedMorphs(animated);
798
- const rigParts = parts.map((part, i) => ({
799
- part,
800
- slotOf: slotMaps.get(part),
801
- ...foldMorphs(part, morphs[i].statics)
802
- }));
803
- const width = slotCount * RIG_TEXELS_PER_SLOT;
804
- if (width > maxTextureSize) {
805
- throw new RigRefusal(
806
- `three-vat: rig texture width ${width} (${slotCount} slots \xD7 ${RIG_TEXELS_PER_SLOT} texels) exceeds maxTextureSize ${maxTextureSize}`
807
- );
808
- }
809
- const { frameCounts, totalFrames } = frameCountsFor(clips, fps, maxTextureSize);
810
- const vertexCount = parts.reduce((n, p) => n + p.vertexCount, 0);
811
- const geometry = mergeRigGeometry(rigParts, vertexCount);
812
- const localPosition = geometry.attributes.position.array;
813
- const skinIndex = geometry.attributes.skinIndex.array;
814
- const skinWeight = geometry.attributes.skinWeight.array;
815
- const influenced = new Uint8Array(slotCount);
816
- for (let i = 0; i < skinWeight.length; i++) {
817
- if (skinWeight[i] !== 0) influenced[skinIndex[i]] = 1;
818
- }
819
- refuseAnimatedNonUniformScale(slots, clips, root, influenced);
820
- const _p = new Vector3();
821
- const _slot = new Matrix4();
822
- const _partMatrix = new Matrix4();
823
- const placements = new Map(parts.map((part) => [part, new Matrix4()]));
824
- const _q2 = new Quaternion();
825
- const _t = new Vector3();
826
- const _s = new Vector3();
827
- const restRoot = new Float64Array(vertexCount * 3);
828
- for (const part of parts) {
829
- _partMatrix.multiplyMatrices(rootInverse, part.mesh.matrixWorld);
830
- for (let v = 0; v < part.vertexCount; v++) {
831
- _p.fromBufferAttribute(part.basePos, v).applyMatrix4(_partMatrix);
832
- _p.toArray(restRoot, (part.vertexStart + v) * 3);
833
- }
834
- }
835
- const data = new Float32Array(width * totalFrames * 4);
836
- const slotMatrices = new Float64Array(slotCount * BONE_STRIDE);
837
- const previous = new Float64Array(slotCount * 4);
838
- const bounds = new Box3();
839
- let minX = Infinity;
840
- let minY = Infinity;
841
- let minZ = Infinity;
842
- let maxX = -Infinity;
843
- let maxY = -Infinity;
844
- let maxZ = -Infinity;
845
- const writeFrame = (clip, _f, row) => {
846
- let maxDeltaSq = 0;
847
- for (const [part, placement] of placements) placementOf(part, rootInverse, placement);
848
- for (let slot = 0; slot < slotCount; slot++) {
849
- const { rig, parts: readers } = slots[slot];
850
- const lead = readers[0];
851
- const placement = placements.get(lead);
852
- for (let pi = 1; pi < readers.length; pi++) {
853
- const other = readers[pi];
854
- if (!matricesClose(placement, placements.get(other))) {
855
- throw new RigRefusal(
856
- `three-vat: parts ${partName(lead)} and ${partName(other)} read the same slots but move apart in clip "${clip.name}"; the rig encoding gives them one set of slots, which cannot place them differently, and ${VERTEX_ENCODING_STORES_IT}`
857
- );
858
- }
859
- }
860
- if (rig) {
861
- _slot.fromArray(rig.pose.matrices, rig.bone * BONE_STRIDE).multiply(rig.bindMatrix).premultiply(placement);
862
- } else {
863
- _slot.copy(placement);
864
- }
865
- slotMatrices.set(_slot.elements, slot * BONE_STRIDE);
866
- if (influenced[slot] && (hasNonUniformScale(slotMatrices, slot) || hasShear(slotMatrices, slot))) {
867
- throw nonUniformScale(slotLabel(slots[slot]), clip);
868
- }
869
- const p4 = slot * 4;
870
- const det = _slot.determinant();
871
- let scale;
872
- if (det === 0) {
873
- _t.setFromMatrixPosition(_slot);
874
- _q2.fromArray(previous, p4);
875
- if (_q2.lengthSq() === 0) _q2.identity();
876
- scale = 0;
877
- } else {
878
- if (det < 0) for (const e of MATRIX_BASIS) _slot.elements[e] = -_slot.elements[e];
879
- _slot.decompose(_t, _q2, _s);
880
- scale = det < 0 ? -_s.x : _s.x;
881
- }
882
- if (previous[p4] * _q2.x + previous[p4 + 1] * _q2.y + previous[p4 + 2] * _q2.z + previous[p4 + 3] * _q2.w < 0) {
883
- _q2.set(-_q2.x, -_q2.y, -_q2.z, -_q2.w);
884
- }
885
- previous[p4] = _q2.x;
886
- previous[p4 + 1] = _q2.y;
887
- previous[p4 + 2] = _q2.z;
888
- previous[p4 + 3] = _q2.w;
889
- const o = (row * width + slot * RIG_TEXELS_PER_SLOT) * 4;
890
- const rotation = o + RIG_TEXELS.rotation * 4;
891
- data[rotation] = _q2.x;
892
- data[rotation + 1] = _q2.y;
893
- data[rotation + 2] = _q2.z;
894
- data[rotation + 3] = _q2.w;
895
- const placementTexel = o + RIG_TEXELS.placement * 4;
896
- data[placementTexel] = _t.x;
897
- data[placementTexel + 1] = _t.y;
898
- data[placementTexel + 2] = _t.z;
899
- data[placementTexel + 3] = scale;
900
- }
901
- for (let v = 0; v < vertexCount; v++) {
902
- const o3 = v * 3;
903
- const o4 = v * 4;
904
- const x = localPosition[o3];
905
- const y = localPosition[o3 + 1];
906
- const z = localPosition[o3 + 2];
907
- let px = 0;
908
- let py = 0;
909
- let pz = 0;
910
- for (let i = 0; i < 4; i++) {
911
- const w = skinWeight[o4 + i];
912
- if (w === 0) continue;
913
- const m = skinIndex[o4 + i] * BONE_STRIDE;
914
- px += w * (slotMatrices[m] * x + slotMatrices[m + 4] * y + slotMatrices[m + 8] * z + slotMatrices[m + 12]);
915
- py += w * (slotMatrices[m + 1] * x + slotMatrices[m + 5] * y + slotMatrices[m + 9] * z + slotMatrices[m + 13]);
916
- pz += w * (slotMatrices[m + 2] * x + slotMatrices[m + 6] * y + slotMatrices[m + 10] * z + slotMatrices[m + 14]);
917
- }
918
- if (px < minX) minX = px;
919
- if (px > maxX) maxX = px;
920
- if (py < minY) minY = py;
921
- if (py > maxY) maxY = py;
922
- if (pz < minZ) minZ = pz;
923
- if (pz > maxZ) maxZ = pz;
924
- const dx = px - restRoot[o3];
925
- const dy = py - restRoot[o3 + 1];
926
- const dz = pz - restRoot[o3 + 2];
927
- const deltaSq = dx * dx + dy * dy + dz * dz;
928
- if (deltaSq > maxDeltaSq) maxDeltaSq = deltaSq;
929
- }
930
- return maxDeltaSq;
931
- };
932
- const clipTable = sampleClips(root, resolved, frameCounts, poses, writeFrame);
933
- bounds.min.set(minX, minY, minZ);
934
- bounds.max.set(maxX, maxY, maxZ);
935
- geometry.boundingBox = bounds.clone();
936
- geometry.boundingSphere = bounds.getBoundingSphere(new Sphere());
937
- const materials = [];
938
- for (const part of parts) materials[part.materialIndex] = part.material;
939
- return {
940
- encoding: "rig",
941
- rigTexture: makeVATTexture(data, width, totalFrames),
942
- slotCount,
943
- clips: clipTable,
944
- bounds,
945
- vertexCount,
946
- totalFrames,
947
- geometry,
948
- materials
949
- };
950
- }
951
- function mergeRigGeometry(rigParts, total) {
952
- const position = new Float32Array(total * 3);
953
- const normal = new Float32Array(total * 3);
954
- const slotIndex = new Uint16Array(total * 4);
955
- const slotWeight = new Float32Array(total * 4);
956
- for (const { part, slotOf, position: restPos, normal: restNrm } of rigParts) {
957
- const start = part.vertexStart;
958
- const srcIndex = part.pose ? part.skinIndex : null;
959
- const srcWeight = part.pose ? part.skinWeight : null;
960
- position.set(restPos, start * 3);
961
- normal.set(restNrm, start * 3);
962
- for (let v = 0; v < part.vertexCount; v++) {
963
- const o4 = (start + v) * 4;
964
- if (srcIndex && srcWeight) {
965
- for (let i = 0; i < 4; i++) {
966
- slotIndex[o4 + i] = slotOf[srcIndex.getComponent(v, i)];
967
- slotWeight[o4 + i] = srcWeight.getComponent(v, i);
968
- }
969
- } else {
970
- slotIndex[o4] = slotOf[0];
971
- slotWeight[o4] = 1;
972
- }
973
- }
974
- }
975
- const merged = new BufferGeometry();
976
- merged.setAttribute("position", new BufferAttribute(position, 3));
977
- merged.setAttribute("normal", new BufferAttribute(normal, 3));
978
- merged.setAttribute("skinIndex", new BufferAttribute(slotIndex, 4));
979
- merged.setAttribute("skinWeight", new BufferAttribute(slotWeight, 4));
980
- mergeSurface(merged, rigParts.map((r) => r.part), total, null);
981
- return merged;
150
+ const IndexArray = runs[0].constructor;
151
+ const indices = new IndexArray(runs.reduce((n, run) => n + run.length, 0));
152
+ extension.groups.forEach((group, i) => indices.set(runs[i], group.start));
153
+ geometry.setIndex(new BufferAttribute(indices, 1));
154
+ for (const { start, count, materialIndex } of extension.groups) geometry.addGroup(start, count, materialIndex);
155
+ return geometry;
982
156
  }
983
157
  var REQUEST = "three-vat:bake";
984
158
  var RESPONSE = "three-vat:baked";
@@ -1137,7 +311,7 @@ function rebuildTrack(record) {
1137
311
  if (record.settings) Object.assign(track, { settings: record.settings });
1138
312
  return track;
1139
313
  }
1140
- function isAction2(input) {
314
+ function isAction(input) {
1141
315
  return typeof input.getClip === "function";
1142
316
  }
1143
317
  function recordScene(root, animations, mergeFlat) {
@@ -1230,7 +404,7 @@ function recordScene(root, animations, mergeFlat) {
1230
404
  return clips.push(clip) - 1;
1231
405
  };
1232
406
  const inputs = animations.map(
1233
- (input) => isAction2(input) ? {
407
+ (input) => isAction(input) ? {
1234
408
  clip: clipOf(input.getClip()),
1235
409
  action: {
1236
410
  weight: input.weight,
@@ -1343,6 +517,8 @@ function recordVAT(vat, stand) {
1343
517
  height: texture.image.height,
1344
518
  normals: normals ? transferable(normals, true, transfer) : null,
1345
519
  slotCount: vat.encoding === "rig" ? vat.slotCount : 0,
520
+ // Transferred, so detached here: the worker's VAT is dropped once it is sent.
521
+ restSlots: vat.encoding === "rig" ? transferable(restSlotsOf(vat), true, transfer) : null,
1346
522
  fallback: vat.encoding === "delta" ? vat.fallback : null,
1347
523
  rowsPerFrame: vat.encoding === "delta" ? vat.rowsPerFrame : 1,
1348
524
  geometry: recordGeometry(vat.geometry, true, transfer, /* @__PURE__ */ new Map(), []),
@@ -1376,6 +552,7 @@ function rebuildVAT(record, materials) {
1376
552
  slotCount: record.slotCount,
1377
553
  ...base
1378
554
  };
555
+ keepRestSlots(vat2, record.restSlots);
1379
556
  return vat2;
1380
557
  }
1381
558
  const vat = {
@@ -1445,4 +622,4 @@ function serveVATBakes(scope = globalThis) {
1445
622
  return () => scope.removeEventListener("message", onMessage);
1446
623
  }
1447
624
 
1448
- export { bakeVAT, bakeVATInWorker, decodeOctahedral, encodeOctahedral, serveVATBakes };
625
+ export { bakeVATInWorker, loadVAT, serveVATBakes };