@mochiya/avatar-composition 0.1.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 ADDED
@@ -0,0 +1,1800 @@
1
+ // src/schema.ts
2
+ import { z } from "zod";
3
+ var EXTENSION_NAME = "MOCHIYA_avatar_composition";
4
+ var SPEC_VERSION = "0.1";
5
+ var ASSET_KINDS = ["avatar", "attachment"];
6
+ var CAPABILITIES = [
7
+ "mergeArmature",
8
+ "boneProxy",
9
+ "shapeChanger",
10
+ "blendshapeSync",
11
+ "objectToggle",
12
+ "materialSetter",
13
+ "menuItem"
14
+ ];
15
+ var index = z.number().int().nonnegative();
16
+ var number = z.number().finite();
17
+ var keywords = z.array(z.string().min(1).max(256)).max(32);
18
+ var selectorSchema = z.object({
19
+ asset: z.enum(["self", "base"]),
20
+ node: index.optional(),
21
+ path: z.array(z.string().min(1).max(256)).max(128).optional(),
22
+ boneKeywords: keywords.optional(),
23
+ meshKeywords: keywords.optional(),
24
+ nodeKeywords: keywords.optional(),
25
+ blendshapeKeywords: keywords.optional(),
26
+ morphIndex: index.optional(),
27
+ humanBone: z.string().max(64).optional(),
28
+ humanBonePath: z.array(z.string().min(1).max(256)).max(128).optional(),
29
+ parentKeywords: keywords.optional()
30
+ }).strict().superRefine((s, ctx) => {
31
+ if (s.asset === "self" && s.node === void 0)
32
+ ctx.addIssue({
33
+ code: "custom",
34
+ message: "Local selectors require a node index"
35
+ });
36
+ if (s.asset === "base" && (s.node !== void 0 || s.morphIndex !== void 0))
37
+ ctx.addIssue({
38
+ code: "custom",
39
+ message: "External selectors use paths/keywords, never another file's indices"
40
+ });
41
+ });
42
+ var conditionSchema = z.object({
43
+ type: z.enum(["nodeActive", "control"]),
44
+ asset: z.enum(["self", "base"]).optional(),
45
+ node: index.optional(),
46
+ nodeKeywords: keywords.optional(),
47
+ path: z.array(z.string()).max(128).optional(),
48
+ control: z.string().max(128).optional(),
49
+ value: z.union([number, z.boolean()]).optional(),
50
+ inverse: z.boolean().optional()
51
+ }).strict().superRefine((c, ctx) => {
52
+ if (c.type === "control" && !c.control)
53
+ ctx.addIssue({
54
+ code: "custom",
55
+ message: "Control condition requires an ID"
56
+ });
57
+ if (c.type === "nodeActive" && c.node === void 0 && !c.nodeKeywords?.length && c.path === void 0)
58
+ ctx.addIssue({
59
+ code: "custom",
60
+ message: "Node condition requires a target"
61
+ });
62
+ if (c.type === "nodeActive" && c.asset === "base" && c.node !== void 0)
63
+ ctx.addIssue({
64
+ code: "custom",
65
+ message: "External conditions cannot use local indices"
66
+ });
67
+ });
68
+ var curveSchema = z.object({
69
+ interpolation: z.enum(["linear", "step"]),
70
+ points: z.array(z.tuple([number, number])).min(2).max(4096)
71
+ }).strict().superRefine((c, ctx) => {
72
+ if (!c.points.every((p, i) => i === 0 || p[0] > c.points[i - 1][0]))
73
+ ctx.addIssue({ code: "custom", message: "Curve inputs must increase" });
74
+ });
75
+ var common = {
76
+ id: z.string().min(1).max(128),
77
+ sourceNode: index,
78
+ origin: z.enum(["modularAvatar", "referenceRig", "colliderAnchor", "authored"]).default("authored")
79
+ };
80
+ var componentSchema = z.discriminatedUnion("type", [
81
+ z.object({
82
+ ...common,
83
+ type: z.literal("mergeArmature"),
84
+ target: selectorSchema,
85
+ prefix: z.string().max(256).default(""),
86
+ suffix: z.string().max(256).default(""),
87
+ lockMode: z.enum(["unidirectional", "bidirectional", "notLocked"]).default("unidirectional"),
88
+ mangleNames: z.boolean().default(true)
89
+ }).strict(),
90
+ z.object({
91
+ ...common,
92
+ type: z.literal("boneProxy"),
93
+ target: selectorSchema,
94
+ attachmentMode: z.enum(["keepWorldPose", "atRoot", "keepPosition", "keepRotation"]).default("keepWorldPose"),
95
+ matchScale: z.boolean().default(false)
96
+ }).strict(),
97
+ z.object({
98
+ ...common,
99
+ type: z.literal("shapeChanger"),
100
+ threshold: number.nonnegative().default(0.01),
101
+ condition: conditionSchema.optional(),
102
+ shapes: z.array(
103
+ z.object({
104
+ target: selectorSchema,
105
+ changeType: z.enum(["set", "delete"]),
106
+ value: number.default(0)
107
+ }).strict()
108
+ ).max(1e4)
109
+ }).strict(),
110
+ z.object({
111
+ ...common,
112
+ type: z.literal("blendshapeSync"),
113
+ condition: conditionSchema.optional(),
114
+ bindings: z.array(
115
+ z.object({
116
+ driver: selectorSchema,
117
+ driven: selectorSchema,
118
+ curve: curveSchema.optional()
119
+ }).strict()
120
+ ).max(1e4)
121
+ }).strict(),
122
+ z.object({
123
+ ...common,
124
+ type: z.literal("objectToggle"),
125
+ condition: conditionSchema.optional(),
126
+ objects: z.array(
127
+ z.object({ target: selectorSchema, value: z.boolean() }).strict()
128
+ ).max(1e4)
129
+ }).strict(),
130
+ z.object({
131
+ ...common,
132
+ type: z.literal("materialSetter"),
133
+ condition: conditionSchema.optional(),
134
+ objects: z.array(
135
+ z.object({ target: selectorSchema, slot: index, material: index }).strict()
136
+ ).max(1e4)
137
+ }).strict(),
138
+ z.object({
139
+ ...common,
140
+ type: z.literal("menuItem"),
141
+ label: z.string().max(256),
142
+ controlType: z.enum(["toggle", "button"]),
143
+ parameter: z.string().min(1).max(128).optional(),
144
+ value: number.default(1),
145
+ defaultValue: z.union([number, z.boolean()]).default(0),
146
+ automatic: z.boolean().default(true)
147
+ }).strict()
148
+ ]);
149
+ var manifestSchema = z.object({
150
+ specVersion: z.literal(SPEC_VERSION),
151
+ assetKind: z.enum(ASSET_KINDS),
152
+ requiredCapabilities: z.array(z.string().max(64)).max(32).default([]),
153
+ matching: z.object({
154
+ mode: z.literal("keywordBestEffort"),
155
+ armatureKeywords: keywords.default([]),
156
+ onUnresolved: z.literal("warnAndContinue")
157
+ }).strict().optional(),
158
+ rig: z.object({ role: z.enum(["avatar", "attachmentReference"]) }).strict().optional(),
159
+ nodes: z.array(
160
+ z.object({
161
+ node: index,
162
+ aliases: keywords.default([]),
163
+ active: z.boolean().default(true)
164
+ }).strict()
165
+ ).max(1e5).default([]),
166
+ components: z.array(componentSchema).max(1e4).default([])
167
+ }).strict();
168
+ var CompositionError = class extends Error {
169
+ constructor(code, message) {
170
+ super(message);
171
+ this.code = code;
172
+ this.name = "CompositionError";
173
+ }
174
+ code;
175
+ };
176
+ function parseManifest(input) {
177
+ const result = manifestSchema.safeParse(input);
178
+ if (!result.success)
179
+ throw new CompositionError(
180
+ "INVALID_MANIFEST",
181
+ result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")
182
+ );
183
+ const manifest = result.data;
184
+ for (const capability of manifest.requiredCapabilities)
185
+ if (!CAPABILITIES.includes(capability))
186
+ throw new CompositionError(
187
+ "UNSUPPORTED_CAPABILITY",
188
+ `Unsupported required component: ${capability}`
189
+ );
190
+ const ids = /* @__PURE__ */ new Set();
191
+ for (const component of manifest.components) {
192
+ if (ids.has(component.id))
193
+ throw new CompositionError(
194
+ "DUPLICATE_ID",
195
+ `Duplicate ID: ${component.id}`
196
+ );
197
+ ids.add(component.id);
198
+ }
199
+ return manifest;
200
+ }
201
+ function menuItems(manifest) {
202
+ return manifest?.components.filter((c) => c.type === "menuItem") ?? [];
203
+ }
204
+
205
+ // src/asset.ts
206
+ var MochiyaAvatarCompositionLoaderPlugin = class {
207
+ constructor(parser) {
208
+ this.parser = parser;
209
+ }
210
+ parser;
211
+ name = EXTENSION_NAME;
212
+ async afterRoot(gltf) {
213
+ const value = this.parser.json.extensions?.[EXTENSION_NAME];
214
+ if (value) gltf.userData.mochiyaAvatarComposition = parseManifest(value);
215
+ }
216
+ };
217
+ var AvatarAsset = class {
218
+ constructor(scene, options = {}) {
219
+ this.scene = scene;
220
+ this.manifest = options.manifest ? parseManifest(options.manifest) : void 0;
221
+ this.vrm = options.vrm;
222
+ this.materials = options.materials ?? [];
223
+ scene.updateWorldMatrix(true, true);
224
+ this.rootRestWorld = scene.matrixWorld.clone();
225
+ let next = 0;
226
+ scene.traverse((node) => {
227
+ if (options.authoredObjects && !options.authoredObjects.has(node)) return;
228
+ this.restWorld.set(node, node.matrixWorld.clone());
229
+ this.names.set(node, [
230
+ ...new Set(
231
+ [node.name, ...options.aliases?.get(node) ?? []].filter(Boolean)
232
+ )
233
+ ]);
234
+ this.authoredActive.set(node, node.visible);
235
+ this.authoredParents.set(node, node.parent);
236
+ if (node.isBone) this.bones.push(node);
237
+ if (node.isMesh) {
238
+ const mesh = node;
239
+ this.meshes.push(mesh);
240
+ if (!options.materials) {
241
+ for (const m of Array.isArray(mesh.material) ? mesh.material : [mesh.material])
242
+ if (!this.materials.includes(m)) this.materials.push(m);
243
+ }
244
+ }
245
+ if (!options.nodes) this.nodes.set(next++, node);
246
+ });
247
+ const resources = options.resources ?? {
248
+ geometries: this.meshes.map((m) => m.geometry),
249
+ skeletons: this.meshes.filter((m) => !!m.isSkinnedMesh).map((m) => m.skeleton),
250
+ materials: this.materials
251
+ };
252
+ this.resources = /* @__PURE__ */ new Set([
253
+ ...resources.geometries ?? [],
254
+ ...resources.skeletons ?? [],
255
+ ...resources.materials ?? [],
256
+ ...resources.textures ?? []
257
+ ]);
258
+ if (options.nodes)
259
+ for (const [index2, node] of options.nodes) this.nodes.set(index2, node);
260
+ for (const [index2, node] of this.nodes) this.indices.set(node, index2);
261
+ for (const entry of this.manifest?.nodes ?? []) {
262
+ const node = this.nodes.get(entry.node);
263
+ if (!node) throw new Error(`Invalid local node ${entry.node}`);
264
+ this.names.set(node, [
265
+ .../* @__PURE__ */ new Set([...this.names.get(node) ?? [], ...entry.aliases])
266
+ ]);
267
+ this.authoredActive.set(node, entry.active);
268
+ node.visible = entry.active;
269
+ }
270
+ }
271
+ scene;
272
+ resources;
273
+ disposed = false;
274
+ meshes = [];
275
+ bones = [];
276
+ names = /* @__PURE__ */ new Map();
277
+ nodes = /* @__PURE__ */ new Map();
278
+ indices = /* @__PURE__ */ new Map();
279
+ primitiveSlots = /* @__PURE__ */ new Map();
280
+ materials;
281
+ restWorld = /* @__PURE__ */ new Map();
282
+ authoredActive = /* @__PURE__ */ new Map();
283
+ authoredParents = /* @__PURE__ */ new Map();
284
+ rootRestWorld;
285
+ manifest;
286
+ vrm;
287
+ nodeMeshes(node) {
288
+ if (node.isMesh) return [node];
289
+ return this.meshes.filter((mesh) => {
290
+ for (let p = mesh.parent; p; p = p.parent) {
291
+ if (p === node) return true;
292
+ if (this.indices.has(p)) return false;
293
+ }
294
+ return false;
295
+ });
296
+ }
297
+ restAtCurrentRoot(node) {
298
+ this.scene.updateWorldMatrix(true, false);
299
+ return this.scene.matrixWorld.clone().multiply(this.rootRestWorld.clone().invert()).multiply(this.restWorld.get(node) ?? node.matrixWorld);
300
+ }
301
+ };
302
+ async function prepareAvatarAsset(gltf) {
303
+ const parser = gltf.parser;
304
+ const nodes = /* @__PURE__ */ new Map();
305
+ const aliases = /* @__PURE__ */ new Map();
306
+ const loaded = await parser.getDependencies("node");
307
+ loaded.forEach((node, index2) => {
308
+ nodes.set(index2, node);
309
+ aliases.set(node, [parser.json.nodes?.[index2]?.name ?? ""]);
310
+ });
311
+ const materials = await parser.getDependencies("material");
312
+ const textures = new Set(await parser.getDependencies("texture"));
313
+ const authoredObjects = /* @__PURE__ */ new Set([gltf.scene, ...nodes.values()]);
314
+ const meshes = [];
315
+ gltf.scene.traverse((node) => {
316
+ const association = parser.associations.get(node);
317
+ if (node.isMesh && association?.meshes !== void 0) {
318
+ meshes.push(node);
319
+ authoredObjects.add(node);
320
+ }
321
+ });
322
+ const ownedMaterials = new Set(materials);
323
+ for (const mesh of meshes) {
324
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material])
325
+ ownedMaterials.add(material);
326
+ }
327
+ for (const material of ownedMaterials) {
328
+ for (const value of Object.values(material)) {
329
+ if (value?.isTexture) textures.add(value);
330
+ }
331
+ }
332
+ const manifest = gltf.userData.mochiyaAvatarComposition ?? parser.json.extensions?.[EXTENSION_NAME];
333
+ const asset = new AvatarAsset(gltf.scene, {
334
+ vrm: gltf.userData.vrm,
335
+ manifest,
336
+ nodes,
337
+ aliases,
338
+ materials,
339
+ authoredObjects,
340
+ resources: {
341
+ geometries: meshes.map((m) => m.geometry),
342
+ skeletons: meshes.filter((m) => !!m.isSkinnedMesh).map((m) => m.skeleton),
343
+ materials: ownedMaterials,
344
+ textures
345
+ }
346
+ });
347
+ for (const mesh of asset.meshes) {
348
+ const association = parser.associations.get(mesh);
349
+ if (association?.primitives !== void 0)
350
+ asset.primitiveSlots.set(mesh, association.primitives);
351
+ }
352
+ return asset;
353
+ }
354
+ function disposeAvatarAsset(asset) {
355
+ if (asset.disposed) return;
356
+ asset.disposed = true;
357
+ asset.scene.removeFromParent();
358
+ asset.vrm?.springBoneManager?.reset();
359
+ asset.resources.forEach((resource) => resource.dispose());
360
+ asset.resources.clear();
361
+ }
362
+
363
+ // src/matching.ts
364
+ function tokens(value) {
365
+ return value.normalize("NFKC").replace(/([a-z\d])([A-Z])/g, "$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
366
+ }
367
+ function anatomicalSide(value) {
368
+ const t = tokens(value);
369
+ return t.some((x) => x === "left" || x === "l") ? "left" : t.some((x) => x === "right" || x === "r") ? "right" : void 0;
370
+ }
371
+ function keywordScore(name, query) {
372
+ if (name === query) return 100;
373
+ const a = tokens(name), b = tokens(query), na = a.join(""), nb = b.join("");
374
+ if (!nb) return 0;
375
+ const left = anatomicalSide(name), right = anatomicalSide(query);
376
+ if (left && right && left !== right) return 0;
377
+ if (na === nb) return 90;
378
+ if (b.every((t) => a.includes(t))) return 70;
379
+ return nb.length >= 3 && na.includes(nb) ? 50 : 0;
380
+ }
381
+ var NameResolver = class {
382
+ constructor(base, self) {
383
+ this.base = base;
384
+ this.self = self;
385
+ }
386
+ base;
387
+ self;
388
+ asset(selector) {
389
+ return selector.asset === "base" ? this.base : this.self;
390
+ }
391
+ node(selector, kind = "node") {
392
+ const asset = this.asset(selector);
393
+ if (selector.asset === "self") {
394
+ const node = asset.nodes.get(selector.node);
395
+ if (!node)
396
+ throw new CompositionError(
397
+ "INVALID_LOCAL_REFERENCE",
398
+ `Local node ${selector.node} does not exist`
399
+ );
400
+ return { value: node };
401
+ }
402
+ const words = selector.boneKeywords ?? selector.meshKeywords ?? selector.nodeKeywords ?? selector.path?.slice(-1) ?? [];
403
+ const candidates = kind === "bone" ? [...asset.nodes.values()].filter((n) => !asset.nodeMeshes(n).length) : kind === "mesh" ? [...asset.nodes.values()].filter((n) => asset.nodeMeshes(n).length) : [...asset.nodes.values()];
404
+ if (selector.path?.length === 0) return { value: asset.scene };
405
+ if (selector.path?.length) {
406
+ const exact = candidates.filter(
407
+ (n) => this.pathMatches(asset, n, selector.path)
408
+ );
409
+ if (exact.length === 1) return { value: exact[0] };
410
+ }
411
+ const ranked = candidates.map((node) => ({ node, score: this.score(node, words, selector) })).filter((x) => x.score > 0).sort((a, b) => b.score - a.score);
412
+ if (ranked.length && (ranked.length === 1 || ranked[0].score > ranked[1].score))
413
+ return {
414
+ value: ranked[0].node,
415
+ warning: selector.path?.length ? {
416
+ code: "PATH_HINT_FALLBACK",
417
+ query: selector,
418
+ message: `Hierarchy path was not found; keyword match ${ranked[0].node.name} was used.`
419
+ } : void 0
420
+ };
421
+ if (kind === "bone" && selector.humanBone && asset.vrm) {
422
+ let bone = asset.vrm.humanoid.getRawBoneNode(
423
+ selector.humanBone
424
+ );
425
+ for (const segment of selector.humanBonePath ?? []) {
426
+ const children = [...asset.nodes.values()].filter(
427
+ (n) => asset.authoredParents.get(n) === bone
428
+ );
429
+ const rankedChildren = children.map((n) => ({
430
+ node: n,
431
+ score: Math.max(
432
+ 0,
433
+ ...(asset.names.get(n) ?? [n.name]).map(
434
+ (name) => keywordScore(name, segment)
435
+ )
436
+ )
437
+ })).filter((n) => n.score > 0).sort((a, b) => b.score - a.score);
438
+ bone = rankedChildren.length && (rankedChildren.length === 1 || rankedChildren[0].score > rankedChildren[1].score) ? rankedChildren[0].node : void 0;
439
+ if (!bone) break;
440
+ }
441
+ if (bone)
442
+ return {
443
+ value: bone,
444
+ warning: {
445
+ code: "HUMANOID_HINT_FALLBACK",
446
+ query: selector,
447
+ message: "Named target was unavailable; the humanoid bone reference was used."
448
+ }
449
+ };
450
+ }
451
+ return {
452
+ warning: this.warning(
453
+ selector,
454
+ ranked.map((x) => x.node.name)
455
+ )
456
+ };
457
+ }
458
+ pathMatches(asset, node, path) {
459
+ let current = node;
460
+ for (let i = path.length - 1; i >= 0; i--) {
461
+ if (!current || !(asset.names.get(current) ?? [current.name]).includes(path[i]))
462
+ return false;
463
+ current = asset.authoredParents.get(current);
464
+ }
465
+ return true;
466
+ }
467
+ score(node, words, selector) {
468
+ const names = this.asset(selector).names.get(node) ?? [node.name];
469
+ const score = Math.max(
470
+ 0,
471
+ ...words.flatMap((w) => names.map((n) => keywordScore(n, w)))
472
+ );
473
+ const pathScore = selector.path?.length && this.pathMatches(this.asset(selector), node, selector.path) ? 1e3 : 0;
474
+ if (!score && !pathScore) return 0;
475
+ const parentHint = selector.parentKeywords ?? this.self.manifest?.matching?.armatureKeywords ?? [];
476
+ let bonus = 0;
477
+ for (let p = node.parent; p && p !== this.base.scene.parent; p = p.parent)
478
+ if (parentHint.some((w) => keywordScore(p.name, w) > 0)) {
479
+ bonus = 1;
480
+ break;
481
+ }
482
+ return score + bonus + pathScore;
483
+ }
484
+ morph(selector) {
485
+ const asset = this.asset(selector);
486
+ if (selector.asset === "self") {
487
+ const node = this.node(selector).value;
488
+ const results = asset.nodeMeshes(node).flatMap((mesh) => {
489
+ const index2 = selector.morphIndex;
490
+ if (index2 !== void 0 && mesh.morphTargetInfluences && index2 < mesh.morphTargetInfluences.length)
491
+ return [{ mesh, index: index2 }];
492
+ return [];
493
+ });
494
+ if (!results.length)
495
+ throw new CompositionError(
496
+ "INVALID_LOCAL_MORPH",
497
+ `Local morph ${selector.node}:${selector.morphIndex} does not exist`
498
+ );
499
+ return { value: results };
500
+ }
501
+ const matches = [];
502
+ for (const mesh of asset.meshes) {
503
+ let group = mesh;
504
+ while (!asset.indices.has(group) && group.parent && group.parent !== asset.scene)
505
+ group = group.parent;
506
+ const meshScore = this.score(
507
+ group,
508
+ selector.meshKeywords ?? selector.path?.slice(-1) ?? [],
509
+ selector
510
+ );
511
+ for (const [name, index2] of Object.entries(
512
+ mesh.morphTargetDictionary ?? {}
513
+ )) {
514
+ const morphScore = Math.max(
515
+ 0,
516
+ ...(selector.blendshapeKeywords ?? []).map(
517
+ (q) => keywordScore(name, q)
518
+ )
519
+ );
520
+ if (morphScore)
521
+ matches.push({
522
+ mesh,
523
+ index: index2,
524
+ score: morphScore * 1e3 + meshScore,
525
+ group
526
+ });
527
+ }
528
+ }
529
+ matches.sort((a, b) => b.score - a.score);
530
+ if (matches.length) {
531
+ const best = matches.filter((x) => x.score === matches[0].score);
532
+ if (new Set(best.map((x) => x.group)).size === 1 && new Set(best.map((x) => x.mesh)).size === best.length)
533
+ return {
534
+ value: best.map(({ mesh, index: index2 }) => ({ mesh, index: index2 })),
535
+ warning: selector.meshKeywords?.length && !this.score(best[0].group, selector.meshKeywords, selector) ? {
536
+ code: "MESH_HINT_FALLBACK",
537
+ message: `Mesh hint was not found; the unique morph on ${best[0].mesh.name} was used.`,
538
+ query: selector
539
+ } : void 0
540
+ };
541
+ }
542
+ return {
543
+ warning: this.warning(
544
+ selector,
545
+ matches.map((x) => `${x.mesh.name}:${x.index}`)
546
+ )
547
+ };
548
+ }
549
+ warning(query, candidates = []) {
550
+ return {
551
+ code: candidates.length ? "AMBIGUOUS_MATCH" : "MISSING_MATCH",
552
+ message: candidates.length ? "Several targets match; this operation was skipped." : "No named target found; other operations continue.",
553
+ query,
554
+ candidates
555
+ };
556
+ }
557
+ };
558
+
559
+ // src/session.ts
560
+ import {
561
+ AnimationMixer
562
+ } from "three";
563
+
564
+ // src/operations.ts
565
+ function operations(component, sourceOrder) {
566
+ const common2 = {
567
+ componentId: component.id,
568
+ sourceOrder,
569
+ condition: "condition" in component ? component.condition : void 0
570
+ };
571
+ switch (component.type) {
572
+ case "shapeChanger":
573
+ return component.shapes.map((s, i) => ({
574
+ ...common2,
575
+ id: `${component.id}/${i}`,
576
+ target: s.target,
577
+ ...s.changeType === "delete" ? { type: "geometry.delete", threshold: component.threshold } : { type: "morph.override", value: s.value }
578
+ }));
579
+ case "blendshapeSync":
580
+ return component.bindings.map((b, i) => ({
581
+ ...common2,
582
+ ...b,
583
+ id: `${component.id}/${i}`,
584
+ type: "morph.sync"
585
+ }));
586
+ case "objectToggle":
587
+ return component.objects.map((o, i) => ({
588
+ ...common2,
589
+ ...o,
590
+ id: `${component.id}/${i}`,
591
+ type: "node.active"
592
+ }));
593
+ case "materialSetter":
594
+ return component.objects.map((o, i) => ({
595
+ ...common2,
596
+ ...o,
597
+ id: `${component.id}/${i}`,
598
+ type: "material.swap"
599
+ }));
600
+ case "menuItem":
601
+ return component.automatic ? [true, false].map((active) => ({
602
+ ...common2,
603
+ id: `${component.id}/${active}`,
604
+ type: "node.active",
605
+ target: { asset: "self", node: component.sourceNode },
606
+ value: active,
607
+ condition: {
608
+ type: "control",
609
+ control: component.parameter ?? component.id,
610
+ value: component.value,
611
+ inverse: !active
612
+ }
613
+ })) : [];
614
+ default:
615
+ return [];
616
+ }
617
+ }
618
+
619
+ // src/deletion.ts
620
+ import { BufferAttribute } from "three";
621
+ var ShapeDeletion = class {
622
+ states = /* @__PURE__ */ new Map();
623
+ apply(requests, registered) {
624
+ const live = new Set(registered.map((r) => r.mesh));
625
+ for (const [mesh, state] of this.states)
626
+ if (!live.has(mesh)) {
627
+ this.release(mesh, state);
628
+ this.states.delete(mesh);
629
+ }
630
+ for (const r of registered)
631
+ Object.assign(r.diagnostic, {
632
+ active: false,
633
+ selectedVertices: 0,
634
+ removedTriangles: 0,
635
+ fallback: void 0
636
+ });
637
+ const groups = /* @__PURE__ */ new Map();
638
+ for (const request of requests) {
639
+ const group = groups.get(request.mesh) ?? [];
640
+ group.push(request);
641
+ groups.set(request.mesh, group);
642
+ }
643
+ for (const [mesh, state] of this.states)
644
+ if (!groups.has(mesh) && mesh.geometry === state.copy)
645
+ mesh.geometry = state.source;
646
+ for (const [mesh, group] of groups) {
647
+ let state = this.states.get(mesh);
648
+ if (!state) {
649
+ state = {
650
+ source: mesh.geometry,
651
+ stamp: [],
652
+ masks: /* @__PURE__ */ new Map(),
653
+ selection: ""
654
+ };
655
+ this.states.set(mesh, state);
656
+ }
657
+ try {
658
+ if (mesh.geometry !== state.source && mesh.geometry !== state.copy)
659
+ throw new Error(
660
+ "The host replaced the mesh geometry; detach and reattach to use the replacement."
661
+ );
662
+ const source = state.source;
663
+ const stamp = geometryStamp(source);
664
+ if (stamp.length !== state.stamp.length || stamp.some((v, i) => v !== state.stamp[i])) {
665
+ this.release(mesh, state);
666
+ state.stamp = stamp;
667
+ state.masks.clear();
668
+ state.selection = "";
669
+ }
670
+ validateGeometry(source);
671
+ const masks = [];
672
+ const keys = [];
673
+ for (const r of group) {
674
+ try {
675
+ const key = `${r.index}/${r.threshold}`;
676
+ let mask = state.masks.get(key);
677
+ if (typeof mask === "string") throw new Error(mask);
678
+ if (!mask) {
679
+ try {
680
+ mask = select(source, r.index, r.threshold);
681
+ } catch (error) {
682
+ state.masks.set(
683
+ key,
684
+ error instanceof Error ? error.message : String(error)
685
+ );
686
+ throw error;
687
+ }
688
+ state.masks.set(key, mask);
689
+ }
690
+ masks.push(mask);
691
+ keys.push(key);
692
+ Object.assign(r.diagnostic, {
693
+ active: true,
694
+ selectedVertices: mask.vertices,
695
+ removedTriangles: mask.count
696
+ });
697
+ } catch (error) {
698
+ this.fallback(r, error);
699
+ }
700
+ }
701
+ if (!masks.some((m) => m.count > 0)) {
702
+ if (mesh.geometry === state.copy) mesh.geometry = source;
703
+ continue;
704
+ }
705
+ const selection = [...new Set(keys)].sort().join(";");
706
+ if (!state.copy) state.copy = source.clone();
707
+ if (selection !== state.selection) {
708
+ filterIndices(source, state.copy, masks);
709
+ state.selection = selection;
710
+ }
711
+ mesh.geometry = state.copy;
712
+ } catch (error) {
713
+ if (mesh.geometry === state.copy) mesh.geometry = state.source;
714
+ for (const r of group) this.fallback(r, error);
715
+ }
716
+ }
717
+ }
718
+ fallback(request, error) {
719
+ const reason = error instanceof Error ? error.message : String(error);
720
+ Object.assign(request.diagnostic, { active: true, fallback: reason });
721
+ request.fallback(reason);
722
+ }
723
+ release(mesh, state) {
724
+ if (mesh.geometry === state.copy) mesh.geometry = state.source;
725
+ state.copy?.dispose();
726
+ state.copy = void 0;
727
+ }
728
+ dispose() {
729
+ for (const [mesh, state] of this.states) this.release(mesh, state);
730
+ this.states.clear();
731
+ }
732
+ };
733
+ function geometryStamp(g) {
734
+ const attributes = [
735
+ g.index,
736
+ ...Object.values(g.attributes),
737
+ ...Object.values(g.morphAttributes).flat()
738
+ ];
739
+ return [
740
+ g.morphTargetsRelative,
741
+ g.drawRange.start,
742
+ g.drawRange.count,
743
+ ...g.groups.flatMap((r) => [r.start, r.count, r.materialIndex]),
744
+ ...attributes.flatMap((a) => {
745
+ if (!a) return [a];
746
+ return [
747
+ a,
748
+ a.array,
749
+ a.count,
750
+ a.itemSize,
751
+ a.normalized,
752
+ "data" in a ? a.data.version : a.version
753
+ ];
754
+ })
755
+ ];
756
+ }
757
+ function validateGeometry(g) {
758
+ const positions = g.getAttribute("position");
759
+ if (!positions || positions.itemSize < 3)
760
+ throw new Error("Position data is unavailable.");
761
+ const count = g.index?.count ?? positions.count;
762
+ if (count % 3 !== 0 || g.index && g.index.itemSize !== 1)
763
+ throw new Error("Geometry must contain triangle indices.");
764
+ if (g.drawRange.start < 0 || g.drawRange.start % 3 !== 0 || g.drawRange.count < 0 || g.drawRange.count !== Infinity && g.drawRange.count % 3 !== 0)
765
+ throw new Error("The draw range does not follow triangle boundaries.");
766
+ for (const group of g.groups)
767
+ if (group.start < 0 || group.start % 3 !== 0 || group.count < 0 || group.count % 3 !== 0 || group.start + group.count > count)
768
+ throw new Error("Material groups do not follow triangle boundaries.");
769
+ }
770
+ function select(g, index2, threshold) {
771
+ const positions = g.getAttribute("position"), morph = g.morphAttributes.position?.[index2];
772
+ if (!morph || morph.itemSize < 3 || morph.count !== positions.count)
773
+ throw new Error("The blendshape has no compatible position deltas.");
774
+ const vertices = new Uint8Array(positions.count);
775
+ let selected = 0;
776
+ for (let v = 0; v < vertices.length; v++) {
777
+ const x = morph.getX(v) - (g.morphTargetsRelative ? 0 : positions.getX(v));
778
+ const y = morph.getY(v) - (g.morphTargetsRelative ? 0 : positions.getY(v));
779
+ const z2 = morph.getZ(v) - (g.morphTargetsRelative ? 0 : positions.getZ(v));
780
+ if (![x, y, z2].every(Number.isFinite))
781
+ throw new Error("The blendshape contains non-finite position data.");
782
+ if (x * x + y * y + z2 * z2 > threshold * threshold) {
783
+ vertices[v] = 1;
784
+ selected++;
785
+ }
786
+ }
787
+ const indexCount = g.index?.count ?? positions.count;
788
+ const triangles = new Uint8Array(indexCount / 3);
789
+ let count = 0;
790
+ for (let i = 0; i < indexCount; i += 3) {
791
+ let remove = false;
792
+ for (let j = 0; j < 3; j++) {
793
+ const vertex = g.index?.getX(i + j) ?? i + j;
794
+ if (!Number.isInteger(vertex) || vertex < 0 || vertex >= vertices.length)
795
+ throw new Error("A triangle refers to an invalid vertex.");
796
+ remove ||= !!vertices[vertex];
797
+ }
798
+ if (remove) {
799
+ triangles[i / 3] = 1;
800
+ count++;
801
+ }
802
+ }
803
+ return { vertices: selected, triangles, count };
804
+ }
805
+ function filterIndices(source, copy, masks) {
806
+ const count = source.index?.count ?? source.getAttribute("position").count;
807
+ const indices = [];
808
+ const offsets = new Uint32Array(count / 3 + 1);
809
+ for (let i = 0; i < count; i += 3) {
810
+ offsets[i / 3] = indices.length;
811
+ if (masks.some((m) => m.triangles[i / 3])) continue;
812
+ for (let j = 0; j < 3; j++)
813
+ indices.push(source.index?.getX(i + j) ?? i + j);
814
+ }
815
+ offsets[count / 3] = indices.length;
816
+ const array = source.getAttribute("position").count > 65535 ? new Uint32Array(indices) : new Uint16Array(indices);
817
+ let buffer = copy.index;
818
+ if (!buffer || buffer.array.length !== count || buffer.array.constructor !== array.constructor) {
819
+ buffer = new BufferAttribute(
820
+ array instanceof Uint32Array ? new Uint32Array(count) : new Uint16Array(count),
821
+ 1
822
+ );
823
+ copy.setIndex(buffer);
824
+ }
825
+ buffer.array.set(array);
826
+ buffer.needsUpdate = true;
827
+ copy.clearGroups();
828
+ for (const group of source.groups) {
829
+ const start2 = offsets[group.start / 3], end2 = offsets[(group.start + group.count) / 3];
830
+ copy.addGroup(start2, end2 - start2, group.materialIndex);
831
+ }
832
+ const start = Math.min(count, Math.max(0, source.drawRange.start));
833
+ const end = Math.min(count, start + source.drawRange.count);
834
+ copy.setDrawRange(offsets[start / 3], offsets[end / 3] - offsets[start / 3]);
835
+ }
836
+
837
+ // src/rig.ts
838
+ import { Bone, Matrix4, Quaternion, Vector3 } from "three";
839
+ function bindArmatures(base, asset, warnings, results, undo) {
840
+ const resolver = new NameResolver(base, asset);
841
+ const components = asset.manifest?.components.filter(
842
+ (c) => c.type === "mergeArmature" || c.type === "boneProxy"
843
+ ) ?? [];
844
+ const roots = new Set(components.map((c) => c.sourceNode));
845
+ const planned = /* @__PURE__ */ new Map();
846
+ let requested = 0;
847
+ function record(source, target, id, query, snap = false) {
848
+ requested++;
849
+ results.push({
850
+ componentId: id,
851
+ operation: "bone",
852
+ sourceNode: asset.indices.get(source),
853
+ target: target?.name,
854
+ status: target ? "resolved" : "skipped",
855
+ query
856
+ });
857
+ if (target) {
858
+ if (planned.has(source))
859
+ warnings.push({
860
+ code: "OVERLAPPING_RIG",
861
+ operation: id,
862
+ message: `Multiple instructions address ${source.name}; the later instruction wins.`
863
+ });
864
+ planned.set(source, { target, snap, id });
865
+ }
866
+ }
867
+ for (const component of components) {
868
+ let walk2 = function(parent, matchedParent) {
869
+ for (const child of parent.children) {
870
+ const index2 = asset.indices.get(child);
871
+ if (index2 !== void 0 && roots.has(index2)) continue;
872
+ if (asset.nodeMeshes(child).length) continue;
873
+ const names = (asset.names.get(child) ?? [child.name]).map(
874
+ (name) => name.startsWith(prefix) && name.endsWith(suffix) && name.length > prefix.length + suffix.length ? name.slice(prefix.length, suffix ? -suffix.length : void 0) : name
875
+ );
876
+ const query = { asset: "base", boneKeywords: names };
877
+ const rank = (nodes) => nodes.map((node) => ({
878
+ node,
879
+ score: Math.max(
880
+ 0,
881
+ ...names.flatMap(
882
+ (q) => (base.names.get(node) ?? [node.name]).map(
883
+ (n) => keywordScore(n, q)
884
+ )
885
+ )
886
+ )
887
+ })).filter((x) => x.score > 0).sort((a, b) => b.score - a.score);
888
+ let ranked = rank(
889
+ pool.filter((n) => base.authoredParents.get(n) === matchedParent)
890
+ );
891
+ if (!ranked.length) ranked = rank(pool);
892
+ const target = ranked.length && (ranked.length === 1 || ranked[0].score > ranked[1].score) ? ranked[0].node : void 0;
893
+ if (!target)
894
+ warnings.push({
895
+ ...resolver.warning(
896
+ query,
897
+ ranked.map((x) => x.node.name)
898
+ ),
899
+ operation: component.id
900
+ });
901
+ if (index2 !== void 0) record(child, target, component.id, query);
902
+ walk2(child, target);
903
+ }
904
+ };
905
+ var walk = walk2;
906
+ const source = asset.nodes.get(component.sourceNode);
907
+ if (!source)
908
+ throw new CompositionError(
909
+ "INVALID_RIG_REFERENCE",
910
+ `Missing component root ${component.sourceNode}`
911
+ );
912
+ if (component.type === "mergeArmature" && component.lockMode !== "unidirectional")
913
+ warnings.push({
914
+ code: "UNSUPPORTED_LOCK_MODE",
915
+ operation: component.id,
916
+ message: `MA position lock '${component.lockMode}' is not supported; using unidirectional base-to-attachment following.`
917
+ });
918
+ if (component.type === "boneProxy" && (component.matchScale || component.attachmentMode === "keepPosition" || component.attachmentMode === "keepRotation"))
919
+ warnings.push({
920
+ code: "BONE_PROXY_FALLBACK",
921
+ operation: component.id,
922
+ message: "Partial-pose/scale matching is unsupported; using Keep World Pose."
923
+ });
924
+ if (component.target.asset !== "base") {
925
+ warnings.push({
926
+ code: "LOCAL_RIG_UNMERGED",
927
+ operation: component.id,
928
+ message: "Local armatures remain separate. Only base-to-attachment following is supported."
929
+ });
930
+ results.push({
931
+ componentId: component.id,
932
+ operation: "bone",
933
+ sourceNode: component.sourceNode,
934
+ status: "skipped",
935
+ query: component.target
936
+ });
937
+ continue;
938
+ }
939
+ const rootMatch = resolver.node(component.target, "bone");
940
+ if (rootMatch.warning)
941
+ warnings.push({ ...rootMatch.warning, operation: component.id });
942
+ record(
943
+ source,
944
+ rootMatch.value,
945
+ component.id,
946
+ component.target,
947
+ component.type === "boneProxy" && component.attachmentMode === "atRoot" && !component.matchScale
948
+ );
949
+ if (component.type !== "mergeArmature") continue;
950
+ const { prefix, suffix } = component;
951
+ const targetRoot = rootMatch.value;
952
+ const pool = [...base.nodes.values()].filter(
953
+ (n) => !base.nodeMeshes(n).length && (!targetRoot || isDescendant(n, targetRoot))
954
+ );
955
+ walk2(source, targetRoot);
956
+ }
957
+ if (!asset.manifest)
958
+ for (const source of asset.bones) {
959
+ const query = {
960
+ asset: "base",
961
+ boneKeywords: asset.names.get(source) ?? [source.name]
962
+ };
963
+ const match = resolver.node(query, "bone");
964
+ if (match.warning)
965
+ warnings.push({ ...match.warning, operation: "nameFallback" });
966
+ record(source, match.value, "nameFallback", query);
967
+ }
968
+ const entries = [...planned].map(([source, plan]) => ({
969
+ source,
970
+ ...plan,
971
+ rest: base.restAtCurrentRoot(plan.target),
972
+ sourceRest: asset.restAtCurrentRoot(source)
973
+ }));
974
+ let matched = 0;
975
+ for (const { source, target, snap, id, rest, sourceRest } of entries) {
976
+ if (source === asset.scene || Math.abs(rest.determinant()) < 1e-12) {
977
+ warnings.push({
978
+ code: "INVALID_BIND_TRANSFORM",
979
+ operation: id,
980
+ message: `Cannot reparent ${source.name}; its original rig is retained.`
981
+ });
982
+ const result = [...results].reverse().find(
983
+ (r) => r.componentId === id && r.sourceNode === asset.indices.get(source)
984
+ );
985
+ if (result) result.status = "skipped";
986
+ continue;
987
+ }
988
+ const helper = new Bone();
989
+ helper.name = `${source.name}:mochiya-offset`;
990
+ helper.userData.mochiyaGenerated = true;
991
+ helper.matrixAutoUpdate = false;
992
+ if (snap) {
993
+ const position2 = new Vector3(), rotation = new Quaternion(), scale2 = new Vector3();
994
+ sourceRest.decompose(new Vector3(), new Quaternion(), scale2);
995
+ rest.decompose(position2, rotation, new Vector3());
996
+ helper.matrix.copy(
997
+ rest.invert().multiply(new Matrix4().compose(position2, rotation, scale2))
998
+ );
999
+ } else helper.matrix.copy(rest.invert().multiply(sourceRest));
1000
+ const parent = source.parent, matrix = source.matrix.clone(), position = source.position.clone(), quaternion = source.quaternion.clone(), scale = source.scale.clone(), automatic = source.matrixAutoUpdate;
1001
+ const sibling = parent?.children.indexOf(source) ?? -1;
1002
+ target.add(helper);
1003
+ helper.add(source);
1004
+ source.position.set(0, 0, 0);
1005
+ source.quaternion.identity();
1006
+ source.scale.set(1, 1, 1);
1007
+ source.matrix.identity();
1008
+ source.matrixAutoUpdate = true;
1009
+ undo.push(() => {
1010
+ source.removeFromParent();
1011
+ if (parent) {
1012
+ parent.add(source);
1013
+ if (sibling >= 0) {
1014
+ parent.children.splice(parent.children.indexOf(source), 1);
1015
+ parent.children.splice(sibling, 0, source);
1016
+ }
1017
+ }
1018
+ source.position.copy(position);
1019
+ source.quaternion.copy(quaternion);
1020
+ source.scale.copy(scale);
1021
+ source.matrix.copy(matrix);
1022
+ source.matrixAutoUpdate = automatic;
1023
+ helper.removeFromParent();
1024
+ });
1025
+ matched++;
1026
+ }
1027
+ base.scene.updateWorldMatrix(true, true);
1028
+ asset.scene.updateWorldMatrix(true, true);
1029
+ return { matched, requested };
1030
+ }
1031
+ function isDescendant(node, root) {
1032
+ for (let p = node.parent; p; p = p.parent) if (p === root) return true;
1033
+ return false;
1034
+ }
1035
+
1036
+ // src/session.ts
1037
+ var owners = /* @__PURE__ */ new WeakMap();
1038
+ function evaluateCurve(curve, value) {
1039
+ if (!curve) return value;
1040
+ const points = curve.points;
1041
+ let i = points.findIndex((p) => p[0] > value) - 1;
1042
+ if (i < 0) i = value < points[0][0] ? 0 : points.length - 2;
1043
+ const a = points[i], b = points[i + 1];
1044
+ if (curve.interpolation === "step")
1045
+ return value >= points.at(-1)[0] ? points.at(-1)[1] : a[1];
1046
+ return a[1] + (b[1] - a[1]) * ((value - a[0]) / (b[0] - a[0]));
1047
+ }
1048
+ var AvatarCompositionSession = class {
1049
+ base;
1050
+ items = /* @__PURE__ */ new Map();
1051
+ layers = /* @__PURE__ */ new Map();
1052
+ baseItem;
1053
+ disposed = false;
1054
+ mixer;
1055
+ animation;
1056
+ userMorphs = /* @__PURE__ */ new Map();
1057
+ meshOwners = /* @__PURE__ */ new Map();
1058
+ morphWriters = /* @__PURE__ */ new Map();
1059
+ indexMorphs() {
1060
+ this.meshOwners.clear();
1061
+ this.morphWriters.clear();
1062
+ for (const item of [this.baseItem, ...this.items.values()]) {
1063
+ for (const mesh of item.asset.meshes) this.meshOwners.set(mesh, item);
1064
+ for (const action of item.actions) {
1065
+ if (action.action.type !== "morph.sync" && action.action.type !== "morph.override")
1066
+ continue;
1067
+ for (const { mesh, index: index2 } of action.morphTargets ?? []) {
1068
+ let indices = this.morphWriters.get(mesh);
1069
+ if (!indices) this.morphWriters.set(mesh, indices = /* @__PURE__ */ new Map());
1070
+ let writers = indices.get(index2);
1071
+ if (!writers) indices.set(index2, writers = []);
1072
+ writers.push({ item, action });
1073
+ }
1074
+ }
1075
+ }
1076
+ }
1077
+ deletion = new ShapeDeletion();
1078
+ constructor(options) {
1079
+ this.base = options.base;
1080
+ if (this.base.manifest?.assetKind === "attachment")
1081
+ throw new CompositionError(
1082
+ "INVALID_ASSET_KIND",
1083
+ "This file declares an attachment. Load an avatar as the base, then add this file as an attachment."
1084
+ );
1085
+ if (owners.has(this.base))
1086
+ throw new CompositionError(
1087
+ "ASSET_ALREADY_ATTACHED",
1088
+ "The base is already owned by another composition session"
1089
+ );
1090
+ this.baseItem = {
1091
+ id: "base",
1092
+ asset: this.base,
1093
+ state: { id: "base" },
1094
+ resolver: new NameResolver(this.base, this.base),
1095
+ actions: [],
1096
+ undo: [],
1097
+ status: "attached",
1098
+ warnings: [],
1099
+ matchedBones: 0,
1100
+ requestedBones: 0,
1101
+ appliedActions: 0,
1102
+ resolved: []
1103
+ };
1104
+ this.baseItem.actions = this.compileComponents(this.baseItem);
1105
+ this.checkGraph([this.baseItem]);
1106
+ this.indexMorphs();
1107
+ owners.set(this.base, this);
1108
+ try {
1109
+ this.evaluate();
1110
+ } catch (error) {
1111
+ this.restoreLayers();
1112
+ this.deletion.dispose();
1113
+ owners.delete(this.base);
1114
+ throw error;
1115
+ }
1116
+ }
1117
+ get warnings() {
1118
+ return this.baseItem.warnings;
1119
+ }
1120
+ get resolved() {
1121
+ return this.baseItem.resolved;
1122
+ }
1123
+ get attachments() {
1124
+ return [...this.items.values()];
1125
+ }
1126
+ attach(asset, state) {
1127
+ this.requireLive();
1128
+ if (asset.manifest?.assetKind === "avatar")
1129
+ throw new CompositionError(
1130
+ "INVALID_ASSET_KIND",
1131
+ "This file declares an avatar. Load it as the base, or export the dependent asset as an attachment."
1132
+ );
1133
+ if (!state.id || this.items.has(state.id))
1134
+ throw new CompositionError(
1135
+ "DUPLICATE_INSTANCE",
1136
+ `Duplicate or empty item ID: ${state.id}`
1137
+ );
1138
+ if (owners.has(asset))
1139
+ throw new CompositionError(
1140
+ "ASSET_ALREADY_ATTACHED",
1141
+ "Load an independent asset instance before attaching it again"
1142
+ );
1143
+ this.restoreLayers();
1144
+ const item = {
1145
+ id: state.id,
1146
+ asset,
1147
+ state: this.state(state),
1148
+ resolver: new NameResolver(this.base, asset),
1149
+ actions: [],
1150
+ undo: [],
1151
+ status: "attached",
1152
+ warnings: [],
1153
+ matchedBones: 0,
1154
+ requestedBones: 0,
1155
+ appliedActions: 0,
1156
+ resolved: []
1157
+ };
1158
+ try {
1159
+ item.actions = this.compileComponents(item);
1160
+ this.checkGraph([this.baseItem, ...this.items.values(), item]);
1161
+ for (const other of this.items.values())
1162
+ for (const action of item.actions)
1163
+ if (other.actions.some(
1164
+ (previous) => previous.action.type === action.action.type && previous.writes.some((key) => action.writes.includes(key))
1165
+ ))
1166
+ item.warnings.push({
1167
+ code: "OVERLAPPING_WRITERS",
1168
+ operation: action.action.id,
1169
+ message: `This action overlaps ${other.id}; layer order and instance ID determine the final value.`
1170
+ });
1171
+ this.bindRig(item);
1172
+ item.status = item.requestedBones > 0 && item.matchedBones === 0 ? "unbound" : item.warnings.length ? "partial" : "attached";
1173
+ item.appliedActions = item.actions.length;
1174
+ this.items.set(item.id, item);
1175
+ this.indexMorphs();
1176
+ owners.set(asset, this);
1177
+ this.evaluate();
1178
+ return item;
1179
+ } catch (error) {
1180
+ this.restoreLayers();
1181
+ this.items.delete(item.id);
1182
+ this.indexMorphs();
1183
+ owners.delete(asset);
1184
+ for (const undo of item.undo.reverse()) undo();
1185
+ this.evaluate();
1186
+ throw error;
1187
+ }
1188
+ }
1189
+ setItemState(id, patch) {
1190
+ this.requireLive();
1191
+ const item = this.items.get(id);
1192
+ if (!item)
1193
+ throw new CompositionError("MISSING_INSTANCE", `Unknown item ${id}`);
1194
+ this.restoreLayers();
1195
+ const wasVisible = item.state.visible !== false;
1196
+ item.state = this.state({
1197
+ ...item.state,
1198
+ ...patch,
1199
+ controls: { ...item.state.controls, ...patch.controls },
1200
+ nodeVisibility: { ...item.state.nodeVisibility, ...patch.nodeVisibility }
1201
+ });
1202
+ if (!wasVisible && item.state.visible !== false)
1203
+ item.asset.vrm?.springBoneManager?.reset();
1204
+ this.evaluate();
1205
+ }
1206
+ setBaseControl(id, value) {
1207
+ this.requireLive();
1208
+ this.restoreLayers();
1209
+ this.baseItem.state = this.state({
1210
+ ...this.baseItem.state,
1211
+ controls: { ...this.baseItem.state.controls, [id]: value }
1212
+ });
1213
+ this.evaluate();
1214
+ }
1215
+ /** Use for explicit edits so removing an attachment never overwrites newer user values. */
1216
+ setBaseMorph(selector, value) {
1217
+ this.requireLive();
1218
+ if (!Number.isFinite(value)) throw new Error("Morph value must be finite");
1219
+ this.restoreLayers();
1220
+ const match = new NameResolver(this.base, this.base).morph({
1221
+ ...selector,
1222
+ asset: "base"
1223
+ });
1224
+ for (const { mesh, index: index2 } of match.value ?? [])
1225
+ mesh.morphTargetInfluences[index2] = value;
1226
+ this.evaluate();
1227
+ }
1228
+ /** Whether an active component currently owns this mesh weight. Geometry deletion alone does not drive it. */
1229
+ isMorphControlled(mesh, index2) {
1230
+ const writers = this.morphWriters.get(mesh)?.get(index2);
1231
+ if (!writers) return false;
1232
+ for (const { item, action } of writers)
1233
+ if (item.state.visible !== false && action.condition()) return true;
1234
+ return false;
1235
+ }
1236
+ /** Edit any session-owned mesh without overriding a composition-driven weight. */
1237
+ setMorph(mesh, index2, value, options = {}) {
1238
+ this.requireLive();
1239
+ if (!Number.isFinite(value)) throw new Error("Morph value must be finite");
1240
+ if (!this.meshOwners.has(mesh) || mesh.morphTargetInfluences?.[index2] === void 0)
1241
+ throw new Error("Mesh morph is not owned by this session");
1242
+ if (this.isMorphControlled(mesh, index2)) return false;
1243
+ if (!options.deferEvaluation) this.restoreLayers();
1244
+ mesh.morphTargetInfluences[index2] = value;
1245
+ const edits = this.userMorphs.get(mesh) ?? /* @__PURE__ */ new Map();
1246
+ edits.set(index2, value);
1247
+ this.userMorphs.set(mesh, edits);
1248
+ if (!options.deferEvaluation) this.evaluate();
1249
+ return true;
1250
+ }
1251
+ /** Supply a clip retargeted to the base. Attachments follow the base through composition. */
1252
+ setAnimation(clip, time = 0) {
1253
+ this.requireLive();
1254
+ if (!Number.isFinite(time) || time < 0)
1255
+ throw new Error("Animation time must be finite and nonnegative");
1256
+ this.mixer?.stopAllAction();
1257
+ if (this.animation) this.mixer?.uncacheClip(this.animation);
1258
+ this.base.vrm?.humanoid.resetNormalizedPose();
1259
+ this.animation = clip ?? void 0;
1260
+ if (!clip) {
1261
+ this.mixer = void 0;
1262
+ return;
1263
+ }
1264
+ this.mixer ??= new AnimationMixer(this.base.scene);
1265
+ this.mixer.clipAction(clip).reset().play();
1266
+ this.mixer.setTime(Math.max(0, time));
1267
+ }
1268
+ get animationTime() {
1269
+ return this.mixer?.time ?? 0;
1270
+ }
1271
+ /** Complete frame lifecycle; use instead of separately advancing base and attachment VRMs. */
1272
+ update(delta, paused = false) {
1273
+ if (!Number.isFinite(delta) || delta < 0)
1274
+ throw new Error("Frame delta must be finite and nonnegative");
1275
+ this.beforeVrmUpdate();
1276
+ this.mixer?.update(paused ? 0 : delta);
1277
+ this.base.vrm?.update(delta);
1278
+ this.base.scene.updateWorldMatrix(true, true);
1279
+ this.afterVrmUpdate(delta);
1280
+ }
1281
+ beforeVrmUpdate() {
1282
+ this.requireLive();
1283
+ this.restoreLayers();
1284
+ this.evaluate("visibility");
1285
+ }
1286
+ afterVrmUpdate(delta) {
1287
+ this.requireLive();
1288
+ for (const item of this.items.values()) {
1289
+ if (item.state.visible === false) continue;
1290
+ const vrm = item.asset.vrm;
1291
+ vrm?.expressionManager?.update();
1292
+ vrm?.nodeConstraintManager?.update();
1293
+ vrm?.springBoneManager?.update(delta);
1294
+ }
1295
+ for (const [mesh, edits] of this.userMorphs)
1296
+ for (const [index2, value] of edits)
1297
+ if (mesh.morphTargetInfluences[index2] !== value)
1298
+ mesh.morphTargetInfluences[index2] = value;
1299
+ this.evaluate("properties");
1300
+ }
1301
+ detach(id) {
1302
+ const item = this.items.get(id);
1303
+ if (!item) return;
1304
+ this.restoreLayers();
1305
+ this.items.delete(id);
1306
+ this.indexMorphs();
1307
+ for (const mesh of item.asset.meshes) this.userMorphs.delete(mesh);
1308
+ owners.delete(item.asset);
1309
+ for (const undo of item.undo.reverse()) undo();
1310
+ item.asset.scene.updateWorldMatrix(true, true);
1311
+ this.refreshSprings(item.asset);
1312
+ this.evaluate();
1313
+ }
1314
+ dispose() {
1315
+ if (this.disposed) return;
1316
+ this.mixer?.stopAllAction();
1317
+ this.mixer?.uncacheRoot(this.base.scene);
1318
+ this.mixer = void 0;
1319
+ this.userMorphs.clear();
1320
+ for (const id of [...this.items.keys()]) this.detach(id);
1321
+ this.restoreLayers();
1322
+ this.deletion.dispose();
1323
+ owners.delete(this.base);
1324
+ this.meshOwners.clear();
1325
+ this.morphWriters.clear();
1326
+ this.disposed = true;
1327
+ }
1328
+ requireLive() {
1329
+ if (this.disposed) throw new Error("Composition session is disposed");
1330
+ }
1331
+ state(state) {
1332
+ if (!Number.isFinite(state.layerOrder ?? 0))
1333
+ throw new Error("Layer order must be finite");
1334
+ for (const value of Object.values(state.controls ?? {}))
1335
+ if (typeof value !== "boolean" && !Number.isFinite(value))
1336
+ throw new Error("Control value must be finite");
1337
+ return {
1338
+ ...state,
1339
+ controls: { ...state.controls },
1340
+ nodeVisibility: { ...state.nodeVisibility }
1341
+ };
1342
+ }
1343
+ orderedItems() {
1344
+ return [
1345
+ this.baseItem,
1346
+ ...[...this.items.values()].sort(
1347
+ (a, b) => (a.state.layerOrder ?? 0) - (b.state.layerOrder ?? 0) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
1348
+ )
1349
+ ];
1350
+ }
1351
+ take(item, match, operation) {
1352
+ if (match.warning) item.warnings.push({ ...match.warning, operation });
1353
+ return match.value;
1354
+ }
1355
+ bindRig(item) {
1356
+ const counts = bindArmatures(
1357
+ this.base,
1358
+ item.asset,
1359
+ item.warnings,
1360
+ item.resolved,
1361
+ item.undo
1362
+ );
1363
+ item.matchedBones = counts.matched;
1364
+ item.requestedBones = counts.requested;
1365
+ this.refreshSprings(item.asset);
1366
+ }
1367
+ compileComponents(item) {
1368
+ return (item.asset.manifest?.components ?? []).flatMap(
1369
+ (component, order) => {
1370
+ if (!item.asset.nodes.has(component.sourceNode))
1371
+ throw new CompositionError(
1372
+ "INVALID_LOCAL_REFERENCE",
1373
+ `Missing component source ${component.sourceNode}`
1374
+ );
1375
+ if (item === this.baseItem && (component.type === "mergeArmature" || component.type === "boneProxy")) {
1376
+ item.warnings.push({
1377
+ code: "LOCAL_RIG_UNMERGED",
1378
+ operation: component.id,
1379
+ message: "Avatar armatures remain separate; base-to-attachment following is applied only when attaching an asset."
1380
+ });
1381
+ const diagnostic = {
1382
+ componentId: component.id,
1383
+ operation: "bone",
1384
+ sourceNode: component.sourceNode,
1385
+ status: "skipped",
1386
+ query: component.target
1387
+ };
1388
+ item.resolved.push(diagnostic);
1389
+ }
1390
+ if (component.type === "menuItem" && !component.automatic && component.parameter)
1391
+ item.warnings.push({
1392
+ code: "MENU_PARAMETER_ONLY",
1393
+ operation: component.id,
1394
+ message: "Named menu parameter is available locally; arbitrary Animator parameter effects are not executed."
1395
+ });
1396
+ return operations(component, order).flatMap((action) => {
1397
+ const compiled = this.compile(item, action);
1398
+ const diagnostic = {
1399
+ componentId: component.id,
1400
+ operation: action.id,
1401
+ status: compiled ? "resolved" : "skipped",
1402
+ target: compiled?.targets.join(", "),
1403
+ query: action.type === "morph.sync" ? action.driven : action.target
1404
+ };
1405
+ item.resolved.push(diagnostic);
1406
+ if (compiled) compiled.diagnostic = diagnostic;
1407
+ return compiled ?? [];
1408
+ });
1409
+ }
1410
+ );
1411
+ }
1412
+ refreshSprings(asset) {
1413
+ const manager = asset.vrm?.springBoneManager;
1414
+ if (!manager) return;
1415
+ const joints = [...manager.joints];
1416
+ joints.forEach((j) => manager.deleteJoint(j));
1417
+ joints.forEach((j) => manager.addJoint(j));
1418
+ manager.setInitState();
1419
+ }
1420
+ logicalActive(item, node, asset) {
1421
+ if (asset === item.asset && item.state.visible === false) return false;
1422
+ for (let current = node; current && asset.authoredActive.has(current); current = asset.authoredParents.get(current) ?? null)
1423
+ if (!current.visible) return false;
1424
+ return true;
1425
+ }
1426
+ condition(item, condition) {
1427
+ if (!condition) return () => true;
1428
+ if (condition.type === "control") {
1429
+ const controls = menuItems(item.asset.manifest).filter(
1430
+ (c) => (c.parameter ?? c.id) === condition.control
1431
+ );
1432
+ const control = controls.find((c) => Number(c.defaultValue) !== 0) ?? controls[0];
1433
+ if (!control)
1434
+ throw new CompositionError(
1435
+ "INVALID_CONTROL",
1436
+ `Unknown control ${condition.control}`
1437
+ );
1438
+ return () => {
1439
+ const value = item.state.controls?.[control.parameter ?? control.id] ?? control.defaultValue;
1440
+ const result = condition.value === void 0 ? Boolean(value) : Number(value) === Number(condition.value);
1441
+ return condition.inverse ? !result : result;
1442
+ };
1443
+ }
1444
+ const selector = {
1445
+ asset: condition.asset ?? "self",
1446
+ node: condition.node,
1447
+ nodeKeywords: condition.nodeKeywords,
1448
+ path: condition.path
1449
+ };
1450
+ const node = this.take(item, item.resolver.node(selector), "condition");
1451
+ if (!node) return void 0;
1452
+ const asset = item.resolver.asset(selector);
1453
+ const menus = menuItems(item.asset.manifest);
1454
+ let menu;
1455
+ if (asset === item.asset) {
1456
+ for (let current = node; current; current = asset.authoredParents.get(current) ?? void 0) {
1457
+ menu = menus.find((c) => asset.nodes.get(c.sourceNode) === current);
1458
+ if (menu) break;
1459
+ }
1460
+ }
1461
+ return () => {
1462
+ let active = this.logicalActive(item, node, asset);
1463
+ if (menu) {
1464
+ const key = menu.parameter ?? menu.id;
1465
+ const defaultValue = menus.find(
1466
+ (c) => (c.parameter ?? c.id) === key && Number(c.defaultValue) !== 0
1467
+ )?.defaultValue ?? menu.defaultValue;
1468
+ active &&= Number(item.state.controls?.[key] ?? defaultValue) === menu.value;
1469
+ }
1470
+ return condition.inverse ? !active : active;
1471
+ };
1472
+ }
1473
+ morphBinding(mesh, index2) {
1474
+ return {
1475
+ key: `${mesh.uuid}:morph:${index2}`,
1476
+ get: () => mesh.morphTargetInfluences[index2],
1477
+ set: (v) => {
1478
+ mesh.morphTargetInfluences[index2] = Number(v);
1479
+ }
1480
+ };
1481
+ }
1482
+ visibleBinding(node) {
1483
+ return {
1484
+ key: `${node.uuid}:active`,
1485
+ get: () => node.visible,
1486
+ set: (v) => {
1487
+ node.visible = Boolean(v);
1488
+ }
1489
+ };
1490
+ }
1491
+ compile(item, action) {
1492
+ const condition = this.condition(item, action.condition);
1493
+ if (!condition) return;
1494
+ const result = {
1495
+ action,
1496
+ condition,
1497
+ execute: () => {
1498
+ },
1499
+ reads: [],
1500
+ writes: [],
1501
+ conditionReads: [],
1502
+ targets: []
1503
+ };
1504
+ if (action.condition?.type === "nodeActive") {
1505
+ const selector = {
1506
+ asset: action.condition.asset ?? "self",
1507
+ node: action.condition.node,
1508
+ nodeKeywords: action.condition.nodeKeywords,
1509
+ path: action.condition.path
1510
+ };
1511
+ const asset = item.resolver.asset(selector);
1512
+ for (let node = item.resolver.node(selector).value; node; node = asset.authoredParents.get(node) ?? void 0) {
1513
+ if (!asset.authoredActive.has(node)) break;
1514
+ result.conditionReads.push(this.visibleBinding(node).key);
1515
+ }
1516
+ }
1517
+ if (action.type === "morph.sync" || action.type === "morph.override" || action.type === "geometry.delete") {
1518
+ const targets = this.take(
1519
+ item,
1520
+ item.resolver.morph(
1521
+ action.type === "morph.sync" ? action.driven : action.target
1522
+ ),
1523
+ action.id
1524
+ );
1525
+ if (!targets) return;
1526
+ const bindings = targets.map((t) => this.morphBinding(t.mesh, t.index));
1527
+ result.morphTargets = targets;
1528
+ result.targets = targets.map(
1529
+ ({ mesh, index: index2 }) => `${mesh.name}:${Object.keys(mesh.morphTargetDictionary ?? {}).find((name) => mesh.morphTargetDictionary[name] === index2) ?? index2}`
1530
+ );
1531
+ result.writes = bindings.map((b) => b.key);
1532
+ if (action.type === "geometry.delete") {
1533
+ result.writes = bindings.map((b) => `${b.key}:delete`);
1534
+ result.deletions = targets.map(({ mesh, index: index2 }, i) => {
1535
+ const reasons = /* @__PURE__ */ new Set();
1536
+ return {
1537
+ mesh,
1538
+ index: index2,
1539
+ threshold: action.threshold,
1540
+ diagnostic: {
1541
+ active: false,
1542
+ selectedVertices: 0,
1543
+ removedTriangles: 0
1544
+ },
1545
+ fallback: (reason) => {
1546
+ if (!reasons.has(reason)) {
1547
+ reasons.add(reason);
1548
+ item.warnings.push({
1549
+ code: "SHAPE_DELETE_FALLBACK",
1550
+ operation: action.id,
1551
+ query: action.target,
1552
+ message: `${mesh.name}: ${reason} Delete uses reversible blendshape weight 0.`
1553
+ });
1554
+ if (item.status === "attached") item.status = "partial";
1555
+ }
1556
+ this.write(bindings[i], 0);
1557
+ }
1558
+ };
1559
+ });
1560
+ } else if (action.type === "morph.override")
1561
+ result.execute = () => bindings.forEach((b) => this.write(b, action.value));
1562
+ else {
1563
+ const source = this.take(
1564
+ item,
1565
+ item.resolver.morph(action.driver),
1566
+ action.id
1567
+ );
1568
+ if (!source) return;
1569
+ const driver = this.morphBinding(source[0].mesh, source[0].index);
1570
+ result.reads = source.map(
1571
+ (t) => this.morphBinding(t.mesh, t.index).key
1572
+ );
1573
+ result.execute = () => bindings.forEach(
1574
+ (b) => this.write(b, evaluateCurve(action.curve, Number(driver.get())))
1575
+ );
1576
+ }
1577
+ } else if (action.type === "node.active") {
1578
+ const target = this.take(
1579
+ item,
1580
+ item.resolver.node(action.target),
1581
+ action.id
1582
+ );
1583
+ if (!target) return;
1584
+ const binding = this.visibleBinding(target);
1585
+ result.targets = [target.name];
1586
+ result.writes = [binding.key];
1587
+ result.execute = () => this.write(binding, action.value);
1588
+ } else if (action.type === "material.swap") {
1589
+ const target = this.take(
1590
+ item,
1591
+ item.resolver.node(action.target, "mesh"),
1592
+ action.id
1593
+ );
1594
+ if (!target) return;
1595
+ const material = item.asset.materials[action.material];
1596
+ if (!material)
1597
+ throw new CompositionError(
1598
+ "INVALID_MATERIAL",
1599
+ `Missing local material ${action.material}`
1600
+ );
1601
+ const targetAsset = item.resolver.asset(action.target);
1602
+ const meshes = targetAsset.nodeMeshes(target);
1603
+ const valid = meshes.filter(
1604
+ (mesh, index2) => targetAsset.primitiveSlots.has(mesh) ? targetAsset.primitiveSlots.get(mesh) === action.slot : !target.isMesh ? index2 === action.slot : action.slot < (Array.isArray(mesh.material) ? mesh.material.length : 1)
1605
+ );
1606
+ if (!valid.length) {
1607
+ item.warnings.push({
1608
+ code: "MISSING_SLOT",
1609
+ operation: action.id,
1610
+ message: `Material slot ${action.slot} is unavailable.`
1611
+ });
1612
+ return;
1613
+ }
1614
+ result.targets = valid.map(
1615
+ (mesh) => `${mesh.name}:material[${action.slot}]`
1616
+ );
1617
+ result.writes = valid.map(
1618
+ (mesh) => `${mesh.uuid}:material:${targetAsset.primitiveSlots.has(mesh) || !target.isMesh ? "primitive" : action.slot}`
1619
+ );
1620
+ result.execute = () => valid.forEach((mesh) => {
1621
+ const wholePrimitive = targetAsset.primitiveSlots.has(mesh) || !target.isMesh;
1622
+ const slot = targetAsset.primitiveSlots.has(mesh) || !target.isMesh ? 0 : action.slot;
1623
+ const binding = {
1624
+ key: `${mesh.uuid}:material:${wholePrimitive ? "primitive" : slot}`,
1625
+ get: () => !wholePrimitive && Array.isArray(mesh.material) ? mesh.material[slot] : mesh.material,
1626
+ set: (value) => {
1627
+ if (wholePrimitive)
1628
+ mesh.material = value;
1629
+ else if (Array.isArray(mesh.material)) {
1630
+ mesh.material = [...mesh.material];
1631
+ mesh.material[slot] = value;
1632
+ } else mesh.material = value;
1633
+ }
1634
+ };
1635
+ this.write(binding, material);
1636
+ });
1637
+ }
1638
+ return result;
1639
+ }
1640
+ checkGraph(items) {
1641
+ const actions = items.flatMap((i) => i.actions);
1642
+ const syncs = actions.filter((a) => a.action.type === "morph.sync");
1643
+ for (const a of syncs)
1644
+ for (const b of syncs)
1645
+ if (a.writes.some((k) => b.reads.includes(k)))
1646
+ throw new CompositionError(
1647
+ "SYNC_CHAIN",
1648
+ "Chained or cyclic morph synchronization is unsupported"
1649
+ );
1650
+ const visibility = actions.filter((a) => a.action.type === "node.active");
1651
+ const visiting = /* @__PURE__ */ new Set(), done = /* @__PURE__ */ new Set();
1652
+ const visit = (action) => {
1653
+ if (visiting.has(action))
1654
+ throw new CompositionError(
1655
+ "VISIBILITY_CYCLE",
1656
+ "Cyclic visibility conditions are unsupported"
1657
+ );
1658
+ if (done.has(action)) return;
1659
+ visiting.add(action);
1660
+ for (const dependency of visibility)
1661
+ if (dependency.writes.some((key) => action.conditionReads.includes(key)))
1662
+ visit(dependency);
1663
+ visiting.delete(action);
1664
+ done.add(action);
1665
+ };
1666
+ visibility.forEach(visit);
1667
+ }
1668
+ write(binding, value) {
1669
+ const layer = this.layers.get(binding.key) ?? {
1670
+ binding,
1671
+ original: binding.get(),
1672
+ written: void 0
1673
+ };
1674
+ if (binding.get() !== value) binding.set(value);
1675
+ layer.written = value;
1676
+ this.layers.set(binding.key, layer);
1677
+ }
1678
+ restoreLayers() {
1679
+ for (const { binding, original, written } of this.layers.values())
1680
+ if (binding.get() === written) binding.set(original);
1681
+ this.layers.clear();
1682
+ }
1683
+ evaluate(phase = "all") {
1684
+ const items = this.orderedItems();
1685
+ if (phase !== "properties") {
1686
+ for (const item of items) {
1687
+ if (item !== this.baseItem)
1688
+ this.write(
1689
+ this.visibleBinding(item.asset.scene),
1690
+ item.state.visible !== false
1691
+ );
1692
+ for (const [index2, active] of Object.entries(
1693
+ item.state.nodeVisibility ?? {}
1694
+ )) {
1695
+ const node = item.asset.nodes.get(Number(index2));
1696
+ if (node) this.write(this.visibleBinding(node), active);
1697
+ }
1698
+ }
1699
+ const pending = items.flatMap(
1700
+ (item) => [...item.actions].sort((a, b) => a.action.sourceOrder - b.action.sourceOrder).filter((a) => a.action.type === "node.active").map((compiled) => ({ item, compiled }))
1701
+ );
1702
+ const done = /* @__PURE__ */ new Set();
1703
+ const execute = (entry) => {
1704
+ if (done.has(entry.compiled)) return;
1705
+ for (const dependency of pending)
1706
+ if (dependency.compiled.writes.some(
1707
+ (key) => entry.compiled.conditionReads.includes(key)
1708
+ ))
1709
+ execute(dependency);
1710
+ done.add(entry.compiled);
1711
+ if (entry.item.state.visible !== false && entry.compiled.condition())
1712
+ entry.compiled.execute();
1713
+ };
1714
+ pending.forEach(execute);
1715
+ for (const item of items)
1716
+ for (const mesh of item.asset.meshes)
1717
+ if (!this.logicalActive(item, mesh, item.asset))
1718
+ this.write(this.visibleBinding(mesh), false);
1719
+ for (const type of ["material.swap"])
1720
+ for (const item of items)
1721
+ for (const compiled of [...item.actions].sort(
1722
+ (a, b) => a.action.sourceOrder - b.action.sourceOrder
1723
+ ))
1724
+ if (compiled.action.type === type && item.state.visible !== false && compiled.condition())
1725
+ compiled.execute();
1726
+ }
1727
+ if (phase !== "visibility") {
1728
+ const key = (r) => `${r.mesh.uuid}/${r.index}`;
1729
+ const registered = items.flatMap(
1730
+ (item) => item.actions.flatMap((a) => a.deletions ?? [])
1731
+ );
1732
+ const thresholds = /* @__PURE__ */ new Map();
1733
+ for (const r of registered)
1734
+ thresholds.set(
1735
+ key(r),
1736
+ Math.min(thresholds.get(key(r)) ?? Infinity, r.threshold)
1737
+ );
1738
+ const active = /* @__PURE__ */ new Map();
1739
+ for (const item of items) {
1740
+ if (item.state.visible === false) continue;
1741
+ for (const compiled of [...item.actions].sort(
1742
+ (a, b) => a.action.sourceOrder - b.action.sourceOrder
1743
+ )) {
1744
+ if (!compiled.condition()) continue;
1745
+ if (compiled.action.type === "morph.override") {
1746
+ compiled.execute();
1747
+ for (const r of compiled.morphTargets ?? []) active.delete(key(r));
1748
+ } else if (compiled.action.type === "geometry.delete") {
1749
+ for (const r of compiled.deletions ?? [])
1750
+ active.set(key(r), { ...r, threshold: thresholds.get(key(r)) });
1751
+ }
1752
+ }
1753
+ }
1754
+ this.deletion.apply([...active.values()], registered);
1755
+ for (const item of items)
1756
+ for (const compiled of item.actions) {
1757
+ if (!compiled.deletions || !compiled.diagnostic) continue;
1758
+ const stats = compiled.deletions.map((r) => r.diagnostic);
1759
+ compiled.diagnostic.deletion = {
1760
+ active: stats.some((s) => s.active),
1761
+ selectedVertices: stats.reduce((n, s) => n + s.selectedVertices, 0),
1762
+ removedTriangles: stats.reduce((n, s) => n + s.removedTriangles, 0),
1763
+ fallback: stats.map((s) => s.fallback).filter(Boolean).join("; ") || void 0
1764
+ };
1765
+ }
1766
+ for (const type of ["morph.sync"])
1767
+ for (const item of items) {
1768
+ if (item.state.visible === false) continue;
1769
+ for (const compiled of [...item.actions].sort(
1770
+ (a, b) => a.action.sourceOrder - b.action.sourceOrder
1771
+ ))
1772
+ if (compiled.action.type === type && compiled.condition())
1773
+ compiled.execute();
1774
+ }
1775
+ }
1776
+ }
1777
+ };
1778
+ export {
1779
+ ASSET_KINDS,
1780
+ AvatarAsset,
1781
+ AvatarCompositionSession,
1782
+ CAPABILITIES,
1783
+ CompositionError,
1784
+ EXTENSION_NAME,
1785
+ MochiyaAvatarCompositionLoaderPlugin,
1786
+ NameResolver,
1787
+ SPEC_VERSION,
1788
+ componentSchema,
1789
+ conditionSchema,
1790
+ curveSchema,
1791
+ disposeAvatarAsset,
1792
+ evaluateCurve,
1793
+ keywordScore,
1794
+ manifestSchema,
1795
+ menuItems,
1796
+ parseManifest,
1797
+ prepareAvatarAsset,
1798
+ selectorSchema,
1799
+ tokens
1800
+ };