@lovelace_lol/embody 0.0.8 → 0.0.10

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/three.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as THREE3 from 'three';
2
- import { NoBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NormalBlending, Vector3, Box3, Matrix4, Quaternion, MathUtils, Mesh, PlaneGeometry, ShadowMaterial, HemisphereLight, DirectionalLight, SRGBColorSpace, ACESFilmicToneMapping, WebGLRenderer, Scene, Color, PerspectiveCamera, PCFShadowMap, PCFSoftShadowMap, InterpolateDiscrete, NumberKeyframeTrack, QuaternionKeyframeTrack, VectorKeyframeTrack, AnimationClip, PMREMGenerator, FloatType, Float32BufferAttribute, Euler, PropertyBinding, BufferAttribute, WebGPUCoordinateSystem, WebGLCoordinateSystem } from 'three';
3
- import { initEmbodyCore, requireInitializedEmbodyCore } from '@lovelace_lol/embody/wasm';
2
+ import { NoBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NormalBlending, Vector3, Box3, Timer, Matrix4, AnimationMixer, AdditiveAnimationBlendMode, NormalAnimationBlendMode, LoopOnce, LoopRepeat, LoopPingPong, PropertyBinding, Euler, Quaternion, AnimationUtils, InterpolateDiscrete, InterpolateLinear, MathUtils, Mesh, PlaneGeometry, ShadowMaterial, HemisphereLight, DirectionalLight, SRGBColorSpace, ACESFilmicToneMapping, WebGLRenderer, Scene, Color, PerspectiveCamera, PCFShadowMap, PCFSoftShadowMap, NumberKeyframeTrack, QuaternionKeyframeTrack, VectorKeyframeTrack, AnimationClip, PMREMGenerator, FloatType, Float32BufferAttribute, BufferAttribute, WebGPUCoordinateSystem, WebGLCoordinateSystem } from 'three';
3
+ import { CC4_HUMANOID_SKELETON_TEMPLATE, HUMANOID_SKELETON_TEMPLATES, DEFAULT_HAIR_COLOR_APPEARANCE, initEmbodyCore, requireInitializedEmbodyCore } from '@lovelace_lol/embody/wasm';
4
+ export { CC4_HUMANOID_SKELETON_TEMPLATE, DEFAULT_AXIS_TO_CHANNEL, DEFAULT_BONE_MAX_DEGREES, DEFAULT_HAIR_COLOR_APPEARANCE, HAIR_COLOR_PRESETS, HUMANOID_SKELETON_TEMPLATES, JOINT_CONTROL_SECTION, VISEME_KEYS } from '@lovelace_lol/embody/wasm';
4
5
  import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
5
6
  import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
6
7
  import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader.js';
@@ -449,6 +450,59 @@ function drawModelForRender(renderer, scene, camera, model) {
449
450
  if (globalShadow && renderer.shadowMap.enabled) globalShadow.needsUpdate = true;
450
451
  };
451
452
  }
453
+ var bindings = /* @__PURE__ */ new WeakMap();
454
+ function bindPlaybackRendering(model, mixer, afterFrame) {
455
+ const binding = { mixer, enabled: true, afterFrame };
456
+ const entries = bindings.get(model) ?? /* @__PURE__ */ new Set();
457
+ entries.add(binding);
458
+ bindings.set(model, entries);
459
+ return {
460
+ setEnabled(enabled) {
461
+ binding.enabled = enabled;
462
+ },
463
+ dispose() {
464
+ entries.delete(binding);
465
+ if (!entries.size) bindings.delete(model);
466
+ }
467
+ };
468
+ }
469
+ function renderScenePlayback(scene, timer) {
470
+ const mixers = /* @__PURE__ */ new Set();
471
+ const active = [];
472
+ scene.traverse((object) => {
473
+ for (const binding of bindings.get(object) ?? []) {
474
+ if (binding.enabled) {
475
+ active.push(binding);
476
+ mixers.add(binding.mixer);
477
+ }
478
+ }
479
+ });
480
+ for (const mixer of mixers) mixer.update(timer.getDelta());
481
+ for (const binding of active) binding.afterFrame();
482
+ }
483
+ function createScenePlaybackFrame(scene, document2) {
484
+ const timer = new Timer();
485
+ if (document2) timer.connect(document2);
486
+ let disposed = false;
487
+ let initialized = false;
488
+ return {
489
+ onFrame(timestamp) {
490
+ if (disposed) return;
491
+ timer.update(timestamp);
492
+ if (!initialized) {
493
+ initialized = true;
494
+ return;
495
+ }
496
+ renderScenePlayback(scene, timer);
497
+ },
498
+ dispose() {
499
+ if (!disposed) {
500
+ disposed = true;
501
+ timer.dispose();
502
+ }
503
+ }
504
+ };
505
+ }
452
506
 
453
507
  // three/annotations/DOMControls.ts
454
508
  var RUNTIME_ANNOTATION_REGION_PREFIX = "runtime:annotation:";
@@ -1111,8 +1165,8 @@ function getAnnotationRegionLabel(region) {
1111
1165
  const trimmed = label.trim();
1112
1166
  return trimmed.length > 0 ? trimmed : void 0;
1113
1167
  }
1114
- function isFiniteClipPoint(point3) {
1115
- return Number.isFinite(point3.x) && Number.isFinite(point3.y) && Number.isFinite(point3.z) && Number.isFinite(point3.w);
1168
+ function isFiniteClipPoint(point2) {
1169
+ return Number.isFinite(point2.x) && Number.isFinite(point2.y) && Number.isFinite(point2.z) && Number.isFinite(point2.w);
1116
1170
  }
1117
1171
  function resolveViewportSafeBounds(params) {
1118
1172
  return requireAnnotationCameraCore().resolveViewportSafeBounds(params);
@@ -3913,9 +3967,9 @@ function resolveRuntimeAnnotationAUBoneTargets(auId, candidates, targetSide) {
3913
3967
  const boneTargets = [];
3914
3968
  for (const candidate of candidates) {
3915
3969
  if (!isPlainRecord(candidate.auToBones)) continue;
3916
- const bindings = candidate.auToBones[auId];
3917
- if (!Array.isArray(bindings)) continue;
3918
- for (const binding of bindings) {
3970
+ const bindings2 = candidate.auToBones[auId];
3971
+ if (!Array.isArray(bindings2)) continue;
3972
+ for (const binding of bindings2) {
3919
3973
  const target = readRuntimeAnnotationBoneTarget(binding);
3920
3974
  if (!target || seen.has(target.boneName)) continue;
3921
3975
  seen.add(target.boneName);
@@ -4079,6 +4133,7 @@ var DPthreeCameraController = class {
4079
4133
  __publicField(this, "domElement");
4080
4134
  // Renderer and render loop (when controller manages the render loop)
4081
4135
  __publicField(this, "renderer", null);
4136
+ __publicField(this, "playbackTimer", new THREE3.Timer());
4082
4137
  __publicField(this, "renderFrame");
4083
4138
  __publicField(this, "resizeRenderer");
4084
4139
  __publicField(this, "onRenderError");
@@ -4189,15 +4244,25 @@ var DPthreeCameraController = class {
4189
4244
  startRenderLoop(propagateFailure = false) {
4190
4245
  if (!this.renderer) return;
4191
4246
  const renderer = this.renderer;
4247
+ this.playbackTimer.disconnect();
4248
+ const ownerDocument = renderer.domElement?.ownerDocument;
4249
+ if (ownerDocument) this.playbackTimer.connect(ownerDocument);
4250
+ this.playbackTimer.reset();
4251
+ let playbackStarted = false;
4192
4252
  try {
4193
- const started = renderer.setAnimationLoop(() => {
4194
- if (this.disposed || this.renderFailed || this.renderingSuspended || this.framePending || renderer !== this.renderer) return;
4253
+ const started = renderer.setAnimationLoop((timestamp) => {
4254
+ if (this.disposed || renderer !== this.renderer) return;
4255
+ this.playbackTimer.update(timestamp);
4256
+ const samplePlayback = playbackStarted;
4257
+ playbackStarted = true;
4258
+ if (this.renderFailed || this.renderingSuspended || this.framePending) return;
4195
4259
  try {
4196
4260
  const preparationDraw = this.modelPreparation?.draw;
4197
4261
  if (preparationDraw) {
4198
4262
  preparationDraw();
4199
4263
  return;
4200
4264
  }
4265
+ if (samplePlayback) renderScenePlayback(this.scene, this.playbackTimer);
4201
4266
  this.update();
4202
4267
  const frame = this.renderFrame ? this.renderFrame(this.renderer, this.scene, this.camera) : this.renderer.render(this.scene, this.camera);
4203
4268
  if (frame) {
@@ -4246,6 +4311,7 @@ var DPthreeCameraController = class {
4246
4311
  * Stop the render loop
4247
4312
  */
4248
4313
  stopRenderLoop() {
4314
+ this.playbackTimer.reset();
4249
4315
  try {
4250
4316
  const stopped = this.renderer?.setAnimationLoop(null);
4251
4317
  if (stopped) void stopped.catch((error) => console.error("Character camera render loop stop failed.", error));
@@ -4331,18 +4397,18 @@ var DPthreeCameraController = class {
4331
4397
  resolve = yes;
4332
4398
  reject = no;
4333
4399
  });
4334
- const request2 = {
4400
+ const request3 = {
4335
4401
  promise,
4336
4402
  draw: null,
4337
4403
  cancel: (reason) => {
4338
4404
  cancelled ?? (cancelled = reason);
4339
4405
  invalidatePreparedShadows?.();
4340
- request2.draw = null;
4406
+ request3.draw = null;
4341
4407
  rejectDraw?.(cancelled);
4342
4408
  }
4343
4409
  };
4344
- this.modelPreparation = request2;
4345
- const abort = () => request2.cancel(renderPreparationAborted());
4410
+ this.modelPreparation = request3;
4411
+ const abort = () => request3.cancel(renderPreparationAborted());
4346
4412
  options.signal?.addEventListener("abort", abort, { once: true });
4347
4413
  const checkCancelled = () => {
4348
4414
  if (cancelled) throw cancelled;
@@ -4361,8 +4427,8 @@ var DPthreeCameraController = class {
4361
4427
  checkCancelled();
4362
4428
  await new Promise((done, failed) => {
4363
4429
  rejectDraw = failed;
4364
- request2.draw = () => {
4365
- request2.draw = null;
4430
+ request3.draw = () => {
4431
+ request3.draw = null;
4366
4432
  try {
4367
4433
  checkCancelled();
4368
4434
  invalidatePreparedShadows = drawModelForRender(renderer, this.scene, this.camera, model);
@@ -4377,7 +4443,7 @@ var DPthreeCameraController = class {
4377
4443
  checkCancelled();
4378
4444
  } finally {
4379
4445
  options.signal?.removeEventListener("abort", abort);
4380
- if (this.modelPreparation === request2) this.modelPreparation = null;
4446
+ if (this.modelPreparation === request3) this.modelPreparation = null;
4381
4447
  }
4382
4448
  })().then(resolve, reject);
4383
4449
  return promise;
@@ -4416,10 +4482,10 @@ var DPthreeCameraController = class {
4416
4482
  */
4417
4483
  async loadRegions(config) {
4418
4484
  if (this.disposed) return;
4419
- const request2 = ++this.regionLoadGeneration;
4485
+ const request3 = ++this.regionLoadGeneration;
4420
4486
  const model = this.model;
4421
4487
  const runtimeConfig = await this.resolveCharacterConfig(config);
4422
- if (!this.isRegionLoadCurrent(request2, model)) return;
4488
+ if (!this.isRegionLoadCurrent(request3, model)) return;
4423
4489
  await this.prepareRegionsAndMarkersForReveal(runtimeConfig);
4424
4490
  }
4425
4491
  /**
@@ -4439,12 +4505,12 @@ var DPthreeCameraController = class {
4439
4505
  async prepareRegionsAndMarkersForReveal(config, beforeReveal) {
4440
4506
  if (this.disposed) return;
4441
4507
  this.prepareRegionState(config);
4442
- const request2 = this.regionLoadGeneration;
4508
+ const request3 = this.regionLoadGeneration;
4443
4509
  const model = this.model;
4444
4510
  await this.loadMarkersForCurrentRegions(true);
4445
- if (!this.isRegionLoadCurrent(request2, model) || this.characterConfig !== config) return;
4511
+ if (!this.isRegionLoadCurrent(request3, model) || this.characterConfig !== config) return;
4446
4512
  if (beforeReveal && !await beforeReveal()) return;
4447
- if (this.isRegionLoadCurrent(request2, model) && this.characterConfig === config) {
4513
+ if (this.isRegionLoadCurrent(request3, model) && this.characterConfig === config) {
4448
4514
  this.startPreparedCameraTransition(config);
4449
4515
  }
4450
4516
  }
@@ -4479,14 +4545,14 @@ var DPthreeCameraController = class {
4479
4545
  return;
4480
4546
  }
4481
4547
  const characterConfig = this.characterConfig;
4482
- const request2 = this.regionLoadGeneration;
4548
+ const request3 = this.regionLoadGeneration;
4483
4549
  const model = this.model;
4484
4550
  this.ensureMarkersForCurrentStyle();
4485
4551
  const markers = this.markers;
4486
4552
  if (!markers) return;
4487
4553
  markers.setVisible(this.markersVisible);
4488
4554
  await markers.loadRegions(characterConfig, { sliceSurfaceQueries });
4489
- if (!this.isRegionLoadCurrent(request2, model) || markers !== this.markers || characterConfig !== this.characterConfig) {
4555
+ if (!this.isRegionLoadCurrent(request3, model) || markers !== this.markers || characterConfig !== this.characterConfig) {
4490
4556
  return;
4491
4557
  }
4492
4558
  if (this.currentRegion) {
@@ -4656,8 +4722,8 @@ var DPthreeCameraController = class {
4656
4722
  * @param zoomDuration - Duration of the final zoom in ms (default: 1500)
4657
4723
  */
4658
4724
  async playIntroAnimation(orbitDuration = 3e3, zoomDuration = 1500) {
4659
- const request2 = await this.beginCameraRequest();
4660
- if (request2 === null) return;
4725
+ const request3 = await this.beginCameraRequest();
4726
+ if (request3 === null) return;
4661
4727
  if (!this.model) {
4662
4728
  return;
4663
4729
  }
@@ -4672,12 +4738,12 @@ var DPthreeCameraController = class {
4672
4738
  const orbitRadius = Math.max(horizontalExtent, verticalExtent) * 1.8;
4673
4739
  const orbitHeight = center.y;
4674
4740
  await this.animateOrbit(center, orbitRadius, orbitHeight, orbitDuration);
4675
- if (!this.isCameraRequestCurrent(request2)) return;
4741
+ if (!this.isCameraRequestCurrent(request3)) return;
4676
4742
  const leftEyeRegion = this.findIntroLeftEyeRegion();
4677
4743
  const leftEyeFocus = leftEyeRegion ? this.calculateIntroLeftEyeFocusPosition(leftEyeRegion) : null;
4678
4744
  if (leftEyeFocus && leftEyeRegion) {
4679
4745
  await this.animateCamera(leftEyeFocus.position, leftEyeFocus.target, zoomDuration);
4680
- if (!this.isCameraRequestCurrent(request2)) return;
4746
+ if (!this.isCameraRequestCurrent(request3)) return;
4681
4747
  this.currentRegion = leftEyeRegion.name;
4682
4748
  this.notifyRegionChange(leftEyeRegion.name);
4683
4749
  return;
@@ -4686,7 +4752,7 @@ var DPthreeCameraController = class {
4686
4752
  const fullBodyRegion = this.regions.find((region) => this.isFullBodyRegion(region));
4687
4753
  const focusPos = this.calculateFullBodyFocusPosition(fullBodyRegion?.paddingFactor, finalAngle, "world");
4688
4754
  await this.animateCamera(focusPos.position, focusPos.target, zoomDuration);
4689
- if (!this.isCameraRequestCurrent(request2)) return;
4755
+ if (!this.isCameraRequestCurrent(request3)) return;
4690
4756
  if (fullBodyRegion) {
4691
4757
  this.currentRegion = fullBodyRegion.name;
4692
4758
  this.notifyRegionChange(fullBodyRegion.name);
@@ -5390,6 +5456,7 @@ var DPthreeCameraController = class {
5390
5456
  this.regionLoadGeneration += 1;
5391
5457
  this.cameraRequestGeneration += 1;
5392
5458
  this.stopRenderLoop();
5459
+ this.playbackTimer.dispose();
5393
5460
  const renderingSettled = this.unbindRendering?.();
5394
5461
  this.unbindRendering = null;
5395
5462
  this.cleanupResizeHandling();
@@ -5703,19 +5770,19 @@ var DPthreeCameraController = class {
5703
5770
  this.laterality = detectAnnotationLaterality(this.model, this.regions, boneResolutionProfile(this.characterConfig));
5704
5771
  }
5705
5772
  /** Resolver and paint continuations belong to one model/configuration load. */
5706
- isRegionLoadCurrent(request2, model) {
5707
- return !this.disposed && request2 === this.regionLoadGeneration && model === this.model;
5773
+ isRegionLoadCurrent(request3, model) {
5774
+ return !this.disposed && request3 === this.regionLoadGeneration && model === this.model;
5708
5775
  }
5709
5776
  /** Await Wasm once per request and abandon requests superseded during initialization. */
5710
5777
  async beginCameraRequest() {
5711
- const request2 = ++this.cameraRequestGeneration;
5778
+ const request3 = ++this.cameraRequestGeneration;
5712
5779
  this.cancelCameraAnimation();
5713
5780
  if (this.disposed) return null;
5714
5781
  await getAnnotationCameraCore();
5715
- return this.isCameraRequestCurrent(request2) ? request2 : null;
5782
+ return this.isCameraRequestCurrent(request3) ? request3 : null;
5716
5783
  }
5717
- isCameraRequestCurrent(request2) {
5718
- return !this.disposed && request2 === this.cameraRequestGeneration;
5784
+ isCameraRequestCurrent(request3) {
5785
+ return !this.disposed && request3 === this.cameraRequestGeneration;
5719
5786
  }
5720
5787
  cancelCameraAnimation() {
5721
5788
  this.timerAnimationFallbackToken += 1;
@@ -6448,6 +6515,99 @@ function pickContinuumAnnotationAuId(value, negId, posId, stickyId) {
6448
6515
  if (value > 0) return posId;
6449
6516
  return negId;
6450
6517
  }
6518
+ var json = (value) => JSON.stringify(value ?? {});
6519
+ function request2(op, payload = {}) {
6520
+ return JSON.parse(requireInitializedEmbodyCore().embody_request(json({ op, payload })));
6521
+ }
6522
+ var getPreset = (id) => request2("preset.get", { id });
6523
+ var extendCharacterConfigWithPreset = (config) => request2("profile.extendConfig", { config });
6524
+ var extractProfileOverrides = (config) => request2("profile.extractOverrides", { config });
6525
+ var mergeCharacterRegionsByName = (base, override) => request2("profile.mergeRegions", { base, override });
6526
+ var getMeshNamesForAUProfile = (profile, auId) => request2("profile.getMeshNamesForAU", { profile, auId });
6527
+ var getHumanoidSpecification = () => request2("humanoid.getSpecification");
6528
+ var setAUMorphTargets = (profile, auId, side, targets) => request2("profile.setAUMorphTargets", { profile, auId, side, targets });
6529
+ var setHumanoidRoleBinding = (profile, role, boneName) => request2("profile.setHumanoidRoleBinding", { profile, role, boneName });
6530
+ var resolveHumanoidCharacterization = (profile) => request2("profile.resolveHumanoidCharacterization", { profile });
6531
+ var hasLeftRightMorphs = (profile, auId) => request2("profile.hasLeftRightMorphs", { profile, auId });
6532
+ var isMixedAU = (profile, auId) => request2("profile.isMixedAU", { profile, auId });
6533
+ var resolveVisemeProfile = (profile) => request2("profile.resolveVisemes", { profile });
6534
+ var isMaxDegreesOnlyAxisBindingUpdate = (update) => request2("bone.isMaxDegreesOnlyUpdate", { update });
6535
+ var findNodeKeyForBone = (boneName, profile) => profile ? request2("bone.findNodeKey", { profile, boneName }) : null;
6536
+ var ensureBoneNodeKey = (profile, boneName) => request2("bone.ensureNodeKey", { profile, boneName });
6537
+ var ensureBilateralBoneNodeKeys = (profile, leftBoneName, rightBoneName) => request2("bone.ensureBilateralNodeKeys", { profile, leftBoneName, rightBoneName });
6538
+ var resolveBoneNameForNodeKey = (profile, nodeKey) => request2("bone.resolveBoneName", { profile, nodeKey });
6539
+ var stripConfiguredBoneAffixes = (profile, boneName) => request2("bone.stripAffixes", { profile: profile ?? {}, boneName });
6540
+ var inferChiralBoneNamePair = (boneNames, selectedBoneName) => request2("bone.inferChiralPair", { boneNames, selectedBoneName });
6541
+ var formatAxisLabel = (axis) => request2("bone.formatAxisLabel", { axis });
6542
+ var formatAxisDirectionLabel = (axis, direction) => request2("bone.formatDirectionLabel", { axis, direction });
6543
+ var getAxisFromChannel = (channel) => channel ? request2("bone.getAxisFromChannel", { channel }) : null;
6544
+ var getBoneAxisBindingState = (profile, boneName, axis) => request2("bone.getAxisState", { profile, boneName, axis });
6545
+ var resolveBoneAxisChannel = (profile, boneName, axis) => request2("bone.resolveAxisChannel", { profile, boneName, axis });
6546
+ var getBilateralAxisBindingState = (profile, boneName, axis) => request2("bone.getBilateralAxisState", { profile, boneName, axis });
6547
+ var getAUBoneBindingState = (profile, auId) => request2("bone.getAUBindingState", { profile, auId });
6548
+ var inferEyeControlScope = (profile, binding) => request2("bone.inferEyeScope", { profile, binding });
6549
+ var inferEyeControlFamily = (binding) => request2("bone.inferEyeFamily", { binding });
6550
+ var applyBoneAxisBindingUpdate = (profile, boneName, axis, update) => request2("bone.applyAxisUpdate", { profile, boneName, axis, update });
6551
+ var applyBilateralAxisBindingUpdate = (profile, boneName, axis, scope, update) => request2("bone.applyBilateralAxisUpdate", { profile, boneName, axis, scope, update });
6552
+ var applyAUBoneBindingUpdate = (profile, auId, update) => request2("bone.applyAUBindingUpdate", { profile, auId, update });
6553
+ var createBoneAxisAu = (profile, boneName, axis, direction, options = {}) => request2("bone.createAxisAU", { profile, boneName, axis, direction, name: options.name });
6554
+ var createBilateralBoneAxisAu = (profile, boneName, axis, scope, direction, options = {}) => request2("bone.createBilateralAxisAU", { profile, boneName, axis, scope, direction, name: options.name });
6555
+ var buildBoneAuOptions = (profile) => request2("bone.buildAUOptions", { profile });
6556
+ var isJointControlAuInfo = (info) => request2("bone.isJointControlInfo", { info });
6557
+ var classifyAuAsJointControl = (profile, auId, options = {}) => request2("bone.classifyJointControl", { profile, auId, boneName: options.boneName, nodeKey: options.nodeKey });
6558
+ var resolveContinuumDisplayLabel = (profile, negativeAuId, positiveAuId) => request2("bone.resolveContinuumLabel", { profile, negativeAuId, positiveAuId }) ?? `AU ${negativeAuId} <-> AU ${positiveAuId}`;
6559
+ function inspectModel(model, meshes, profile) {
6560
+ return new ThreeModelInspector().inspectModel(model, { meshes, profile });
6561
+ }
6562
+ function getBodyControls(profile, model) {
6563
+ return request2("profile.getBodyControls", { profile, ...model ? { model: inspectModel(model, void 0, profile).descriptor } : {} });
6564
+ }
6565
+ function extractModelData(model, meshes, animations = []) {
6566
+ const inspection = inspectModel(model, meshes);
6567
+ return JSON.parse(requireInitializedEmbodyCore().extract_model_data_json(json(inspection.descriptor), json(serializeAnimationClips(model, animations, inspection))));
6568
+ }
6569
+ async function analyzeModel(options) {
6570
+ const source = options.source;
6571
+ const model = source.type === "gltf" ? source.gltf.scene ?? source.gltf.scenes[0] : source.model;
6572
+ const animations = source.type === "gltf" ? source.gltf.animations : source.animations ?? [];
6573
+ const inspection = inspectModel(model, source.type === "runtime" ? source.meshes : void 0);
6574
+ return JSON.parse(requireInitializedEmbodyCore().analyze_model_descriptor(json(inspection.descriptor), json(serializeAnimationClips(model, animations, inspection)), options.preset ? json(options.preset) : "", json({ suggestCorrections: Boolean(options.suggestCorrections) })));
6575
+ }
6576
+ function validateMappings(meshes, skeleton, profile, options = {}) {
6577
+ let nextMorphId = 1;
6578
+ const morphTargets = [];
6579
+ const descriptorMeshes = (meshes ?? []).map((value, index) => {
6580
+ const mesh = value;
6581
+ const id = index + 1;
6582
+ const morphTargetIds = Object.entries(mesh.morphTargetDictionary ?? mesh.geometry?.morphTargetDictionary ?? {}).map(([name, hostIndex]) => {
6583
+ const morphId = nextMorphId++;
6584
+ morphTargets.push({ id: morphId, meshId: id, name, hostIndex });
6585
+ return morphId;
6586
+ });
6587
+ return { id, name: mesh.name ?? "", morphTargetIds, visible: true };
6588
+ });
6589
+ const bones = (skeleton?.bones ?? []).map((bone, index) => ({ id: index + 1, name: typeof bone === "string" ? bone : bone.name ?? "" }));
6590
+ return JSON.parse(requireInitializedEmbodyCore().validate_profile_model(json(profile), json({ meshes: descriptorMeshes, morphTargets, bones, objects: [] }), json(options)));
6591
+ }
6592
+ function validateHumanoidCharacterization(model, profile) {
6593
+ return JSON.parse(requireInitializedEmbodyCore().validate_humanoid_characterization(json(profile), json(inspectModel(model, void 0, profile).descriptor)));
6594
+ }
6595
+ function normalizeHairColorAppearance(value, fallback = DEFAULT_HAIR_COLOR_APPEARANCE) {
6596
+ return JSON.parse(requireInitializedEmbodyCore().normalize_hair_color_appearance_json(json(value), json(fallback)));
6597
+ }
6598
+ var getHumanoidSkeletonTemplate = (id) => HUMANOID_SKELETON_TEMPLATES.find((template) => template.id === id) ?? null;
6599
+ function getHumanoidSkeletonTemplateBoneNames(template = CC4_HUMANOID_SKELETON_TEMPLATE) {
6600
+ return JSON.parse(requireInitializedEmbodyCore().humanoid_skeleton_template_bone_names(json(template)));
6601
+ }
6602
+ function createValidationSkeletonFromHumanoidTemplate(template = CC4_HUMANOID_SKELETON_TEMPLATE) {
6603
+ return JSON.parse(requireInitializedEmbodyCore().create_validation_skeleton_json(json(template)));
6604
+ }
6605
+ function computeHumanoidSkeletonTemplateRestBounds(template) {
6606
+ return Array.from(requireInitializedEmbodyCore().compute_humanoid_skeleton_template_rest_bounds(json(template)));
6607
+ }
6608
+ function extractHumanoidSkeletonTemplateFromModel(model, options) {
6609
+ return JSON.parse(requireInitializedEmbodyCore().extract_humanoid_skeleton_template_json(json(inspectModel(model).descriptor), json(options)));
6610
+ }
6451
6611
  var isBone = (object) => !!(object.isBone || object.type === "Bone");
6452
6612
  var finite = (values, description) => {
6453
6613
  if (!values.every(Number.isFinite)) {
@@ -6558,332 +6718,1667 @@ function extendModelReferencePose(model, previous) {
6558
6718
  }
6559
6719
  function bindModelReferencePose(model, referencePose) {
6560
6720
  if (referencePose.version !== 1) throw new Error("Unsupported model reference pose version");
6561
- const bindings = /* @__PURE__ */ new Map();
6721
+ const bindings2 = /* @__PURE__ */ new Map();
6562
6722
  let index = 0;
6563
6723
  const bind = (object, path, parentPath) => {
6564
6724
  const node = referencePose.nodes[index++];
6565
6725
  if (!matchesNode(object, node, path, parentPath) || node.childCount !== object.children.length) {
6566
6726
  throw incompatible(object, path);
6567
6727
  }
6568
- bindings.set(object, node);
6728
+ bindings2.set(object, node);
6569
6729
  object.children.forEach((child, childIndex) => bind(child, `${path}/${childIndex}`, path));
6570
6730
  };
6571
6731
  bind(model, "", null);
6572
6732
  if (index !== referencePose.nodes.length) throw new Error("Incompatible reference pose hierarchy: extra captured nodes");
6573
- return bindings;
6574
- }
6575
- var EPSILON = 1e-8;
6576
- var finite2 = (value, fallback = 0) => typeof value === "number" && Number.isFinite(value) ? value : fallback;
6577
- var bounded = (value) => Math.max(-1, Math.min(1, finite2(value)));
6578
- var contribution = (value) => Math.max(0, Math.min(1, finite2(value, 1)));
6579
- var point2 = (value) => ({ x: value.x, y: value.y, z: value.z });
6580
- var vector = (value) => new Vector3(finite2(value?.x), finite2(value?.y), finite2(value?.z));
6581
- var axisVector = (channel) => channel === "rx" ? new Vector3(1, 0, 0) : channel === "ry" ? new Vector3(0, 1, 0) : channel === "rz" ? new Vector3(0, 0, 1) : void 0;
6582
- var ThreeGazeFocus = class {
6583
- constructor(model, profile, options = {}) {
6584
- this.model = model;
6585
- this.profile = profile;
6586
- __publicField(this, "head");
6587
- __publicField(this, "eyes", []);
6588
- __publicField(this, "saved", /* @__PURE__ */ new Map());
6589
- __publicField(this, "references");
6590
- __publicField(this, "limits");
6591
- this.references = bindModelReferencePose(model, options.referencePose ?? captureModelReferencePose(model));
6592
- this.head = this.joint("HEAD", "head", [51, 52, 53, 54, 56, 55]);
6593
- this.eyes = [
6594
- this.joint("EYE_L", "leftEye", [61, 62, 63, 64]),
6595
- this.joint("EYE_R", "rightEye", [61, 62, 63, 64])
6596
- ].filter((value) => !!value);
6597
- this.limits = {
6598
- headYaw: this.capacity(51, 52),
6599
- headPitch: this.capacity(53, 54),
6600
- eyeYaw: this.capacity(61, 62),
6601
- eyePitch: this.capacity(63, 64)
6602
- };
6733
+ return bindings2;
6734
+ }
6735
+ function withComponentTracks(clip) {
6736
+ let expanded = false;
6737
+ const tracks = clip.tracks.flatMap((track) => {
6738
+ const parsed = PropertyBinding.parseTrackName(track.name);
6739
+ const euler = parsed.propertyName === "rotation";
6740
+ if (!euler && !["morphTargetInfluences", "weights"].includes(parsed.propertyName) || parsed.propertyIndex !== void 0) return [track];
6741
+ const cubic = track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true;
6742
+ const parts = cubic ? 3 : 1;
6743
+ const width = track.getValueSize() / parts;
6744
+ if (!Number.isInteger(width) || width < 1 || euler && width !== 3) throw new Error(`Invalid component track ${JSON.stringify(track.name)}.`);
6745
+ expanded = true;
6746
+ return Array.from({ length: width }, (_, component) => {
6747
+ const scalar = track.clone();
6748
+ scalar.name = `${track.name}[${euler ? ["x", "y", "z"][component] : component}]`;
6749
+ scalar.values = track.values.slice(0, track.times.length * parts);
6750
+ for (let sample = 0; sample < scalar.values.length; sample += 1) scalar.values[sample] = track.values[sample * width + component];
6751
+ return scalar;
6752
+ });
6753
+ });
6754
+ if (!expanded) return clip;
6755
+ const indexed = clip.clone();
6756
+ indexed.tracks = tracks;
6757
+ return indexed;
6758
+ }
6759
+ function concreteTrackName(target, inspection) {
6760
+ if (!target) return void 0;
6761
+ if (target.kind === "morphTarget") {
6762
+ const binding = inspection.morphBindings.get(Number(target.morphTargetId));
6763
+ return binding && `${binding.mesh.uuid}.morphTargetInfluences[${binding.index}]`;
6764
+ }
6765
+ if (target.kind === "boneTransform" || target.kind === "objectTransform") {
6766
+ const object = target.kind === "boneTransform" ? inspection.boneBindings.get(Number(target.boneId)) : inspection.objectBindings.get(Number(target.objectId));
6767
+ const property = target.property ?? "rotation";
6768
+ if (!object) return void 0;
6769
+ if (property === "rotation" || property === "quaternion") return `${object.uuid}.quaternion`;
6770
+ if (property === "eulerX" || property === "eulerY" || property === "eulerZ") return `${object.uuid}.rotation[${property.slice(-1).toLowerCase()}]`;
6771
+ if (property === "position" || property === "scale") return `${object.uuid}.${property}`;
6603
6772
  }
6604
- name(node) {
6605
- const base = this.profile.boneNodes?.[node] ?? node;
6606
- const prefix = this.profile.bonePrefix ?? "";
6607
- const suffix = this.profile.boneSuffix ?? "";
6608
- return `${base.startsWith(prefix) ? "" : prefix}${base}${base.endsWith(suffix) ? "" : suffix}`;
6609
- }
6610
- binding(node, id) {
6611
- const binding = this.profile.auToBones?.[id]?.find((candidate) => this.name(candidate.node) === this.name(node));
6612
- const axis = binding && axisVector(binding.channel);
6613
- const radians = finite2(binding?.maxDegrees) * finite2(binding?.scale, 1) * Math.PI / 180;
6614
- return axis && Math.abs(radians) > EPSILON ? { axis, radians } : void 0;
6615
- }
6616
- capacity(positive, negative) {
6617
- const magnitude = (id) => {
6618
- const seen = /* @__PURE__ */ new Set();
6619
- const values = [];
6620
- for (const row of this.profile.auToBones?.[id] ?? []) {
6621
- const name = this.name(row.node);
6622
- if (!axisVector(row.channel) || seen.has(name)) continue;
6623
- seen.add(name);
6624
- values.push(Math.abs(finite2(row.maxDegrees) * finite2(row.scale, 1)));
6773
+ if (target.kind === "meshVisibility") {
6774
+ const mesh = inspection.meshBindings.get(Number(target.meshId));
6775
+ return mesh && `${mesh.uuid}.visible`;
6776
+ }
6777
+ return void 0;
6778
+ }
6779
+ function cloneWithConcreteTrackNames(clip, tracks, inspection) {
6780
+ const native = clip.clone();
6781
+ for (let index = 0; index < tracks.length; index += 1) {
6782
+ const name = concreteTrackName(tracks[index].target, inspection);
6783
+ if (!name) throw new Error("Every native playback track must resolve on the bound model.");
6784
+ native.tracks[index].name = name;
6785
+ }
6786
+ return native;
6787
+ }
6788
+
6789
+ // three/nativePlayback.ts
6790
+ var sampleSize = (track) => track.getValueSize() / (track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ? 3 : 1);
6791
+ var asError = (error) => error instanceof Error ? error : new Error(String(error));
6792
+ var blendMode = (mode) => mode === "additive" ? AdditiveAnimationBlendMode : NormalAnimationBlendMode;
6793
+ var loopMode = (mode) => mode === "once" ? LoopOnce : mode === "repeat" ? LoopRepeat : LoopPingPong;
6794
+ function validateBinding(binding) {
6795
+ if (!binding.model?.isObject3D || binding.mixer && binding.mixer.getRoot() !== binding.model) {
6796
+ throw new Error("Native playback requires a Three model and its render integration mixer.");
6797
+ }
6798
+ const objects = /* @__PURE__ */ new Set();
6799
+ binding.model.traverse((object) => objects.add(object));
6800
+ const { inspection } = binding;
6801
+ for (const object of [
6802
+ ...inspection.meshBindings.values(),
6803
+ ...inspection.boneBindings.values(),
6804
+ ...inspection.objectBindings.values(),
6805
+ ...Array.from(inspection.morphBindings.values(), (entry) => entry.mesh)
6806
+ ]) {
6807
+ if (!objects.has(object)) throw new Error("Native playback inspection contains an object outside the bound model.");
6808
+ }
6809
+ }
6810
+ var ThreeNativePlaybackConnector = class {
6811
+ constructor(session, binding) {
6812
+ this.session = session;
6813
+ __publicField(this, "binding");
6814
+ __publicField(this, "rendering");
6815
+ __publicField(this, "renderingEnabled", true);
6816
+ __publicField(this, "resources", /* @__PURE__ */ new Map());
6817
+ __publicField(this, "actionHandles", /* @__PURE__ */ new Map());
6818
+ __publicField(this, "listeners", /* @__PURE__ */ new Set());
6819
+ __publicField(this, "pending", []);
6820
+ __publicField(this, "notifications", []);
6821
+ __publicField(this, "depth", 0);
6822
+ __publicField(this, "flushingNotifications", false);
6823
+ __publicField(this, "notificationScheduled", false);
6824
+ __publicField(this, "sessionDisposed", false);
6825
+ __publicField(this, "disposed", false);
6826
+ __publicField(this, "onError");
6827
+ __publicField(this, "onRelease");
6828
+ __publicField(this, "finished", (event) => {
6829
+ const handle = this.actionHandles.get(event.action);
6830
+ if (!handle || this.disposed) return;
6831
+ this.notifications.push({ type: this.resources.get(handle)?.fadingOut ? "cancelled" : "completed", handle });
6832
+ if (this.notificationScheduled) return;
6833
+ this.notificationScheduled = true;
6834
+ queueMicrotask(() => {
6835
+ this.notificationScheduled = false;
6836
+ if (this.disposed) return;
6837
+ try {
6838
+ this.flushNotifications();
6839
+ } catch (error) {
6840
+ const failure = asError(error);
6841
+ if (this.onError) this.onError(failure);
6842
+ else throw failure;
6843
+ }
6844
+ });
6845
+ });
6846
+ validateBinding(binding);
6847
+ this.binding = { ...binding, mixer: binding.mixer ?? new AnimationMixer(binding.model) };
6848
+ this.onError = binding.onError;
6849
+ this.onRelease = binding.onRelease;
6850
+ this.binding.mixer.addEventListener("finished", this.finished);
6851
+ this.rendering = bindPlaybackRendering(binding.model, this.binding.mixer, () => this.flushEvents());
6852
+ }
6853
+ /** Prepare bindings first; old actions are released before the new binding is exposed. */
6854
+ rebind(modelKey, profileKey, binding = this.binding) {
6855
+ validateBinding(binding);
6856
+ this.beforeOperation();
6857
+ this.dispatch(this.session.rebind(modelKey, profileKey), void 0, () => {
6858
+ this.binding.mixer.removeEventListener("finished", this.finished);
6859
+ this.rendering.dispose();
6860
+ this.binding = { ...binding, mixer: binding.mixer ?? new AnimationMixer(binding.model) };
6861
+ this.binding.mixer.addEventListener("finished", this.finished);
6862
+ this.rendering = bindPlaybackRendering(binding.model, this.binding.mixer, () => this.flushEvents());
6863
+ this.rendering.setEnabled(this.renderingEnabled);
6864
+ });
6865
+ }
6866
+ play(clip, options = {}) {
6867
+ this.beforeOperation();
6868
+ const native = createAnimationClipFromClipIR(clip, this.binding.inspection);
6869
+ if (native.tracks.length !== clip.tracks.length) {
6870
+ throw new Error("Every playback track must resolve on the bound model.");
6871
+ }
6872
+ return this.dispatch(this.session.play(JSON.stringify(clip), JSON.stringify(options)), native).handle;
6873
+ }
6874
+ /**
6875
+ * Validate native track bindings through the existing serializer, then retain
6876
+ * the native clone's interpolants and authored/additive sample values. Concrete
6877
+ * binding names match compiled tracks so Three shares their PropertyMixer.
6878
+ */
6879
+ playNativeClip(clip, options = {}) {
6880
+ this.beforeOperation();
6881
+ clip = withComponentTracks(clip);
6882
+ const [ir] = serializeAnimationClips(this.binding.model, [clip], this.binding.inspection);
6883
+ if (ir.tracks.length !== clip.tracks.length) {
6884
+ throw new Error("Every native playback track must serialize against the bound model.");
6885
+ }
6886
+ const native = cloneWithConcreteTrackNames(clip, ir.tracks, this.binding.inspection);
6887
+ const settings = {
6888
+ ...options,
6889
+ blendMode: options.blendMode ?? (clip.blendMode === AdditiveAnimationBlendMode ? "additive" : "normal")
6890
+ };
6891
+ return this.dispatch(this.session.play(JSON.stringify(ir), JSON.stringify(settings)), native).handle;
6892
+ }
6893
+ control(handle, control) {
6894
+ this.beforeOperation();
6895
+ this.dispatch(this.session.control(handle, JSON.stringify(control)));
6896
+ }
6897
+ setRendering(enabled) {
6898
+ this.beforeOperation();
6899
+ if (enabled === this.renderingEnabled) return;
6900
+ this.renderingEnabled = enabled;
6901
+ this.rendering.setEnabled(enabled);
6902
+ for (const resource of this.resources.values()) {
6903
+ if (!resource.action) continue;
6904
+ if (!enabled) {
6905
+ resource.suspendedPaused = resource.action.paused;
6906
+ this.pauseFade(resource);
6907
+ resource.action.paused = true;
6908
+ } else if (resource.suspendedPaused !== void 0) {
6909
+ resource.action.paused = resource.suspendedPaused;
6910
+ if (!resource.explicitlyPaused) this.resumeFade(resource);
6911
+ resource.suspendedPaused = void 0;
6912
+ }
6913
+ }
6914
+ }
6915
+ setTimeScale(value) {
6916
+ this.beforeOperation();
6917
+ if (!Number.isFinite(value)) throw new Error("Native mixer speed must be finite.");
6918
+ this.binding.mixer.timeScale = value;
6919
+ }
6920
+ fadeIn(handle, seconds) {
6921
+ this.control(handle, { type: "fadeIn", seconds });
6922
+ }
6923
+ fadeOut(handle, seconds) {
6924
+ this.control(handle, { type: "fadeOut", seconds });
6925
+ }
6926
+ /** Edit authored samples, retaining the native action and its loop/fade progress. */
6927
+ replaceClip(handle, clip) {
6928
+ this.beforeOperation();
6929
+ clip = withComponentTracks(clip);
6930
+ const resource = this.resources.get(handle);
6931
+ if (!resource) throw new Error("Unknown, foreign or stale playback handle.");
6932
+ const [ir] = serializeAnimationClips(this.binding.model, [clip], this.binding.inspection);
6933
+ if (ir.tracks.length !== clip.tracks.length) throw new Error("Every edited track must resolve on the bound model.");
6934
+ const native = cloneWithConcreteTrackNames(clip, ir.tracks, this.binding.inspection);
6935
+ if (native.tracks.length !== resource.clip.tracks.length || native.tracks.some((track, index) => {
6936
+ const old = resource.clip.tracks[index];
6937
+ return track.name !== old.name || track.ValueTypeName !== old.ValueTypeName || sampleSize(track) !== sampleSize(old);
6938
+ })) throw new Error("Editing samples must preserve track bindings; play a new clip to change its bindings.");
6939
+ const editable = resource.action;
6940
+ if (!editable || !Array.isArray(editable._interpolants) || editable._interpolants.length !== native.tracks.length) {
6941
+ throw new Error("This Three version does not support editing native action samples.");
6942
+ }
6943
+ this.dispatch(this.session.replace_clip(handle, JSON.stringify(ir)), native);
6944
+ }
6945
+ /** Native state for the owning adapter; never exposed through Polymer. */
6946
+ getAction(handle) {
6947
+ return this.resources.get(handle)?.action;
6948
+ }
6949
+ /** Deliver native completion after the borrowed mixer has finished sampling. */
6950
+ flushEvents() {
6951
+ if (this.disposed) return;
6952
+ this.notificationScheduled = false;
6953
+ for (const [handle, resource] of this.resources) {
6954
+ if (resource.fadingOut && resource.action?.getEffectiveWeight() === 0) {
6955
+ resource.fadingOut = false;
6956
+ this.notifications.push({ type: "cancelled", handle });
6625
6957
  }
6626
- return values.length ? Math.min(...values) : 0;
6958
+ }
6959
+ this.flushNotifications();
6960
+ }
6961
+ subscribe(listener) {
6962
+ if (this.disposed) throw new Error("Native playback connector is disposed.");
6963
+ this.listeners.add(listener);
6964
+ return () => {
6965
+ this.listeners.delete(listener);
6627
6966
  };
6628
- return { positive: magnitude(positive), negative: magnitude(negative) };
6629
6967
  }
6630
- joint(node, calibration, ids) {
6631
- const object = this.model.getObjectByName(this.name(node));
6632
- if (!object) return void 0;
6633
- const yaw = { positive: this.binding(node, ids[0]), negative: this.binding(node, ids[1]) };
6634
- const pitch = { positive: this.binding(node, ids[2]), negative: this.binding(node, ids[3]) };
6635
- const roll = { positive: this.binding(node, ids[4]), negative: this.binding(node, ids[5]) };
6636
- const explicit = this.profile.gazeCalibration?.[calibration]?.opticalAxis;
6637
- let optical = explicit ? vector(explicit) : new Vector3();
6638
- if (optical.lengthSq() < EPSILON) {
6639
- const positiveAxis = (axis) => axis.positive ? axis.positive.axis.clone().multiplyScalar(Math.sign(axis.positive.radians)) : axis.negative?.axis.clone().multiplyScalar(-Math.sign(axis.negative.radians));
6640
- const yawAxis = positiveAxis(yaw);
6641
- const pitchAxis = positiveAxis(pitch);
6642
- if (yawAxis && pitchAxis) optical.crossVectors(yawAxis, pitchAxis);
6643
- }
6644
- if (optical.lengthSq() < EPSILON) return void 0;
6645
- const reference = this.references.get(object);
6646
- const ancestors = [];
6647
- for (let parent = object.parent; parent && parent !== this.model; parent = parent.parent) ancestors.push(parent);
6648
- const referenceParent = new Matrix4();
6649
- for (const parent of ancestors.reverse()) referenceParent.multiply(new Matrix4().fromArray(this.references.get(parent).localMatrix));
6650
- const rotation = reference.transform.rotation;
6651
- return {
6652
- object,
6653
- optical: optical.normalize(),
6654
- yaw,
6655
- pitch,
6656
- roll,
6657
- reference: new Quaternion(rotation.x, rotation.y, rotation.z, rotation.w),
6658
- referenceParent,
6659
- referenceScale: vector(reference.transform.scale)
6968
+ dispose() {
6969
+ if (this.disposed) return;
6970
+ this.retryPending();
6971
+ if (!this.sessionDisposed) {
6972
+ const batch = this.session.dispose();
6973
+ this.sessionDisposed = true;
6974
+ this.dispatch(batch);
6975
+ }
6976
+ this.binding.mixer.removeEventListener("finished", this.finished);
6977
+ this.rendering.dispose();
6978
+ this.notifications.length = 0;
6979
+ this.listeners.clear();
6980
+ this.session.free();
6981
+ this.disposed = true;
6982
+ }
6983
+ pauseFade(resource) {
6984
+ const action = resource.action;
6985
+ const fade = action?._weightInterpolant;
6986
+ if (!action || !fade) return;
6987
+ resource.pausedFade = {
6988
+ seconds: Math.max(0, fade.parameterPositions[1] - resource.binding.mixer.time),
6989
+ from: fade.evaluate(resource.binding.mixer.time)[0],
6990
+ to: fade.sampleValues[1],
6991
+ weight: action.weight
6660
6992
  };
6993
+ action.stopFading();
6994
+ action.setEffectiveWeight(resource.pausedFade.weight * resource.pausedFade.from);
6995
+ }
6996
+ resumeFade(resource) {
6997
+ const action = resource.action;
6998
+ const fade = resource.pausedFade;
6999
+ if (!action || !fade) return;
7000
+ resource.pausedFade = void 0;
7001
+ action.setEffectiveWeight(fade.weight);
7002
+ action.fadeIn(fade.seconds);
7003
+ const interpolant = action._weightInterpolant;
7004
+ interpolant.sampleValues[0] = fade.from;
7005
+ interpolant.sampleValues[1] = fade.to;
7006
+ }
7007
+ beforeOperation() {
7008
+ if (this.disposed || this.sessionDisposed) throw new Error("Native playback connector is disposed.");
7009
+ this.retryPending();
7010
+ }
7011
+ retryPending() {
7012
+ if (this.pending.length) this.drain();
7013
+ }
7014
+ dispatch(serialized, clip, afterCommands) {
7015
+ const batch = JSON.parse(serialized);
7016
+ this.pending.push({ batch, nextCommand: 0, clip, afterCommands });
7017
+ this.drain();
7018
+ return batch;
7019
+ }
7020
+ drain() {
7021
+ const errors = [];
7022
+ this.depth += 1;
7023
+ try {
7024
+ while (this.pending.length) {
7025
+ const pending = this.pending[0];
7026
+ while (pending.nextCommand < pending.batch.commands.length) {
7027
+ const command = pending.batch.commands[pending.nextCommand];
7028
+ try {
7029
+ this.execute(command, pending.clip);
7030
+ } catch (error) {
7031
+ if (command.type === "release") throw asError(error);
7032
+ const failure = asError(error);
7033
+ errors.push(failure);
7034
+ this.notifications.push({ type: "error", handle: command.handle, message: failure.message || "Native operation failed." });
7035
+ }
7036
+ pending.nextCommand += 1;
7037
+ }
7038
+ pending.afterCommands?.();
7039
+ this.pending.shift();
7040
+ for (const event of pending.batch.events) {
7041
+ for (const listener of [...this.listeners]) {
7042
+ try {
7043
+ listener(event);
7044
+ } catch (error) {
7045
+ const failure = asError(error);
7046
+ queueMicrotask(() => {
7047
+ if (this.onError) this.onError(failure);
7048
+ else throw failure;
7049
+ });
7050
+ }
7051
+ }
7052
+ }
7053
+ }
7054
+ } finally {
7055
+ this.depth -= 1;
7056
+ }
7057
+ if (this.depth === 0 && !this.flushingNotifications) this.flushNotifications();
7058
+ if (errors.length) throw errors[0];
7059
+ }
7060
+ execute(command, preparedClip) {
7061
+ if (command.type === "release") {
7062
+ const resource2 = this.resources.get(command.handle);
7063
+ if (!resource2) return;
7064
+ resource2.action?.stop();
7065
+ resource2.binding.mixer.uncacheAction(resource2.clip, resource2.binding.model);
7066
+ resource2.binding.mixer.uncacheClip(resource2.clip);
7067
+ if (resource2.action) this.actionHandles.delete(resource2.action);
7068
+ this.resources.delete(command.handle);
7069
+ try {
7070
+ this.onRelease?.(command.handle);
7071
+ } catch (error) {
7072
+ const failure = asError(error);
7073
+ queueMicrotask(() => {
7074
+ if (this.onError) this.onError(failure);
7075
+ else throw failure;
7076
+ });
7077
+ }
7078
+ return;
7079
+ }
7080
+ if (command.type === "replaceClip") {
7081
+ const resource2 = this.resources.get(command.handle);
7082
+ if (!resource2 || !preparedClip) throw new Error("Native clip edit has no owned resource.");
7083
+ const action2 = resource2.action;
7084
+ const tracks = preparedClip.tracks.map((track) => track.clone());
7085
+ const interpolants = tracks.map((track, index) => {
7086
+ const interpolant = track.createInterpolant(action2._interpolants[index].resultBuffer);
7087
+ if (interpolant.settings) Object.assign(action2._interpolantSettings, interpolant.settings);
7088
+ interpolant.settings = action2._interpolantSettings;
7089
+ return interpolant;
7090
+ });
7091
+ resource2.clip.tracks = tracks;
7092
+ action2._interpolants = interpolants;
7093
+ return;
7094
+ }
7095
+ if (command.type === "play") {
7096
+ if (!preparedClip) throw new Error("Native playback has no prepared clip.");
7097
+ const resource2 = { clip: preparedClip, binding: this.binding };
7098
+ this.resources.set(command.handle, resource2);
7099
+ const settings = command.settings;
7100
+ const action2 = this.binding.mixer.clipAction(preparedClip, this.binding.model, blendMode(settings.blendMode));
7101
+ resource2.action = action2;
7102
+ this.actionHandles.set(action2, command.handle);
7103
+ action2.setLoop(loopMode(settings.loop.mode), settings.loop.count ?? Infinity);
7104
+ action2.clampWhenFinished = settings.finalPose === "hold";
7105
+ action2.setEffectiveTimeScale(settings.speed);
7106
+ action2.setEffectiveWeight(settings.weight);
7107
+ action2.time = settings.startSeconds;
7108
+ if (!this.renderingEnabled) {
7109
+ resource2.suspendedPaused = false;
7110
+ action2.paused = true;
7111
+ }
7112
+ action2.play();
7113
+ return;
7114
+ }
7115
+ const resource = this.resources.get(command.handle);
7116
+ const action = resource?.action;
7117
+ if (!resource || !action) throw new Error("Native playback action is unavailable.");
7118
+ const control = command.control;
7119
+ switch (control.type) {
7120
+ case "pause":
7121
+ resource.explicitlyPaused = true;
7122
+ this.pauseFade(resource);
7123
+ action.paused = true;
7124
+ if (!this.renderingEnabled) this.resources.get(command.handle).suspendedPaused = true;
7125
+ break;
7126
+ case "resume":
7127
+ resource.explicitlyPaused = false;
7128
+ if (this.renderingEnabled) {
7129
+ action.paused = false;
7130
+ this.resumeFade(resource);
7131
+ } else this.resources.get(command.handle).suspendedPaused = false;
7132
+ break;
7133
+ case "seek":
7134
+ action.time = control.seconds;
7135
+ break;
7136
+ case "setSpeed":
7137
+ action.setEffectiveTimeScale(control.speed);
7138
+ break;
7139
+ case "setWeight":
7140
+ resource.pausedFade = void 0;
7141
+ action.setEffectiveWeight(control.weight);
7142
+ this.resources.get(command.handle).fadingOut = false;
7143
+ break;
7144
+ case "setBlendMode":
7145
+ action.blendMode = blendMode(control.blendMode);
7146
+ break;
7147
+ case "setLoop":
7148
+ action.setLoop(loopMode(control.loop.mode), control.loop.count ?? Infinity);
7149
+ break;
7150
+ case "setFinalPose":
7151
+ action.clampWhenFinished = control.finalPose === "hold";
7152
+ break;
7153
+ case "fadeIn":
7154
+ resource.pausedFade = void 0;
7155
+ action.fadeIn(control.seconds);
7156
+ resource.fadingOut = false;
7157
+ if (resource.explicitlyPaused || !this.renderingEnabled) this.pauseFade(resource);
7158
+ break;
7159
+ case "fadeOut":
7160
+ resource.pausedFade = void 0;
7161
+ if (control.seconds === 0) this.notifications.push({ type: "cancelled", handle: command.handle });
7162
+ else {
7163
+ action.fadeOut(control.seconds);
7164
+ resource.fadingOut = true;
7165
+ if (resource.explicitlyPaused || !this.renderingEnabled) this.pauseFade(resource);
7166
+ }
7167
+ break;
7168
+ case "stop":
7169
+ throw new Error("Rust must translate stop into a resource release.");
7170
+ }
6661
7171
  }
6662
- restore() {
6663
- for (const [object, value] of this.saved) {
6664
- const current = object.quaternion;
6665
- const norm = Math.sqrt(current.lengthSq() * value.applied.lengthSq());
6666
- if (norm > 0 && Number.isFinite(norm) && Math.abs(current.dot(value.applied)) / norm > 1 - 1e-12) {
6667
- current.copy(value.base);
7172
+ flushNotifications() {
7173
+ if (this.flushingNotifications || this.depth > 0 || this.disposed || this.notificationScheduled) return;
7174
+ this.flushingNotifications = true;
7175
+ try {
7176
+ while (this.notifications.length) {
7177
+ const event = this.notifications.shift();
7178
+ this.dispatch(this.session.notify(JSON.stringify(event)));
6668
7179
  }
7180
+ } finally {
7181
+ this.flushingNotifications = false;
6669
7182
  }
6670
- this.saved.clear();
6671
- this.model.updateMatrixWorld(true);
6672
7183
  }
6673
- controlLimits() {
6674
- const combine = (head, eye) => ({
6675
- negative: head.negative + eye.negative,
6676
- positive: head.positive + eye.positive
7184
+ };
7185
+
7186
+ // three/character.ts
7187
+ var json2 = (value) => JSON.stringify(value ?? {});
7188
+ var targetKey = (target) => JSON.stringify([target.kind, target.meshId, target.morphTargetId, target.boneId, target.objectId, target.property]);
7189
+ var copy = (value) => JSON.parse(JSON.stringify(value));
7190
+ var parse = (value) => JSON.parse(value);
7191
+ var finite2 = (value) => typeof value === "number" && Number.isFinite(value);
7192
+ var intensity = (options, fallback = 1) => {
7193
+ const value = options.intensityScale ?? options.intensity ?? options.weight;
7194
+ return finite2(value) ? Math.max(0, Math.min(2, value)) : fallback;
7195
+ };
7196
+ var presetId = (value) => value?.trim().toLowerCase() || "cc4";
7197
+ function supportsRustEmbodyPreset(value) {
7198
+ return requireInitializedEmbodyCore().has_preset(presetId(value));
7199
+ }
7200
+ var Embody = class _Embody {
7201
+ constructor(config = {}) {
7202
+ this.config = config;
7203
+ __publicField(this, "meshes", []);
7204
+ __publicField(this, "meshByName", /* @__PURE__ */ new Map());
7205
+ __publicField(this, "bones", {});
7206
+ __publicField(this, "wasm", requireInitializedEmbodyCore());
7207
+ __publicField(this, "core");
7208
+ __publicField(this, "inspector", new ThreeModelInspector());
7209
+ __publicField(this, "applier", new ThreeFrameApplier());
7210
+ __publicField(this, "references", /* @__PURE__ */ new WeakMap());
7211
+ __publicField(this, "referenceBindings", /* @__PURE__ */ new Map());
7212
+ __publicField(this, "boundModel");
7213
+ __publicField(this, "inspection");
7214
+ __publicField(this, "connector");
7215
+ __publicField(this, "profile");
7216
+ __publicField(this, "profileSource");
7217
+ __publicField(this, "profileMode");
7218
+ __publicField(this, "preset");
7219
+ __publicField(this, "sources", /* @__PURE__ */ new Map());
7220
+ __publicField(this, "playbacks", /* @__PURE__ */ new Map());
7221
+ __publicField(this, "current", /* @__PURE__ */ new Map());
7222
+ __publicField(this, "playDepth", 0);
7223
+ __publicField(this, "pendingEvents", []);
7224
+ __publicField(this, "bindingGeneration", 0);
7225
+ __publicField(this, "disposed", false);
7226
+ __publicField(this, "rendering", true);
7227
+ __publicField(this, "timeScale", 1);
7228
+ __publicField(this, "nextLiveTarget", 0);
7229
+ __publicField(this, "liveTargets", /* @__PURE__ */ new Map());
7230
+ __publicField(this, "hairObjects", /* @__PURE__ */ new Map());
7231
+ __publicField(this, "hairConfig", {});
7232
+ __publicField(this, "hairAppearance", {
7233
+ hairColor: copy(DEFAULT_HAIR_COLOR_APPEARANCE),
7234
+ eyebrowColor: copy(DEFAULT_HAIR_COLOR_APPEARANCE),
7235
+ showOutline: false,
7236
+ outlineColor: "#000000",
7237
+ outlineOpacity: 1
6677
7238
  });
6678
- return { yaw: combine(this.limits.headYaw, this.limits.eyeYaw), pitch: combine(this.limits.headPitch, this.limits.eyePitch) };
6679
- }
6680
- angles(direction) {
6681
- const local = direction.clone().applyQuaternion(this.model.getWorldQuaternion(new Quaternion()).invert());
6682
- return {
6683
- yaw: Math.atan2(local.x, local.z) * 180 / Math.PI,
6684
- pitch: Math.atan2(local.y, Math.hypot(local.x, local.z)) * 180 / Math.PI
7239
+ const mode = config.profileMode ?? "preset";
7240
+ if (mode !== "profile" && mode !== "preset") throw new Error(`Unknown profile mode: ${mode}`);
7241
+ if (mode === "profile" && !config.profile) throw new Error("Resolved profile mode requires a profile object.");
7242
+ this.profileMode = mode;
7243
+ this.preset = presetId(config.presetId ?? config.presetType);
7244
+ if (mode === "preset" && !this.wasm.has_preset(this.preset)) throw new Error(`Unknown Embody preset: ${this.preset}`);
7245
+ this.profileSource = this.validateProfile(config.profile ?? {});
7246
+ this.profile = this.resolveProfile(this.profileSource);
7247
+ this.core = new this.wasm.RuntimeCore(0);
7248
+ }
7249
+ get model() {
7250
+ return this.boundModel;
7251
+ }
7252
+ static async create(config = {}) {
7253
+ await initEmbodyCore();
7254
+ return new _Embody(config);
7255
+ }
7256
+ assertAlive() {
7257
+ if (this.disposed) throw new Error("Character is disposed.");
7258
+ }
7259
+ requireModel() {
7260
+ this.assertAlive();
7261
+ if (!this.boundModel) throw new Error("Bind a character model with onReady before using this operation.");
7262
+ return this.boundModel;
7263
+ }
7264
+ requireConnector() {
7265
+ this.requireModel();
7266
+ if (!this.connector) throw new Error("Character playback is not bound.");
7267
+ return this.connector;
7268
+ }
7269
+ validateProfile(value) {
7270
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Embody profile must be a JSON object.");
7271
+ return copy(value);
7272
+ }
7273
+ resolveProfile(value) {
7274
+ return this.profileMode === "profile" ? copy(value) : parse(this.wasm.merge_embedded_preset(this.preset, json2(value)));
7275
+ }
7276
+ onReady(options) {
7277
+ this.assertAlive();
7278
+ const model = options.model;
7279
+ if (!model?.isObject3D) throw new Error("onReady requires a Three Object3D model.");
7280
+ const reference = this.references.get(model) ?? options.referencePose ?? (!this.boundModel ? this.config.referencePose : void 0) ?? captureModelReferencePose(model);
7281
+ const inspection = this.inspector.inspectModel(model, { meshes: options.meshes, profile: this.profile, referencePose: reference });
7282
+ this.bind(model, reference, inspection, this.profileSource, this.profile);
7283
+ if (options.animations) this.loadAnimationClips(options.animations);
7284
+ }
7285
+ bind(model, reference, inspection, source, profile, preserveLiveState = true) {
7286
+ const referenceBindings = bindModelReferencePose(model, reference);
7287
+ const runtimeDescriptor = {
7288
+ ...inspection.descriptor,
7289
+ morphTargets: inspection.descriptor.morphTargets.map((morph) => {
7290
+ const binding = inspection.morphBindings.get(morph.id);
7291
+ const baseline = binding && referenceBindings.get(binding.mesh)?.morphInfluences?.[binding.index];
7292
+ return { ...morph, initialValue: baseline ?? morph.initialValue };
7293
+ })
6685
7294
  };
7295
+ const replacingModel = !!this.boundModel && this.boundModel !== model;
7296
+ const core2 = new this.wasm.RuntimeCore(0);
7297
+ try {
7298
+ if (this.profileMode === "profile") core2.configure_with_profile(json2(source), json2(runtimeDescriptor));
7299
+ else core2.configure_with_preset(this.preset, json2(source), json2(runtimeDescriptor));
7300
+ if (preserveLiveState && this.boundModel) core2.copy_live_state_from(this.core);
7301
+ for (const registered of replacingModel ? [] : this.sources.values()) {
7302
+ if (registered.kind === "native") {
7303
+ const [clip] = serializeAnimationClips(model, [registered.clip], inspection);
7304
+ core2.register_animation_clip(json2(clip), "baked");
7305
+ }
7306
+ }
7307
+ } catch (error) {
7308
+ core2.free();
7309
+ throw error;
7310
+ }
7311
+ try {
7312
+ this.connector?.dispose();
7313
+ } catch (error) {
7314
+ core2.free();
7315
+ throw error;
7316
+ }
7317
+ this.core.free();
7318
+ this.core = core2;
7319
+ if (replacingModel) this.sources.clear();
7320
+ this.boundModel = model;
7321
+ this.inspection = inspection;
7322
+ this.referenceBindings = referenceBindings;
7323
+ this.references.set(model, reference);
7324
+ this.profileSource = source;
7325
+ this.profile = profile;
7326
+ this.bindingGeneration += 1;
7327
+ this.playbacks.clear();
7328
+ this.current.clear();
7329
+ this.liveTargets.clear();
7330
+ this.meshes.splice(0, this.meshes.length, ...inspection.morphMeshes.length ? inspection.morphMeshes : inspection.allMeshes);
7331
+ this.meshByName = inspection.meshByName;
7332
+ this.bones = inspection.bones;
7333
+ this.applier.setBindings(inspection);
7334
+ this.applier.applyMeshMaterialConfigs(model, profile.meshes ?? {});
7335
+ const session = new this.wasm.NativePlaybackSession();
7336
+ try {
7337
+ this.connector = new ThreeNativePlaybackConnector(session, {
7338
+ model,
7339
+ inspection,
7340
+ onRelease: (id) => {
7341
+ const playback = this.playbacks.get(id);
7342
+ if (playback?.terminal) this.forget(playback);
7343
+ }
7344
+ });
7345
+ } catch (error) {
7346
+ session.free();
7347
+ throw error;
7348
+ }
7349
+ this.connector.rebind(model.uuid, String(this.bindingGeneration));
7350
+ this.connector.setRendering(this.rendering);
7351
+ this.connector.setTimeScale(this.timeScale);
7352
+ this.connector.subscribe((event) => this.onPlaybackEvent(event));
7353
+ this.hairConfig = parse(this.core.get_hair_config_json());
7354
+ this.registerHairObjects(inspection.allMeshes.filter((mesh) => ["hair", "eyebrow"].includes(this.meshCategory(mesh))));
7355
+ if (preserveLiveState) this.commitLive();
7356
+ }
7357
+ bindModel(meshes) {
7358
+ const model = this.requireModel();
7359
+ const reference = this.references.get(model);
7360
+ const inspection = this.inspector.inspectModel(model, { meshes, profile: this.profile, referencePose: reference });
7361
+ this.bind(model, reference, inspection, this.profileSource, this.profile);
7362
+ }
7363
+ extendReferencePose() {
7364
+ const model = this.requireModel();
7365
+ const reference = extendModelReferencePose(model, this.references.get(model));
7366
+ const inspection = this.inspector.inspectModel(model, { profile: this.profile, referencePose: reference });
7367
+ this.bind(model, reference, inspection, this.profileSource, this.profile);
7368
+ return reference;
7369
+ }
7370
+ setProfile(value) {
7371
+ this.assertAlive();
7372
+ const source = this.validateProfile(value);
7373
+ const profile = this.resolveProfile(source);
7374
+ if (!this.boundModel) {
7375
+ this.profileSource = source;
7376
+ this.profile = profile;
7377
+ return;
7378
+ }
7379
+ const reference = this.references.get(this.boundModel);
7380
+ const inspection = this.inspector.inspectModel(this.boundModel, { profile, referencePose: reference });
7381
+ this.bind(this.boundModel, reference, inspection, source, profile, false);
6686
7382
  }
6687
- ratio(degrees, limits) {
6688
- const capacity = degrees < 0 ? limits.negative : limits.positive;
6689
- return capacity > EPSILON ? bounded(degrees / capacity) : 0;
7383
+ getProfile() {
7384
+ return this.profile;
6690
7385
  }
6691
- degrees(control, limits) {
6692
- return bounded(control) * (control < 0 ? limits.negative : limits.positive);
7386
+ getProfileMode() {
7387
+ return this.profileMode;
6693
7388
  }
6694
- direction(yawDegrees, pitchDegrees) {
6695
- const yaw = yawDegrees * Math.PI / 180;
6696
- const pitch = pitchDegrees * Math.PI / 180;
6697
- return new Vector3(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), Math.cos(yaw) * Math.cos(pitch)).applyQuaternion(this.model.getWorldQuaternion(new Quaternion())).normalize();
7389
+ getPresetId() {
7390
+ return this.profileMode === "preset" ? this.preset : null;
6698
7391
  }
6699
- ray(joint) {
6700
- return joint.optical.clone().transformDirection(joint.object.matrixWorld);
7392
+ supportsPreset(value) {
7393
+ return supportsRustEmbodyPreset(value);
6701
7394
  }
6702
- /** Seed motor clips from the rendered bearing when enabling pose constraints. */
6703
- readControlState(options = {}) {
6704
- this.model.updateMatrixWorld(true);
6705
- const active = this.controlLimits();
6706
- const gaze = new Vector3();
6707
- const eyeBases = /* @__PURE__ */ new Map();
6708
- const eyeGain = contribution(options.eyeIntensity);
6709
- for (const eye of this.eyes) {
6710
- const value = options.eyeBaseQuaternions?.[eye.object.name];
6711
- const base = value ? new Quaternion(finite2(value.x), finite2(value.y), finite2(value.z), finite2(value.w, 1)).normalize() : (this.saved.get(eye.object)?.base ?? eye.object.quaternion).clone();
6712
- const actual = this.ray(eye);
6713
- const excursion = this.solveJoint(eye, actual, 0, base);
6714
- gaze.add(this.jointPose(
6715
- eye,
6716
- base,
6717
- eyeGain > EPSILON ? bounded(excursion.yaw / eyeGain) : 0,
6718
- eyeGain > EPSILON ? bounded(excursion.pitch / eyeGain) : 0
6719
- ).direction);
6720
- eyeBases.set(eye, { base, actual });
6721
- }
6722
- if (gaze.lengthSq() < EPSILON) gaze.copy(this.head ? this.ray(this.head) : this.direction(0, 0));
6723
- const eyes = this.angles(gaze.normalize());
6724
- let head = this.angles(this.direction(0, 0));
6725
- let headSeedLimited = false;
6726
- if (this.head) {
6727
- const value = options.headBaseQuaternion;
6728
- const base = value ? new Quaternion(finite2(value.x), finite2(value.y), finite2(value.z), finite2(value.w, 1)).normalize() : (this.saved.get(this.head.object)?.base ?? this.head.object.quaternion).clone();
6729
- const actual = this.ray(this.head);
6730
- const excursion = this.solveJoint(this.head, actual, 0, base);
6731
- const gain = contribution(options.headIntensity);
6732
- const yaw = gain > EPSILON ? bounded(excursion.yaw / gain) : 0;
6733
- const pitch = gain > EPSILON ? bounded(excursion.pitch / gain) : 0;
6734
- const preferred = this.jointPose(
6735
- this.head,
6736
- this.head.reference,
6737
- yaw,
6738
- pitch,
6739
- 0,
6740
- this.referenceParent(this.head),
6741
- this.head.referenceScale
6742
- );
6743
- head = this.angles(preferred.direction);
6744
- const represented = this.direction(
6745
- this.degrees(this.ratio(head.yaw, this.limits.headYaw), this.limits.headYaw),
6746
- this.degrees(this.ratio(head.pitch, this.limits.headPitch), this.limits.headPitch)
6747
- );
6748
- headSeedLimited = this.contributedPose(this.head, represented, 0, gain, true, base).direction.angleTo(actual) > 1e-3;
6749
- }
6750
- const destination = options.worldTarget ? this.angles(vector(options.worldTarget).sub(this.origin())) : void 0;
6751
- const eyeTarget = { x: -this.ratio(eyes.yaw, active.yaw), y: this.ratio(eyes.pitch, active.pitch), z: 0 };
6752
- const origin = this.origin();
6753
- const distance = options.worldTarget ? Math.max(EPSILON, vector(options.worldTarget).distanceTo(origin)) : 1;
6754
- const representedTarget = origin.clone().addScaledVector(this.direction(
6755
- this.degrees(-eyeTarget.x, active.yaw),
6756
- this.degrees(eyeTarget.y, active.pitch)
6757
- ), distance);
6758
- const eyeSeedLimited = this.eyes.some((eye) => {
6759
- const { base, actual } = eyeBases.get(eye);
6760
- const desired = representedTarget.clone().sub(eye.object.getWorldPosition(new Vector3())).normalize();
6761
- return this.contributedPose(eye, desired, 0, eyeGain, false, base).direction.angleTo(actual) > 1e-3;
6762
- });
7395
+ onPlaybackEvent(event) {
7396
+ if (this.playDepth) {
7397
+ this.pendingEvents.push(event);
7398
+ return;
7399
+ }
7400
+ const playback = this.playbacks.get(event.handle);
7401
+ if (!playback) return;
7402
+ playback.terminal = true;
7403
+ if (!playback.connector.getAction(playback.id)) {
7404
+ this.playbacks.delete(playback.id);
7405
+ if (this.current.get(playback.source.name) === playback) this.current.delete(playback.source.name);
7406
+ }
7407
+ playback.notify({ ...event, actionId: event.handle, clipName: playback.source.name });
7408
+ }
7409
+ compile(source, options) {
7410
+ const buildOptions = { ..."options" in source ? source.options : {}, ...options, intensityScale: intensity(options) };
7411
+ switch (source.kind) {
7412
+ case "curves":
7413
+ return parse(this.core.build_clip(source.name, json2(source.input), json2(buildOptions)));
7414
+ case "typed":
7415
+ return parse(this.core.build_typed_clip(source.name, json2(source.input), json2(buildOptions)));
7416
+ case "semantic":
7417
+ return parse(this.core.build_semantic_clip(source.name, json2(source.input), json2(buildOptions)));
7418
+ case "compiled":
7419
+ return source.clip;
7420
+ case "native":
7421
+ throw new Error("Native animation sources do not require semantic compilation.");
7422
+ }
7423
+ }
7424
+ restValues(track) {
7425
+ const model = this.requireModel();
7426
+ const parsed = PropertyBinding.parseTrackName(track.name);
7427
+ let object = PropertyBinding.findNode(model, parsed.nodeName);
7428
+ if (parsed.objectName === "bones" && object) {
7429
+ const skeleton = object.skeleton;
7430
+ object = skeleton?.bones.find((bone) => bone.name === String(parsed.objectIndex)) ?? skeleton?.bones[Number(parsed.objectIndex)];
7431
+ }
7432
+ if (!object) return void 0;
7433
+ const reference = this.referenceBindings.get(object);
7434
+ if (!reference) return void 0;
7435
+ switch (parsed.propertyName) {
7436
+ case "quaternion":
7437
+ return Object.values(reference.transform.rotation);
7438
+ case "rotation": {
7439
+ const rotation = reference.transform.rotation;
7440
+ const euler = reference.rotationEuler ?? new Euler().setFromQuaternion(new Quaternion(rotation.x, rotation.y, rotation.z, rotation.w), reference.rotationOrder);
7441
+ const axis = parsed.propertyIndex;
7442
+ return axis === "x" || axis === "y" || axis === "z" ? [euler[axis]] : [euler.x, euler.y, euler.z];
7443
+ }
7444
+ case "position":
7445
+ return Object.values(reference.transform.position);
7446
+ case "scale":
7447
+ return Object.values(reference.transform.scale);
7448
+ case "weights":
7449
+ case "morphTargetInfluences": {
7450
+ const mesh = object;
7451
+ const index = typeof parsed.propertyIndex === "string" && !/^\d+$/.test(parsed.propertyIndex) ? mesh.morphTargetDictionary?.[parsed.propertyIndex] : Number(parsed.propertyIndex);
7452
+ return [reference.morphInfluences?.[index ?? -1] ?? 0];
7453
+ }
7454
+ default:
7455
+ return void 0;
7456
+ }
7457
+ }
7458
+ materialize(source, options, inheritedStarts = /* @__PURE__ */ new Map()) {
7459
+ if (!this.inspection) throw new Error("Character has no model inspection.");
7460
+ const nativeSource = source.kind === "native";
7461
+ let ir;
7462
+ if (!nativeSource) {
7463
+ ir = this.compile(source, options);
7464
+ }
7465
+ const clip = nativeSource ? withComponentTracks(source.clip).clone() : createAnimationClipFromClipIR(ir, this.inspection);
7466
+ if (ir) {
7467
+ const predecessor = this.current.get(source.name);
7468
+ const outgoing = predecessor?.connector.getAction(predecessor.id);
7469
+ for (let index = 0; index < ir.tracks.length; index += 1) {
7470
+ if (!ir.tracks[index].inheritStart) continue;
7471
+ const track = clip.tracks[index];
7472
+ if (!track) throw new Error("Every inherited track must bind to the character.");
7473
+ const startKey = `${index}:${track.name}`;
7474
+ let previous = inheritedStarts.get(startKey);
7475
+ if (!previous && options.blendMode === "additive") {
7476
+ const rest = this.restValues(track);
7477
+ const candidates = outgoing?.getClip().tracks;
7478
+ const oldTrack = candidates?.[index]?.name === track.name ? candidates[index] : candidates?.find((candidate) => candidate.name === track.name);
7479
+ if (oldTrack && outgoing) {
7480
+ previous = Array.from(oldTrack.createInterpolant().evaluate(outgoing.time));
7481
+ if (outgoing.blendMode === AdditiveAnimationBlendMode && rest) {
7482
+ previous = track.ValueTypeName === "quaternion" ? new Quaternion().fromArray(rest).multiply(new Quaternion().fromArray(previous)).toArray() : previous.map((value, axis) => value + rest[axis]);
7483
+ }
7484
+ } else if (rest) previous = rest;
7485
+ }
7486
+ if (previous) track.values.set(previous, 0);
7487
+ inheritedStarts.set(startKey, previous ?? Array.from(track.values.subarray(0, track.getValueSize())));
7488
+ }
7489
+ }
7490
+ const authoredAdditive = clip.blendMode === AdditiveAnimationBlendMode;
7491
+ const scale = intensity(options);
7492
+ const additive = options.blendMode === "additive" || options.blendMode === void 0 && authoredAdditive;
7493
+ this.applyEasing(clip, options.easing ?? "linear", nativeSource && (scale !== 1 || additive !== authoredAdditive));
7494
+ if (nativeSource && scale !== 1) {
7495
+ for (const track of clip.tracks) {
7496
+ const rest = authoredAdditive ? track.ValueTypeName === "quaternion" ? [0, 0, 0, 1] : Array(track.getValueSize()).fill(0) : this.restValues(track);
7497
+ if (!rest) continue;
7498
+ const stride = track.getValueSize();
7499
+ const cubic = track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true;
7500
+ const width = cubic ? stride / 3 : stride;
7501
+ for (let offset = 0; offset < track.values.length; offset += stride) {
7502
+ const sample = offset + (cubic ? width : 0);
7503
+ if (track.ValueTypeName === "quaternion") {
7504
+ const neutral = new Quaternion().fromArray(rest);
7505
+ const value = new Quaternion().fromArray(track.values, sample);
7506
+ neutral.slerp(value, scale).toArray(track.values, sample);
7507
+ } else {
7508
+ for (let axis = 0; axis < width; axis += 1) {
7509
+ track.values[sample + axis] = rest[axis] + (track.values[sample + axis] - rest[axis]) * scale;
7510
+ if (cubic) {
7511
+ track.values[offset + axis] *= scale;
7512
+ track.values[offset + 2 * width + axis] *= scale;
7513
+ }
7514
+ }
7515
+ }
7516
+ }
7517
+ }
7518
+ }
7519
+ if (additive && !authoredAdditive) {
7520
+ const reference = clip.clone();
7521
+ for (const track of reference.tracks) {
7522
+ const rest = this.restValues(track);
7523
+ if (!rest) continue;
7524
+ const width = track.getValueSize();
7525
+ for (let offset = 0; offset < track.values.length; offset += width) track.values.set(rest, offset);
7526
+ }
7527
+ const explicitReference = options.additiveReferenceTimeSec;
7528
+ if (finite2(explicitReference)) AnimationUtils.makeClipAdditive(clip, explicitReference * 30, clip.clone(), 30);
7529
+ else AnimationUtils.makeClipAdditive(clip, 0, reference, 30);
7530
+ }
7531
+ if (!additive && authoredAdditive) {
7532
+ for (const track of clip.tracks) {
7533
+ const rest = this.restValues(track);
7534
+ if (!rest) continue;
7535
+ const width = track.getValueSize();
7536
+ for (let offset = 0; offset < track.values.length; offset += width) {
7537
+ if (track.ValueTypeName === "quaternion") new Quaternion().fromArray(rest).multiply(new Quaternion().fromArray(track.values, offset)).toArray(track.values, offset);
7538
+ else for (let axis = 0; axis < width; axis += 1) track.values[offset + axis] += rest[axis];
7539
+ }
7540
+ }
7541
+ }
7542
+ clip.blendMode = additive ? AdditiveAnimationBlendMode : NormalAnimationBlendMode;
7543
+ return clip;
7544
+ }
7545
+ applyEasing(clip, easing, resampleCustom = false) {
7546
+ if (easing === "linear" && !resampleCustom) return;
7547
+ const curve = (progress2) => {
7548
+ switch (easing) {
7549
+ case "easeIn":
7550
+ return progress2 * progress2;
7551
+ case "easeOut":
7552
+ return 1 - (1 - progress2) ** 2;
7553
+ case "easeInOut":
7554
+ return progress2 < 0.5 ? 2 * progress2 * progress2 : 1 - (-2 * progress2 + 2) ** 2 / 2;
7555
+ case "easeInOutCubic":
7556
+ return progress2 < 0.5 ? 4 * progress2 ** 3 : 1 - (-2 * progress2 + 2) ** 3 / 2;
7557
+ default:
7558
+ return progress2;
7559
+ }
7560
+ };
7561
+ for (const track of clip.tracks) {
7562
+ if (track.getInterpolation() === InterpolateDiscrete || track.times.length === 0) continue;
7563
+ const customInterpolant = track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true;
7564
+ if (track.times.length === 1) {
7565
+ if (customInterpolant && resampleCustom) {
7566
+ track.values = new Float32Array(track.createInterpolant().evaluate(track.times[0]));
7567
+ track.setInterpolation(InterpolateLinear);
7568
+ }
7569
+ continue;
7570
+ }
7571
+ if ((customInterpolant || track.getInterpolation() !== InterpolateLinear) && easing === "linear" && !resampleCustom) continue;
7572
+ const stride = track.getValueSize();
7573
+ const width = customInterpolant ? stride / 3 : stride;
7574
+ const interpolant = track.createInterpolant();
7575
+ const times = [];
7576
+ const values = [];
7577
+ const append = (time, value) => {
7578
+ times.push(time);
7579
+ for (let axis = 0; axis < width; axis += 1) values.push(value[axis]);
7580
+ };
7581
+ for (let index = 0; index < track.times.length - 1; index += 1) {
7582
+ const start = track.times[index];
7583
+ const end = track.times[index + 1];
7584
+ const offset = index * stride + (customInterpolant ? width : 0);
7585
+ append(start, track.values.subarray(offset, offset + width));
7586
+ if (end <= start) continue;
7587
+ for (let part = 1; part < 16; part += 1) {
7588
+ const progress2 = part / 16;
7589
+ append(start + (end - start) * progress2, interpolant.evaluate(start + (end - start) * curve(progress2)));
7590
+ }
7591
+ }
7592
+ const lastOffset = (track.times.length - 1) * stride + (customInterpolant ? width : 0);
7593
+ append(track.times[track.times.length - 1], track.values.subarray(lastOffset, lastOffset + width));
7594
+ track.times = new Float32Array(times);
7595
+ track.values = new Float32Array(values);
7596
+ if (customInterpolant || track.getInterpolation() !== InterpolateLinear) track.setInterpolation(InterpolateLinear);
7597
+ }
7598
+ }
7599
+ nativeOptions(options, clip) {
7600
+ const mode = clip.duration === 0 ? "once" : options.loopMode ?? (options.loop === true ? "repeat" : "once");
7601
+ const count = finite2(options.repeatCount) && options.repeatCount > 0 ? options.repeatCount : null;
7602
+ let speed = options.speed ?? options.playbackRate ?? options.rate ?? options.timeScale ?? 1;
7603
+ if (options.reverse === true) speed = -Math.abs(speed);
6763
7604
  return {
6764
- target: destination ? { x: -this.ratio(destination.yaw, active.yaw), y: this.ratio(destination.pitch, active.pitch), z: 0 } : void 0,
6765
- eyeTarget,
6766
- headTarget: { x: -this.ratio(head.yaw, this.limits.headYaw), y: this.ratio(head.pitch, this.limits.headPitch), z: 0 },
6767
- headRoll: 0,
6768
- headSeedLimited,
6769
- eyeSeedLimited
7605
+ startSeconds: finite2(options.time) ? options.time : finite2(options.offsetSec) ? options.offsetSec : speed < 0 ? clip.duration : 0,
7606
+ speed,
7607
+ weight: finite2(options.mixerWeight) ? options.mixerWeight : 1,
7608
+ blendMode: clip.blendMode === AdditiveAnimationBlendMode ? "additive" : "normal",
7609
+ loop: { mode: mode === "once" ? "once" : mode === "pingpong" || mode === "pingPong" ? "pingPong" : "repeat", count: mode === "once" ? 1 : count },
7610
+ finalPose: options.finalPose === "release" || options.clampWhenFinished === false ? "release" : "hold"
6770
7611
  };
6771
7612
  }
6772
- origin() {
6773
- const origin = new Vector3();
6774
- for (const eye of this.eyes) origin.add(eye.object.getWorldPosition(new Vector3()));
6775
- if (this.eyes.length) origin.divideScalar(this.eyes.length);
6776
- else if (this.head) origin.copy(this.head.object.getWorldPosition(new Vector3()));
6777
- else origin.copy(this.model.getWorldPosition(new Vector3()));
6778
- return origin;
6779
- }
6780
- rotation(axis, value) {
6781
- const binding = value < 0 ? axis.negative : axis.positive;
6782
- return binding ? new Quaternion().setFromAxisAngle(binding.axis, Math.abs(bounded(value)) * binding.radians) : new Quaternion();
6783
- }
6784
- referenceParent(joint) {
6785
- return new Matrix4().multiplyMatrices(this.model.matrixWorld, joint.referenceParent);
6786
- }
6787
- jointPose(joint, base, yaw, pitch, roll = 0, parent = joint.object.parent?.matrixWorld ?? new Matrix4(), scale = joint.object.scale) {
6788
- const object = joint.object;
6789
- const quaternion = base.clone().multiply(this.rotation(joint.yaw, yaw)).multiply(this.rotation(joint.pitch, pitch)).multiply(this.rotation(joint.roll, roll));
6790
- const matrix = new Matrix4().multiplyMatrices(parent, new Matrix4().compose(object.position, quaternion, scale));
6791
- return { quaternion, direction: joint.optical.clone().transformDirection(matrix) };
6792
- }
6793
- solveJoint(joint, desired, roll = 0, base = joint.object.quaternion.clone(), parent = joint.object.parent?.matrixWorld ?? new Matrix4(), scale = joint.object.scale) {
6794
- const evaluate = (yaw2, pitch2) => this.jointPose(joint, base, yaw2, pitch2, roll, parent, scale);
6795
- let yaw = 0;
6796
- let pitch = 0;
6797
- let best = evaluate(yaw, pitch);
6798
- for (let iteration = 0; iteration < 24; iteration += 1) {
6799
- const error = desired.clone().sub(best.direction);
6800
- if (error.lengthSq() < 1e-14) break;
6801
- const derivative = (axis) => {
6802
- const value = axis === 0 ? yaw : pitch;
6803
- const lo = Math.max(-1, value - 1e-4);
6804
- const hi = Math.min(1, value + 1e-4);
6805
- return evaluate(axis === 0 ? hi : yaw, axis === 1 ? hi : pitch).direction.sub(evaluate(axis === 0 ? lo : yaw, axis === 1 ? lo : pitch).direction).divideScalar(hi - lo);
7613
+ validateEasing(options) {
7614
+ if (options.easing !== void 0 && !["linear", "easeIn", "easeOut", "easeInOut", "easeInOutCubic"].includes(options.easing)) throw new Error(`Unknown playback easing: ${options.easing}`);
7615
+ }
7616
+ handle(source, options, autoPlay) {
7617
+ options = { ..."options" in source ? source.options : {}, ...options };
7618
+ const listeners = /* @__PURE__ */ new Set();
7619
+ const generation = this.bindingGeneration;
7620
+ let current;
7621
+ let resolvePromise = () => {
7622
+ };
7623
+ const result = { name: source.name };
7624
+ Object.defineProperty(result, "finished", { get: () => result.promise, enumerable: true });
7625
+ const newPromise = () => {
7626
+ result.promise = new Promise((resolve) => {
7627
+ resolvePromise = resolve;
7628
+ });
7629
+ };
7630
+ newPromise();
7631
+ result.subscribe = (listener) => {
7632
+ const callback = typeof listener === "function" ? listener : (event) => listener.next(event);
7633
+ listeners.add(callback);
7634
+ return () => {
7635
+ listeners.delete(callback);
6806
7636
  };
6807
- const a = derivative(0);
6808
- const b = derivative(1);
6809
- const aa = a.dot(a) + 1e-7;
6810
- const ab = a.dot(b);
6811
- const bb = b.dot(b) + 1e-7;
6812
- const determinant = aa * bb - ab * ab;
6813
- if (determinant < 1e-14) break;
6814
- const ay = a.dot(error);
6815
- const by = b.dot(error);
6816
- const dy = Math.max(-0.5, Math.min(0.5, (ay * bb - by * ab) / determinant));
6817
- const dp = Math.max(-0.5, Math.min(0.5, (by * aa - ay * ab) / determinant));
6818
- let improved = false;
6819
- for (const step of [1, 0.5, 0.25, 0.125]) {
6820
- const nextYaw = bounded(yaw + dy * step);
6821
- const nextPitch = bounded(pitch + dp * step);
6822
- const next = evaluate(nextYaw, nextPitch);
6823
- if (next.direction.distanceToSquared(desired) < error.lengthSq()) {
6824
- yaw = nextYaw;
6825
- pitch = nextPitch;
6826
- best = next;
6827
- improved = true;
6828
- break;
7637
+ };
7638
+ const start = () => {
7639
+ if (generation !== this.bindingGeneration) throw new Error("Playback handle belongs to an obsolete model binding.");
7640
+ this.validateEasing(options);
7641
+ const connector = this.requireConnector();
7642
+ const inheritedStarts = /* @__PURE__ */ new Map();
7643
+ const clip = this.materialize(source, options, inheritedStarts);
7644
+ const hairMotion = this.authoredHeadMotion(clip);
7645
+ const previous = this.current.get(source.name);
7646
+ const settings = this.nativeOptions(options, clip);
7647
+ if (previous && connector.getAction(previous.id)) settings.replace = previous.id;
7648
+ if (current) newPromise();
7649
+ const resolve = resolvePromise;
7650
+ let settled = false;
7651
+ this.playDepth += 1;
7652
+ let id;
7653
+ try {
7654
+ id = connector.playNativeClip(clip, settings);
7655
+ } catch (error) {
7656
+ this.playDepth -= 1;
7657
+ while (!this.playDepth && this.pendingEvents.length) this.onPlaybackEvent(this.pendingEvents.shift());
7658
+ throw error;
7659
+ }
7660
+ const playback = {
7661
+ id,
7662
+ source,
7663
+ options: { ...options, intensityScale: intensity(options) },
7664
+ connector,
7665
+ terminal: false,
7666
+ inheritedStarts,
7667
+ replay: (next) => {
7668
+ options = next;
7669
+ return start();
7670
+ },
7671
+ notify: (event) => {
7672
+ if (settled) return;
7673
+ settled = true;
7674
+ resolve(event);
7675
+ for (const listener of [...listeners]) {
7676
+ try {
7677
+ listener(event);
7678
+ } catch (error) {
7679
+ queueMicrotask(() => {
7680
+ throw error;
7681
+ });
7682
+ }
7683
+ }
7684
+ }
7685
+ };
7686
+ current = playback;
7687
+ result.actionId = id;
7688
+ this.playbacks.set(id, playback);
7689
+ this.current.set(source.name, playback);
7690
+ const ensure = () => {
7691
+ this.assertAlive();
7692
+ if (this.connector !== connector || !connector.getAction(id)) throw new Error("Unknown, released or obsolete playback handle.");
7693
+ };
7694
+ const control = (command) => {
7695
+ ensure();
7696
+ connector.control(id, command);
7697
+ if (command.type === "stop") this.forget(playback);
7698
+ return result;
7699
+ };
7700
+ result.stop = result.cancel = () => {
7701
+ if (this.connector !== connector || !connector.getAction(id)) return result;
7702
+ ensure();
7703
+ const seconds = finite2(playback.options.fadeOutSec) ? playback.options.fadeOutSec : 0;
7704
+ if (seconds > 0 && !playback.terminal) connector.fadeOut(id, seconds);
7705
+ else control({ type: "stop" });
7706
+ return result;
7707
+ };
7708
+ result.pause = () => control({ type: "pause" });
7709
+ result.resume = () => {
7710
+ ensure();
7711
+ if (playback.terminal) {
7712
+ options = { ...playback.options, time: connector.getAction(id).time };
7713
+ return start();
6829
7714
  }
7715
+ return control({ type: "resume" });
7716
+ };
7717
+ result.setSpeed = result.setPlaybackRate = (speed) => {
7718
+ ensure();
7719
+ this.updatePlayback(playback, { speed });
7720
+ return result;
7721
+ };
7722
+ result.setTime = result.seek = (seconds) => control({ type: "seek", seconds });
7723
+ result.setWeight = result.setIntensity = (value) => {
7724
+ ensure();
7725
+ this.updatePlayback(playback, { intensityScale: value });
7726
+ return result;
7727
+ };
7728
+ result.updateParams = result.setParams = (value) => {
7729
+ ensure();
7730
+ this.updatePlayback(playback, value);
7731
+ return result;
7732
+ };
7733
+ try {
7734
+ const fade = options.fadeInSec ?? options.crossfadeDuration;
7735
+ if (finite2(fade) && fade > 0) connector.fadeIn(id, fade);
7736
+ } finally {
7737
+ this.playDepth -= 1;
7738
+ while (!this.playDepth && this.pendingEvents.length) this.onPlaybackEvent(this.pendingEvents.shift());
7739
+ }
7740
+ if (hairMotion && connector.getAction(id)) {
7741
+ this.playHairImpulse(hairMotion.horizontal, hairMotion.vertical);
7742
+ this.setHairGravity(hairMotion.pitch, clip.duration);
7743
+ }
7744
+ return result;
7745
+ };
7746
+ result.play = () => {
7747
+ if (current) options = { ...current.options };
7748
+ return start();
7749
+ };
7750
+ const beforePlay = () => {
7751
+ throw new Error("Play this compiled clip before changing playback.");
7752
+ };
7753
+ result.stop = result.cancel = () => result;
7754
+ result.pause = result.resume = beforePlay;
7755
+ result.updateParams = result.setParams = (patch) => {
7756
+ this.assertAlive();
7757
+ this.validateEasing(patch);
7758
+ options = { ...options, ...patch };
7759
+ if ("finalPose" in patch && !("clampWhenFinished" in patch)) options.clampWhenFinished = patch.finalPose !== "release";
7760
+ if ("clampWhenFinished" in patch && !("finalPose" in patch)) options.finalPose = patch.clampWhenFinished === false ? "release" : "hold";
7761
+ if ("loop" in patch && !("loopMode" in patch)) options.loopMode = patch.loop ? "repeat" : "once";
7762
+ if ("loopMode" in patch && !("repeatCount" in patch)) delete options.repeatCount;
7763
+ if ("weight" in patch || "intensity" in patch || "intensityScale" in patch) options.intensityScale = intensity(patch);
7764
+ if ("time" in patch || "offsetSec" in patch) options.time = patch.time ?? patch.offsetSec;
7765
+ if ("speed" in patch || "playbackRate" in patch || "rate" in patch || "timeScale" in patch || "reverse" in patch) {
7766
+ let speed = patch.speed ?? patch.playbackRate ?? patch.rate ?? patch.timeScale ?? options.speed ?? options.playbackRate ?? options.rate ?? options.timeScale ?? 1;
7767
+ if ("reverse" in patch) speed = Math.abs(speed) * (patch.reverse ? -1 : 1);
7768
+ options.speed = speed;
7769
+ delete options.reverse;
7770
+ }
7771
+ return result;
7772
+ };
7773
+ result.setWeight = result.setIntensity = (value) => result.updateParams({ intensityScale: value });
7774
+ result.setSpeed = result.setPlaybackRate = (speed) => result.updateParams({ speed });
7775
+ result.setTime = result.seek = (time) => result.updateParams({ time });
7776
+ return autoPlay ? start() : result;
7777
+ }
7778
+ forget(playback) {
7779
+ this.playbacks.delete(playback.id);
7780
+ if (this.current.get(playback.source.name) === playback) this.current.delete(playback.source.name);
7781
+ }
7782
+ updatePlayback(playback, patch) {
7783
+ this.validateEasing(patch);
7784
+ const connector = playback.connector;
7785
+ const action = connector.getAction(playback.id);
7786
+ if (connector !== this.connector || !action) throw new Error("Unknown, released or obsolete playback handle.");
7787
+ const options = { ...playback.options, ...patch };
7788
+ if ("finalPose" in patch && !("clampWhenFinished" in patch)) options.clampWhenFinished = patch.finalPose !== "release";
7789
+ if ("clampWhenFinished" in patch && !("finalPose" in patch)) options.finalPose = patch.clampWhenFinished === false ? "release" : "hold";
7790
+ if ("loop" in patch && !("loopMode" in patch)) options.loopMode = patch.loop ? "repeat" : "once";
7791
+ if ("loopMode" in patch && !("repeatCount" in patch)) delete options.repeatCount;
7792
+ if ("weight" in patch || "intensity" in patch || "intensityScale" in patch) options.intensityScale = intensity(patch);
7793
+ if (["weight", "intensity", "intensityScale", "blendMode", "easing", "balance", "balanceMap", "mixWeights"].some((key) => key in patch)) {
7794
+ const clip = this.materialize(playback.source, options, playback.inheritedStarts);
7795
+ connector.replaceClip(playback.id, clip);
7796
+ if ("blendMode" in patch) connector.control(playback.id, { type: "setBlendMode", blendMode: clip.blendMode === AdditiveAnimationBlendMode ? "additive" : "normal" });
7797
+ }
7798
+ if ("mixerWeight" in patch) connector.control(playback.id, { type: "setWeight", weight: patch.mixerWeight });
7799
+ if ("speed" in patch || "playbackRate" in patch || "rate" in patch || "timeScale" in patch || "reverse" in patch) {
7800
+ let speed = patch.speed ?? patch.playbackRate ?? patch.rate ?? patch.timeScale ?? action.timeScale;
7801
+ if ("reverse" in patch) speed = Math.abs(speed) * (patch.reverse ? -1 : 1);
7802
+ connector.control(playback.id, { type: "setSpeed", speed });
7803
+ options.speed = speed;
7804
+ delete options.reverse;
7805
+ }
7806
+ if ("time" in patch || "offsetSec" in patch) {
7807
+ options.time = patch.time ?? patch.offsetSec;
7808
+ connector.control(playback.id, { type: "seek", seconds: options.time });
7809
+ }
7810
+ if ("loopMode" in patch || "loop" in patch || "repeatCount" in patch) {
7811
+ if (playback.terminal) {
7812
+ playback.replay({ ...options, time: action.time });
7813
+ return;
6830
7814
  }
6831
- if (!improved) break;
7815
+ connector.control(playback.id, { type: "setLoop", loop: this.nativeOptions(options, action.getClip()).loop });
7816
+ }
7817
+ if ("clampWhenFinished" in patch || "finalPose" in patch) connector.control(playback.id, { type: "setFinalPose", finalPose: this.nativeOptions(options, action.getClip()).finalPose });
7818
+ playback.options = options;
7819
+ if (!connector.getAction(playback.id)) this.forget(playback);
7820
+ }
7821
+ registerAnimationClips(clips) {
7822
+ const model = this.requireModel();
7823
+ for (const clip of clips) {
7824
+ if (this.sources.get(clip.name)?.kind === "native" && this.sources.get(clip.name).clip === clip) continue;
7825
+ const [ir] = serializeAnimationClips(model, [clip], this.inspection);
7826
+ this.core.register_animation_clip(json2(ir), "baked");
7827
+ this.sources.set(clip.name, { name: clip.name, kind: "native", clip });
6832
7828
  }
6833
- return { ...best, limited: best.direction.angleTo(desired) > 1e-3, yaw, pitch };
6834
7829
  }
6835
- contributedPose(joint, desired, roll, intensity, fromReference, base = joint.object.quaternion.clone()) {
6836
- const full = fromReference ? this.solveJoint(joint, desired, roll, joint.reference, this.referenceParent(joint), joint.referenceScale) : this.solveJoint(joint, desired, roll, base);
6837
- const gain = contribution(intensity);
6838
- const result = this.jointPose(joint, base, full.yaw * gain, full.pitch * gain, bounded(roll) * gain);
6839
- return { ...result, limited: result.direction.angleTo(desired) > 1e-3 };
7830
+ loadAnimationClips(clips) {
7831
+ this.stopAllAnimations();
7832
+ for (const source of [...this.sources.values()]) if (source.kind === "native") {
7833
+ this.sources.delete(source.name);
7834
+ this.core.remove_animation_clip(source.name);
7835
+ }
7836
+ this.registerAnimationClips(clips ?? []);
7837
+ this.restartHair();
6840
7838
  }
6841
- solve(joint, desired, roll = 0, intensity = 1, fromReference = false) {
6842
- const result = this.contributedPose(joint, desired, roll, intensity, fromReference);
6843
- this.saved.set(joint.object, { base: joint.object.quaternion.clone(), applied: result.quaternion.clone() });
6844
- joint.object.quaternion.copy(result.quaternion);
6845
- joint.object.updateMatrixWorld(true);
6846
- return result;
7839
+ removeAnimationClip(name) {
7840
+ this.stopAnimation(name);
7841
+ this.sources.delete(name);
7842
+ return this.core.remove_animation_clip(name);
6847
7843
  }
6848
- apply(request2, controls) {
6849
- this.restore();
6850
- const active = this.controlLimits();
6851
- const intendedWorldTarget = vector(request2.worldTarget);
6852
- const origin = this.origin();
6853
- const intendedOffset = intendedWorldTarget.clone().sub(origin);
6854
- const intendedBearing = this.angles(intendedOffset);
6855
- const remainingYaw = this.degrees(-finite2(controls.eyeYaw), active.yaw) - this.degrees(-finite2(request2.target?.x), active.yaw);
6856
- const remainingPitch = this.degrees(finite2(controls.eyePitch), active.pitch) - this.degrees(finite2(request2.target?.y), active.pitch);
6857
- const target = origin.clone().addScaledVector(
6858
- this.direction(intendedBearing.yaw + remainingYaw, intendedBearing.pitch + remainingPitch),
6859
- intendedOffset.length()
6860
- );
6861
- let headLimited = false;
6862
- const headControlsPresent = controls.headYaw !== void 0 || controls.headPitch !== void 0 || controls.headRoll !== void 0;
6863
- const eyeControlsPresent = controls.eyeYaw !== void 0 || controls.eyePitch !== void 0;
6864
- if (request2.headEnabled !== false && headControlsPresent && this.head) {
6865
- headLimited = this.solve(this.head, this.direction(
6866
- this.degrees(-finite2(controls.headYaw), this.limits.headYaw),
6867
- this.degrees(finite2(controls.headPitch), this.limits.headPitch)
6868
- ), finite2(controls.headRoll), contribution(controls.headIntensity ?? request2.headIntensity), true).limited;
6869
- }
6870
- const eyes = [];
6871
- for (const eye of this.eyes) {
6872
- const eyeOrigin = eye.object.getWorldPosition(new Vector3());
6873
- const desired = target.clone().sub(eyeOrigin).normalize();
6874
- const solved = request2.eyesEnabled !== false && eyeControlsPresent ? this.solve(eye, desired, 0, contribution(controls.eyeIntensity ?? request2.eyeIntensity)) : { limited: false };
6875
- const direction = this.ray(eye);
6876
- eyes.push({
6877
- name: eye.object.name,
6878
- origin: point2(eyeOrigin),
6879
- direction: point2(direction),
6880
- errorDegrees: direction.angleTo(desired) * 180 / Math.PI,
6881
- limited: solved.limited
7844
+ getAnimationClips() {
7845
+ return parse(this.core.get_animation_clips());
7846
+ }
7847
+ playAnimation(name, options = {}) {
7848
+ const source = this.sources.get(name);
7849
+ if (!source) throw new Error(`Unknown animation clip: ${name}`);
7850
+ return this.handle(source, options, true);
7851
+ }
7852
+ build(source, options, play) {
7853
+ this.requireModel();
7854
+ this.validateEasing(options);
7855
+ this.compile(source, options);
7856
+ this.sources.set(source.name, source);
7857
+ return this.handle(source, options, play);
7858
+ }
7859
+ buildClip(name, curves, options = {}) {
7860
+ return options.semanticAnimation ? this.semanticAnimationToClip(name, options.semanticAnimation, { ...options, faceCurves: curves }) : this.build({ name, kind: "curves", input: copy(curves), options: copy(options) }, options, false);
7861
+ }
7862
+ snippetToClip(name, curves, options = {}) {
7863
+ return this.buildClip(name, curves, options);
7864
+ }
7865
+ buildTypedClip(name, channels, options = {}) {
7866
+ return this.build({ name, kind: "typed", input: copy(channels), options: copy(options) }, options, false);
7867
+ }
7868
+ typedSnippetToClip(name, channels, options = {}) {
7869
+ return this.buildTypedClip(name, channels, options);
7870
+ }
7871
+ semanticAnimationToClip(name, animation, options = {}) {
7872
+ return this.build({ name, kind: "semantic", input: copy(animation), options: copy(options) }, options, false);
7873
+ }
7874
+ playSnippet(snippet, curvesOrOptions = {}, options = {}) {
7875
+ return typeof snippet === "string" ? this.buildClip(snippet, curvesOrOptions, options).play() : this.buildClip(snippet.name, snippet.curves, curvesOrOptions).play();
7876
+ }
7877
+ playTypedSnippet(snippet, options = {}) {
7878
+ return this.buildTypedClip(snippet.name, snippet.channels, options).play();
7879
+ }
7880
+ playClip(value) {
7881
+ return typeof value === "string" ? this.playAnimation(value) : value.play();
7882
+ }
7883
+ supportsClipCurves() {
7884
+ return true;
7885
+ }
7886
+ cleanupSnippet(name) {
7887
+ this.stopAnimation(name);
7888
+ this.sources.delete(name);
7889
+ this.core.cleanup_snippet(name);
7890
+ }
7891
+ crossfadeTo(name, seconds, options = {}) {
7892
+ const outgoing = [...this.current.values()].filter((playback) => !playback.source.name.startsWith("__embody_"));
7893
+ const handle = this.playAnimation(name, { ...options, fadeInSec: seconds });
7894
+ for (const playback of outgoing) if (playback.connector.getAction(playback.id)) playback.connector.fadeOut(playback.id, seconds);
7895
+ return handle;
7896
+ }
7897
+ stopAnimation(name) {
7898
+ const playback = this.current.get(name);
7899
+ if (!playback) return;
7900
+ if (playback.connector.getAction(playback.id)) playback.connector.control(playback.id, { type: "stop" });
7901
+ this.forget(playback);
7902
+ }
7903
+ stopAllAnimations() {
7904
+ for (const playback of [...this.playbacks.values()]) {
7905
+ if (playback.source.kind === "compiled") continue;
7906
+ if (playback.connector.getAction(playback.id)) playback.connector.control(playback.id, { type: "stop" });
7907
+ this.forget(playback);
7908
+ }
7909
+ }
7910
+ pauseAnimation(name) {
7911
+ const p = this.current.get(name);
7912
+ if (p) p.connector.control(p.id, { type: "pause" });
7913
+ }
7914
+ resumeAnimation(name) {
7915
+ const p = this.current.get(name);
7916
+ if (!p) return;
7917
+ if (p.terminal) p.replay({ ...p.options, time: p.connector.getAction(p.id)?.time ?? 0 });
7918
+ else p.connector.control(p.id, { type: "resume" });
7919
+ }
7920
+ pauseAllAnimations() {
7921
+ for (const p of this.playbacks.values()) if (!p.terminal) p.connector.control(p.id, { type: "pause" });
7922
+ }
7923
+ resumeAllAnimations() {
7924
+ for (const name of [...this.current.keys()]) this.resumeAnimation(name);
7925
+ }
7926
+ updateClipParams(name, options) {
7927
+ const p = this.current.get(name);
7928
+ if (p) this.updatePlayback(p, options);
7929
+ }
7930
+ setAnimationSpeed(name, value) {
7931
+ this.updateClipParams(name, { speed: value });
7932
+ }
7933
+ setAnimationIntensity(name, value) {
7934
+ this.updateClipParams(name, { intensityScale: value });
7935
+ }
7936
+ setAnimationLoop(name, value) {
7937
+ this.updateClipParams(name, { loopMode: value ? "repeat" : "once" });
7938
+ }
7939
+ setAnimationLoopMode(name, value) {
7940
+ this.updateClipParams(name, { loopMode: value });
7941
+ }
7942
+ setAnimationRepeatCount(name, value) {
7943
+ this.updateClipParams(name, { loopMode: "repeat", repeatCount: value });
7944
+ }
7945
+ setAnimationReverse(name, value) {
7946
+ this.updateClipParams(name, { reverse: value });
7947
+ }
7948
+ setAnimationBlendMode(name, value) {
7949
+ this.updateClipParams(name, { blendMode: value });
7950
+ }
7951
+ setAnimationEasing(name, value) {
7952
+ this.validateEasing({ easing: value });
7953
+ this.updateClipParams(name, { easing: value });
7954
+ }
7955
+ seekAnimation(name, value) {
7956
+ this.updateClipParams(name, { time: value });
7957
+ }
7958
+ setAnimationTime(name, value) {
7959
+ this.seekAnimation(name, value);
7960
+ }
7961
+ setSnippetTime(name, value) {
7962
+ this.seekAnimation(name, value);
7963
+ }
7964
+ seekSnippet(name, value) {
7965
+ this.seekAnimation(name, value);
7966
+ }
7967
+ seek(name, value) {
7968
+ this.seekAnimation(name, value);
7969
+ }
7970
+ setAnimationTimeScale(value) {
7971
+ this.requireConnector().setTimeScale(value);
7972
+ this.timeScale = value;
7973
+ }
7974
+ getAnimationState(name) {
7975
+ const p = this.current.get(name);
7976
+ const action = p?.connector.getAction(p.id);
7977
+ if (!action || !p) {
7978
+ if (p) this.forget(p);
7979
+ return { name, playing: false, isPlaying: false };
7980
+ }
7981
+ const playing = action.isRunning();
7982
+ return {
7983
+ name,
7984
+ actionId: p.id,
7985
+ playing,
7986
+ isPlaying: playing,
7987
+ paused: action.paused,
7988
+ completed: p.terminal,
7989
+ time: action.time,
7990
+ duration: action.getClip().duration,
7991
+ speed: action.timeScale,
7992
+ intensityScale: intensity(p.options),
7993
+ mixerWeight: action.getEffectiveWeight(),
7994
+ loopMode: action.loop === LoopOnce ? "once" : action.loop === LoopPingPong ? "pingpong" : "repeat",
7995
+ repeatCount: Number.isFinite(action.repetitions) ? action.repetitions : null,
7996
+ blendMode: action.blendMode === AdditiveAnimationBlendMode ? "additive" : "replace"
7997
+ };
7998
+ }
7999
+ getPlayingAnimations() {
8000
+ return [...this.current.keys()].filter((name) => this.getAnimationState(name).playing);
8001
+ }
8002
+ commitLive(durationMs = 0) {
8003
+ const connector = this.requireConnector();
8004
+ const duration = Math.max(0, durationMs) / 1e3;
8005
+ const clip = parse(this.core.build_live_clip("__embody_live", duration));
8006
+ const touched = new Set(parse(this.core.live_command_targets_json()).map(targetKey));
8007
+ const tracks = new Map(clip.tracks.map((track) => [targetKey(track.target), track]));
8008
+ const handles = [];
8009
+ for (const [key, previous] of this.liveTargets) {
8010
+ if (tracks.has(key)) continue;
8011
+ if (previous.releasing && !touched.has(key)) continue;
8012
+ const action = previous.handle.actionId && connector.getAction(previous.handle.actionId);
8013
+ if (!action || duration === 0) {
8014
+ previous.handle.stop();
8015
+ this.liveTargets.delete(key);
8016
+ continue;
8017
+ }
8018
+ const nativeTrack = action.getClip().tracks[0];
8019
+ const sample = Array.from(nativeTrack.createInterpolant().evaluate(action.time));
8020
+ const released = { ...previous.track, times: [0, duration], values: [...sample, ...sample], inheritStart: false };
8021
+ const releaseClip = { ...clip, name: previous.handle.name, tracks: [released] };
8022
+ const handle = this.handle(
8023
+ { name: releaseClip.name, kind: "compiled", clip: releaseClip },
8024
+ { loopMode: "once", finalPose: "release", mixerWeight: action.getEffectiveWeight() },
8025
+ true
8026
+ );
8027
+ connector.fadeOut(handle.actionId, duration);
8028
+ const record = { track: released, handle, releasing: true };
8029
+ this.liveTargets.set(key, record);
8030
+ void handle.promise.then(() => {
8031
+ if (this.liveTargets.get(key) === record) this.liveTargets.delete(key);
6882
8032
  });
8033
+ handles.push(handle);
8034
+ }
8035
+ for (const [key, track] of tracks) {
8036
+ const previous = this.liveTargets.get(key);
8037
+ const endpoint = (value) => value.values.slice(value.values.length / value.times.length * (value.times.length - 1));
8038
+ if (previous && !previous.releasing && !touched.has(key) && json2(endpoint(previous.track)) === json2(endpoint(track))) continue;
8039
+ const name = previous?.handle.name ?? `__embody_live_${this.nextLiveTarget++}`;
8040
+ const outgoing = previous?.handle.actionId && connector.getAction(previous.handle.actionId);
8041
+ let nativeTrack = track;
8042
+ if (duration > 0 && outgoing) {
8043
+ const start = Array.from(outgoing.getClip().tracks[0].createInterpolant().evaluate(outgoing.time));
8044
+ nativeTrack = { ...track, values: [...start, ...endpoint(track)], inheritStart: false };
8045
+ }
8046
+ const targetClip = { ...clip, name, tracks: [nativeTrack] };
8047
+ const handle = this.handle({ name, kind: "compiled", clip: targetClip }, { loopMode: "once", finalPose: "hold" }, true);
8048
+ this.liveTargets.set(key, { track, handle, releasing: false });
8049
+ handles.push(handle);
8050
+ }
8051
+ return handles;
8052
+ }
8053
+ mutateLive(mutate, durationMs = 0) {
8054
+ this.requireModel();
8055
+ this.core.begin_live_command();
8056
+ mutate();
8057
+ return this.commitLive(durationMs);
8058
+ }
8059
+ transition(handles) {
8060
+ let settled = handles.length === 0;
8061
+ const promise = Promise.all(handles.map((handle) => handle.promise)).then(() => {
8062
+ settled = true;
8063
+ });
8064
+ const control = (command) => {
8065
+ if (settled) return;
8066
+ for (const handle of handles) {
8067
+ const playback = handle.actionId && this.playbacks.get(handle.actionId);
8068
+ if (!playback || !playback.connector.getAction(playback.id)) continue;
8069
+ if (command === "cancel" || !playback.terminal) handle[command]();
8070
+ }
8071
+ };
8072
+ return { promise, pause: () => control("pause"), resume: () => control("resume"), cancel: () => control("cancel") };
8073
+ }
8074
+ setAU(id, value, balance = this.core.get_au_balance(id)) {
8075
+ this.mutateLive(() => this.core.set_au_signed(id, value, balance));
8076
+ }
8077
+ getAU(id) {
8078
+ return this.core.get_au(id);
8079
+ }
8080
+ getAUBalance(id) {
8081
+ return this.core.get_au_balance(id);
8082
+ }
8083
+ getBodyControls() {
8084
+ return parse(this.core.get_body_controls_json());
8085
+ }
8086
+ getSemanticPoseCatalog() {
8087
+ return parse(this.core.get_semantic_pose_catalog_json());
8088
+ }
8089
+ captureSemanticPose() {
8090
+ return parse(this.core.capture_semantic_pose_json());
8091
+ }
8092
+ validateSemanticPose(pose) {
8093
+ return parse(this.core.validate_semantic_pose_json(json2(pose)));
8094
+ }
8095
+ applySemanticPose(pose) {
8096
+ this.mutateLive(() => this.core.apply_semantic_pose_json(json2(pose)));
8097
+ }
8098
+ validateSemanticAnimation(animation, options = {}) {
8099
+ this.core.validate_semantic_animation_json(json2(animation), json2(options));
8100
+ }
8101
+ resetBodyControls() {
8102
+ this.mutateLive(() => this.core.reset_body_controls());
8103
+ }
8104
+ setContinuum(negative, positive, value, balance = NaN) {
8105
+ this.mutateLive(() => this.core.set_continuum(negative, positive, value, balance));
8106
+ }
8107
+ getContinuum(negative, positive) {
8108
+ return this.core.get_continuum(negative, positive);
8109
+ }
8110
+ transitionAU(id, value, durationMs = 200, balance = this.core.get_au_balance(id)) {
8111
+ return this.transition(this.mutateLive(() => this.core.set_au_signed(id, value, balance), durationMs));
8112
+ }
8113
+ setViseme(index, value, jawScale = 1) {
8114
+ this.mutateLive(() => {
8115
+ this.core.set_viseme(index, value);
8116
+ this.core.set_viseme_jaw_scale(index, jawScale);
8117
+ });
8118
+ }
8119
+ getViseme(index) {
8120
+ return this.core.get_viseme(index);
8121
+ }
8122
+ getVisemeJawScale(index) {
8123
+ return this.core.get_viseme_jaw_scale(index);
8124
+ }
8125
+ setVisemeById(id, value, jawScale = 1) {
8126
+ const index = this.core.viseme_slot_index(id);
8127
+ if (index < 0) throw new Error(`Unknown viseme: ${id}`);
8128
+ this.setViseme(index, value, jawScale);
8129
+ }
8130
+ transitionViseme(index, value, durationMs = 80, jawScale = 1) {
8131
+ return this.transition(this.mutateLive(() => {
8132
+ this.core.set_viseme(index, value);
8133
+ this.core.set_viseme_jaw_scale(index, jawScale);
8134
+ }, durationMs));
8135
+ }
8136
+ transitionVisemeById(id, value, durationMs = 80, jawScale = 1) {
8137
+ const index = this.core.viseme_slot_index(id);
8138
+ if (index < 0) return this.transition([]);
8139
+ return this.transitionViseme(index, value, durationMs, jawScale);
8140
+ }
8141
+ setAUMixWeight(id, value) {
8142
+ var _a, _b;
8143
+ const weight = Math.max(0, Math.min(1, value));
8144
+ this.mutateLive(() => this.core.set_au_mix_weight(id, weight));
8145
+ ((_a = this.profile).auMixDefaults ?? (_a.auMixDefaults = {}))[id] = weight;
8146
+ ((_b = this.profileSource).auMixDefaults ?? (_b.auMixDefaults = {}))[id] = weight;
8147
+ }
8148
+ getAUMixWeight(id) {
8149
+ return this.core.get_au_mix_weight(id);
8150
+ }
8151
+ hasLeftRightBones(id) {
8152
+ return this.core.has_left_right_bones(id);
8153
+ }
8154
+ setMorph(key, value, meshNames = []) {
8155
+ this.mutateLive(() => {
8156
+ if (typeof key === "number") this.core.set_morph_index(key, value, json2(meshNames));
8157
+ else this.core.set_morph(key, value, json2(meshNames));
8158
+ });
8159
+ }
8160
+ setMorphOnMeshes(meshNames, key, value) {
8161
+ this.setMorph(key, value, meshNames);
8162
+ }
8163
+ releaseMorph(key, meshNames = []) {
8164
+ this.mutateLive(() => {
8165
+ if (typeof key === "number") this.core.release_morph_index(key, json2(meshNames));
8166
+ else this.core.release_morph(key, json2(meshNames));
8167
+ });
8168
+ }
8169
+ transitionMorph(key, value, durationMs = 120, meshNames = []) {
8170
+ return this.transition(this.mutateLive(() => {
8171
+ if (typeof key === "number") this.core.set_morph_index(key, value, json2(meshNames));
8172
+ else this.core.set_morph(key, value, json2(meshNames));
8173
+ }, durationMs));
8174
+ }
8175
+ getMorphTargets() {
8176
+ return Object.fromEntries(this.meshes.map((mesh) => [mesh.name, Object.keys(mesh.morphTargetDictionary ?? {}).sort()]));
8177
+ }
8178
+ getMorphTargetIndices() {
8179
+ return Object.fromEntries(this.meshes.map((mesh) => [mesh.name, Object.entries(mesh.morphTargetDictionary ?? {}).map(([name, index]) => ({ name, index })).sort((a, b) => a.index - b.index)]));
8180
+ }
8181
+ addMorphTarget(target, options) {
8182
+ const index = this.applier.addMorphTarget(this.requireModel(), target, options);
8183
+ this.bindModel();
8184
+ return index;
8185
+ }
8186
+ addMorphTargets(targets, options) {
8187
+ const result = this.applier.addMorphTargets(this.requireModel(), targets, options);
8188
+ this.bindModel();
8189
+ return result;
8190
+ }
8191
+ meshCategory(mesh) {
8192
+ return this.profile.meshes?.[mesh.name]?.category ?? "other";
8193
+ }
8194
+ getMeshList() {
8195
+ return (this.inspection?.allMeshes ?? []).map((mesh) => ({ name: mesh.name, visible: mesh.visible, morphCount: mesh.morphTargetInfluences?.length ?? 0, category: this.meshCategory(mesh) }));
8196
+ }
8197
+ getBones() {
8198
+ return this.bones;
8199
+ }
8200
+ meshProfile(name) {
8201
+ var _a, _b;
8202
+ return (_b = (_a = this.profile).meshes ?? (_a.meshes = {}))[name] ?? (_b[name] = { category: "other" });
8203
+ }
8204
+ setMeshVisible(name, visible) {
8205
+ this.applier.setMeshVisible(this.requireModel(), name, visible);
8206
+ this.meshProfile(name).visible = visible;
8207
+ }
8208
+ highlightMesh(name, color, value) {
8209
+ this.applier.highlightMesh(this.requireModel(), name, color, value);
8210
+ }
8211
+ getMeshMaterialConfig(name) {
8212
+ return this.applier.getMeshMaterialConfig(this.requireModel(), name);
8213
+ }
8214
+ setMeshMaterialConfig(name, value) {
8215
+ this.applier.setMeshMaterialConfig(this.requireModel(), name, value);
8216
+ const entry = this.meshProfile(name);
8217
+ entry.material = { ...entry.material, ...value };
8218
+ }
8219
+ registerHairObjects(objects) {
8220
+ this.hairObjects.clear();
8221
+ for (const object of objects) if (object.isMesh) this.hairObjects.set(object.name, object);
8222
+ for (const category of ["hair", "eyebrow"]) {
8223
+ const mesh = [...this.hairObjects.values()].find((object) => this.meshCategory(object) === category);
8224
+ const material = mesh && (Array.isArray(mesh.material) ? mesh.material[0] : mesh.material);
8225
+ if (material) this.hairAppearance[`${category}Color`] = { ...this.hairAppearance[`${category}Color`], baseColor: material.color ? `#${material.color.getHexString()}` : "#000000", emissive: material.emissive ? `#${material.emissive.getHexString()}` : "#000000", emissiveIntensity: material.emissiveIntensity ?? 0 };
8226
+ }
8227
+ this.restartHair();
8228
+ return [...this.hairObjects.values()].map((mesh) => ({ name: mesh.name, isMesh: true, isEyebrow: this.meshCategory(mesh) === "eyebrow" }));
8229
+ }
8230
+ getRegisteredHairObjects() {
8231
+ return [...this.hairObjects.values()];
8232
+ }
8233
+ getHairMorphTargets(name) {
8234
+ const meshes = name ? [this.hairObjects.get(name)] : [...this.hairObjects.values()];
8235
+ return [...new Set(meshes.flatMap((mesh) => Object.keys(mesh?.morphTargetDictionary ?? {})))].sort();
8236
+ }
8237
+ getHairAppearance() {
8238
+ return copy(this.hairAppearance);
8239
+ }
8240
+ setHairAppearance(category, value) {
8241
+ const key = `${category}Color`;
8242
+ const next = parse(this.wasm.normalize_hair_color_appearance_json(json2(value), json2(this.hairAppearance[key])));
8243
+ this.hairAppearance[key] = next;
8244
+ this.applier.applyHairAppearance([...this.hairObjects.values()].filter((mesh) => this.meshCategory(mesh) === category), next);
8245
+ }
8246
+ setHairColor(value) {
8247
+ this.setHairAppearance("hair", value);
8248
+ }
8249
+ setEyebrowColor(value) {
8250
+ this.setHairAppearance("eyebrow", value);
8251
+ }
8252
+ setHairBaseColor(value) {
8253
+ this.setHairColor({ baseColor: value });
8254
+ }
8255
+ setEyebrowBaseColor(value) {
8256
+ this.setEyebrowColor({ baseColor: value });
8257
+ }
8258
+ setHairGlow(color, value) {
8259
+ this.setHairColor({ emissive: color, emissiveIntensity: value });
8260
+ }
8261
+ setEyebrowGlow(color, value) {
8262
+ this.setEyebrowColor({ emissive: color, emissiveIntensity: value });
8263
+ }
8264
+ setHairOutline(value) {
8265
+ Object.assign(this.hairAppearance, { showOutline: value.show }, value.color ? { outlineColor: value.color } : {}, value.opacity !== void 0 ? { outlineOpacity: value.opacity } : {});
8266
+ }
8267
+ restartHair() {
8268
+ for (const name of [...this.current.keys()]) if (name.startsWith("__embody_hair")) this.stopAnimation(name);
8269
+ if (!this.hairConfig.enabled || !this.hairObjects.size || !this.connector) return;
8270
+ if (this.hairConfig.idleSwayAmount > 0 || this.hairConfig.windStrength > 0) {
8271
+ const curves = parse(this.wasm.build_hair_idle_curves(json2(this.hairConfig), this.hairConfig.idleClipDuration));
8272
+ if (Object.keys(curves).length) this.playSnippet("__embody_hair_idle", curves, { loopMode: "repeat", meshNames: [...this.hairObjects.keys()], source: "hair", blendMode: "additive" });
6883
8273
  }
6884
- return { target: point2(target), eyes, headLimited, missingHead: !this.head, missingEyes: this.eyes.length < 2 };
8274
+ }
8275
+ setHairPhysicsEnabled(value) {
8276
+ this.setHairPhysicsConfig({ enabled: value });
8277
+ }
8278
+ isHairPhysicsEnabled() {
8279
+ return !!this.hairConfig.enabled;
8280
+ }
8281
+ setHairPhysicsConfig(value) {
8282
+ this.hairConfig = parse(this.core.set_hair_config_json(json2(value)));
8283
+ this.restartHair();
8284
+ }
8285
+ getHairPhysicsConfig() {
8286
+ return copy(this.hairConfig);
8287
+ }
8288
+ validateHairMorphTargets() {
8289
+ return parse(this.core.get_missing_hair_morph_targets_json(json2(this.getHairMorphTargets())));
8290
+ }
8291
+ applyHairStateToObject(name, state) {
8292
+ const mesh = this.hairObjects.get(name);
8293
+ if (!mesh) return;
8294
+ if (state.visible !== void 0) mesh.visible = state.visible;
8295
+ if (state.scale) mesh.scale.set(state.scale.x, state.scale.y, state.scale.z);
8296
+ if (state.position) mesh.position.set(state.position.x, state.position.y, state.position.z);
8297
+ if (state.color) this.applier.applyHairAppearance([mesh], state.color);
8298
+ }
8299
+ authoredHeadMotion(clip) {
8300
+ if (!this.hairConfig.enabled || clip.name.startsWith("__embody_hair") || !this.hairObjects.size) return void 0;
8301
+ const tracks = [];
8302
+ for (const track of clip.tracks) {
8303
+ if (track.ValueTypeName !== "quaternion") continue;
8304
+ const parsed = PropertyBinding.parseTrackName(track.name);
8305
+ let object = PropertyBinding.findNode(this.requireModel(), parsed.nodeName);
8306
+ if (parsed.objectName === "bones" && object) {
8307
+ const skeleton = object.skeleton;
8308
+ object = skeleton?.bones.find((bone) => bone.name === String(parsed.objectIndex)) ?? skeleton?.bones[Number(parsed.objectIndex)];
8309
+ }
8310
+ if (!object) continue;
8311
+ const cubic = track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true;
8312
+ const stride = track.getValueSize();
8313
+ const reference = this.restValues(track);
8314
+ if (!reference) continue;
8315
+ const samples = [];
8316
+ for (let index = 0; index < track.times.length; index += 1) {
8317
+ const offset = index * stride + (cubic ? 4 : 0);
8318
+ samples.push(Array.from(track.values.subarray(offset, offset + 4)));
8319
+ }
8320
+ tracks.push({ boneName: object.name, current: object.quaternion.toArray(), reference, samples });
8321
+ }
8322
+ return parse(this.core.resolve_hair_motion_json(json2(tracks), clip.blendMode === AdditiveAnimationBlendMode)) ?? void 0;
8323
+ }
8324
+ setHairGravity(pitch, durationSeconds) {
8325
+ const clip = parse(this.core.build_hair_gravity_clip("__embody_hair_gravity", pitch, durationSeconds, json2({ meshNames: [...this.hairObjects.keys()], source: "hair" })));
8326
+ if (!clip.tracks.length) return;
8327
+ this.handle({ name: clip.name, kind: "compiled", clip }, { loopMode: "once", finalPose: "hold", blendMode: "additive" }, true);
8328
+ }
8329
+ playHairImpulse(horizontal, vertical) {
8330
+ if (!this.hairConfig.enabled || !this.hairObjects.size) return void 0;
8331
+ const curves = parse(this.wasm.build_hair_impulse_curves(json2(this.hairConfig), this.hairConfig.impulseClipDuration, horizontal, vertical));
8332
+ if (!Object.keys(curves).length) return void 0;
8333
+ return this.playSnippet("__embody_hair_impulse", curves, { loopMode: "once", finalPose: "release", meshNames: [...this.hairObjects.keys()], source: "hair", blendMode: "additive" });
8334
+ }
8335
+ start() {
8336
+ this.assertAlive();
8337
+ this.rendering = true;
8338
+ this.connector?.setRendering(true);
8339
+ }
8340
+ stop() {
8341
+ this.assertAlive();
8342
+ this.rendering = false;
8343
+ this.connector?.setRendering(false);
8344
+ }
8345
+ clear() {
8346
+ this.mutateLive(() => this.core.clear());
8347
+ }
8348
+ resetToNeutral() {
8349
+ this.clear();
8350
+ }
8351
+ dispose() {
8352
+ if (this.disposed) return;
8353
+ this.connector?.dispose();
8354
+ this.core.free();
8355
+ this.playbacks.clear();
8356
+ this.current.clear();
8357
+ this.sources.clear();
8358
+ this.hairObjects.clear();
8359
+ this.meshes.length = 0;
8360
+ this.meshByName.clear();
8361
+ this.bones = {};
8362
+ this.liveTargets.clear();
8363
+ this.connector = void 0;
8364
+ this.inspection = void 0;
8365
+ this.boundModel = void 0;
8366
+ this.disposed = true;
6885
8367
  }
6886
8368
  };
8369
+ function createRustEmbodyHostUnbound(config = {}) {
8370
+ return new Embody(config);
8371
+ }
8372
+ async function createRustEmbodyHost(model, config = {}) {
8373
+ const character = await Embody.create(config);
8374
+ try {
8375
+ character.onReady({ model, meshes: config.meshes, referencePose: config.referencePose });
8376
+ return character;
8377
+ } catch (error) {
8378
+ character.dispose();
8379
+ throw error;
8380
+ }
8381
+ }
6887
8382
  var draco = null;
6888
8383
  var dracoPath = "";
6889
8384
  var gltfLoader = null;
@@ -7437,7 +8932,7 @@ function createDefaultCharacterSceneRuntime(container, options = {}) {
7437
8932
  if (pendingRendererChange && preference === settings.preference && (status === "initializing" || status === "switching")) return pendingRendererChange;
7438
8933
  if (status === "ready" && preference === settings.preference) return Promise.resolve(getSnapshot());
7439
8934
  settings = { preference };
7440
- const request2 = ++generation;
8935
+ const request3 = ++generation;
7441
8936
  const previous = pending;
7442
8937
  status = active ? "switching" : "initializing";
7443
8938
  error = null;
@@ -7451,7 +8946,7 @@ function createDefaultCharacterSceneRuntime(container, options = {}) {
7451
8946
  let restoreModelSkinning = () => {
7452
8947
  };
7453
8948
  const check = () => {
7454
- if (disposed || generation !== request2) throw renderingAborted();
8949
+ if (disposed || generation !== request3) throw renderingAborted();
7455
8950
  if (!active) throwIfAborted(options.signal);
7456
8951
  if (candidate?.lost) throw candidate.lost;
7457
8952
  };
@@ -7534,7 +9029,7 @@ function createDefaultCharacterSceneRuntime(container, options = {}) {
7534
9029
  if (attached && candidate?.renderer.domElement.parentElement === container) container.removeChild(candidate.renderer.domElement);
7535
9030
  rollback(() => environment?.dispose());
7536
9031
  rollback(() => candidate?.dispose());
7537
- const canceled = disposed || generation !== request2 || !active && options.signal?.aborted;
9032
+ const canceled = disposed || generation !== request3 || !active && options.signal?.aborted;
7538
9033
  if (!disposed) {
7539
9034
  rollback(restoreModelSkinning);
7540
9035
  rollback(restoreCameraCoordinates);
@@ -7546,7 +9041,7 @@ function createDefaultCharacterSceneRuntime(container, options = {}) {
7546
9041
  owner.reportFailure(resumeError, active.renderer);
7547
9042
  }
7548
9043
  }
7549
- if (generation === request2) {
9044
+ if (generation === request3) {
7550
9045
  status = active?.lost ? "lost" : "error";
7551
9046
  error = failure instanceof Error ? failure : new Error(String(failure));
7552
9047
  notify();
@@ -7723,6 +9218,184 @@ async function createDefaultCharacterSceneAsync(container, options = {}) {
7723
9218
  }
7724
9219
  }
7725
9220
 
9221
+ // three/characterHost.ts
9222
+ async function createCharacterHost(options) {
9223
+ if (!options.container) throw new Error("createCharacterHost requires a container HTMLElement");
9224
+ if (!options.character?.modelUrl) throw new Error("createCharacterHost requires character.modelUrl");
9225
+ let loaded;
9226
+ let state;
9227
+ let engine;
9228
+ let controller;
9229
+ let disposed = false;
9230
+ let disposal;
9231
+ let switching = Promise.resolve();
9232
+ let mountedCanvas;
9233
+ const aborted = () => new DOMException("Character host creation was aborted", "AbortError");
9234
+ const checkCreation = () => {
9235
+ if (options.signal?.aborted) throw aborted();
9236
+ };
9237
+ const releaseModel = async (value) => {
9238
+ const release = () => disposeCharacterModel(state?.scene ?? null, value.model);
9239
+ if (state?.rendering) await state.rendering.releaseSceneResources(release);
9240
+ else release();
9241
+ };
9242
+ const makeEngine = (value, character) => {
9243
+ const next = new Embody({ ...options.embody, presetType: character.presetType ?? options.embody?.presetType, profile: character.profile ?? options.embody?.profile });
9244
+ try {
9245
+ next.onReady(value);
9246
+ return next;
9247
+ } catch (error) {
9248
+ try {
9249
+ next.dispose();
9250
+ } catch {
9251
+ }
9252
+ throw error;
9253
+ }
9254
+ };
9255
+ const dispose = () => {
9256
+ if (disposal) return disposal;
9257
+ disposed = true;
9258
+ disposal = (async () => {
9259
+ let failure;
9260
+ const attempt = async (release) => {
9261
+ try {
9262
+ await release();
9263
+ } catch (error) {
9264
+ failure ?? (failure = error);
9265
+ }
9266
+ };
9267
+ await attempt(() => controller?.dispose());
9268
+ await switching.catch(() => {
9269
+ });
9270
+ await attempt(() => engine?.dispose());
9271
+ const ownedScene = !options.external && state && "dispose" in state ? state : void 0;
9272
+ if (ownedScene) await attempt(() => ownedScene.dispose());
9273
+ const lastModel = loaded;
9274
+ if (lastModel) await attempt(() => releaseModel(lastModel));
9275
+ mountedCanvas?.remove();
9276
+ if (failure !== void 0) throw failure;
9277
+ })();
9278
+ return disposal;
9279
+ };
9280
+ try {
9281
+ checkCreation();
9282
+ loaded = await loadCharacterModel(options.character.modelUrl, options.loader);
9283
+ checkCreation();
9284
+ state = options.external ?? await createDefaultCharacterSceneAsync(options.container, { ...options.scene, signal: options.signal });
9285
+ checkCreation();
9286
+ await initEmbodyCore();
9287
+ checkCreation();
9288
+ applyCharacterModelTransform(loaded.model, options.character);
9289
+ state.scene.add(loaded.model);
9290
+ engine = makeEngine(loaded, options.character);
9291
+ if (options.external?.mountCanvas && !state.renderer.domElement.parentElement) {
9292
+ mountedCanvas = state.renderer.domElement;
9293
+ options.container.appendChild(mountedCanvas);
9294
+ }
9295
+ if (options.renderLoop ?? !options.external) {
9296
+ if (!(state.camera instanceof PerspectiveCamera)) throw new Error("Character host rendering requires a PerspectiveCamera");
9297
+ controller = new DPthreeCameraController({
9298
+ scene: state.scene,
9299
+ camera: state.camera,
9300
+ domElement: state.renderer.domElement,
9301
+ ...state.rendering ? { rendering: state.rendering } : { renderer: state.renderer },
9302
+ showDOMControls: false
9303
+ });
9304
+ controller.setModel(loaded.model);
9305
+ await controller.prepareModelForRender(loaded.model, { signal: options.signal });
9306
+ if (options.autoFrame !== false) await controller.focusFullBody(0);
9307
+ }
9308
+ checkCreation();
9309
+ if (options.autoStart === false) engine.stop();
9310
+ else engine.start();
9311
+ const sceneState = state;
9312
+ const rendering = state.rendering ?? null;
9313
+ const host = {
9314
+ engine,
9315
+ scene: state.scene,
9316
+ camera: state.camera,
9317
+ get renderer() {
9318
+ return rendering ? rendering.getSnapshot().renderer : sceneState.renderer;
9319
+ },
9320
+ get backend() {
9321
+ return rendering ? rendering.getSnapshot().backend : sceneState.backend ?? null;
9322
+ },
9323
+ rendering,
9324
+ model: loaded.model,
9325
+ meshes: loaded.meshes,
9326
+ animations: loaded.animations,
9327
+ lighting: "lighting" in state ? state.lighting : null,
9328
+ ownsScene: !options.external,
9329
+ container: options.container,
9330
+ resize() {
9331
+ if ("resize" in sceneState) sceneState.resize();
9332
+ },
9333
+ setCharacter(character, loader = options.loader) {
9334
+ if (disposed) return Promise.reject(new Error("Character host is disposed"));
9335
+ const change = switching.catch(() => {
9336
+ }).then(async () => {
9337
+ if (disposed) throw new Error("Character host is disposed");
9338
+ const next = await loadCharacterModel(character.modelUrl, loader);
9339
+ let nextEngine;
9340
+ try {
9341
+ if (disposed) throw new Error("Character host is disposed");
9342
+ applyCharacterModelTransform(next.model, character);
9343
+ nextEngine = makeEngine(next, character);
9344
+ nextEngine.stop();
9345
+ sceneState.scene.add(next.model);
9346
+ if (controller) await controller.prepareModelForRender(next.model);
9347
+ if (disposed) throw new Error("Character host is disposed");
9348
+ } catch (error) {
9349
+ try {
9350
+ nextEngine?.dispose();
9351
+ } catch {
9352
+ }
9353
+ try {
9354
+ await releaseModel(next);
9355
+ } catch {
9356
+ }
9357
+ throw error;
9358
+ }
9359
+ const previous = loaded;
9360
+ try {
9361
+ engine.dispose();
9362
+ } catch (error) {
9363
+ try {
9364
+ nextEngine?.dispose();
9365
+ } catch {
9366
+ }
9367
+ try {
9368
+ await releaseModel(next);
9369
+ } catch {
9370
+ }
9371
+ throw error;
9372
+ }
9373
+ engine = nextEngine;
9374
+ loaded = next;
9375
+ host.engine = engine;
9376
+ host.model = next.model;
9377
+ host.meshes = next.meshes;
9378
+ host.animations = next.animations;
9379
+ controller?.setModel(next.model);
9380
+ if (options.autoStart !== false) engine.start();
9381
+ await releaseModel(previous);
9382
+ if (controller && options.autoFrame !== false) await controller.focusFullBody(0);
9383
+ });
9384
+ switching = change;
9385
+ return change;
9386
+ },
9387
+ dispose
9388
+ };
9389
+ return host;
9390
+ } catch (error) {
9391
+ try {
9392
+ await dispose();
9393
+ } catch {
9394
+ }
9395
+ throw error;
9396
+ }
9397
+ }
9398
+
7726
9399
  // three/index.ts
7727
9400
  var THREE_BLENDING_MODES = {
7728
9401
  Normal: NormalBlending,
@@ -7731,6 +9404,7 @@ var THREE_BLENDING_MODES = {
7731
9404
  Multiply: MultiplyBlending,
7732
9405
  None: NoBlending
7733
9406
  };
9407
+ var BLENDING_MODES = THREE_BLENDING_MODES;
7734
9408
  var MORPH_ATTRIBUTE_SEMANTICS = ["position", "normal", "tangent", "color"];
7735
9409
  var createNeutralMorphAttribute = (geometry, semantic, name) => {
7736
9410
  const base = geometry.getAttribute(semantic);
@@ -7925,6 +9599,8 @@ function createAnimationClipFromClipIR(clip, inspection) {
7925
9599
  const tracks = [];
7926
9600
  for (const track of clip.tracks ?? []) {
7927
9601
  const kind = track.target?.kind;
9602
+ const trackName = concreteTrackName(track.target, inspection);
9603
+ if (!trackName) continue;
7928
9604
  const times = Array.from(track.times ?? []);
7929
9605
  const values = Array.from(track.values ?? []);
7930
9606
  if (!times.length || !values.length) continue;
@@ -7932,7 +9608,6 @@ function createAnimationClipFromClipIR(clip, inspection) {
7932
9608
  if (kind === "morphTarget") {
7933
9609
  const binding = inspection.morphBindings.get(Number(track.target.morphTargetId));
7934
9610
  if (!binding?.mesh) continue;
7935
- const trackName = `${binding.mesh.uuid}.morphTargetInfluences[${binding.index}]`;
7936
9611
  if (track.inheritStart) {
7937
9612
  values[0] = binding.mesh.morphTargetInfluences?.[binding.index] ?? 0;
7938
9613
  }
@@ -7945,13 +9620,17 @@ function createAnimationClipFromClipIR(clip, inspection) {
7945
9620
  const property = track.target.property ?? "rotation";
7946
9621
  if (property === "rotation" || property === "quaternion") {
7947
9622
  if (track.inheritStart) object.quaternion.toArray(values, 0);
7948
- tracks.push(new QuaternionKeyframeTrack(`${object.uuid}.quaternion`, times, values, interpolation));
9623
+ tracks.push(new QuaternionKeyframeTrack(trackName, times, values, interpolation));
9624
+ } else if (property === "eulerX" || property === "eulerY" || property === "eulerZ") {
9625
+ const axis = property.slice(-1).toLowerCase();
9626
+ if (track.inheritStart) values[0] = object.rotation[axis];
9627
+ tracks.push(new NumberKeyframeTrack(trackName, times, values, interpolation));
7949
9628
  } else if (property === "position") {
7950
9629
  if (track.inheritStart) object.position.toArray(values, 0);
7951
- tracks.push(new VectorKeyframeTrack(`${object.uuid}.position`, times, values, interpolation));
9630
+ tracks.push(new VectorKeyframeTrack(trackName, times, values, interpolation));
7952
9631
  } else if (property === "scale") {
7953
9632
  if (track.inheritStart) object.scale.toArray(values, 0);
7954
- tracks.push(new VectorKeyframeTrack(`${object.uuid}.scale`, times, values, interpolation));
9633
+ tracks.push(new VectorKeyframeTrack(trackName, times, values, interpolation));
7955
9634
  }
7956
9635
  continue;
7957
9636
  }
@@ -7959,7 +9638,7 @@ function createAnimationClipFromClipIR(clip, inspection) {
7959
9638
  const mesh = inspection.meshBindings.get(Number(track.target.meshId));
7960
9639
  if (!mesh) continue;
7961
9640
  if (track.inheritStart) values[0] = Number(mesh.visible);
7962
- tracks.push(new NumberKeyframeTrack(`${mesh.uuid}.visible`, times, values, interpolation));
9641
+ tracks.push(new NumberKeyframeTrack(trackName, times, values, interpolation));
7963
9642
  }
7964
9643
  }
7965
9644
  const duration = Number.isFinite(clip.durationSeconds) ? Number(clip.durationSeconds) : -1;
@@ -7979,7 +9658,7 @@ function serializeAnimationClips(model, clips, inspection) {
7979
9658
  channelKinds.set(kind, id);
7980
9659
  return id;
7981
9660
  };
7982
- clip.tracks.forEach((track, index) => {
9661
+ withComponentTracks(clip).tracks.forEach((track, index) => {
7983
9662
  const found = findTrackTarget(model, track);
7984
9663
  if (!found?.object) return;
7985
9664
  const { parsed, object } = found;
@@ -7994,7 +9673,7 @@ function serializeAnimationClips(model, clips, inspection) {
7994
9673
  } else if (property === "visible" && object.isMesh) {
7995
9674
  target = { kind: "meshVisibility", meshId: meshIds.get(object) };
7996
9675
  } else {
7997
- const transformProperty = property === "quaternion" || property === "rotation" ? "rotation" : property === "position" ? "position" : property === "scale" ? "scale" : null;
9676
+ const transformProperty = property === "rotation" && ["x", "y", "z"].includes(String(parsed.propertyIndex)) ? `euler${String(parsed.propertyIndex).toUpperCase()}` : property === "quaternion" ? "rotation" : property === "position" ? "position" : property === "scale" ? "scale" : null;
7998
9677
  if (transformProperty) {
7999
9678
  const boneId = boneIds.get(object);
8000
9679
  target = boneId ? { kind: "boneTransform", boneId, property: transformProperty } : { kind: "objectTransform", objectId: objectIds.get(object), property: transformProperty };
@@ -8002,14 +9681,19 @@ function serializeAnimationClips(model, clips, inspection) {
8002
9681
  }
8003
9682
  if (!target) return;
8004
9683
  const kind = target.kind === "morphTarget" ? "face" : target.kind === "boneTransform" ? "body" : "scene";
8005
- const size = track.getValueSize();
9684
+ const cubic = !!track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline;
9685
+ const size = track.getValueSize() / (cubic ? 3 : 1);
9686
+ if (!Array.from(track.values).every(Number.isFinite)) {
9687
+ throw new Error(`Animation track ${JSON.stringify(track.name)} contains non-finite samples.`);
9688
+ }
9689
+ const values = cubic ? Array.from(track.times).flatMap((_, key) => Array.from(track.values.slice((key * 3 + 1) * size, (key * 3 + 2) * size))) : Array.from(track.values);
8006
9690
  tracks.push({
8007
9691
  id: index + 1,
8008
9692
  channelId: channelId(kind),
8009
9693
  target,
8010
9694
  valueType: size === 4 ? "quat" : size === 3 ? "vec3" : "scalar",
8011
9695
  times: Array.from(track.times),
8012
- values: Array.from(track.values),
9696
+ values,
8013
9697
  interpolation: track.getInterpolation() === InterpolateDiscrete ? "step" : "linear",
8014
9698
  sourceName: track.name
8015
9699
  });
@@ -8098,7 +9782,7 @@ var ThreeFrameApplier = class {
8098
9782
  mesh.visible = visible;
8099
9783
  });
8100
9784
  }
8101
- highlightMesh(root, name, color = 65535, intensity = 0.5) {
9785
+ highlightMesh(root, name, color = 65535, intensity2 = 0.5) {
8102
9786
  root.traverse((object) => {
8103
9787
  if (!object.isMesh) return;
8104
9788
  for (const material of materials(object.material)) {
@@ -8107,7 +9791,7 @@ var ThreeFrameApplier = class {
8107
9791
  if (name === object.name) {
8108
9792
  if (!this.originalEmissive.has(key)) this.originalEmissive.set(key, { color: material.emissive.getHex(), intensity: material.emissiveIntensity ?? 0 });
8109
9793
  material.emissive.setHex(color);
8110
- material.emissiveIntensity = intensity;
9794
+ material.emissiveIntensity = intensity2;
8111
9795
  } else {
8112
9796
  const original = this.originalEmissive.get(key);
8113
9797
  if (original) {
@@ -8276,6 +9960,6 @@ var collectMorphMeshes = (root) => {
8276
9960
  return meshes;
8277
9961
  };
8278
9962
 
8279
- export { CHARACTER_SCENE_TYPES, CHARACTER_SCENE_TYPE_IDS, DPthreeCameraController as CameraController, CameraDOMControls, CameraDOMControls as Controls, DEFAULT_CHARACTER_LIGHTING_PRESETS, DEFAULT_CHARACTER_LIGHTING_PRESET_ID, DEFAULT_CHARACTER_LIGHTING_PRESET_IDS, DEFAULT_CHARACTER_LIGHTING_SETTINGS, DEFAULT_CHARACTER_SCENE_TYPE_ID, DEFAULT_MARKER_AUTO_HIDE_MS, DEFAULT_PREVIEW_AUTO_CLEAR_MS, DPthree, DPthree3DMarkers, DPthreeCameraController, DPthreeHTMLMarkers, DPthreeMarkers, DPthree3DMarkers as Markers3D, DPthreeHTMLMarkers as MarkersHTML, RUNTIME_ANNOTATION_REGION_PREFIX, RustAnnotationCameraCore, THREE_BLENDING_MODES, ThreeFrameApplier, ThreeGazeFocus, ThreeModelInspector, applyCharacterModelTransform, bindModelReferencePose, boneResolutionProfile, buildRegionDisplayOptions, captureModelReferencePose, collectMorphMeshes, createAnimationClipFromClipIR, createDefaultCharacterLighting, createDefaultCharacterScene, createDefaultCharacterSceneAsync, createDefaultCharacterSceneRuntime, createMarkerLifecycleRevealOptions, createMarkerVisibilityLifecycle, createRuntimeAnnotationPreviewLifecycle, createRustAnnotationCameraCore, createShadowPlane, detectAnnotationLaterality, disposeCharacterModel, extendModelReferencePose, filterCameraViewRegions, getDefaultAnnotationLaterality, getModelLocalOrbitAngle, getRuntimeAUMeshSideOffset, getRuntimeAUMorphAnchorPoint, getRuntimeAnnotationSide, getSemanticHorizontalSign, getSemanticHorizontalSignForSide, getWorldDirectionForCameraAngle, inferRuntimeAnnotationPreviewSide, isRuntimeAnnotationRegionName, loadCharacterModel, normalizeDefaultCharacterLightingSettings, parseCharacterModel, passesMarkerCameraAngleGate, pickContinuumAnnotationAuId, resolveAnnotationCharacterConfig, resolveFaceCenter, resolveMarkerAnchorRegion, resolveRegionCameraAngle, resolveRegionVisibilityCameraAngle, serializeAnimationClips, shouldProjectMarkerAnchorToSurface, shouldUseFaceCenterForMarkerAnchor, toWorldDirection };
9963
+ export { BLENDING_MODES, CHARACTER_SCENE_TYPES, CHARACTER_SCENE_TYPE_IDS, DPthreeCameraController as CameraController, CameraDOMControls, CameraDOMControls as Controls, DEFAULT_CHARACTER_LIGHTING_PRESETS, DEFAULT_CHARACTER_LIGHTING_PRESET_ID, DEFAULT_CHARACTER_LIGHTING_PRESET_IDS, DEFAULT_CHARACTER_LIGHTING_SETTINGS, DEFAULT_CHARACTER_SCENE_TYPE_ID, DEFAULT_MARKER_AUTO_HIDE_MS, DEFAULT_PREVIEW_AUTO_CLEAR_MS, DPthree, DPthree3DMarkers, DPthreeCameraController, DPthreeHTMLMarkers, DPthreeMarkers, Embody, DPthree3DMarkers as Markers3D, DPthreeHTMLMarkers as MarkersHTML, RUNTIME_ANNOTATION_REGION_PREFIX, RustAnnotationCameraCore, THREE_BLENDING_MODES, ThreeFrameApplier, ThreeModelInspector, ThreeNativePlaybackConnector, analyzeModel, applyAUBoneBindingUpdate, applyBilateralAxisBindingUpdate, applyBoneAxisBindingUpdate, applyCharacterModelTransform, bindModelReferencePose, boneResolutionProfile, buildBoneAuOptions, buildRegionDisplayOptions, captureModelReferencePose, classifyAuAsJointControl, collectMorphMeshes, computeHumanoidSkeletonTemplateRestBounds, createAnimationClipFromClipIR, createBilateralBoneAxisAu, createBoneAxisAu, createCharacterHost, createDefaultCharacterLighting, createDefaultCharacterScene, createDefaultCharacterSceneAsync, createDefaultCharacterSceneRuntime, createMarkerLifecycleRevealOptions, createMarkerVisibilityLifecycle, createRuntimeAnnotationPreviewLifecycle, createRustAnnotationCameraCore, createRustEmbodyHost, createRustEmbodyHostUnbound, createScenePlaybackFrame, createShadowPlane, createValidationSkeletonFromHumanoidTemplate, detectAnnotationLaterality, disposeCharacterModel, ensureBilateralBoneNodeKeys, ensureBoneNodeKey, extendCharacterConfigWithPreset, extendModelReferencePose, extractHumanoidSkeletonTemplateFromModel, extractModelData, extractProfileOverrides, filterCameraViewRegions, findNodeKeyForBone, formatAxisDirectionLabel, formatAxisLabel, fuzzyNameMatch, getAUBoneBindingState, getAxisFromChannel, getBilateralAxisBindingState, getBodyControls, getBoneAxisBindingState, getDefaultAnnotationLaterality, getHumanoidSkeletonTemplate, getHumanoidSkeletonTemplateBoneNames, getHumanoidSpecification, getMeshNamesForAUProfile, getModelLocalOrbitAngle, getPreset, getRuntimeAUMeshSideOffset, getRuntimeAUMorphAnchorPoint, getRuntimeAnnotationSide, getSemanticHorizontalSign, getSemanticHorizontalSignForSide, getWorldDirectionForCameraAngle, hasLeftRightMorphs, inferChiralBoneNamePair, inferEyeControlFamily, inferEyeControlScope, inferRuntimeAnnotationPreviewSide, isJointControlAuInfo, isMaxDegreesOnlyAxisBindingUpdate, isMixedAU, isRuntimeAnnotationRegionName, loadCharacterModel, mergeCharacterRegionsByName, normalizeDefaultCharacterLightingSettings, normalizeHairColorAppearance, parseCharacterModel, passesMarkerCameraAngleGate, pickContinuumAnnotationAuId, renderScenePlayback, resolveAnnotationCharacterConfig, resolveBoneAxisChannel, resolveBoneNameForNodeKey, resolveBoneNames, resolveContinuumDisplayLabel, resolveFaceCenter, resolveHumanoidCharacterization, resolveMarkerAnchorRegion, resolveRegionCameraAngle, resolveRegionVisibilityCameraAngle, resolveVisemeProfile, serializeAnimationClips, setAUMorphTargets, setHumanoidRoleBinding, shouldProjectMarkerAnchorToSurface, shouldUseFaceCenterForMarkerAnchor, stripConfiguredBoneAffixes, supportsRustEmbodyPreset, toWorldDirection, validateHumanoidCharacterization, validateMappings };
8280
9964
  //# sourceMappingURL=three.js.map
8281
9965
  //# sourceMappingURL=three.js.map