@asiyst/sdk 0.1.34 → 0.1.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -85,7 +85,7 @@ var ALL_ACTION_KINDS = [
85
85
  // src/core/constants.ts
86
86
  function resolveSdkVersion() {
87
87
  {
88
- return "0.1.34";
88
+ return "0.1.36";
89
89
  }
90
90
  }
91
91
  var SDK_VERSION = resolveSdkVersion();
@@ -612,9 +612,30 @@ var HttpTransport = class {
612
612
  if (req.body !== void 0) {
613
613
  defaultHeaders["Content-Type"] = "application/json";
614
614
  }
615
+ const mergedHeaders = new Headers();
616
+ for (const [key, value] of Object.entries(defaultHeaders)) {
617
+ mergedHeaders.set(key, value);
618
+ }
619
+ if (req.headers) {
620
+ if (typeof req.headers.forEach === "function" && !Array.isArray(req.headers)) {
621
+ req.headers.forEach((value, key) => {
622
+ mergedHeaders.set(key, value);
623
+ });
624
+ } else if (Array.isArray(req.headers)) {
625
+ for (const [key, value] of req.headers) {
626
+ mergedHeaders.set(key, value);
627
+ }
628
+ } else if (typeof req.headers === "object") {
629
+ for (const [key, value] of Object.entries(req.headers)) {
630
+ if (value !== void 0 && value !== null) {
631
+ mergedHeaders.set(key, String(value));
632
+ }
633
+ }
634
+ }
635
+ }
615
636
  const response = await fetch(url, {
616
637
  method: req.method,
617
- headers: req.headers ?? defaultHeaders,
638
+ headers: mergedHeaders,
618
639
  body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
619
640
  signal: controller.signal
620
641
  });
@@ -832,9 +853,18 @@ var CloudClient = class {
832
853
  avatarId: this.avatarId || void 0
833
854
  }
834
855
  );
835
- let response;
836
- try {
837
- response = await this.transport.request({
856
+ let token;
857
+ if (this.runtimeAuth) {
858
+ try {
859
+ token = await this.getAuthToken();
860
+ } catch {
861
+ token = this.activeToken;
862
+ }
863
+ } else {
864
+ token = this.activeToken;
865
+ }
866
+ const executeRequest = async (authToken) => {
867
+ return this.transport.request({
838
868
  path: runtimeAvatarUrl,
839
869
  method: "GET",
840
870
  idempotent: true,
@@ -844,10 +874,26 @@ var CloudClient = class {
844
874
  "X-Asiyst-Public-Key": this.publicKey,
845
875
  "X-Asiyst-Project-Key": this.publicKey,
846
876
  "X-Asiyst-Project-Id": this.projectId,
877
+ "X-Asiyst-SDK-Version": SDK_VERSION,
847
878
  ...this.avatarId ? { "X-Asiyst-Avatar-Id": this.avatarId } : {},
848
- ...etag ? { "If-None-Match": etag } : {}
879
+ ...etag ? { "If-None-Match": etag } : {},
880
+ ...authToken ? { Authorization: `Bearer ${authToken}` } : {},
881
+ ...this.sessionId ? { "X-Asiyst-Session-Id": this.sessionId } : {}
849
882
  }
850
883
  });
884
+ };
885
+ let response;
886
+ try {
887
+ response = await executeRequest(token);
888
+ if (response.status === 401 && this.runtimeAuth) {
889
+ this.runtimeAuth.invalidate();
890
+ try {
891
+ token = await this.runtimeAuth.getToken();
892
+ this.activeToken = token;
893
+ response = await executeRequest(token);
894
+ } catch {
895
+ }
896
+ }
851
897
  } catch (err) {
852
898
  throw new AsiystError({
853
899
  code: "CORS_OR_NETWORK_FAILURE",
@@ -3303,27 +3349,57 @@ var RigDetector = class {
3303
3349
  return rawName.trim().replace(/^.*[:|/]/, "").replace(/^(mixamorig\d*|bip01|armature|root)[:_ ]?/i, "").replace(/[^a-zA-Z0-9._-]/g, "").toLowerCase();
3304
3350
  }
3305
3351
  /**
3306
- * Analyzes an imported 3D model root, identifies all bones, maps them to canonical AUBR,
3307
- * validates hierarchy, and reports capability profile.
3352
+ * Analyzes an imported 3D model root, identifies all bones and skinned meshes,
3353
+ * maps them to canonical AUBR, validates hierarchy, and reports capability profile.
3308
3354
  */
3309
- static detect(modelRoot) {
3355
+ static detect(modelRoot, options) {
3310
3356
  const allBones = [];
3357
+ const seenBones = /* @__PURE__ */ new Set();
3358
+ const skinnedMeshes = [];
3311
3359
  modelRoot.traverse((node) => {
3312
- if (node.isBone) {
3360
+ if (node.isSkinnedMesh) {
3361
+ const sm = node;
3362
+ skinnedMeshes.push(sm);
3363
+ if (sm.skeleton?.bones) {
3364
+ for (const b of sm.skeleton.bones) {
3365
+ if (b && !seenBones.has(b)) {
3366
+ seenBones.add(b);
3367
+ allBones.push(b);
3368
+ }
3369
+ }
3370
+ }
3371
+ }
3372
+ if (node.isBone && !seenBones.has(node)) {
3373
+ seenBones.add(node);
3313
3374
  allBones.push(node);
3314
3375
  }
3315
3376
  });
3316
3377
  if (allBones.length === 0) {
3317
3378
  modelRoot.traverse((node) => {
3379
+ if (node.isMesh) return;
3318
3380
  if (node.name && (node.type === "Bone" || /bone|joint|limb|hips|spine|arm|leg|head/i.test(node.name))) {
3319
- if (!allBones.includes(node)) {
3381
+ if (!seenBones.has(node)) {
3382
+ seenBones.add(node);
3320
3383
  allBones.push(node);
3321
3384
  }
3322
3385
  }
3323
3386
  });
3324
3387
  }
3388
+ const embeddedAnimationCount = typeof options?.embeddedAnimationCount === "number" && Number.isFinite(options.embeddedAnimationCount) ? Math.max(0, Math.floor(options.embeddedAnimationCount)) : Array.isArray(modelRoot.animations) ? modelRoot.animations.length : 0;
3389
+ const hasEmbeddedAnimations = embeddedAnimationCount > 0;
3390
+ const skinnedMeshCount = skinnedMeshes.length;
3391
+ const hasSkinnedMesh = skinnedMeshCount > 0;
3392
+ const boneCount = allBones.length;
3393
+ const hasSkeleton = boneCount > 0;
3325
3394
  if (allBones.length === 0) {
3326
- const caps = this.createUnsupportedCapabilities("unsupported", ["hips", "spine", "head"]);
3395
+ const caps = this.createUnsupportedCapabilities("unsupported", ["hips", "spine", "head"], {
3396
+ hasSkeleton,
3397
+ hasSkinnedMesh,
3398
+ boneCount,
3399
+ skinnedMeshCount,
3400
+ embeddedAnimationCount,
3401
+ hasEmbeddedAnimations
3402
+ });
3327
3403
  return {
3328
3404
  rigType: "unsupported",
3329
3405
  capabilities: caps,
@@ -3364,26 +3440,43 @@ var RigDetector = class {
3364
3440
  const hasArms = matchedBones.has("leftUpperArm") && matchedBones.has("leftLowerArm") && matchedBones.has("rightUpperArm") && matchedBones.has("rightLowerArm");
3365
3441
  const isHumanoid = hasHipsAndSpine && (hasLegs || hasArms);
3366
3442
  let finalRigType = rigFlavor;
3443
+ const detectedRigFlavor = isHumanoid ? rigFlavor : "unsupported";
3367
3444
  if (!isHumanoid) {
3368
3445
  finalRigType = "unsupported";
3369
3446
  } else if (missingRequired.length > 0) {
3370
3447
  finalRigType = "partial_humanoid";
3371
3448
  }
3449
+ const proceduralIdle = isHumanoid && hasHipsAndSpine && hasHead;
3450
+ const proceduralLocomotion = isHumanoid && hasLegs;
3451
+ const proceduralRunning = isHumanoid && hasLegs;
3452
+ const upperBodyGestures = isHumanoid && hasArms && hasHipsAndSpine;
3453
+ const proceduralAnimationAvailable = proceduralIdle || proceduralLocomotion || upperBodyGestures;
3454
+ const clipPlayback = hasSkeleton && allBones.length > 5 || hasEmbeddedAnimations;
3455
+ const animationSourceMode = proceduralAnimationAvailable && hasEmbeddedAnimations ? "embedded_and_procedural" : proceduralAnimationAvailable ? "procedural_only" : hasEmbeddedAnimations ? "embedded_only" : "static";
3372
3456
  const capabilities = {
3373
3457
  rigType: finalRigType,
3458
+ detectedRigFlavor,
3374
3459
  isHumanoid,
3460
+ hasSkeleton,
3461
+ hasSkinnedMesh,
3462
+ boneCount,
3463
+ skinnedMeshCount,
3375
3464
  confidence: Math.round(confidence * 100) / 100,
3376
- proceduralIdle: hasHipsAndSpine && hasHead,
3377
- proceduralLocomotion: isHumanoid && hasLegs,
3378
- proceduralRunning: isHumanoid && hasLegs,
3465
+ proceduralAnimationAvailable,
3466
+ proceduralIdle,
3467
+ proceduralLocomotion,
3468
+ proceduralRunning,
3379
3469
  turning: isHumanoid,
3380
- legIK: hasLegs,
3381
- armIK: hasArms,
3382
- footPlacement: hasLegs,
3383
- headLookAt: hasHead,
3384
- upperBodyGestures: hasArms && hasHipsAndSpine,
3470
+ legIK: isHumanoid && hasLegs,
3471
+ armIK: isHumanoid && hasArms,
3472
+ footPlacement: isHumanoid && hasLegs,
3473
+ headLookAt: isHumanoid && hasHead,
3474
+ upperBodyGestures,
3385
3475
  facialAnimation: this.detectFacialCapabilities(modelRoot),
3386
- clipPlayback: allBones.length > 5,
3476
+ hasEmbeddedAnimations,
3477
+ embeddedAnimationCount,
3478
+ clipPlayback,
3479
+ animationSourceMode,
3387
3480
  missingRequiredBones: missingRequired,
3388
3481
  missingOptionalBones: missingOptional
3389
3482
  };
@@ -3398,15 +3491,15 @@ var RigDetector = class {
3398
3491
  /**
3399
3492
  * Alias for detect()
3400
3493
  */
3401
- static detectRig(modelRoot) {
3402
- return this.detect(modelRoot);
3494
+ static detectRig(modelRoot, options) {
3495
+ return this.detect(modelRoot, options);
3403
3496
  }
3404
3497
  /**
3405
3498
  * Assesses avatar rig capabilities from detection result or model.
3406
3499
  */
3407
- static assessCapabilities(detection, modelRoot) {
3500
+ static assessCapabilities(detection, modelRoot, options) {
3408
3501
  if (modelRoot) {
3409
- return this.detect(modelRoot).capabilities;
3502
+ return this.detect(modelRoot, options).capabilities;
3410
3503
  }
3411
3504
  return detection.capabilities;
3412
3505
  }
@@ -3471,6 +3564,24 @@ var RigDetector = class {
3471
3564
  if (rightLow && rightFoot && !this.isDescendantOf(rightFoot, rightLow)) {
3472
3565
  matched.delete("rightFoot");
3473
3566
  }
3567
+ const leftUpArm = matched.get("leftUpperArm");
3568
+ const leftLowArm = matched.get("leftLowerArm");
3569
+ const leftHand = matched.get("leftHand");
3570
+ if (leftUpArm && leftLowArm && !this.isDescendantOf(leftLowArm, leftUpArm)) {
3571
+ matched.delete("leftLowerArm");
3572
+ }
3573
+ if (leftLowArm && leftHand && !this.isDescendantOf(leftHand, leftLowArm)) {
3574
+ matched.delete("leftHand");
3575
+ }
3576
+ const rightUpArm = matched.get("rightUpperArm");
3577
+ const rightLowArm = matched.get("rightLowerArm");
3578
+ const rightHand = matched.get("rightHand");
3579
+ if (rightUpArm && rightLowArm && !this.isDescendantOf(rightLowArm, rightUpArm)) {
3580
+ matched.delete("rightLowerArm");
3581
+ }
3582
+ if (rightLowArm && rightHand && !this.isDescendantOf(rightHand, rightLowArm)) {
3583
+ matched.delete("rightHand");
3584
+ }
3474
3585
  const hips = matched.get("hips");
3475
3586
  const spine = matched.get("spine");
3476
3587
  const head = matched.get("head");
@@ -3499,11 +3610,19 @@ var RigDetector = class {
3499
3610
  });
3500
3611
  return hasMorphTargets;
3501
3612
  }
3502
- static createUnsupportedCapabilities(rigType, missingReq) {
3613
+ static createUnsupportedCapabilities(rigType, missingReq, meta) {
3614
+ const hasEmbeddedAnimations = meta?.hasEmbeddedAnimations ?? false;
3615
+ const embeddedAnimationCount = meta?.embeddedAnimationCount ?? 0;
3503
3616
  return {
3504
3617
  rigType,
3618
+ detectedRigFlavor: rigType,
3505
3619
  isHumanoid: false,
3620
+ hasSkeleton: meta?.hasSkeleton ?? false,
3621
+ hasSkinnedMesh: meta?.hasSkinnedMesh ?? false,
3622
+ boneCount: meta?.boneCount ?? 0,
3623
+ skinnedMeshCount: meta?.skinnedMeshCount ?? 0,
3506
3624
  confidence: 0,
3625
+ proceduralAnimationAvailable: false,
3507
3626
  proceduralIdle: false,
3508
3627
  proceduralLocomotion: false,
3509
3628
  proceduralRunning: false,
@@ -3514,7 +3633,10 @@ var RigDetector = class {
3514
3633
  headLookAt: false,
3515
3634
  upperBodyGestures: false,
3516
3635
  facialAnimation: false,
3517
- clipPlayback: false,
3636
+ hasEmbeddedAnimations,
3637
+ embeddedAnimationCount,
3638
+ clipPlayback: hasEmbeddedAnimations,
3639
+ animationSourceMode: hasEmbeddedAnimations ? "embedded_only" : "static",
3518
3640
  missingRequiredBones: missingReq,
3519
3641
  missingOptionalBones: [...OPTIONAL_CANONICAL_BONES]
3520
3642
  };
@@ -3575,12 +3697,16 @@ ScratchMath.v4 = new THREE.Vector3();
3575
3697
  ScratchMath.v5 = new THREE.Vector3();
3576
3698
  ScratchMath.v6 = new THREE.Vector3();
3577
3699
  ScratchMath.v7 = new THREE.Vector3();
3700
+ ScratchMath.v8 = new THREE.Vector3();
3701
+ ScratchMath.v9 = new THREE.Vector3();
3578
3702
  // Quaternion scratch pool
3579
3703
  ScratchMath.q0 = new THREE.Quaternion();
3580
3704
  ScratchMath.q1 = new THREE.Quaternion();
3581
3705
  ScratchMath.q2 = new THREE.Quaternion();
3582
3706
  ScratchMath.q3 = new THREE.Quaternion();
3583
3707
  ScratchMath.q4 = new THREE.Quaternion();
3708
+ ScratchMath.q5 = new THREE.Quaternion();
3709
+ ScratchMath.q6 = new THREE.Quaternion();
3584
3710
  // Matrix4 scratch pool
3585
3711
  ScratchMath.m0 = new THREE.Matrix4();
3586
3712
  ScratchMath.m1 = new THREE.Matrix4();
@@ -3597,16 +3723,29 @@ ScratchMath.LEFT = new THREE.Vector3(-1, 0, 0);
3597
3723
 
3598
3724
  // src/avatar/procedural/AUBRSkeleton.ts
3599
3725
  var AUBRSkeleton = class {
3600
- constructor(modelRoot) {
3726
+ constructor(modelRoot, options) {
3601
3727
  this.joints = /* @__PURE__ */ new Map();
3728
+ /** Rest foot positions in modelRoot local space */
3729
+ this.restLeftFootModelPos = new THREE.Vector3();
3730
+ this.restRightFootModelPos = new THREE.Vector3();
3602
3731
  this.boneToCanonical = /* @__PURE__ */ new Map();
3732
+ this.restModelQuat = /* @__PURE__ */ new Map();
3733
+ this.restModelQuatInv = /* @__PURE__ */ new Map();
3603
3734
  this.modelRoot = modelRoot;
3604
- const detection = RigDetector.detect(modelRoot);
3735
+ this.modelRoot.updateMatrixWorld(true);
3736
+ const detection = RigDetector.detect(modelRoot, options);
3605
3737
  this.capabilities = detection.capabilities;
3738
+ const rootWorldQuatInv = new THREE.Quaternion();
3739
+ this.modelRoot.getWorldQuaternion(rootWorldQuatInv).invert();
3606
3740
  for (const [canonicalName, bone] of detection.matchedBones.entries()) {
3607
3741
  const restPos = bone.position.clone();
3608
3742
  const restQuat = bone.quaternion.clone();
3609
3743
  const restScale = bone.scale.clone();
3744
+ const boneWorldQuat = new THREE.Quaternion();
3745
+ bone.getWorldQuaternion(boneWorldQuat);
3746
+ const boneModelQuat = rootWorldQuatInv.clone().multiply(boneWorldQuat).normalize();
3747
+ this.restModelQuat.set(canonicalName, boneModelQuat);
3748
+ this.restModelQuatInv.set(canonicalName, boneModelQuat.clone().invert());
3610
3749
  let restDir = new THREE.Vector3(0, 1, 0);
3611
3750
  let boneLen = 0.2;
3612
3751
  if (bone.children.length > 0) {
@@ -3635,6 +3774,79 @@ var AUBRSkeleton = class {
3635
3774
  this.boneToCanonical.set(bone, canonicalName);
3636
3775
  }
3637
3776
  this.proportions = this.calculateProportions(detection.matchedBones);
3777
+ this.worldUnitsPerMeter = this.proportions.totalHeight / 1.8;
3778
+ const hipsBone = detection.matchedBones.get("hips");
3779
+ let hipsParentScale = 1;
3780
+ if (hipsBone?.parent) {
3781
+ const parentScaleVec = new THREE.Vector3();
3782
+ hipsBone.parent.getWorldScale(parentScaleVec);
3783
+ const avg = (Math.abs(parentScaleVec.x) + Math.abs(parentScaleVec.y) + Math.abs(parentScaleVec.z)) / 3;
3784
+ if (Number.isFinite(avg) && avg > 1e-5) {
3785
+ hipsParentScale = avg;
3786
+ }
3787
+ }
3788
+ this.hipsLocalPerMeter = this.worldUnitsPerMeter / hipsParentScale;
3789
+ const leftArmRest = this.measureArmRest("leftUpperArm", "leftLowerArm", 1);
3790
+ const rightArmRest = this.measureArmRest("rightUpperArm", "rightLowerArm", -1);
3791
+ this.leftArmRestAngleFromDown = leftArmRest.angleFromDown;
3792
+ this.leftArmLowerSign = leftArmRest.lowerSign;
3793
+ this.rightArmRestAngleFromDown = rightArmRest.angleFromDown;
3794
+ this.rightArmLowerSign = rightArmRest.lowerSign;
3795
+ const leftFoot = detection.matchedBones.get("leftFoot");
3796
+ const rightFoot = detection.matchedBones.get("rightFoot");
3797
+ if (leftFoot && rightFoot) {
3798
+ leftFoot.getWorldPosition(this.restLeftFootModelPos);
3799
+ this.modelRoot.worldToLocal(this.restLeftFootModelPos);
3800
+ rightFoot.getWorldPosition(this.restRightFootModelPos);
3801
+ this.modelRoot.worldToLocal(this.restRightFootModelPos);
3802
+ this.hasRestFootPositions = true;
3803
+ } else {
3804
+ this.hasRestFootPositions = false;
3805
+ }
3806
+ }
3807
+ measureArmRest(upperName, lowerName, defaultLateralX) {
3808
+ const upper = this.joints.get(upperName)?.bone;
3809
+ const lower = this.joints.get(lowerName)?.bone;
3810
+ if (!upper || !lower) {
3811
+ return { angleFromDown: 0, lowerSign: defaultLateralX >= 0 ? -1 : 1 };
3812
+ }
3813
+ upper.getWorldPosition(ScratchMath.v0);
3814
+ lower.getWorldPosition(ScratchMath.v1);
3815
+ this.modelRoot.worldToLocal(ScratchMath.v0);
3816
+ this.modelRoot.worldToLocal(ScratchMath.v1);
3817
+ const dir = ScratchMath.v2.subVectors(ScratchMath.v1, ScratchMath.v0);
3818
+ if (dir.lengthSq() < 1e-8) {
3819
+ return { angleFromDown: 0, lowerSign: defaultLateralX >= 0 ? -1 : 1 };
3820
+ }
3821
+ dir.normalize();
3822
+ const dotDown = Math.max(-1, Math.min(1, dir.dot(ScratchMath.DOWN)));
3823
+ const lateralX = Math.abs(dir.x) > 0.05 ? dir.x : defaultLateralX;
3824
+ return {
3825
+ angleFromDown: Math.acos(dotDown),
3826
+ lowerSign: lateralX >= 0 ? -1 : 1
3827
+ };
3828
+ }
3829
+ /**
3830
+ * Applies a rotation delta defined in character model space (+Y up, +Z forward, +X right/left)
3831
+ * relative to the joint's rest pose, converted cleanly into the bone's local coordinate frame.
3832
+ * Allocation-free and rig-agnostic across Mixamo, Rigify, Unreal, VRM, and generic humanoids.
3833
+ */
3834
+ applyModelDeltaRotation(name, modelDeltaQuat, weight = 1, additive = false) {
3835
+ const joint = this.joints.get(name);
3836
+ const restModel = this.restModelQuat.get(name);
3837
+ const restModelInv = this.restModelQuatInv.get(name);
3838
+ if (!joint || !restModel || !restModelInv || weight <= 1e-3) return;
3839
+ ScratchMath.q5.copy(restModelInv).multiply(modelDeltaQuat).multiply(restModel);
3840
+ if (additive) {
3841
+ ScratchMath.q6.copy(joint.targetQuaternion).multiply(ScratchMath.q5);
3842
+ } else {
3843
+ ScratchMath.q6.copy(joint.restQuaternion).multiply(ScratchMath.q5);
3844
+ }
3845
+ if (weight >= 0.999) {
3846
+ joint.targetQuaternion.copy(ScratchMath.q6);
3847
+ } else {
3848
+ joint.targetQuaternion.slerp(ScratchMath.q6, Math.max(0, Math.min(1, weight)));
3849
+ }
3638
3850
  }
3639
3851
  getJoint(name) {
3640
3852
  return this.joints.get(name);
@@ -3701,67 +3913,102 @@ var AUBRSkeleton = class {
3701
3913
  }
3702
3914
  }
3703
3915
  calculateProportions(bones) {
3704
- const box = new THREE.Box3().setFromObject(this.modelRoot);
3705
- const size = box.getSize(new THREE.Vector3());
3706
- const totalHeight = size.y > 0 ? size.y : 1.78;
3916
+ const box = new THREE.Box3();
3917
+ try {
3918
+ box.setFromObject(this.modelRoot);
3919
+ } catch {
3920
+ box.makeEmpty();
3921
+ }
3922
+ const size = box.isEmpty() ? new THREE.Vector3(0, 0, 0) : box.getSize(new THREE.Vector3());
3923
+ let totalHeight = size.y > 0.01 ? size.y : 0;
3924
+ const head = bones.get("head");
3925
+ const leftFoot = bones.get("leftFoot");
3926
+ const rightFoot = bones.get("rightFoot");
3927
+ const hips = bones.get("hips");
3928
+ if (totalHeight <= 0.01 && head && (leftFoot || rightFoot)) {
3929
+ head.getWorldPosition(ScratchMath.v0);
3930
+ (leftFoot || rightFoot).getWorldPosition(ScratchMath.v1);
3931
+ const headToFoot = Math.abs(ScratchMath.v0.y - ScratchMath.v1.y);
3932
+ if (headToFoot > 0.01) {
3933
+ totalHeight = headToFoot * 1.15;
3934
+ }
3935
+ }
3936
+ if (totalHeight <= 0.01 && head && hips) {
3937
+ head.getWorldPosition(ScratchMath.v0);
3938
+ hips.getWorldPosition(ScratchMath.v1);
3939
+ const headToHips = ScratchMath.v0.distanceTo(ScratchMath.v1);
3940
+ if (headToHips > 0.01) {
3941
+ totalHeight = headToHips * 2.2;
3942
+ }
3943
+ }
3944
+ if (totalHeight <= 0.01) {
3945
+ totalHeight = 1.78;
3946
+ }
3707
3947
  const leftUp = bones.get("leftUpperLeg");
3708
3948
  const leftLow = bones.get("leftLowerLeg");
3709
- const leftFoot = bones.get("leftFoot");
3710
- let thighLength = 0.45;
3711
- let shinLength = 0.43;
3712
- let footHeight = 0.08;
3949
+ let thighLength = totalHeight * 0.25;
3950
+ let shinLength = totalHeight * 0.24;
3951
+ let footHeight = totalHeight * 0.045;
3713
3952
  if (leftUp && leftLow) {
3714
3953
  leftUp.getWorldPosition(ScratchMath.v0);
3715
3954
  leftLow.getWorldPosition(ScratchMath.v1);
3716
- thighLength = ScratchMath.v0.distanceTo(ScratchMath.v1);
3955
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
3956
+ if (d > 1e-4) thighLength = d;
3717
3957
  }
3718
3958
  if (leftLow && leftFoot) {
3719
3959
  leftLow.getWorldPosition(ScratchMath.v0);
3720
3960
  leftFoot.getWorldPosition(ScratchMath.v1);
3721
- shinLength = ScratchMath.v0.distanceTo(ScratchMath.v1);
3722
- footHeight = Math.max(leftFoot.position.y, 0.08);
3961
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
3962
+ if (d > 1e-4) shinLength = d;
3963
+ if (!box.isEmpty()) {
3964
+ const rawFootY = ScratchMath.v1.y - box.min.y;
3965
+ footHeight = Math.max(totalHeight * 0.03, Math.min(totalHeight * 0.12, rawFootY));
3966
+ }
3723
3967
  }
3724
3968
  const legLength = thighLength + shinLength + footHeight;
3725
3969
  const spine = bones.get("spine");
3726
- const head = bones.get("head");
3727
- let spineLength = 0.52;
3970
+ let spineLength = totalHeight * 0.29;
3728
3971
  if (spine && head) {
3729
3972
  spine.getWorldPosition(ScratchMath.v0);
3730
3973
  head.getWorldPosition(ScratchMath.v1);
3731
- spineLength = ScratchMath.v0.distanceTo(ScratchMath.v1);
3974
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
3975
+ if (d > 1e-4) spineLength = d;
3732
3976
  }
3733
3977
  const leftArm = bones.get("leftUpperArm");
3734
3978
  const rightArm = bones.get("rightUpperArm");
3735
- let shoulderWidth = 0.42;
3979
+ let shoulderWidth = totalHeight * 0.23;
3736
3980
  if (leftArm && rightArm) {
3737
3981
  leftArm.getWorldPosition(ScratchMath.v0);
3738
3982
  rightArm.getWorldPosition(ScratchMath.v1);
3739
- shoulderWidth = ScratchMath.v0.distanceTo(ScratchMath.v1);
3983
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
3984
+ if (d > 1e-4) shoulderWidth = d;
3740
3985
  }
3741
3986
  const rightUp = bones.get("rightUpperLeg");
3742
- let hipWidth = 0.28;
3987
+ let hipWidth = totalHeight * 0.15;
3743
3988
  if (leftUp && rightUp) {
3744
3989
  leftUp.getWorldPosition(ScratchMath.v0);
3745
3990
  rightUp.getWorldPosition(ScratchMath.v1);
3746
- hipWidth = ScratchMath.v0.distanceTo(ScratchMath.v1);
3991
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
3992
+ if (d > 1e-4) hipWidth = d;
3747
3993
  }
3748
3994
  const leftHand = bones.get("leftHand");
3749
- let armLength = 0.65;
3995
+ let armLength = totalHeight * 0.36;
3750
3996
  if (leftArm && leftHand) {
3751
3997
  leftArm.getWorldPosition(ScratchMath.v0);
3752
3998
  leftHand.getWorldPosition(ScratchMath.v1);
3753
- armLength = ScratchMath.v0.distanceTo(ScratchMath.v1);
3999
+ const d = ScratchMath.v0.distanceTo(ScratchMath.v1);
4000
+ if (d > 1e-4) armLength = d;
3754
4001
  }
3755
4002
  return {
3756
4003
  totalHeight,
3757
- legLength: Math.max(legLength, 0.4),
3758
- thighLength: Math.max(thighLength, 0.2),
3759
- shinLength: Math.max(shinLength, 0.2),
3760
- footHeight: Math.max(footHeight, 0.05),
3761
- spineLength: Math.max(spineLength, 0.3),
3762
- shoulderWidth: Math.max(shoulderWidth, 0.25),
3763
- hipWidth: Math.max(hipWidth, 0.15),
3764
- armLength: Math.max(armLength, 0.35)
4004
+ legLength: Math.max(legLength, totalHeight * 0.25),
4005
+ thighLength: Math.max(thighLength, totalHeight * 0.12),
4006
+ shinLength: Math.max(shinLength, totalHeight * 0.12),
4007
+ footHeight: Math.max(footHeight, totalHeight * 0.025),
4008
+ spineLength: Math.max(spineLength, totalHeight * 0.15),
4009
+ shoulderWidth: Math.max(shoulderWidth, totalHeight * 0.12),
4010
+ hipWidth: Math.max(hipWidth, totalHeight * 0.08),
4011
+ armLength: Math.max(armLength, totalHeight * 0.2)
3765
4012
  };
3766
4013
  }
3767
4014
  };
@@ -3855,35 +4102,91 @@ var TwoBoneIK = class {
3855
4102
  };
3856
4103
  }
3857
4104
  /**
3858
- * Applies solved two-bone IK rotations to the target AUBR joints in-place.
4105
+ * Applies solved two-bone IK rotations to the target AUBR leg joints in-place
4106
+ * using rest-pose-preserving world-space delta rotations so Mixamo, Rigify, Unreal,
4107
+ * VRM, and generic humanoid bone orientations are never distorted.
4108
+ *
4109
+ * `targetFootPosWorld` and `poleDirWorld` are in world space (or model space when
4110
+ * `modelRoot` is omitted and bones are evaluated in local space).
3859
4111
  */
3860
- static applyLegIK(thighBone, shinBone, footBone, thighLength, shinLength, targetFootPosModel, poleVector, weight = 1, modelRoot) {
4112
+ static applyLegIK(thighBone, shinBone, footBone, thighLength, shinLength, targetFootPosWorld, poleDirWorld, weight = 1, _modelRoot) {
3861
4113
  if (weight <= 1e-3) return;
3862
- const rootPos = ScratchMath.v3;
3863
- thighBone.getWorldPosition(rootPos);
3864
- if (modelRoot) {
3865
- modelRoot.worldToLocal(rootPos);
3866
- } else if (thighBone.parent) {
3867
- thighBone.parent.worldToLocal(rootPos);
3868
- }
3869
- const chain = {
3870
- rootBone: thighBone,
3871
- midBone: shinBone,
3872
- endBone: footBone,
3873
- poleVector,
3874
- length1: thighLength,
3875
- length2: shinLength
3876
- };
3877
- const result = this.solveAnalytical(chain, targetFootPosModel, rootPos, poleVector);
3878
- if (weight >= 0.999) {
3879
- thighBone.quaternion.copy(result.rootRotation);
3880
- shinBone.quaternion.copy(result.midRotation);
4114
+ const clampedWeight = Math.max(0, Math.min(1, weight));
4115
+ const hipPos = ScratchMath.v0;
4116
+ const kneePos = ScratchMath.v1;
4117
+ const anklePos = ScratchMath.v2;
4118
+ thighBone.getWorldPosition(hipPos);
4119
+ shinBone.getWorldPosition(kneePos);
4120
+ footBone.getWorldPosition(anklePos);
4121
+ let l1 = hipPos.distanceTo(kneePos);
4122
+ let l2 = kneePos.distanceTo(anklePos);
4123
+ if (l1 < 1e-5) l1 = Math.max(thighLength, 0.05);
4124
+ if (l2 < 1e-5) l2 = Math.max(shinLength, 0.05);
4125
+ const maxReach = l1 + l2;
4126
+ const minReach = Math.abs(l1 - l2);
4127
+ const toTarget = ScratchMath.v3.subVectors(targetFootPosWorld, hipPos);
4128
+ const dist = toTarget.length();
4129
+ const clampedDist = Math.max(minReach + 1e-4, Math.min(dist, maxReach * 0.99999));
4130
+ if (dist < 1e-6) {
4131
+ toTarget.copy(ScratchMath.DOWN);
4132
+ } else {
4133
+ toTarget.divideScalar(dist);
4134
+ }
4135
+ const bendDir = ScratchMath.v4.copy(poleDirWorld);
4136
+ const poleProj = bendDir.dot(toTarget);
4137
+ bendDir.addScaledVector(toTarget, -poleProj);
4138
+ if (bendDir.lengthSq() < 1e-6) {
4139
+ bendDir.crossVectors(toTarget, ScratchMath.RIGHT);
4140
+ if (bendDir.lengthSq() < 1e-6) {
4141
+ bendDir.crossVectors(toTarget, ScratchMath.FORWARD);
4142
+ }
4143
+ }
4144
+ bendDir.normalize();
4145
+ const cosAlpha = Math.max(
4146
+ -1,
4147
+ Math.min(1, (l1 * l1 + clampedDist * clampedDist - l2 * l2) / (2 * l1 * clampedDist))
4148
+ );
4149
+ const sinAlpha = Math.sqrt(Math.max(0, 1 - cosAlpha * cosAlpha));
4150
+ const desiredThighDir = ScratchMath.v5.copy(toTarget).multiplyScalar(cosAlpha).addScaledVector(bendDir, sinAlpha).normalize();
4151
+ const desiredKneePos = ScratchMath.v6.copy(hipPos).addScaledVector(desiredThighDir, l1);
4152
+ const desiredShinDir = ScratchMath.v7.subVectors(targetFootPosWorld, desiredKneePos);
4153
+ if (desiredShinDir.lengthSq() < 1e-8) {
4154
+ desiredShinDir.copy(toTarget);
3881
4155
  } else {
3882
- thighBone.quaternion.slerp(result.rootRotation, weight);
3883
- shinBone.quaternion.slerp(result.midRotation, weight);
4156
+ desiredShinDir.normalize();
4157
+ }
4158
+ const currentThighDir = ScratchMath.v8.subVectors(kneePos, hipPos);
4159
+ if (currentThighDir.lengthSq() > 1e-10) {
4160
+ currentThighDir.normalize();
4161
+ ScratchMath.q0.setFromUnitVectors(currentThighDir, desiredThighDir);
4162
+ thighBone.getWorldQuaternion(ScratchMath.q1);
4163
+ ScratchMath.q2.copy(ScratchMath.q1).invert();
4164
+ ScratchMath.q3.copy(ScratchMath.q2).multiply(ScratchMath.q0).multiply(ScratchMath.q1);
4165
+ ScratchMath.q4.copy(thighBone.quaternion).multiply(ScratchMath.q3);
4166
+ if (clampedWeight >= 0.999) {
4167
+ thighBone.quaternion.copy(ScratchMath.q4);
4168
+ } else {
4169
+ thighBone.quaternion.slerp(ScratchMath.q4, clampedWeight);
4170
+ }
4171
+ thighBone.updateMatrixWorld(true);
4172
+ }
4173
+ shinBone.getWorldPosition(kneePos);
4174
+ footBone.getWorldPosition(anklePos);
4175
+ const currentShinDir = ScratchMath.v8.subVectors(anklePos, kneePos);
4176
+ if (currentShinDir.lengthSq() > 1e-10) {
4177
+ currentShinDir.normalize();
4178
+ ScratchMath.q0.setFromUnitVectors(currentShinDir, desiredShinDir);
4179
+ shinBone.getWorldQuaternion(ScratchMath.q1);
4180
+ ScratchMath.q2.copy(ScratchMath.q1).invert();
4181
+ ScratchMath.q3.copy(ScratchMath.q2).multiply(ScratchMath.q0).multiply(ScratchMath.q1);
4182
+ ScratchMath.q4.copy(shinBone.quaternion).multiply(ScratchMath.q3);
4183
+ if (clampedWeight >= 0.999) {
4184
+ shinBone.quaternion.copy(ScratchMath.q4);
4185
+ } else {
4186
+ shinBone.quaternion.slerp(ScratchMath.q4, clampedWeight);
4187
+ }
4188
+ shinBone.updateMatrixWorld(true);
3884
4189
  }
3885
- ScratchMath.q2.setFromAxisAngle(ScratchMath.RIGHT, 0);
3886
- footBone.quaternion.slerp(ScratchMath.q2, weight * 0.85);
3887
4190
  }
3888
4191
  };
3889
4192
  var _FABRIKSolver = class _FABRIKSolver {
@@ -4036,43 +4339,52 @@ var _FABRIKSolver = class _FABRIKSolver {
4036
4339
  };
4037
4340
  }
4038
4341
  /**
4039
- * Projects middle hinge joint onto plane defined by pole vector.
4342
+ * Projects middle hinge joint onto the half-plane defined by the pole direction vector.
4040
4343
  */
4041
4344
  static applyPoleVector(root, hinge, end, pole) {
4042
- const line = ScratchMath.v1.subVectors(end, root).normalize();
4345
+ const line = ScratchMath.v1.subVectors(end, root);
4346
+ if (line.lengthSq() < 1e-10) return;
4347
+ line.normalize();
4043
4348
  const toHinge = ScratchMath.v2.subVectors(hinge, root);
4044
4349
  const projDist = toHinge.dot(line);
4045
4350
  const projPoint = ScratchMath.v3.copy(root).addScaledVector(line, projDist);
4046
- const currentNormal = ScratchMath.v4.subVectors(hinge, projPoint).normalize();
4047
- const desiredNormal = ScratchMath.v5.subVectors(pole, projPoint).normalize();
4048
- if (currentNormal.lengthSq() > 1e-3 && desiredNormal.lengthSq() > 1e-3) {
4351
+ const desiredNormal = ScratchMath.v5.copy(pole).addScaledVector(line, -pole.dot(line));
4352
+ if (desiredNormal.lengthSq() > 1e-6) {
4353
+ desiredNormal.normalize();
4049
4354
  const hingeDist = hinge.distanceTo(projPoint);
4050
- hinge.copy(projPoint).addScaledVector(desiredNormal, Math.max(hingeDist, 0.05));
4355
+ hinge.copy(projPoint).addScaledVector(desiredNormal, Math.max(hingeDist, 0.02));
4051
4356
  }
4052
4357
  }
4053
4358
  /**
4054
4359
  * Converts solved world positions back into local bone rotations for the Three.js hierarchy.
4360
+ * Calculates delta rotation in world space from current bone direction to solved target direction,
4361
+ * transforming into local bone space to guarantee zero deformation when positions match rest pose.
4055
4362
  */
4056
4363
  static applyPositionsToBones(chain, solvedPositions, weight = 1) {
4057
4364
  if (solvedPositions.length < 2 || weight <= 1e-3) return;
4058
4365
  for (let i = 0; i < chain.bones.length - 1; i++) {
4059
4366
  const bone = chain.bones[i];
4367
+ const nextBone = chain.bones[i + 1];
4060
4368
  const nextPos = solvedPositions[i + 1];
4061
- if (!bone || !nextPos) continue;
4369
+ if (!bone || !nextBone || !nextPos) continue;
4062
4370
  bone.getWorldPosition(ScratchMath.v0);
4371
+ nextBone.getWorldPosition(ScratchMath.v2);
4372
+ const currentDirWorld = ScratchMath.v3.subVectors(ScratchMath.v2, ScratchMath.v0);
4373
+ if (currentDirWorld.lengthSq() < 1e-10) continue;
4374
+ currentDirWorld.normalize();
4063
4375
  const targetDirWorld = ScratchMath.v1.subVectors(nextPos, ScratchMath.v0);
4064
4376
  if (targetDirWorld.lengthSq() < 1e-10) continue;
4065
4377
  targetDirWorld.normalize();
4066
- if (bone.parent) {
4067
- ScratchMath.m0.copy(bone.parent.matrixWorld).invert();
4068
- targetDirWorld.transformDirection(ScratchMath.m0).normalize();
4069
- }
4070
- const restDir = ScratchMath.RIGHT;
4071
- ScratchMath.q0.setFromUnitVectors(restDir, targetDirWorld);
4378
+ ScratchMath.q0.setFromUnitVectors(currentDirWorld, targetDirWorld);
4379
+ bone.getWorldQuaternion(ScratchMath.q1);
4380
+ ScratchMath.q2.copy(ScratchMath.q1).invert();
4381
+ ScratchMath.q3.copy(ScratchMath.q2).multiply(ScratchMath.q0).multiply(ScratchMath.q1);
4382
+ const currentLocalQuat = ScratchMath.q4.copy(bone.quaternion);
4383
+ const targetLocalQuat = ScratchMath.q3.premultiply(currentLocalQuat);
4072
4384
  if (weight >= 0.999) {
4073
- bone.quaternion.copy(ScratchMath.q0);
4385
+ bone.quaternion.copy(targetLocalQuat);
4074
4386
  } else {
4075
- bone.quaternion.slerp(ScratchMath.q0, weight);
4387
+ bone.quaternion.copy(currentLocalQuat).slerp(targetLocalQuat, weight);
4076
4388
  }
4077
4389
  bone.updateMatrixWorld(true);
4078
4390
  }
@@ -4104,21 +4416,25 @@ var IKCoordinator = class {
4104
4416
  }
4105
4417
  /**
4106
4418
  * Solves and applies left leg Two-Bone IK.
4419
+ * `targetFootPosModel` is in `skeleton.modelRoot` local space.
4107
4420
  */
4108
4421
  solveLeftLeg(targetFootPosModel, weight = 1) {
4109
4422
  const thigh = this.skeleton.getJoint("leftUpperLeg");
4110
4423
  const shin = this.skeleton.getJoint("leftLowerLeg");
4111
4424
  const foot = this.skeleton.getJoint("leftFoot");
4112
- if (!thigh || !shin || !foot) return;
4113
- const pole = ScratchMath.v6.copy(ScratchMath.FORWARD);
4425
+ if (!thigh || !shin || !foot || weight <= 1e-3) return;
4426
+ const targetWorld = ScratchMath.v9.copy(targetFootPosModel);
4427
+ this.skeleton.modelRoot.localToWorld(targetWorld);
4428
+ this.skeleton.modelRoot.getWorldQuaternion(ScratchMath.q5);
4429
+ const poleWorld = ScratchMath.v8.copy(ScratchMath.FORWARD).applyQuaternion(ScratchMath.q5).normalize();
4114
4430
  TwoBoneIK.applyLegIK(
4115
4431
  thigh.bone,
4116
4432
  shin.bone,
4117
4433
  foot.bone,
4118
4434
  this.skeleton.proportions.thighLength,
4119
4435
  this.skeleton.proportions.shinLength,
4120
- targetFootPosModel,
4121
- pole,
4436
+ targetWorld,
4437
+ poleWorld,
4122
4438
  weight,
4123
4439
  this.skeleton.modelRoot
4124
4440
  );
@@ -4128,21 +4444,25 @@ var IKCoordinator = class {
4128
4444
  }
4129
4445
  /**
4130
4446
  * Solves and applies right leg Two-Bone IK.
4447
+ * `targetFootPosModel` is in `skeleton.modelRoot` local space.
4131
4448
  */
4132
4449
  solveRightLeg(targetFootPosModel, weight = 1) {
4133
4450
  const thigh = this.skeleton.getJoint("rightUpperLeg");
4134
4451
  const shin = this.skeleton.getJoint("rightLowerLeg");
4135
4452
  const foot = this.skeleton.getJoint("rightFoot");
4136
- if (!thigh || !shin || !foot) return;
4137
- const pole = ScratchMath.v6.copy(ScratchMath.FORWARD);
4453
+ if (!thigh || !shin || !foot || weight <= 1e-3) return;
4454
+ const targetWorld = ScratchMath.v9.copy(targetFootPosModel);
4455
+ this.skeleton.modelRoot.localToWorld(targetWorld);
4456
+ this.skeleton.modelRoot.getWorldQuaternion(ScratchMath.q5);
4457
+ const poleWorld = ScratchMath.v8.copy(ScratchMath.FORWARD).applyQuaternion(ScratchMath.q5).normalize();
4138
4458
  TwoBoneIK.applyLegIK(
4139
4459
  thigh.bone,
4140
4460
  shin.bone,
4141
4461
  foot.bone,
4142
4462
  this.skeleton.proportions.thighLength,
4143
4463
  this.skeleton.proportions.shinLength,
4144
- targetFootPosModel,
4145
- pole,
4464
+ targetWorld,
4465
+ poleWorld,
4146
4466
  weight,
4147
4467
  this.skeleton.modelRoot
4148
4468
  );
@@ -4156,7 +4476,8 @@ var IKCoordinator = class {
4156
4476
  solveArmReach(side, targetPosWorld, weight = 1) {
4157
4477
  const chain = side === "left" ? this.leftArmChain : this.rightArmChain;
4158
4478
  if (!chain || weight <= 1e-3) return;
4159
- const pole = side === "left" ? ScratchMath.v7.set(-0.5, 0, -1).normalize() : ScratchMath.v7.set(0.5, 0, -1).normalize();
4479
+ this.skeleton.modelRoot.getWorldQuaternion(ScratchMath.q5);
4480
+ const pole = (side === "left" ? ScratchMath.v7.set(-0.5, 0, -1).normalize() : ScratchMath.v7.set(0.5, 0, -1).normalize()).applyQuaternion(ScratchMath.q5);
4160
4481
  const result = FABRIKSolver.solve(chain, targetPosWorld, pole);
4161
4482
  FABRIKSolver.applyPositionsToBones(chain, result.solvedPositions, weight);
4162
4483
  const upper = this.skeleton.getJoint(side === "left" ? "leftUpperArm" : "rightUpperArm");
@@ -4180,63 +4501,86 @@ var IdleEngine = class {
4180
4501
  this.targetWeightShift = 0;
4181
4502
  this.nextWeightShiftTime = 3.5;
4182
4503
  }
4504
+ reset() {
4505
+ this.clock = 0;
4506
+ this.breathPhase = 0;
4507
+ this.swayPhase = 0;
4508
+ this.weightShift = 0;
4509
+ this.targetWeightShift = 0;
4510
+ this.nextWeightShiftTime = 3.5;
4511
+ }
4183
4512
  update(delta, weight = 1) {
4184
4513
  if (weight <= 1e-3) return;
4514
+ const w = Math.max(0, Math.min(1, weight));
4185
4515
  this.clock += delta;
4186
4516
  this.breathPhase += delta * 0.28;
4187
- this.swayPhase += delta * 0.12;
4517
+ this.swayPhase += delta * 0.14;
4188
4518
  if (this.clock > this.nextWeightShiftTime) {
4189
- this.targetWeightShift = (Math.random() - 0.5) * 1.6;
4519
+ this.targetWeightShift = (Math.random() - 0.5) * 1.4;
4190
4520
  this.nextWeightShiftTime = this.clock + 4 + Math.random() * 4;
4191
4521
  }
4192
- this.weightShift = ScratchMath.damp(this.weightShift, this.targetWeightShift, 1.2, delta);
4522
+ this.weightShift = ScratchMath.damp(this.weightShift, this.targetWeightShift, 1.4, delta);
4523
+ const localScale = this.skeleton.hipsLocalPerMeter;
4193
4524
  const breathSin = Math.sin(this.breathPhase * Math.PI * 2);
4194
- const spinePitch = breathSin * 0.015;
4195
- const chestPitch = breathSin * 0.022;
4525
+ const spinePitch = breathSin * 0.022 * w;
4526
+ const chestPitch = breathSin * 0.028 * w;
4196
4527
  const swaySin = Math.sin(this.swayPhase * Math.PI * 2);
4197
- const pelvicX = (swaySin * 6e-3 + this.weightShift * 0.012) * weight;
4198
- const pelvicY = breathSin * 4e-3 * weight;
4199
- const pelvicRoll = -this.weightShift * 0.018 * weight;
4528
+ const pelvicX = (swaySin * 8e-3 + this.weightShift * 0.014) * localScale * w;
4529
+ const pelvicY = breathSin * 5e-3 * localScale * w;
4530
+ const pelvicRoll = -this.weightShift * 0.022 * w;
4200
4531
  const hips = this.skeleton.getJoint("hips");
4201
4532
  if (hips) {
4202
4533
  hips.targetPosition.x = hips.restPosition.x + pelvicX;
4203
4534
  hips.targetPosition.y = hips.restPosition.y + pelvicY;
4204
4535
  ScratchMath.e0.set(0, 0, pelvicRoll, "YXZ");
4205
4536
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4206
- hips.targetQuaternion.copy(hips.restQuaternion).multiply(ScratchMath.q0);
4537
+ this.skeleton.applyModelDeltaRotation("hips", ScratchMath.q0, w);
4207
4538
  }
4208
- const spine = this.skeleton.getJoint("spine");
4209
- if (spine) {
4210
- ScratchMath.e0.set(spinePitch * weight, 0, 0, "YXZ");
4539
+ if (this.skeleton.hasJoint("spine")) {
4540
+ ScratchMath.e0.set(spinePitch, swaySin * 0.012 * w, -pelvicRoll * 0.4, "YXZ");
4211
4541
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4212
- spine.targetQuaternion.copy(spine.restQuaternion).multiply(ScratchMath.q0);
4542
+ this.skeleton.applyModelDeltaRotation("spine", ScratchMath.q0, w);
4213
4543
  }
4214
- const chest = this.skeleton.getJoint("chest") || this.skeleton.getJoint("upperChest");
4215
- if (chest) {
4216
- ScratchMath.e0.set(chestPitch * weight, 0, 0, "YXZ");
4544
+ const chestName = this.skeleton.hasJoint("chest") ? "chest" : this.skeleton.hasJoint("upperChest") ? "upperChest" : null;
4545
+ if (chestName) {
4546
+ ScratchMath.e0.set(chestPitch, 0, 0, "YXZ");
4217
4547
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4218
- chest.targetQuaternion.copy(chest.restQuaternion).multiply(ScratchMath.q0);
4548
+ this.skeleton.applyModelDeltaRotation(chestName, ScratchMath.q0, w);
4219
4549
  }
4220
- const head = this.skeleton.getJoint("head");
4221
- if (head) {
4222
- const headCounterRoll = -pelvicRoll * 0.6;
4223
- const headCounterPitch = -spinePitch * 0.5;
4550
+ if (this.skeleton.hasJoint("head")) {
4551
+ const headCounterRoll = -pelvicRoll * 0.5;
4552
+ const headCounterPitch = -spinePitch * 0.45;
4224
4553
  ScratchMath.e0.set(headCounterPitch, 0, headCounterRoll, "YXZ");
4225
4554
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4226
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
4227
- }
4228
- const lArm = this.skeleton.getJoint("leftUpperArm");
4229
- const rArm = this.skeleton.getJoint("rightUpperArm");
4230
- const armSway = breathSin * 0.012 * weight;
4231
- if (lArm) {
4232
- ScratchMath.e0.set(armSway, 0, armSway * 0.5, "YXZ");
4233
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4234
- lArm.targetQuaternion.copy(lArm.restQuaternion).multiply(ScratchMath.q0);
4235
- }
4236
- if (rArm) {
4237
- ScratchMath.e0.set(armSway, 0, -armSway * 0.5, "YXZ");
4238
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4239
- rArm.targetQuaternion.copy(rArm.restQuaternion).multiply(ScratchMath.q0);
4555
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, w);
4556
+ }
4557
+ const targetStandingArmAngle = 0.28;
4558
+ const armBreathSway = breathSin * 0.025;
4559
+ const armOutSway = breathSin * 0.018;
4560
+ if (this.skeleton.hasJoint("leftUpperArm")) {
4561
+ const relaxAngle = Math.max(0, this.skeleton.leftArmRestAngleFromDown - targetStandingArmAngle);
4562
+ const lowerZ = this.skeleton.leftArmLowerSign * (relaxAngle - armOutSway);
4563
+ ScratchMath.q1.setFromAxisAngle(ScratchMath.FORWARD, lowerZ);
4564
+ ScratchMath.q2.setFromAxisAngle(ScratchMath.RIGHT, -armBreathSway);
4565
+ ScratchMath.q0.copy(ScratchMath.q2).multiply(ScratchMath.q1);
4566
+ this.skeleton.applyModelDeltaRotation("leftUpperArm", ScratchMath.q0, w);
4567
+ }
4568
+ if (this.skeleton.hasJoint("rightUpperArm")) {
4569
+ const relaxAngle = Math.max(0, this.skeleton.rightArmRestAngleFromDown - targetStandingArmAngle);
4570
+ const lowerZ = this.skeleton.rightArmLowerSign * (relaxAngle - armOutSway);
4571
+ ScratchMath.q1.setFromAxisAngle(ScratchMath.FORWARD, lowerZ);
4572
+ ScratchMath.q2.setFromAxisAngle(ScratchMath.RIGHT, -armBreathSway);
4573
+ ScratchMath.q0.copy(ScratchMath.q2).multiply(ScratchMath.q1);
4574
+ this.skeleton.applyModelDeltaRotation("rightUpperArm", ScratchMath.q0, w);
4575
+ }
4576
+ const elbowRelaxFlex = 0.16 + breathSin * 0.015;
4577
+ if (this.skeleton.hasJoint("leftLowerArm")) {
4578
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -elbowRelaxFlex);
4579
+ this.skeleton.applyModelDeltaRotation("leftLowerArm", ScratchMath.q0, w);
4580
+ }
4581
+ if (this.skeleton.hasJoint("rightLowerArm")) {
4582
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -elbowRelaxFlex);
4583
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, w);
4240
4584
  }
4241
4585
  }
4242
4586
  };
@@ -4279,9 +4623,10 @@ var LocomotionEngine = class {
4279
4623
  return this.phase;
4280
4624
  }
4281
4625
  calibrateStride() {
4282
- const legLen = this.skeleton.proportions.legLength;
4283
- this.strideLength = Math.max(0.35, legLen * 0.78);
4284
- this.stepHeight = Math.max(0.04, legLen * 0.095);
4626
+ const unitScale = this.skeleton.hipsLocalPerMeter;
4627
+ const legLenLocal = Math.max(0.4 * unitScale, this.skeleton.proportions.legLength / Math.max(this.skeleton.worldUnitsPerMeter, 1e-4) * unitScale);
4628
+ this.strideLength = Math.max(0.35 * unitScale, legLenLocal * 0.72);
4629
+ this.stepHeight = Math.max(0.04 * unitScale, legLenLocal * 0.11);
4285
4630
  }
4286
4631
  setMotion(params) {
4287
4632
  this.targetSpeed = Math.max(0, params.speed);
@@ -4291,113 +4636,128 @@ var LocomotionEngine = class {
4291
4636
  const stridesPerSecond = params.screenVelocityPx / 180;
4292
4637
  this.baseFrequency = Math.max(0.8, Math.min(3.2, stridesPerSecond * 2));
4293
4638
  } else {
4294
- this.baseFrequency = this.isRunning ? 2.6 : 1.5;
4639
+ this.baseFrequency = this.isRunning ? 2.4 : 1.35;
4295
4640
  }
4296
4641
  }
4297
4642
  stop() {
4298
4643
  this.targetSpeed = 0;
4299
4644
  this.moving = false;
4300
4645
  }
4646
+ cancel() {
4647
+ this.targetSpeed = 0;
4648
+ this.currentSpeed = 0;
4649
+ this.moving = false;
4650
+ this.isRunning = false;
4651
+ }
4301
4652
  update(delta, weight = 1) {
4302
- this.currentSpeed = ScratchMath.damp(this.currentSpeed, this.targetSpeed, 4, delta);
4653
+ const speedDamp = this.moving ? 6.5 : 8;
4654
+ this.currentSpeed = ScratchMath.damp(this.currentSpeed, this.targetSpeed, speedDamp, delta);
4303
4655
  if (this.currentSpeed <= 0.01 && weight <= 1e-3) return;
4304
- const effectiveFreq = this.baseFrequency * Math.max(0.3, this.currentSpeed);
4656
+ const w = Math.max(0, Math.min(1, weight));
4657
+ const speedRatio = Math.min(this.currentSpeed, 2.2);
4658
+ const activeAmplitude = Math.min(1, this.currentSpeed / 0.35) * w;
4659
+ if (activeAmplitude <= 1e-3) return;
4660
+ const effectiveFreq = this.baseFrequency * Math.max(0.35, Math.min(1.6, this.currentSpeed));
4305
4661
  this.phase = (this.phase + effectiveFreq * delta) % 1;
4306
4662
  const phi = this.phase;
4307
4663
  const twoPiPhi = phi * Math.PI * 2;
4308
- const speedRatio = Math.min(this.currentSpeed, 2);
4309
- const bobAmplitude = (this.isRunning ? 0.045 : 0.024) * speedRatio;
4664
+ const localScale = this.skeleton.hipsLocalPerMeter;
4665
+ const bobAmplitude = (this.isRunning ? 0.05 : 0.028) * speedRatio * localScale;
4310
4666
  const pelvicY = -bobAmplitude * Math.abs(Math.sin(twoPiPhi));
4311
- const swayAmplitude = (this.isRunning ? 0.018 : 0.028) * speedRatio;
4667
+ const swayAmplitude = (this.isRunning ? 0.02 : 0.03) * speedRatio * localScale;
4312
4668
  const pelvicX = swayAmplitude * Math.sin(twoPiPhi);
4313
4669
  const yawAmplitude = (this.isRunning ? 0.14 : 0.09) * speedRatio;
4314
4670
  const pelvicYaw = yawAmplitude * Math.cos(twoPiPhi);
4315
- const rollAmplitude = 0.035 * speedRatio;
4671
+ const rollAmplitude = 0.04 * speedRatio;
4316
4672
  const pelvicRoll = -rollAmplitude * Math.sin(twoPiPhi);
4317
4673
  const hips = this.skeleton.getJoint("hips");
4318
4674
  if (hips) {
4319
- hips.targetPosition.x = hips.restPosition.x + pelvicX * weight;
4320
- hips.targetPosition.y = hips.restPosition.y + pelvicY * weight;
4321
- ScratchMath.e0.set(0.04 * speedRatio, pelvicYaw * weight, pelvicRoll * weight, "YXZ");
4675
+ hips.targetPosition.x = hips.restPosition.x + pelvicX * w;
4676
+ hips.targetPosition.y = hips.restPosition.y + pelvicY * w;
4677
+ ScratchMath.e0.set((this.isRunning ? 0.08 : 0.04) * speedRatio, pelvicYaw, pelvicRoll, "YXZ");
4322
4678
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4323
- hips.targetQuaternion.copy(hips.restQuaternion).multiply(ScratchMath.q0);
4679
+ this.skeleton.applyModelDeltaRotation("hips", ScratchMath.q0, activeAmplitude);
4324
4680
  }
4325
- const spine = this.skeleton.getJoint("spine");
4326
- if (spine) {
4327
- const spineCounterYaw = -pelvicYaw * 0.65 * weight;
4328
- ScratchMath.e0.set(-0.02 * speedRatio, spineCounterYaw, 0, "YXZ");
4681
+ if (this.skeleton.hasJoint("spine")) {
4682
+ const spineCounterYaw = -pelvicYaw * 0.65;
4683
+ ScratchMath.e0.set((this.isRunning ? 0.08 : 0.03) * speedRatio, spineCounterYaw, -pelvicRoll * 0.35, "YXZ");
4329
4684
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4330
- spine.targetQuaternion.copy(spine.restQuaternion).multiply(ScratchMath.q0);
4685
+ this.skeleton.applyModelDeltaRotation("spine", ScratchMath.q0, activeAmplitude);
4331
4686
  }
4332
- const chest = this.skeleton.getJoint("chest") || this.skeleton.getJoint("upperChest");
4333
- if (chest) {
4334
- const chestCounterYaw = -pelvicYaw * 0.35 * weight;
4335
- ScratchMath.e0.set(0.01, chestCounterYaw, 0, "YXZ");
4687
+ const chestName = this.skeleton.hasJoint("chest") ? "chest" : this.skeleton.hasJoint("upperChest") ? "upperChest" : null;
4688
+ if (chestName) {
4689
+ const chestCounterYaw = -pelvicYaw * 0.35;
4690
+ ScratchMath.e0.set(0.02 * speedRatio, chestCounterYaw, 0, "YXZ");
4336
4691
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4337
- chest.targetQuaternion.copy(chest.restQuaternion).multiply(ScratchMath.q0);
4338
- }
4339
- const hipWidthHalf = this.skeleton.proportions.hipWidth * 0.5;
4340
- const groundY = 0;
4341
- const halfStride = this.strideLength * 0.5 * speedRatio;
4342
- let leftX = -hipWidthHalf;
4343
- let leftY = groundY;
4344
- let leftZ = 0;
4692
+ this.skeleton.applyModelDeltaRotation(chestName, ScratchMath.q0, activeAmplitude);
4693
+ }
4694
+ const halfStride = this.strideLength * 0.5 * Math.min(speedRatio, 1.45);
4695
+ const liftHeight = this.stepHeight * Math.min(speedRatio, 1.5);
4696
+ const baseLeftX = this.skeleton.hasRestFootPositions ? this.skeleton.restLeftFootModelPos.x : -this.skeleton.proportions.hipWidth * 0.5;
4697
+ const baseLeftY = this.skeleton.hasRestFootPositions ? this.skeleton.restLeftFootModelPos.y : 0;
4698
+ const baseLeftZ = this.skeleton.hasRestFootPositions ? this.skeleton.restLeftFootModelPos.z : 0;
4699
+ const baseRightX = this.skeleton.hasRestFootPositions ? this.skeleton.restRightFootModelPos.x : this.skeleton.proportions.hipWidth * 0.5;
4700
+ const baseRightY = this.skeleton.hasRestFootPositions ? this.skeleton.restRightFootModelPos.y : 0;
4701
+ const baseRightZ = this.skeleton.hasRestFootPositions ? this.skeleton.restRightFootModelPos.z : 0;
4702
+ let leftY = baseLeftY;
4703
+ let leftZ = baseLeftZ;
4345
4704
  if (phi < 0.5) {
4346
4705
  const s = phi / 0.5;
4347
- leftZ = halfStride * (1 - 2 * s);
4348
- leftY = groundY;
4706
+ leftZ = baseLeftZ + halfStride * (1 - 2 * s);
4349
4707
  } else {
4350
4708
  const s = (phi - 0.5) / 0.5;
4351
- leftZ = halfStride * (2 * s - 1);
4352
- leftY = groundY + this.stepHeight * speedRatio * (4 * s * (1 - s));
4709
+ leftZ = baseLeftZ + halfStride * (2 * s - 1);
4710
+ leftY = baseLeftY + liftHeight * (4 * s * (1 - s));
4353
4711
  }
4354
- let rightX = hipWidthHalf;
4355
- let rightY = groundY;
4356
- let rightZ = 0;
4712
+ let rightY = baseRightY;
4713
+ let rightZ = baseRightZ;
4357
4714
  if (phi < 0.5) {
4358
4715
  const s = phi / 0.5;
4359
- rightZ = halfStride * (2 * s - 1);
4360
- rightY = groundY + this.stepHeight * speedRatio * (4 * s * (1 - s));
4716
+ rightZ = baseRightZ + halfStride * (2 * s - 1);
4717
+ rightY = baseRightY + liftHeight * (4 * s * (1 - s));
4361
4718
  } else {
4362
4719
  const s = (phi - 0.5) / 0.5;
4363
- rightZ = halfStride * (1 - 2 * s);
4364
- rightY = groundY;
4720
+ rightZ = baseRightZ + halfStride * (1 - 2 * s);
4365
4721
  }
4366
- this.leftFootTarget.set(leftX, leftY, leftZ);
4367
- this.rightFootTarget.set(rightX, rightY, rightZ);
4722
+ this.leftFootTarget.set(baseLeftX, leftY, leftZ);
4723
+ this.rightFootTarget.set(baseRightX, rightY, rightZ);
4368
4724
  if (this.ik) {
4369
- this.ik.solveLeftLeg(this.leftFootTarget, weight);
4370
- this.ik.solveRightLeg(this.rightFootTarget, weight);
4371
- }
4372
- const armSwingAngle = (this.isRunning ? 0.65 : 0.38) * speedRatio * weight;
4373
- const lArmAngle = -Math.sin(twoPiPhi) * armSwingAngle;
4374
- const rArmAngle = Math.sin(twoPiPhi) * armSwingAngle;
4375
- const lArm = this.skeleton.getJoint("leftUpperArm");
4376
- const rArm = this.skeleton.getJoint("rightUpperArm");
4377
- const lForeArm = this.skeleton.getJoint("leftLowerArm");
4378
- const rForeArm = this.skeleton.getJoint("rightLowerArm");
4379
- if (lArm) {
4380
- ScratchMath.e0.set(lArmAngle, 0, 0.05, "YXZ");
4381
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4382
- lArm.targetQuaternion.copy(lArm.restQuaternion).multiply(ScratchMath.q0);
4383
- }
4384
- if (rArm) {
4385
- ScratchMath.e0.set(rArmAngle, 0, -0.05, "YXZ");
4386
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4387
- rArm.targetQuaternion.copy(rArm.restQuaternion).multiply(ScratchMath.q0);
4388
- }
4389
- const elbowFlexBase = this.isRunning ? 0.55 : 0.25;
4390
- if (lForeArm) {
4391
- const flex = elbowFlexBase + Math.max(0, -Math.sin(twoPiPhi)) * 0.35;
4392
- ScratchMath.e0.set(flex * weight, 0, 0, "YXZ");
4393
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4394
- lForeArm.targetQuaternion.copy(lForeArm.restQuaternion).multiply(ScratchMath.q0);
4395
- }
4396
- if (rForeArm) {
4397
- const flex = elbowFlexBase + Math.max(0, Math.sin(twoPiPhi)) * 0.35;
4398
- ScratchMath.e0.set(flex * weight, 0, 0, "YXZ");
4399
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4400
- rForeArm.targetQuaternion.copy(rForeArm.restQuaternion).multiply(ScratchMath.q0);
4725
+ if (hips) {
4726
+ hips.bone.position.copy(hips.targetPosition);
4727
+ hips.bone.quaternion.copy(hips.targetQuaternion);
4728
+ hips.bone.updateMatrixWorld(true);
4729
+ }
4730
+ this.ik.solveLeftLeg(this.leftFootTarget, activeAmplitude);
4731
+ this.ik.solveRightLeg(this.rightFootTarget, activeAmplitude);
4732
+ }
4733
+ const targetStandingArmAngle = 0.25;
4734
+ const armSwingAngle = (this.isRunning ? 0.72 : 0.42) * Math.min(speedRatio, 1.5);
4735
+ const lArmForward = -Math.sin(twoPiPhi) * armSwingAngle;
4736
+ const rArmForward = Math.sin(twoPiPhi) * armSwingAngle;
4737
+ if (this.skeleton.hasJoint("leftUpperArm")) {
4738
+ const relaxAngle = Math.max(0, this.skeleton.leftArmRestAngleFromDown - targetStandingArmAngle);
4739
+ ScratchMath.q1.setFromAxisAngle(ScratchMath.FORWARD, this.skeleton.leftArmLowerSign * relaxAngle);
4740
+ ScratchMath.q2.setFromAxisAngle(ScratchMath.RIGHT, -lArmForward);
4741
+ ScratchMath.q0.copy(ScratchMath.q2).multiply(ScratchMath.q1);
4742
+ this.skeleton.applyModelDeltaRotation("leftUpperArm", ScratchMath.q0, activeAmplitude);
4743
+ }
4744
+ if (this.skeleton.hasJoint("rightUpperArm")) {
4745
+ const relaxAngle = Math.max(0, this.skeleton.rightArmRestAngleFromDown - targetStandingArmAngle);
4746
+ ScratchMath.q1.setFromAxisAngle(ScratchMath.FORWARD, this.skeleton.rightArmLowerSign * relaxAngle);
4747
+ ScratchMath.q2.setFromAxisAngle(ScratchMath.RIGHT, -rArmForward);
4748
+ ScratchMath.q0.copy(ScratchMath.q2).multiply(ScratchMath.q1);
4749
+ this.skeleton.applyModelDeltaRotation("rightUpperArm", ScratchMath.q0, activeAmplitude);
4750
+ }
4751
+ const elbowFlexBase = this.isRunning ? 0.85 : 0.28;
4752
+ if (this.skeleton.hasJoint("leftLowerArm")) {
4753
+ const flex = elbowFlexBase + Math.max(0, lArmForward) * 0.45;
4754
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -flex);
4755
+ this.skeleton.applyModelDeltaRotation("leftLowerArm", ScratchMath.q0, activeAmplitude);
4756
+ }
4757
+ if (this.skeleton.hasJoint("rightLowerArm")) {
4758
+ const flex = elbowFlexBase + Math.max(0, rArmForward) * 0.45;
4759
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -flex);
4760
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, activeAmplitude);
4401
4761
  }
4402
4762
  }
4403
4763
  getPhase() {
@@ -4410,18 +4770,26 @@ var LocomotionEngine = class {
4410
4770
 
4411
4771
  // src/avatar/procedural/TurnEngine.ts
4412
4772
  var TurnEngine = class {
4413
- constructor(skeleton) {
4773
+ constructor(skeleton, turnTarget) {
4414
4774
  this.skeleton = skeleton;
4415
4775
  this.currentYaw = 0;
4416
- // Current character yaw in radians
4776
+ // Current character yaw offset in radians
4417
4777
  this.targetYaw = 0;
4418
- // Target desired yaw in radians
4778
+ // Target desired yaw offset in radians
4419
4779
  this.isTurning = false;
4420
4780
  this.turnAngularVelocity = 0;
4781
+ this.turnTarget = turnTarget ?? skeleton.modelRoot;
4782
+ this.baseYaw = this.turnTarget.rotation.y;
4421
4783
  }
4422
4784
  setTargetHeading(targetYawRad) {
4423
4785
  this.targetYaw = targetYawRad;
4424
4786
  }
4787
+ turnLeft(stepRad = Math.PI / 4) {
4788
+ this.targetYaw -= Math.abs(stepRad);
4789
+ }
4790
+ turnRight(stepRad = Math.PI / 4) {
4791
+ this.targetYaw += Math.abs(stepRad);
4792
+ }
4425
4793
  setFacingDirection(direction) {
4426
4794
  switch (direction) {
4427
4795
  case "left":
@@ -4432,32 +4800,45 @@ var TurnEngine = class {
4432
4800
  break;
4433
4801
  case "center":
4434
4802
  case "forward":
4803
+ case "front":
4435
4804
  default:
4436
4805
  this.targetYaw = 0;
4437
4806
  break;
4438
4807
  }
4439
4808
  }
4809
+ reset() {
4810
+ this.currentYaw = 0;
4811
+ this.targetYaw = 0;
4812
+ this.isTurning = false;
4813
+ this.turnAngularVelocity = 0;
4814
+ this.turnTarget.rotation.y = this.baseYaw;
4815
+ }
4440
4816
  update(delta, isLocomoting = false) {
4441
4817
  const diff = ((this.targetYaw - this.currentYaw) % (Math.PI * 2) + Math.PI * 3) % (Math.PI * 2) - Math.PI;
4442
4818
  this.isTurning = Math.abs(diff) > 0.02;
4443
- const damping = isLocomoting ? 6.5 : 4;
4819
+ const damping = isLocomoting ? 6.5 : 5;
4444
4820
  const prevYaw = this.currentYaw;
4445
4821
  this.currentYaw = ScratchMath.dampAngle(this.currentYaw, this.targetYaw, damping, delta);
4446
4822
  this.turnAngularVelocity = (this.currentYaw - prevYaw) / Math.max(delta, 1e-3);
4447
- this.skeleton.modelRoot.rotation.y = this.currentYaw;
4448
- if (isLocomoting && Math.abs(this.turnAngularVelocity) > 0.2) {
4449
- const bankRoll = -Math.max(-0.06, Math.min(0.06, this.turnAngularVelocity * 0.04));
4450
- const hips = this.skeleton.getJoint("hips");
4451
- if (hips) {
4823
+ this.turnTarget.rotation.y = this.baseYaw + this.currentYaw;
4824
+ if (Math.abs(this.turnAngularVelocity) > 0.15) {
4825
+ const bankRoll = -Math.max(-0.06, Math.min(0.06, this.turnAngularVelocity * (isLocomoting ? 0.04 : 0.02)));
4826
+ if (this.skeleton.hasJoint("hips")) {
4452
4827
  ScratchMath.e0.set(0, 0, bankRoll, "YXZ");
4453
4828
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4454
- hips.targetQuaternion.multiply(ScratchMath.q0);
4829
+ this.skeleton.applyModelDeltaRotation("hips", ScratchMath.q0, 1, true);
4455
4830
  }
4456
4831
  }
4457
4832
  }
4458
4833
  getYaw() {
4459
4834
  return this.currentYaw;
4460
4835
  }
4836
+ getTargetYaw() {
4837
+ return this.targetYaw;
4838
+ }
4839
+ getAngularVelocity() {
4840
+ return this.turnAngularVelocity;
4841
+ }
4461
4842
  isTurnActive() {
4462
4843
  return this.isTurning;
4463
4844
  }
@@ -4473,23 +4854,24 @@ var BalanceEngine = class {
4473
4854
  */
4474
4855
  applyCompensation(reachOffset, weight = 1) {
4475
4856
  if (weight <= 1e-3) return;
4857
+ const localScale = this.skeleton.hipsLocalPerMeter;
4476
4858
  this.targetOffset.set(
4477
- -reachOffset.x * 0.22,
4478
- -Math.abs(reachOffset.z) * 0.05,
4479
- -reachOffset.z * 0.25
4859
+ -reachOffset.x * 0.18 * localScale,
4860
+ -Math.abs(reachOffset.z) * 0.03 * localScale,
4861
+ -reachOffset.z * 0.18 * localScale
4480
4862
  );
4481
4863
  this.centerOfMassOffset.lerp(this.targetOffset, Math.min(1, weight));
4482
4864
  const hips = this.skeleton.getJoint("hips");
4483
4865
  if (hips) {
4484
4866
  hips.targetPosition.add(this.centerOfMassOffset);
4485
4867
  }
4486
- const spine = this.skeleton.getJoint("spine");
4487
- if (spine && this.centerOfMassOffset.lengthSq() > 1e-4) {
4488
- const counterPitch = this.centerOfMassOffset.z * 0.35;
4489
- const counterRoll = -this.centerOfMassOffset.x * 0.35;
4868
+ if (this.skeleton.hasJoint("spine") && this.centerOfMassOffset.lengthSq() > 1e-6) {
4869
+ const invScale = localScale > 1e-4 ? 1 / localScale : 1;
4870
+ const counterPitch = Math.max(-0.12, Math.min(0.12, this.centerOfMassOffset.z * invScale * 0.35));
4871
+ const counterRoll = Math.max(-0.12, Math.min(0.12, -this.centerOfMassOffset.x * invScale * 0.35));
4490
4872
  ScratchMath.e0.set(counterPitch, 0, counterRoll, "YXZ");
4491
4873
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4492
- spine.targetQuaternion.multiply(ScratchMath.q0);
4874
+ this.skeleton.applyModelDeltaRotation("spine", ScratchMath.q0, 1, true);
4493
4875
  }
4494
4876
  }
4495
4877
  reset() {
@@ -4709,177 +5091,146 @@ var GestureEngine = class {
4709
5091
  return "right";
4710
5092
  }
4711
5093
  }
5094
+ /**
5095
+ * Helper: rotates an upper arm from its rest orientation to a target standing-relative Euler pose in model space.
5096
+ */
5097
+ applyStandingArmDelta(side, pitchForwardRad, yawRad, abductOutRad, weight) {
5098
+ const boneName = side === "left" ? "leftUpperArm" : "rightUpperArm";
5099
+ if (!this.skeleton.hasJoint(boneName)) return;
5100
+ const restAngle = side === "left" ? this.skeleton.leftArmRestAngleFromDown : this.skeleton.rightArmRestAngleFromDown;
5101
+ const lowerSign = side === "left" ? this.skeleton.leftArmLowerSign : this.skeleton.rightArmLowerSign;
5102
+ const relaxToDown = Math.max(0, restAngle - abductOutRad);
5103
+ ScratchMath.q1.setFromAxisAngle(ScratchMath.FORWARD, lowerSign * relaxToDown);
5104
+ ScratchMath.e0.set(-pitchForwardRad, yawRad, 0, "YXZ");
5105
+ ScratchMath.q2.setFromEuler(ScratchMath.e0);
5106
+ ScratchMath.q0.copy(ScratchMath.q2).multiply(ScratchMath.q1);
5107
+ this.skeleton.applyModelDeltaRotation(boneName, ScratchMath.q0, weight);
5108
+ }
4712
5109
  // 1. Wave (right hand oscillates back and forth at shoulder height)
4713
5110
  synthesizeWave(progress, weight) {
4714
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4715
- const rLower = this.skeleton.getJoint("rightLowerArm");
4716
- const rHand = this.skeleton.getJoint("rightHand");
4717
- if (rUpper && rLower) {
4718
- ScratchMath.e0.set(-0.6, 0.4, -1.35 * weight, "YXZ");
5111
+ this.applyStandingArmDelta("right", 0.35, -0.25, 1.35, weight);
5112
+ if (this.skeleton.hasJoint("rightLowerArm")) {
5113
+ const waveOsc = Math.sin(progress * Math.PI * 8) * 0.35;
5114
+ ScratchMath.e0.set(-1.35, 0, waveOsc, "YXZ");
4719
5115
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4720
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4721
- ScratchMath.e0.set(1.4 * weight, 0, 0, "YXZ");
5116
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, weight);
5117
+ }
5118
+ if (this.skeleton.hasJoint("rightHand")) {
5119
+ const handWave = Math.sin(progress * Math.PI * 8) * 0.3;
5120
+ ScratchMath.e0.set(0, 0, handWave, "YXZ");
4722
5121
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4723
- rLower.targetQuaternion.slerp(ScratchMath.q0, weight);
4724
- if (rHand) {
4725
- const waveAngle = Math.sin(progress * Math.PI * 8) * 0.45 * weight;
4726
- ScratchMath.e0.set(0, 0, waveAngle, "YXZ");
4727
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4728
- rHand.targetQuaternion.slerp(ScratchMath.q0, weight);
4729
- }
5122
+ this.skeleton.applyModelDeltaRotation("rightHand", ScratchMath.q0, weight);
4730
5123
  }
4731
5124
  }
4732
5125
  // 2. Pointing (arm extends toward target using IK or forward angle)
4733
5126
  synthesizePoint(_progress, weight, targetPos) {
4734
5127
  const isLeft = this.activeGesture?.type === "point_left";
4735
- const armName = isLeft ? "leftUpperArm" : "rightUpperArm";
4736
- const foreName = isLeft ? "leftLowerArm" : "rightLowerArm";
5128
+ const side = isLeft ? "left" : "right";
4737
5129
  if (targetPos && this.ik) {
4738
- this.ik.solveArmReach(isLeft ? "left" : "right", targetPos, weight);
5130
+ this.ik.solveArmReach(side, targetPos, weight);
4739
5131
  } else {
4740
- const upper = this.skeleton.getJoint(armName);
4741
- const fore = this.skeleton.getJoint(foreName);
4742
5132
  const sign = isLeft ? 1 : -1;
4743
- if (upper && fore) {
4744
- ScratchMath.e0.set(-1.45 * weight, sign * 0.25 * weight, sign * 0.15 * weight, "YXZ");
4745
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4746
- upper.targetQuaternion.slerp(ScratchMath.q0, weight);
4747
- ScratchMath.e0.set(0.15 * weight, 0, 0, "YXZ");
4748
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4749
- fore.targetQuaternion.slerp(ScratchMath.q0, weight);
5133
+ this.applyStandingArmDelta(side, 1.35, sign * 0.2, 0.25, weight);
5134
+ const foreName = isLeft ? "leftLowerArm" : "rightLowerArm";
5135
+ if (this.skeleton.hasJoint(foreName)) {
5136
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -0.15);
5137
+ this.skeleton.applyModelDeltaRotation(foreName, ScratchMath.q0, weight);
4750
5138
  }
4751
5139
  }
4752
5140
  }
4753
5141
  // 3. Agree (nod head twice)
4754
5142
  synthesizeAgree(progress, weight) {
4755
- const head = this.skeleton.getJoint("head");
4756
- if (head) {
5143
+ if (this.skeleton.hasJoint("head")) {
4757
5144
  const nodPitch = Math.sin(progress * Math.PI * 4) * 0.24 * weight;
4758
5145
  ScratchMath.e0.set(nodPitch, 0, 0, "YXZ");
4759
5146
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4760
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
5147
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, weight);
4761
5148
  }
4762
5149
  }
4763
5150
  // 4. Disagree (shake head side to side)
4764
5151
  synthesizeDisagree(progress, weight) {
4765
- const head = this.skeleton.getJoint("head");
4766
- if (head) {
5152
+ if (this.skeleton.hasJoint("head")) {
4767
5153
  const shakeYaw = Math.sin(progress * Math.PI * 4) * 0.32 * weight;
4768
5154
  ScratchMath.e0.set(0, shakeYaw, 0, "YXZ");
4769
5155
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4770
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
5156
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, weight);
4771
5157
  }
4772
5158
  }
4773
5159
  // 5. Shrug (raise shoulders, turn palms up, tilt head)
4774
5160
  synthesizeShrug(_progress, weight) {
4775
- const lUpper = this.skeleton.getJoint("leftUpperArm");
4776
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4777
- const lFore = this.skeleton.getJoint("leftLowerArm");
4778
- const rFore = this.skeleton.getJoint("rightLowerArm");
4779
- const head = this.skeleton.getJoint("head");
4780
- const lift = 0.28 * weight;
4781
- if (lUpper && rUpper) {
4782
- ScratchMath.e0.set(-0.25 * weight, 0, lift, "YXZ");
5161
+ this.applyStandingArmDelta("left", 0.2, 0, 0.48, weight);
5162
+ this.applyStandingArmDelta("right", 0.2, 0, 0.48, weight);
5163
+ if (this.skeleton.hasJoint("leftLowerArm")) {
5164
+ ScratchMath.e0.set(-0.95, 0.35, 0, "YXZ");
4783
5165
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4784
- lUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4785
- ScratchMath.e0.set(-0.25 * weight, 0, -lift, "YXZ");
4786
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4787
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
5166
+ this.skeleton.applyModelDeltaRotation("leftLowerArm", ScratchMath.q0, weight);
4788
5167
  }
4789
- if (lFore && rFore) {
4790
- ScratchMath.e0.set(0.85 * weight, 0.4 * weight, 0, "YXZ");
4791
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4792
- lFore.targetQuaternion.slerp(ScratchMath.q0, weight);
4793
- ScratchMath.e0.set(0.85 * weight, -0.4 * weight, 0, "YXZ");
5168
+ if (this.skeleton.hasJoint("rightLowerArm")) {
5169
+ ScratchMath.e0.set(-0.95, -0.35, 0, "YXZ");
4794
5170
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4795
- rFore.targetQuaternion.slerp(ScratchMath.q0, weight);
5171
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, weight);
4796
5172
  }
4797
- if (head) {
5173
+ if (this.skeleton.hasJoint("head")) {
4798
5174
  ScratchMath.e0.set(0.08 * weight, 0, 0.12 * weight, "YXZ");
4799
5175
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4800
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
5176
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, weight);
4801
5177
  }
4802
5178
  }
4803
5179
  // 6. Think (hand to chin / temple, look upward slightly)
4804
5180
  synthesizeThink(_progress, weight) {
4805
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4806
- const rFore = this.skeleton.getJoint("rightLowerArm");
4807
- const head = this.skeleton.getJoint("head");
4808
- if (rUpper && rFore) {
4809
- ScratchMath.e0.set(-1.1 * weight, -0.4 * weight, -0.5 * weight, "YXZ");
4810
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4811
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4812
- ScratchMath.e0.set(1.6 * weight, 0, 0, "YXZ");
5181
+ this.applyStandingArmDelta("right", 0.95, 0.35, 0.35, weight);
5182
+ if (this.skeleton.hasJoint("rightLowerArm")) {
5183
+ ScratchMath.e0.set(-1.55, 0, 0, "YXZ");
4813
5184
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4814
- rFore.targetQuaternion.slerp(ScratchMath.q0, weight);
5185
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, weight);
4815
5186
  }
4816
- if (head) {
5187
+ if (this.skeleton.hasJoint("head")) {
4817
5188
  ScratchMath.e0.set(-0.15 * weight, 0.18 * weight, 0.08 * weight, "YXZ");
4818
5189
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4819
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
5190
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, weight);
4820
5191
  }
4821
5192
  }
4822
5193
  // 7. Explain / Conversational gestures (gentle rhythmic hand gesturing)
4823
5194
  synthesizeExplain(progress, weight) {
4824
- const lUpper = this.skeleton.getJoint("leftUpperArm");
4825
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4826
- const lFore = this.skeleton.getJoint("leftLowerArm");
4827
- const rFore = this.skeleton.getJoint("rightLowerArm");
4828
- const osc = Math.sin(progress * Math.PI * 3) * 0.15 * weight;
4829
- if (lUpper && rUpper) {
4830
- ScratchMath.e0.set(-0.35 * weight + osc, 0.25 * weight, 0.2 * weight, "YXZ");
4831
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4832
- lUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4833
- ScratchMath.e0.set(-0.35 * weight - osc, -0.25 * weight, -0.2 * weight, "YXZ");
4834
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4835
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
5195
+ const osc = Math.sin(progress * Math.PI * 3) * 0.18;
5196
+ this.applyStandingArmDelta("left", 0.35 + osc, 0.2, 0.35, weight);
5197
+ this.applyStandingArmDelta("right", 0.35 - osc, -0.2, 0.35, weight);
5198
+ if (this.skeleton.hasJoint("leftLowerArm")) {
5199
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -0.9);
5200
+ this.skeleton.applyModelDeltaRotation("leftLowerArm", ScratchMath.q0, weight);
4836
5201
  }
4837
- if (lFore && rFore) {
4838
- ScratchMath.e0.set(0.9 * weight, 0, 0, "YXZ");
4839
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4840
- lFore.targetQuaternion.slerp(ScratchMath.q0, weight);
4841
- ScratchMath.e0.set(0.9 * weight, 0, 0, "YXZ");
4842
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4843
- rFore.targetQuaternion.slerp(ScratchMath.q0, weight);
5202
+ if (this.skeleton.hasJoint("rightLowerArm")) {
5203
+ ScratchMath.q0.setFromAxisAngle(ScratchMath.RIGHT, -0.9);
5204
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, weight);
4844
5205
  }
4845
5206
  }
4846
5207
  // 8. Open Hands (Welcome / Present / Invite)
4847
5208
  synthesizeOpenHands(_progress, weight) {
4848
- const lUpper = this.skeleton.getJoint("leftUpperArm");
4849
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4850
- const lFore = this.skeleton.getJoint("leftLowerArm");
4851
- const rFore = this.skeleton.getJoint("rightLowerArm");
4852
- if (lUpper && rUpper) {
4853
- ScratchMath.e0.set(-0.45 * weight, 0.35 * weight, 0.45 * weight, "YXZ");
5209
+ this.applyStandingArmDelta("left", 0.45, 0.35, 0.55, weight);
5210
+ this.applyStandingArmDelta("right", 0.45, -0.35, 0.55, weight);
5211
+ if (this.skeleton.hasJoint("leftLowerArm")) {
5212
+ ScratchMath.e0.set(-0.75, 0.35, 0, "YXZ");
4854
5213
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4855
- lUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4856
- ScratchMath.e0.set(-0.45 * weight, -0.35 * weight, -0.45 * weight, "YXZ");
4857
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4858
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
5214
+ this.skeleton.applyModelDeltaRotation("leftLowerArm", ScratchMath.q0, weight);
4859
5215
  }
4860
- if (lFore && rFore) {
4861
- ScratchMath.e0.set(0.75 * weight, 0.45 * weight, 0, "YXZ");
4862
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4863
- lFore.targetQuaternion.slerp(ScratchMath.q0, weight);
4864
- ScratchMath.e0.set(0.75 * weight, -0.45 * weight, 0, "YXZ");
5216
+ if (this.skeleton.hasJoint("rightLowerArm")) {
5217
+ ScratchMath.e0.set(-0.75, -0.35, 0, "YXZ");
4865
5218
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4866
- rFore.targetQuaternion.slerp(ScratchMath.q0, weight);
5219
+ this.skeleton.applyModelDeltaRotation("rightLowerArm", ScratchMath.q0, weight);
4867
5220
  }
4868
5221
  }
4869
5222
  // 9. Acknowledge (slight bow of head / chest)
4870
5223
  synthesizeAcknowledge(progress, weight) {
4871
- const spine = this.skeleton.getJoint("spine");
4872
- const head = this.skeleton.getJoint("head");
4873
5224
  const bow = Math.sin(progress * Math.PI) * 0.16 * weight;
4874
- if (spine) {
5225
+ if (this.skeleton.hasJoint("spine")) {
4875
5226
  ScratchMath.e0.set(bow, 0, 0, "YXZ");
4876
5227
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4877
- spine.targetQuaternion.copy(spine.restQuaternion).multiply(ScratchMath.q0);
5228
+ this.skeleton.applyModelDeltaRotation("spine", ScratchMath.q0, weight);
4878
5229
  }
4879
- if (head) {
5230
+ if (this.skeleton.hasJoint("head")) {
4880
5231
  ScratchMath.e0.set(bow * 0.5, 0, 0, "YXZ");
4881
5232
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4882
- head.targetQuaternion.copy(head.restQuaternion).multiply(ScratchMath.q0);
5233
+ this.skeleton.applyModelDeltaRotation("head", ScratchMath.q0, weight);
4883
5234
  }
4884
5235
  }
4885
5236
  // 10. Reach
@@ -4890,21 +5241,12 @@ var GestureEngine = class {
4890
5241
  }
4891
5242
  // 11. Celebrate (arms raised in victory, chest open)
4892
5243
  synthesizeCelebrate(_progress, weight) {
4893
- const lUpper = this.skeleton.getJoint("leftUpperArm");
4894
- const rUpper = this.skeleton.getJoint("rightUpperArm");
4895
- const spine = this.skeleton.getJoint("spine");
4896
- if (lUpper && rUpper) {
4897
- ScratchMath.e0.set(-1.8 * weight, 0, 1.2 * weight, "YXZ");
4898
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4899
- lUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4900
- ScratchMath.e0.set(-1.8 * weight, 0, -1.2 * weight, "YXZ");
4901
- ScratchMath.q0.setFromEuler(ScratchMath.e0);
4902
- rUpper.targetQuaternion.slerp(ScratchMath.q0, weight);
4903
- }
4904
- if (spine) {
5244
+ this.applyStandingArmDelta("left", 0.35, 0, 2.45, weight);
5245
+ this.applyStandingArmDelta("right", 0.35, 0, 2.45, weight);
5246
+ if (this.skeleton.hasJoint("spine")) {
4905
5247
  ScratchMath.e0.set(-0.12 * weight, 0, 0, "YXZ");
4906
5248
  ScratchMath.q0.setFromEuler(ScratchMath.e0);
4907
- spine.targetQuaternion.copy(spine.restQuaternion).multiply(ScratchMath.q0);
5249
+ this.skeleton.applyModelDeltaRotation("spine", ScratchMath.q0, weight);
4908
5250
  }
4909
5251
  }
4910
5252
  };
@@ -5202,13 +5544,17 @@ var MotionCoordinator = _MotionCoordinator;
5202
5544
 
5203
5545
  // src/avatar/procedural/ProceduralMovementEngine.ts
5204
5546
  var ProceduralMovementEngine = class {
5205
- constructor(modelRoot) {
5547
+ constructor(modelRoot, options) {
5206
5548
  this.isEnabled = true;
5207
- this.skeleton = new AUBRSkeleton(modelRoot);
5549
+ this.paused = false;
5550
+ this.locomotionBlendWeight = 0;
5551
+ this.startingTimer = 0;
5552
+ this.balanceReachScratch = new THREE.Vector3();
5553
+ this.skeleton = new AUBRSkeleton(modelRoot, options);
5208
5554
  this.ik = new IKCoordinator(this.skeleton);
5209
5555
  this.idle = new IdleEngine(this.skeleton);
5210
5556
  this.locomotion = new LocomotionEngine(this.skeleton, this.ik);
5211
- this.turn = new TurnEngine(this.skeleton);
5557
+ this.turn = new TurnEngine(this.skeleton, options?.turnTarget);
5212
5558
  this.balance = new BalanceEngine(this.skeleton);
5213
5559
  this.lookAtEngine = new LookAtEngine(this.skeleton);
5214
5560
  this.gesture = new GestureEngine(this.skeleton, this.ik);
@@ -5219,42 +5565,110 @@ var ProceduralMovementEngine = class {
5219
5565
  getCapabilities() {
5220
5566
  return this.skeleton.capabilities;
5221
5567
  }
5568
+ getState() {
5569
+ return this.stateMachine.getState();
5570
+ }
5222
5571
  setEnabled(enabled) {
5223
5572
  this.isEnabled = enabled;
5224
5573
  }
5574
+ pause() {
5575
+ this.paused = true;
5576
+ }
5577
+ resume() {
5578
+ this.paused = false;
5579
+ }
5580
+ isPaused() {
5581
+ return this.paused;
5582
+ }
5583
+ resetToRestPose() {
5584
+ this.startingTimer = 0;
5585
+ this.locomotionBlendWeight = 0;
5586
+ this.locomotion.cancel();
5587
+ this.gesture.stopGesture();
5588
+ this.idle.reset();
5589
+ this.turn.reset();
5590
+ this.balance.reset();
5591
+ this.lookAtEngine.clearTarget();
5592
+ this.facial.setSpeaking(false);
5593
+ this.facial.setExpression("neutral");
5594
+ this.stateMachine.transitionTo("idle", 0.05);
5595
+ this.coordinator.setWeights({ locomotionWeight: 0, idleWeight: 1, gestureWeight: 0 });
5596
+ this.skeleton.resetToRestPose();
5597
+ this.skeleton.updateWorldMatrices();
5598
+ }
5225
5599
  // --- High-Level Movement API ---
5600
+ startIdle() {
5601
+ const current = this.stateMachine.getState();
5602
+ if (current === "walking" || current === "running" || current === "starting") {
5603
+ this.stopLocomotion();
5604
+ return;
5605
+ }
5606
+ this.startingTimer = 0;
5607
+ this.gesture.stopGesture();
5608
+ this.stateMachine.transitionTo("idle", 0.2);
5609
+ this.coordinator.setWeights({ locomotionWeight: 0, idleWeight: 1, gestureWeight: 0 });
5610
+ }
5611
+ startWalking(speed = 1, screenVelocityPx) {
5612
+ if (!this.skeleton.capabilities.proceduralLocomotion) return;
5613
+ this.startingTimer = 0.18;
5614
+ this.stateMachine.transitionTo("starting", 0.18);
5615
+ this.locomotion.setMotion({ speed, isRunning: false, screenVelocityPx });
5616
+ }
5226
5617
  walk(speed = 1, screenVelocityPx) {
5227
- this.clearStopTimer();
5228
- this.stateMachine.transitionTo("walking");
5618
+ if (!this.skeleton.capabilities.proceduralLocomotion) return;
5619
+ this.startingTimer = 0;
5620
+ this.stateMachine.transitionTo("walking", 0.2);
5229
5621
  this.locomotion.setMotion({ speed, isRunning: false, screenVelocityPx });
5230
- this.coordinator.setWeights({ locomotionWeight: 1, idleWeight: 0 });
5231
5622
  }
5232
5623
  run(speed = 1.8, screenVelocityPx) {
5233
- this.clearStopTimer();
5234
- this.stateMachine.transitionTo("running");
5624
+ if (!this.skeleton.capabilities.proceduralRunning) return;
5625
+ this.startingTimer = 0;
5626
+ this.stateMachine.transitionTo("running", 0.2);
5235
5627
  this.locomotion.setMotion({ speed, isRunning: true, screenVelocityPx });
5236
- this.coordinator.setWeights({ locomotionWeight: 1, idleWeight: 0 });
5628
+ }
5629
+ stop() {
5630
+ this.stopLocomotion();
5237
5631
  }
5238
5632
  stopLocomotion() {
5239
- this.clearStopTimer();
5633
+ this.startingTimer = 0;
5240
5634
  this.locomotion.stop();
5241
- this.stateMachine.transitionTo("stopping", 0.2);
5242
- this.stopTimer = setTimeout(() => {
5243
- this.stopTimer = void 0;
5244
- if (this.stateMachine.getState() === "stopping") {
5245
- this.stateMachine.transitionTo("idle", 0.25);
5246
- this.coordinator.setWeights({ locomotionWeight: 0, idleWeight: 1 });
5247
- }
5248
- }, 200);
5249
- }
5250
- dispose() {
5251
- this.clearStopTimer();
5252
- this.isEnabled = false;
5253
- }
5254
- clearStopTimer() {
5255
- if (this.stopTimer) {
5256
- clearTimeout(this.stopTimer);
5257
- this.stopTimer = void 0;
5635
+ const state = this.stateMachine.getState();
5636
+ if (state === "walking" || state === "running" || state === "starting") {
5637
+ this.stateMachine.transitionTo("stopping", 0.22);
5638
+ } else if (state !== "stopping") {
5639
+ this.stateMachine.transitionTo("idle", 0.2);
5640
+ }
5641
+ }
5642
+ cancelLocomotion() {
5643
+ this.startingTimer = 0;
5644
+ this.locomotionBlendWeight = 0;
5645
+ this.locomotion.cancel();
5646
+ this.coordinator.setWeights({ locomotionWeight: 0, idleWeight: 1 });
5647
+ this.stateMachine.transitionTo("idle", 0.05);
5648
+ }
5649
+ turnLeft(stepRad = Math.PI / 4) {
5650
+ if (!this.skeleton.capabilities.turning) return;
5651
+ this.turn.turnLeft(stepRad);
5652
+ if (this.stateMachine.getState() === "idle") {
5653
+ this.stateMachine.transitionTo("turning", 0.15);
5654
+ }
5655
+ }
5656
+ turnRight(stepRad = Math.PI / 4) {
5657
+ if (!this.skeleton.capabilities.turning) return;
5658
+ this.turn.turnRight(stepRad);
5659
+ if (this.stateMachine.getState() === "idle") {
5660
+ this.stateMachine.transitionTo("turning", 0.15);
5661
+ }
5662
+ }
5663
+ turnTo(directionOrYaw) {
5664
+ if (!this.skeleton.capabilities.turning) return;
5665
+ if (typeof directionOrYaw === "number") {
5666
+ this.turn.setTargetHeading(directionOrYaw);
5667
+ } else {
5668
+ this.turn.setFacingDirection(directionOrYaw);
5669
+ }
5670
+ if (this.stateMachine.getState() === "idle") {
5671
+ this.stateMachine.transitionTo("turning", 0.15);
5258
5672
  }
5259
5673
  }
5260
5674
  setFacing(direction) {
@@ -5263,10 +5677,26 @@ var ProceduralMovementEngine = class {
5263
5677
  setTargetHeading(yawRad) {
5264
5678
  this.turn.setTargetHeading(yawRad);
5265
5679
  }
5680
+ dispose() {
5681
+ this.isEnabled = false;
5682
+ this.paused = false;
5683
+ this.startingTimer = 0;
5684
+ this.locomotionBlendWeight = 0;
5685
+ this.locomotion.cancel();
5686
+ this.gesture.stopGesture();
5687
+ this.balance.reset();
5688
+ this.lookAtEngine.clearTarget();
5689
+ }
5266
5690
  playGesture(type, options) {
5691
+ if (!this.skeleton.capabilities.upperBodyGestures && !this.skeleton.capabilities.headLookAt) {
5692
+ return false;
5693
+ }
5267
5694
  const success = this.gesture.playGesture(type, options);
5268
5695
  if (success) {
5269
- this.stateMachine.transitionTo("gesturing");
5696
+ const current = this.stateMachine.getState();
5697
+ if (current === "idle" || current === "speaking" || current === "listening" || current === "thinking") {
5698
+ this.stateMachine.transitionTo("gesturing");
5699
+ }
5270
5700
  this.coordinator.setWeights({ gestureWeight: 1 });
5271
5701
  }
5272
5702
  return success;
@@ -5304,41 +5734,83 @@ var ProceduralMovementEngine = class {
5304
5734
  * Restores bones to reference bind pose to prevent cumulative transform drift.
5305
5735
  */
5306
5736
  preMixerUpdate() {
5307
- if (!this.isEnabled) return;
5737
+ if (!this.isEnabled || this.paused) return;
5308
5738
  this.coordinator.preMixerRestore();
5309
5739
  }
5310
5740
  /**
5311
5741
  * Main procedural pipeline tick.
5312
- * Invoked in FbxRenderer.startLoop() after mixer.update(delta) and before renderer.render().
5742
+ * Invoked in FbxRenderer.startLoop() or Avatar Studio after mixer.update(delta) and before renderer.render().
5313
5743
  */
5314
- update(delta, hasActiveMixerClip) {
5315
- if (!this.isEnabled) return;
5744
+ update(delta, hasActiveMixerClip = false) {
5745
+ if (!this.isEnabled || this.paused) return;
5746
+ const dt = Math.min(Math.max(delta, 0), 0.1);
5316
5747
  if (hasActiveMixerClip) {
5317
5748
  this.coordinator.snapshotMixerOutput();
5318
5749
  this.coordinator.setWeights({ clipWeight: 1 });
5319
5750
  } else {
5320
5751
  this.coordinator.setWeights({ clipWeight: 0 });
5321
5752
  }
5322
- const currentState = this.stateMachine.getState();
5753
+ this.stateMachine.update(dt);
5754
+ let currentState = this.stateMachine.getState();
5755
+ if (currentState === "starting") {
5756
+ this.startingTimer -= dt;
5757
+ if (this.startingTimer <= 0) {
5758
+ this.stateMachine.transitionTo("walking", 0.2);
5759
+ currentState = this.stateMachine.getState();
5760
+ }
5761
+ }
5323
5762
  const isLocomoting = currentState === "walking" || currentState === "running" || currentState === "starting";
5324
- this.stateMachine.update(delta);
5325
- this.turn.update(delta, isLocomoting);
5326
- const locoWeight = isLocomoting ? 1 : this.coordinator.getWeights().locomotionWeight;
5327
- if (locoWeight > 0.01) {
5328
- this.locomotion.update(delta, locoWeight);
5763
+ const targetLocoWeight = isLocomoting ? 1 : 0;
5764
+ const blendRate = isLocomoting ? 7.5 : 8.5;
5765
+ this.locomotionBlendWeight = ScratchMath.damp(
5766
+ this.locomotionBlendWeight,
5767
+ targetLocoWeight,
5768
+ blendRate,
5769
+ dt
5770
+ );
5771
+ if (this.locomotionBlendWeight < 5e-3 && !isLocomoting) {
5772
+ this.locomotionBlendWeight = 0;
5773
+ }
5774
+ if (currentState === "stopping" && this.locomotionBlendWeight < 0.02 && this.locomotion.getSpeed() < 0.05) {
5775
+ this.locomotionBlendWeight = 0;
5776
+ this.stateMachine.transitionTo("idle", 0.15);
5777
+ currentState = "idle";
5778
+ }
5779
+ const locoWeight = this.locomotionBlendWeight;
5780
+ const idleWeight = Math.max(0, 1 - locoWeight);
5781
+ this.coordinator.setWeights({
5782
+ locomotionWeight: locoWeight,
5783
+ idleWeight
5784
+ });
5785
+ if (idleWeight > 5e-3 && this.skeleton.capabilities.proceduralIdle) {
5786
+ this.idle.update(dt, idleWeight);
5787
+ }
5788
+ if (locoWeight > 5e-3 && this.skeleton.capabilities.proceduralLocomotion) {
5789
+ this.locomotion.update(dt, locoWeight);
5329
5790
  }
5330
- const idleWeight = !isLocomoting ? 1 : this.coordinator.getWeights().idleWeight;
5331
- if (idleWeight > 0.01) {
5332
- this.idle.update(delta, idleWeight);
5791
+ if (this.skeleton.capabilities.turning) {
5792
+ this.turn.update(dt, isLocomoting);
5793
+ if (currentState === "turning" && !this.turn.isTurnActive()) {
5794
+ this.stateMachine.transitionTo("idle", 0.15);
5795
+ }
5333
5796
  }
5334
5797
  if (this.gesture.isGestureActive()) {
5335
- this.gesture.update(delta);
5798
+ this.gesture.update(dt);
5336
5799
  this.coordinator.setWeights({ gestureWeight: 1 });
5800
+ this.balanceReachScratch.set(0, 0, 0.15);
5801
+ this.balance.applyCompensation(this.balanceReachScratch, Math.min(1, dt * 6));
5337
5802
  } else {
5338
5803
  this.coordinator.setWeights({ gestureWeight: 0 });
5804
+ if (this.stateMachine.getState() === "gesturing") {
5805
+ this.stateMachine.transitionTo("idle", 0.2);
5806
+ }
5807
+ this.balanceReachScratch.set(0, 0, 0);
5808
+ this.balance.applyCompensation(this.balanceReachScratch, Math.min(1, dt * 6));
5339
5809
  }
5340
- this.lookAtEngine.update(delta, 1);
5341
- this.facial.update(delta);
5810
+ if (this.skeleton.capabilities.headLookAt) {
5811
+ this.lookAtEngine.update(dt, 1);
5812
+ }
5813
+ this.facial.update(dt);
5342
5814
  this.coordinator.blendLayers(hasActiveMixerClip);
5343
5815
  this.skeleton.apply();
5344
5816
  this.skeleton.updateWorldMatrices();
@@ -5376,13 +5848,8 @@ var FbxRenderer = class {
5376
5848
  if (!doc) {
5377
5849
  throw new Error("Unable to access document DOM for 3D avatar viewport");
5378
5850
  }
5379
- this.canvas = doc.createElement("canvas");
5380
- this.canvas.className = "asiyst-avatar-canvas";
5381
- this.canvas.setAttribute("role", "presentation");
5382
- this.canvas.style.opacity = "0";
5383
- this.canvas.style.transition = "opacity 0.25s ease";
5384
- this.canvas.style.background = "transparent";
5385
- const glContext = this.canvas.getContext("webgl2") || this.canvas.getContext("webgl");
5851
+ const probeCanvas = doc.createElement("canvas");
5852
+ const glContext = probeCanvas.getContext("webgl2") || probeCanvas.getContext("webgl");
5386
5853
  if (!glContext) {
5387
5854
  throw new AsiystError({
5388
5855
  code: "WEBGL_UNAVAILABLE",
@@ -5390,6 +5857,12 @@ var FbxRenderer = class {
5390
5857
  hint: "Enable hardware acceleration in your browser or use a WebGL-capable device."
5391
5858
  });
5392
5859
  }
5860
+ this.canvas = doc.createElement("canvas");
5861
+ this.canvas.className = "asiyst-avatar-canvas";
5862
+ this.canvas.setAttribute("role", "presentation");
5863
+ this.canvas.style.opacity = "0";
5864
+ this.canvas.style.transition = "opacity 0.25s ease";
5865
+ this.canvas.style.background = "transparent";
5393
5866
  const isMobile = typeof window !== "undefined" && window.innerWidth <= 640;
5394
5867
  const width = options?.width || (isMobile ? 140 : 190);
5395
5868
  const height = options?.height || (isMobile ? 280 : 360);
@@ -5542,7 +6015,10 @@ var FbxRenderer = class {
5542
6015
  });
5543
6016
  this.allAnimations = [...modelAnimations];
5544
6017
  try {
5545
- this.proceduralEngine = new ProceduralMovementEngine(rawObject);
6018
+ this.proceduralEngine = new ProceduralMovementEngine(rawObject, {
6019
+ embeddedAnimationCount: modelAnimations.length,
6020
+ turnTarget: this.modelRoot
6021
+ });
5546
6022
  } catch (procErr) {
5547
6023
  if (typeof console !== "undefined" && typeof console.warn === "function") {
5548
6024
  console.warn("[asiyst] Procedural movement engine initialization notice:", procErr);
@@ -6133,6 +6609,34 @@ var FbxRenderer = class {
6133
6609
  this.mixer = null;
6134
6610
  }
6135
6611
  if (this.scene) {
6612
+ const disposedTextures = /* @__PURE__ */ new Set();
6613
+ const TEXTURE_SLOTS = [
6614
+ "map",
6615
+ "normalMap",
6616
+ "roughnessMap",
6617
+ "metalnessMap",
6618
+ "aoMap",
6619
+ "emissiveMap",
6620
+ "alphaMap",
6621
+ "bumpMap",
6622
+ "displacementMap",
6623
+ "lightMap",
6624
+ "envMap"
6625
+ ];
6626
+ const disposeMat = (m) => {
6627
+ const matRecord = m;
6628
+ for (const slot of TEXTURE_SLOTS) {
6629
+ const texCandidate = matRecord[slot];
6630
+ if (texCandidate && typeof texCandidate === "object" && texCandidate.isTexture) {
6631
+ const tex = texCandidate;
6632
+ if (!disposedTextures.has(tex)) {
6633
+ disposedTextures.add(tex);
6634
+ tex.dispose();
6635
+ }
6636
+ }
6637
+ }
6638
+ m.dispose();
6639
+ };
6136
6640
  this.scene.traverse((obj) => {
6137
6641
  const mesh = obj;
6138
6642
  if (mesh.isMesh) {
@@ -6142,14 +6646,12 @@ var FbxRenderer = class {
6142
6646
  if (mesh.material) {
6143
6647
  if (Array.isArray(mesh.material)) {
6144
6648
  mesh.material.forEach((m) => {
6145
- const mat = m;
6146
- mat.map?.dispose();
6147
- mat.dispose();
6649
+ if (m && typeof m.dispose === "function") {
6650
+ disposeMat(m);
6651
+ }
6148
6652
  });
6149
- } else {
6150
- const mat = mesh.material;
6151
- mat.map?.dispose();
6152
- mat.dispose();
6653
+ } else if (mesh.material && typeof mesh.material.dispose === "function") {
6654
+ disposeMat(mesh.material);
6153
6655
  }
6154
6656
  }
6155
6657
  }
@@ -7465,6 +7967,8 @@ var MovementEngine = class {
7465
7967
  faceDirection(direction) {
7466
7968
  if (direction === "left" || direction === "right") {
7467
7969
  this.renderer.setFacing(direction);
7970
+ } else if (typeof this.renderer.setFacing === "function") {
7971
+ this.renderer.setFacing(direction);
7468
7972
  }
7469
7973
  }
7470
7974
  viewport() {
@@ -8416,10 +8920,12 @@ var RuntimeAuth = class {
8416
8920
  if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
8417
8921
  throw new AuthenticationError("ASIYST runtime authorization has expired.");
8418
8922
  }
8923
+ const lifetimeMs = Math.max(0, expiresAt - Date.now());
8924
+ const refreshBufferMs = Math.min(3e4, Math.floor(lifetimeMs * 0.1));
8419
8925
  const token = {
8420
8926
  value: data.token,
8421
8927
  expiresAt,
8422
- refreshAfter: expiresAt
8928
+ refreshAfter: Math.max(Date.now(), expiresAt - refreshBufferMs)
8423
8929
  };
8424
8930
  this.token = token;
8425
8931
  return token;
@@ -10081,12 +10587,20 @@ var ActionScheduler = class {
10081
10587
  ctx.events.emit("action_started", { actionId: action.id, actionType: action.type });
10082
10588
  try {
10083
10589
  const timeoutMs = typeof action.expirationMs === "number" && action.expirationMs > 0 ? action.expirationMs : 15e3;
10084
- const result = await Promise.race([
10085
- handler(ctx),
10086
- new Promise(
10087
- (_, reject) => setTimeout(() => reject(new Error(`Action ${action.type} timed out after ${timeoutMs}ms`)), timeoutMs)
10088
- )
10089
- ]);
10590
+ let timerId;
10591
+ const timeoutPromise = new Promise((_, reject) => {
10592
+ timerId = setTimeout(() => {
10593
+ reject(new Error(`Action ${action.type} timed out after ${timeoutMs}ms`));
10594
+ }, timeoutMs);
10595
+ });
10596
+ let result;
10597
+ try {
10598
+ result = await Promise.race([handler(ctx), timeoutPromise]);
10599
+ } finally {
10600
+ if (timerId !== void 0) {
10601
+ clearTimeout(timerId);
10602
+ }
10603
+ }
10090
10604
  const durationMs = Date.now() - startTime;
10091
10605
  const ackResult = {
10092
10606
  executionDurationMs: durationMs,
@@ -10734,7 +11248,7 @@ var AsiystRuntime = class {
10734
11248
  apiBaseUrl: options.apiBaseUrl ?? DEFAULT_API_BASE_URL,
10735
11249
  projectId: options.projectId,
10736
11250
  publicKey: options.publicKey,
10737
- installationId: void 0,
11251
+ installationId: this.installationId,
10738
11252
  origin: win.location.origin,
10739
11253
  environment: this.environment
10740
11254
  }) : void 0;
@@ -10816,36 +11330,47 @@ var AsiystRuntime = class {
10816
11330
  (event) => this.cloud.sendRuntimeEvent(event),
10817
11331
  this.events
10818
11332
  );
10819
- this.tourEngine = new TourEngine(
10820
- async (route) => {
11333
+ this.tourEngine = new TourEngine({
11334
+ navigateToRoute: async (route) => {
10821
11335
  const nav = resolveNavigationAdapter(win);
10822
11336
  await nav.navigateToRoute(route);
10823
11337
  },
10824
- async (elId) => {
11338
+ moveToElement: async (elId) => {
10825
11339
  await this.movement.moveTo(elId, "developer");
10826
11340
  },
10827
- async (elId) => {
11341
+ pointAtElement: async (elId) => {
10828
11342
  await this.movement.pointAt(elId, "developer");
10829
11343
  },
10830
- async (elId, style) => {
10831
- const el = this.targetRegistry.get(elId);
10832
- if (el) {
10833
- this.highlights.show(el, style || "spotlight");
11344
+ highlightElement: async (elId, style) => {
11345
+ const resolved = this.resolver.tryResolve(elId, "developer");
11346
+ if (resolved) {
11347
+ this.highlights.show(resolved.element, style || "spotlight");
11348
+ } else {
11349
+ const el = this.targetRegistry.get(elId);
11350
+ if (el) {
11351
+ this.highlights.show(el, style || "spotlight");
11352
+ }
10834
11353
  }
10835
11354
  },
10836
- async (text) => {
11355
+ clearHighlight: () => {
11356
+ this.highlights.hide();
11357
+ },
11358
+ speak: async (text) => {
10837
11359
  await this.speechPlayer.speak(text);
10838
11360
  },
10839
- (event) => {
11361
+ playGesture: (gesture) => {
11362
+ return this.avatar.playGesture(gesture);
11363
+ },
11364
+ onStepChanged: (event) => {
10840
11365
  this.events.emit("asiyst:tour:step_changed", event);
10841
11366
  },
10842
- (tourId) => {
11367
+ onTourCompleted: (tourId) => {
10843
11368
  this.events.emit("asiyst:tour:completed", { tourId });
10844
11369
  },
10845
- (tourId, error) => {
11370
+ onTourError: (tourId, error) => {
10846
11371
  this.events.emit("asiyst:tour:error", { tourId, error });
10847
11372
  }
10848
- );
11373
+ });
10849
11374
  this.actionScheduler = new ActionScheduler(
10850
11375
  (action) => this.createActionContext(action, doc, win)
10851
11376
  );
@@ -11621,8 +12146,8 @@ var AsiystRuntime = class {
11621
12146
  origin
11622
12147
  });
11623
12148
  if (reg?.runtimeSessionId) {
11624
- this.installationId = reg.runtimeSessionId;
11625
- this.runtimeAuth?.setInstallationId(reg.runtimeSessionId);
12149
+ this.visitorSessionId = reg.runtimeSessionId;
12150
+ this.cloud.setSessionId(reg.runtimeSessionId);
11626
12151
  this.registrationSucceeded = true;
11627
12152
  this.connectionStatus = "connected";
11628
12153
  this.verificationStatus = "connected";
@@ -11671,9 +12196,107 @@ var AsiystRuntime = class {
11671
12196
  this.map.replace(inspectDocument(doc));
11672
12197
  });
11673
12198
  }
12199
+ resolveLocalBasicIntent(rawText) {
12200
+ const text = rawText.trim().toLowerCase().replace(/[.,!?;:]/g, "").replace(/\s+/g, " ");
12201
+ if (!text) return null;
12202
+ if (text === "walk" || text === "walk around" || text === "walk forward" || text === "start walking") {
12203
+ return "walk";
12204
+ }
12205
+ if (text === "run" || text === "run around" || text === "start running") {
12206
+ return "run";
12207
+ }
12208
+ if (text === "stop" || text === "stop moving" || text === "halt" || text === "freeze" || text === "pause") {
12209
+ return "stop";
12210
+ }
12211
+ if (text === "idle" || text === "reset pose" || text === "reset" || text === "stand still" || text === "stand") {
12212
+ return "idle";
12213
+ }
12214
+ if (text === "turn left" || text === "look left" || text === "face left") {
12215
+ return "turn_left";
12216
+ }
12217
+ if (text === "turn right" || text === "look right" || text === "face right") {
12218
+ return "turn_right";
12219
+ }
12220
+ if (text === "turn front" || text === "turn forward" || text === "look forward" || text === "face front" || text === "face forward") {
12221
+ return "turn_front";
12222
+ }
12223
+ if (text === "wave" || text === "wave hand" || text === "wave at me") {
12224
+ return "wave";
12225
+ }
12226
+ if (text === "greet me" || text === "say hello" || text === "say hi" || text === "greet") {
12227
+ return "greet";
12228
+ }
12229
+ return null;
12230
+ }
12231
+ executeLocalIntent(intent, doc) {
12232
+ const win = doc.defaultView || (typeof window !== "undefined" ? window : void 0);
12233
+ const width = win?.innerWidth ?? 1024;
12234
+ const height = win?.innerHeight ?? 768;
12235
+ switch (intent) {
12236
+ case "walk": {
12237
+ const targetX = Math.round(Math.max(120, Math.min(width - 120, width * 0.5 + (Math.random() * 200 - 100))));
12238
+ const targetY = Math.round(Math.max(120, Math.min(height - 120, height * 0.65 + (Math.random() * 100 - 50))));
12239
+ void this.avatar.walkTo({ x: targetX, y: targetY }, 1);
12240
+ break;
12241
+ }
12242
+ case "run": {
12243
+ const targetX = Math.round(Math.max(120, Math.min(width - 120, width * 0.5 + (Math.random() * 200 - 100))));
12244
+ const targetY = Math.round(Math.max(120, Math.min(height - 120, height * 0.65 + (Math.random() * 100 - 50))));
12245
+ void this.avatar.runTo({ x: targetX, y: targetY }, 1.5);
12246
+ break;
12247
+ }
12248
+ case "stop": {
12249
+ this.avatar.stop();
12250
+ break;
12251
+ }
12252
+ case "idle": {
12253
+ this.avatar.stopAnimation();
12254
+ this.avatar.stop();
12255
+ this.avatar.turnTo("forward");
12256
+ this.avatar.setExpression("neutral");
12257
+ break;
12258
+ }
12259
+ case "turn_left": {
12260
+ this.avatar.turnTo("left");
12261
+ break;
12262
+ }
12263
+ case "turn_right": {
12264
+ this.avatar.turnTo("right");
12265
+ break;
12266
+ }
12267
+ case "turn_front": {
12268
+ this.avatar.turnTo("front");
12269
+ break;
12270
+ }
12271
+ case "wave":
12272
+ case "greet": {
12273
+ this.avatar.playGesture("wave");
12274
+ break;
12275
+ }
12276
+ }
12277
+ }
11674
12278
  async handleUserMessage(text, doc) {
11675
12279
  this.greetingManager.markUserInteracted();
11676
12280
  this.events.emit("asiyst:conversation:message", { role: "user", text });
12281
+ const localIntent = this.resolveLocalBasicIntent(text);
12282
+ if (localIntent) {
12283
+ this.executeLocalIntent(localIntent, doc);
12284
+ const confirmations = {
12285
+ walk: "Walking.",
12286
+ run: "Running.",
12287
+ stop: "Stopped.",
12288
+ idle: "Reset to idle pose.",
12289
+ turn_left: "Turning left.",
12290
+ turn_right: "Turning right.",
12291
+ turn_front: "Facing forward.",
12292
+ wave: "Waving hello!",
12293
+ greet: "Hello! Ready to help."
12294
+ };
12295
+ const localReply = confirmations[localIntent] ?? `Executed "${text.trim()}" locally.`;
12296
+ this.panel.append("assistant", localReply);
12297
+ this.events.emit("asiyst:conversation:message", { role: "assistant", text: localReply });
12298
+ return;
12299
+ }
11677
12300
  this.avatar.think();
11678
12301
  try {
11679
12302
  const reply = await this.cloud.sendConversationMessage(
@@ -11702,8 +12325,8 @@ var AsiystRuntime = class {
11702
12325
  this.events.emit("asiyst:conversation:message", { role: "assistant", text: reply.message.text });
11703
12326
  } catch (error) {
11704
12327
  const message = error instanceof Error ? error.message : "Asiyst Cloud is unavailable";
11705
- this.panel.append("assistant", message);
11706
12328
  this.events.emit("asiyst:error", { code: "conversation_failed", message });
12329
+ this.panel.append("assistant", message);
11707
12330
  this.avatar.speak(message);
11708
12331
  }
11709
12332
  }
@@ -11806,17 +12429,11 @@ var AsiystRuntime = class {
11806
12429
  async avatarSubmitContext() {
11807
12430
  await this.submitWebsiteContext();
11808
12431
  }
11809
- async avatarHighlight(targetId, style) {
11810
- const el = this.targetRegistry.get(targetId);
11811
- if (el) {
11812
- this.highlights.show(el, style ?? "outline");
11813
- }
12432
+ async avatarHighlight(target, style) {
12433
+ await this.avatar.highlight(target, style ?? "outline", "developer");
11814
12434
  }
11815
- async avatarPointAt(targetId) {
11816
- const el = this.targetRegistry.get(targetId);
11817
- if (el) {
11818
- await this.avatar.pointAt(targetId, "developer");
11819
- }
12435
+ async avatarPointAt(target) {
12436
+ await this.avatar.pointAt(target, "developer");
11820
12437
  }
11821
12438
  async avatarNavigateTo(route) {
11822
12439
  const win = this.host?.chrome?.ownerDocument?.defaultView || (typeof window !== "undefined" ? window : void 0);
@@ -11953,15 +12570,10 @@ var AsiystInstanceImpl = class {
11953
12570
  interact: {
11954
12571
  highlight: async (targetId, options) => {
11955
12572
  const style = typeof options === "string" ? options : options?.style;
11956
- await this.requireInstanceRuntime().avatarHighlight(
11957
- typeof targetId === "string" ? targetId : targetId.id || "",
11958
- style
11959
- );
12573
+ await this.requireInstanceRuntime().avatarHighlight(targetId, style);
11960
12574
  },
11961
12575
  pointAt: async (targetId) => {
11962
- await this.requireInstanceRuntime().avatarPointAt(
11963
- typeof targetId === "string" ? targetId : targetId.id || ""
11964
- );
12576
+ await this.requireInstanceRuntime().avatarPointAt(targetId);
11965
12577
  }
11966
12578
  },
11967
12579
  navigation: {
@@ -12267,10 +12879,10 @@ var Asiyst = {
12267
12879
  interact: {
12268
12880
  async highlight(targetId, options) {
12269
12881
  const style = typeof options === "string" ? options : options?.style;
12270
- await requireRuntime().avatarHighlight(typeof targetId === "string" ? targetId : targetId.id || "", style);
12882
+ await requireRuntime().avatarHighlight(targetId, style);
12271
12883
  },
12272
12884
  async pointAt(targetId) {
12273
- await requireRuntime().avatarPointAt(typeof targetId === "string" ? targetId : targetId.id || "");
12885
+ await requireRuntime().avatarPointAt(targetId);
12274
12886
  }
12275
12887
  },
12276
12888
  navigation: {