@needle-tools/three-mesh-effects 0.3.3 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/README.md +2 -1
- package/build/box-impostor-runtime.js +13 -0
- package/build/box-impostor-runtime.js.map +3 -3
- package/build/deformation-runtime.js +11 -9
- package/build/deformation-runtime.js.map +2 -2
- package/build/impostor-runtime.js +41 -19
- package/build/impostor-runtime.js.map +3 -3
- package/build/internal/box-impostor/box-impostor-runtime.js +13 -0
- package/build/internal/box-impostor/box-impostor-runtime.js.map +3 -3
- package/build/internal/deformation/pin-ik.js +11 -9
- package/build/internal/deformation/pin-ik.js.map +2 -2
- package/build/internal/deformation/pin-wiggle.js.map +1 -1
- package/build/internal/deformation/rig-extension.js.map +1 -1
- package/build/internal/deformation/rig-runtime.js +11 -9
- package/build/internal/deformation/rig-runtime.js.map +2 -2
- package/build/internal/impostor/impostor-node-material.js +41 -19
- package/build/internal/impostor/impostor-node-material.js.map +3 -3
- package/build/internal/pixel-impostor/pixel-impostor-display.js +9 -7
- package/build/internal/pixel-impostor/pixel-impostor-display.js.map +2 -2
- package/build/internal/rendering/classic-webgl-support.js +12 -0
- package/build/internal/rendering/classic-webgl-support.js.map +7 -0
- package/build/internal/rendering/renderer-support.js +13 -0
- package/build/internal/rendering/renderer-support.js.map +3 -3
- package/build/pixel-impostor-runtime.js +9 -7
- package/build/pixel-impostor-runtime.js.map +2 -2
- package/build/types/rendering/classic-webgl-support.d.ts +9 -0
- package/build/types/rendering/classic-webgl-support.js +1 -0
- package/package.json +2 -2
- package/src/deformation/pin-ik.ts +13 -9
- package/src/impostor/impostor-node-material.js +31 -15
- package/src/pixel-impostor/pixel-impostor-display.js +18 -7
- package/src/rendering/classic-webgl-support.js +15 -0
- package/src/rendering/renderer-support.js +5 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/deformation/rig-runtime.ts", "../src/deformation/pin-types.ts", "../src/deformation/limits.ts", "../src/deformation/motion-settings.ts", "../src/deformation/ik-constraints.ts", "../src/deformation/pose-slots.ts", "../src/deformation/pose-timeline.ts", "../src/deformation/wind.ts", "../src/deformation/joints-json.ts", "../src/deformation/pin-ik.ts", "../src/deformation/rig-extension.ts", "../src/deformation/pin-wiggle.ts", "../src/deformation/pin-cloth.ts", "../src/deformation/cloth-surface.ts", "../src/deformation/rig-drivers.ts", "../src/deformation/fur-surface.ts", "../src/rendering/texture-slot.js"],
|
|
4
|
-
"sourcesContent": ["import { AnimationMixer, PropertyBinding, Matrix4, Object3D, Quaternion, SkinnedMesh, Vector3, type AnimationClip, type BufferGeometry, type Texture } from 'three';\nimport type { GLTF, GLTFLoader, GLTFParser } from 'three/addons/loaders/GLTFLoader.js';\nimport type { PinRecord, PinPose } from './pin-types.js';\nimport { NEEDLE_DEFORMATION_RIG, parseRigDescriptor, type RigDescriptor } from './rig-extension.js';\nimport { definedPoses, restPoseSlot, resolvePose } from './pose-slots.js';\nimport { solvePlantedPinIKGoals, solveLocalPinIK, ikChain } from './pin-ik.js';\nimport { PinWiggle } from './pin-wiggle.js';\nimport { PinCloth, type ClothCollider } from './pin-cloth.js';\nimport { ClothSurface, clothSurfaceMotion } from './cloth-surface.js';\nimport { driveRig, referencePose, type BoneDriver } from './rig-drivers.js';\nimport { FurSurface } from './fur-surface.js';\n\nconst runtimes = new WeakMap<Object3D, DeformationRigRuntime>();\nconst matrix = (pose: PinPose) => new Matrix4().compose(new Vector3().fromArray(pose.position), new Quaternion().fromArray(pose.rotation), new Vector3().fromArray(pose.scale));\nfunction pose(matrix: Matrix4): PinPose {\n const p = new Vector3(), q = new Quaternion(), s = new Vector3(); matrix.decompose(p, q, s);\n return { position: p.toArray(), rotation: q.normalize().toArray(), scale: s.toArray() };\n}\n\ntype RuntimeClothMesh = { mesh: SkinnedMesh; original: BufferGeometry; positions: Float32Array; surface: ClothSurface; clothIds: string[]; elapsed: number };\n\n/** Lightweight articulated runtime. Skinning stays on the renderer's GPU;\n * only the small joint graph is solved on the CPU, with no voxel dependency. */\nexport class DeformationRigRuntime {\n /** Stable pin IDs mapped to the glTF bone nodes. Edit a bone for FK. */\n readonly bones = new Map<string, Object3D>();\n /** Scene-local goal objects for IK and secondary controls. Move one before `update()`. */\n readonly targets = new Map<string, Object3D>();\n readonly parents = new Map<string, string>();\n readonly masses = new Map<string, number>();\n readonly helpers: { bone: Object3D; influences: { id: string; weight: number }[] }[] = [];\n private helperReferences = new Map<Object3D, PinPose>();\n private referencePins: readonly PinRecord[] = [];\n private localFrames = new Map<Object3D, number[]>();\n private fittedDrivers:BoneDriver[]=[];\n get drivers(): readonly BoneDriver[] { return this.fittedDrivers; }\n private articulated(pins:readonly PinRecord[]) { const helpers=new Set(this.drivers.map(d=>d.id));return pins.filter(p=>!helpers.has(p.id)); }\n private springs = new PinWiggle();\n private cloth = new PinCloth();\n private clothMeshes: RuntimeClothMesh[] = [];\n readonly furSurface: FurSurface | null;\n private mixer: AnimationMixer;\n private base: readonly PinRecord[];\n private displayed: readonly PinRecord[];\n private disposed = false;\n private dirty = true;\n private targetFrames = new Map<string, string>();\n private editedTargets = new Set<string>();\n private mixedPoseWeights = new Map<number, number>();\n private mixingStaticPoses = false;\n private animationFrames = new Map<Object3D, {position:Vector3;rotation:Quaternion;scale:Vector3;displayedPosition:Vector3;displayedRotation:Quaternion;displayedScale:Vector3}>();\n windStrength:number;\n activePose: number;\n constructor(readonly scene: Object3D, readonly descriptor: RigDescriptor, nodes: readonly Object3D[], readonly clips: readonly AnimationClip[], helperNodes: readonly Object3D[] = []) {\n this.base = descriptor.pins; this.displayed = this.base; this.activePose = descriptor.activePose;this.windStrength=descriptor.windStrength??0;\n descriptor.joints.forEach((joint, i) => {\n const pin = descriptor.pins[i]; this.bones.set(pin.id, nodes[i]); this.masses.set(pin.id, joint.mass);\n if (joint.parent !== null) this.parents.set(pin.id, descriptor.pins[descriptor.joints.findIndex(j => j.node === joint.parent)].id);\n if (pin.ik || pin.wiggle || pin.cloth || pin.fur) { const target = new Object3D(); target.name = `${pin.id} target`; target.visible = false; scene.add(target); this.targets.set(pin.id, target); }\n });\n descriptor.helpers?.forEach((h, i) => this.helpers.push({ bone: helperNodes[i], influences: h.influences.map(w => ({ id: descriptor.pins[descriptor.joints.findIndex(j => j.node === w.node)].id, weight: w.weight })) }));\n if(descriptor.version>=3)this.fittedDrivers=this.helpers.map(h=>({id:[...this.bones].find(([,bone])=>bone===h.bone)![0],influences:h.influences}));\n this.furSurface = descriptor.pins.some(pin => pin.fur) ? new FurSurface(scene, descriptor, nodes, helperNodes) : null;\n this.mixer = new AnimationMixer(scene);\n const bones = [...this.bones.values()];\n const animated = clips.some(clip => clip.tracks.some(track => {\n const node = PropertyBinding.findNode(scene, PropertyBinding.parseTrackName(track.name).nodeName);\n return bones.some(bone => bone === node);\n }));\n if (animated) for (const bone of bones) this.animationFrames.set(bone, this.localFrame(bone));\n this.selectPose(this.activePose);\n if (descriptor.pins.some(pin => pin.cloth)) this.prepareClothMeshes();\n }\n /** Supply a Fur height atlas. The loader calls this for embedded atlases. */\n setFurHeightMap(texture: Texture | null) { this.furSurface?.setHeightMap(texture); }\n /** Keep ordinary glTF materials on renderers without the Fur node shader. */\n setPortableMaterials(portable: boolean) { this.furSurface?.setPortable(portable); }\n /** Joint records in the last displayed frame, including secondary motion. */\n get pins() { return this.displayed; }\n /** Return stable pin IDs from the root of the selected chain to its endpoint. */\n chain(id: string) { return ikChain(this.articulated(this.base), this.parents, id, this.masses).map(p => p.id); }\n /** Clear accumulated spring and Cloth motion after a pose or editor reset. */\n resetSecondary() { this.springs.reset(); this.cloth.reset(); for (const entry of this.clothMeshes) { entry.surface.reset(); entry.elapsed = 0; } }\n\n private prepareClothMeshes() {\n this.scene.updateWorldMatrix(true, true);\n const inverse = this.scene.matrixWorld.clone().invert();\n const candidates: { mesh: SkinnedMesh; original: BufferGeometry; positions: Float32Array; rest: Float32Array; indices: ArrayLike<number> }[] = [];\n this.scene.traverse(object => {\n if (!(object instanceof SkinnedMesh)) return;\n const mesh = object, position = mesh.geometry.getAttribute('position');\n if (!position) return;\n const original = mesh.geometry, positions = new Float32Array(position.count * 3), rest = new Float32Array(position.count * 3);\n for (let i = 0; i < position.count; i++) {\n const point = new Vector3().fromBufferAttribute(position, i);\n positions.set(point.toArray(), i * 3);\n rest.set(mesh.applyBoneTransform(i, point).applyMatrix4(mesh.matrixWorld).applyMatrix4(inverse).toArray(), i * 3);\n }\n candidates.push({ mesh, original, positions, rest,\n indices: original.index?.array ?? Uint32Array.from({ length: position.count }, (_, i) => i) });\n });\n const assigned = new Map<SkinnedMesh, PinRecord[]>();\n for (const pin of this.descriptor.pins.filter(record => record.cloth && !record.guide)) {\n const point = new Vector3().fromArray(pin.pose.position);\n let best = Infinity, owner: SkinnedMesh | null = null;\n for (const candidate of candidates) for (let i = 0; i < candidate.rest.length; i += 3) {\n const dx = candidate.rest[i] - point.x, dy = candidate.rest[i + 1] - point.y, dz = candidate.rest[i + 2] - point.z;\n const distance = dx * dx + dy * dy + dz * dz;\n if (distance < best) { best = distance; owner = candidate.mesh; }\n }\n if (owner) assigned.set(owner, [...assigned.get(owner) ?? [], pin]);\n }\n for (const candidate of candidates) {\n const cloth = assigned.get(candidate.mesh); if (!cloth?.length) continue;\n const fitted = new Set(this.drivers.map(driver => driver.id));\n const pins = [...this.descriptor.pins.filter(pin => !pin.cloth && !pin.guide && !fitted.has(pin.id)), ...cloth]\n .map(pin => ({ ...pin, rest: pin.pose.position }));\n candidate.mesh.geometry = candidate.original.clone();\n this.clothMeshes.push({ mesh: candidate.mesh, original: candidate.original, positions: candidate.positions,\n surface: new ClothSurface(candidate.rest, candidate.indices, pins), clothIds: cloth.map(pin => pin.id), elapsed: 0 });\n }\n }\n\n private updateClothMeshes(seconds: number, colliders: readonly ClothCollider[]) {\n if (!this.clothMeshes.length) return;\n this.scene.updateWorldMatrix(true, true);\n const sceneInverse = this.scene.matrixWorld.clone().invert();\n for (const entry of this.clothMeshes) {\n // Bones still render every frame; the coarse fabric solve runs at 30 Hz.\n entry.elapsed += Math.max(0, seconds);\n if (entry.elapsed < 1 / 30) continue;\n const step = Math.min(entry.elapsed, .05); entry.elapsed = 0;\n const { mesh, positions, surface } = entry, target = mesh.geometry.getAttribute('position');\n mesh.skeleton.update();\n const base = new Float32Array(positions.length);\n for (let i = 0; i < positions.length / 3; i++) {\n const point = new Vector3().fromArray(positions, i * 3);\n base.set(mesh.applyBoneTransform(i, point).applyMatrix4(mesh.matrixWorld).applyMatrix4(sceneInverse).toArray(), i * 3);\n }\n const moved = surface.step(base, step, this.windStrength, colliders,\n clothSurfaceMotion(this.base.filter(pin => entry.clothIds.includes(pin.id))));\n const skinIndex = mesh.geometry.getAttribute('skinIndex'), skinWeight = mesh.geometry.getAttribute('skinWeight');\n const meshInverse = mesh.matrixWorld.clone().invert().multiply(this.scene.matrixWorld);\n const bone = new Matrix4(), blended = new Matrix4(), skin = new Matrix4();\n for (let i = 0; i < positions.length / 3; i++) {\n const elements = blended.elements; elements.fill(0);\n for (let j = 0; j < 4; j++) {\n const weight = skinWeight.getComponent(i, j); if (!weight) continue;\n bone.fromArray(mesh.skeleton.boneMatrices!, skinIndex.getComponent(i, j) * 16);\n for (let k = 0; k < 16; k++) elements[k] += bone.elements[k] * weight;\n }\n skin.copy(mesh.bindMatrixInverse).multiply(blended).multiply(mesh.bindMatrix).invert();\n const local = new Vector3().fromArray(moved, i * 3).applyMatrix4(meshInverse).applyMatrix4(skin);\n target.setXYZ(i, local.x, local.y, local.z);\n }\n target.needsUpdate = true; mesh.geometry.computeVertexNormals();\n mesh.geometry.computeBoundingSphere(); mesh.frustumCulled = false;\n }\n }\n /** Select an exported `Pose N` clip and reset its IK goals and secondary motion. */\n selectPose(slot: number) {\n const stored = slot === 0 ? this.descriptor.poseSlots.find(p=>p.slot===0) ?? (this.descriptor.activePose===0 ? restPoseSlot(this.descriptor.pins) : undefined) : definedPoses(this.descriptor).find(p => p.slot === slot);\n if (!stored) throw new Error(`Pose ${slot} is not included in this GLB.`);\n this.mixer.stopAllAction();\n this.mixingStaticPoses = false;\n const clip = this.clips.find(c => c.name === `Pose ${slot}`);\n if (clip) { this.mixer.clipAction(clip).play(); this.mixer.update(0); }\n this.mixedPoseWeights = new Map([[slot, 1]]);\n this.scene.updateWorldMatrix(true, true);\n const inverse = this.scene.matrixWorld.clone().invert();\n this.referencePins = resolvePose(this.descriptor.pins, stored, this.parents);\n this.helperReferences = new Map(this.helpers.map(h => [h.bone, pose(inverse.clone().multiply(h.bone.matrixWorld))]));\n this.activePose = slot; this.resetSecondary(); this.setPins(resolvePose(this.descriptor.pins, stored, this.parents));\n }\n get poseWeights(): ReadonlyMap<number, number> { return this.mixedPoseWeights; }\n /** Change the editable reference pose without interrupting secondary motion. */\n preparePose(slot: number) {\n const stored = slot === 0 ? this.descriptor.poseSlots.find(p=>p.slot===0) ?? (this.descriptor.activePose===0 ? restPoseSlot(this.descriptor.pins) : undefined) : definedPoses(this.descriptor).find(p => p.slot === slot);\n if (!stored) throw new Error(`Pose ${slot} is not included in this GLB.`);\n this.referencePins = resolvePose(this.descriptor.pins, stored, this.parents);\n this.activePose = slot;\n }\n /** Mix the GLB's standard static pose clips, then simulate on that fitted frame. */\n previewPoseWeights(weights: ReadonlyMap<number, number>, seconds: number) {\n if (this.disposed) return;\n this.mixedPoseWeights = new Map(weights);\n const starting = !this.mixingStaticPoses;\n if (starting) {\n this.mixer.stopAllAction();\n for (const clip of this.clips) if (/^Pose \\d+$/.test(clip.name)) this.mixer.clipAction(clip).play();\n this.mixingStaticPoses = true;\n }\n // Secondary motion changed the same bones after the previous mixer tick.\n // PropertyMixer skips an unchanged clip value, so put its last clip-only\n // frame back before evaluating the next one.\n if (!starting) this.apply(this.base, true);\n for (const clip of this.clips) {\n const match = /^Pose (\\d+)$/.exec(clip.name);\n if (match) this.mixer.clipAction(clip).setEffectiveWeight(weights.get(Number(match[1])) ?? 0);\n }\n this.mixer.update(0);\n this.scene.updateWorldMatrix(true, true);\n const inverse = this.scene.matrixWorld.clone().invert();\n const fitted = this.base.map(pin => ({ ...pin, pose: pose(inverse.clone().multiply(this.bones.get(pin.id)!.matrixWorld)) }));\n this.base = fitted; this.dirty = false;\n this.rememberAnimationFrame(); this.advanceSecondary(seconds, fitted); this.rememberDisplayedAnimationFrame();\n }\n /** Adapter for editors: authored state stays in the caller's action history. */\n setPins(pins: readonly PinRecord[]) {\n if (pins.length !== this.bones.size || pins.some(p => !this.bones.has(p.id))) throw new Error('Rig layout changed; rebuild the GLB.');\n if (this.mixingStaticPoses) { this.mixer.stopAllAction(); this.mixingStaticPoses = false; }\n // These poses already passed the author's solve. In particular, an\n // unreachable IK goal must not perturb that solve again on load/replay.\n this.base = pins; this.dirty = false; this.editedTargets.clear(); this.mixedPoseWeights = new Map([[this.activePose, 1]]);\n for (const [id, target] of this.targets) if (!pins.some(p => p.id === id && (p.ik || p.wiggle || p.cloth || p.fur) && !p.guide)) { target.removeFromParent(); this.targets.delete(id); this.targetFrames.delete(id); }\n for (const pin of pins) {\n if (pin.guide || (!pin.ik && !pin.wiggle && !pin.cloth && !pin.fur)) continue;\n let target = this.targets.get(pin.id);\n if (!target) { target = new Object3D(); target.name = `${pin.id} target`; target.visible = false; this.scene.add(target); this.targets.set(pin.id, target); }\n target.position.fromArray(pin.ikTarget?.position ?? pin.pose.position); target.quaternion.fromArray(pin.ikTarget?.rotation ?? pin.pose.rotation);\n this.targetFrames.set(pin.id, JSON.stringify([target.position.toArray(), target.quaternion.toArray()]));\n }\n this.apply(pins); this.rememberAnimationFrame();\n }\n /** Display a caller-supplied fitted frame. Workbench playback uses the clips. */\n previewPins(pins: readonly PinRecord[]) {\n if (pins.length !== this.bones.size || pins.some(p => !this.bones.has(p.id))) throw new Error('Rig layout changed; rebuild the GLB.');\n if (this.mixingStaticPoses) { this.mixer.stopAllAction(); this.mixingStaticPoses = false; }\n this.base = pins; this.dirty = false;\n this.apply(pins, true); this.rememberAnimationFrame();\n }\n private localFrame(bone: Object3D) {\n return {position:bone.position.clone(),rotation:bone.quaternion.clone(),scale:bone.scale.clone(),\n displayedPosition:bone.position.clone(),displayedRotation:bone.quaternion.clone(),displayedScale:bone.scale.clone()};\n }\n private rememberAnimationFrame() {\n for (const bone of this.animationFrames.keys()) this.animationFrames.set(bone,this.localFrame(bone));\n }\n /** PropertyMixer skips unchanged values. Recover their clip-only components\n * rather than feeding last frame's secondary motion back into animation. */\n private animationFrame() {\n if (!this.animationFrames.size) return null;\n for (const [bone,frame] of this.animationFrames) {\n if (!bone.position.equals(frame.displayedPosition)) frame.position.copy(bone.position);\n if (!bone.quaternion.equals(frame.displayedRotation)) frame.rotation.copy(bone.quaternion);\n if (!bone.scale.equals(frame.displayedScale)) frame.scale.copy(bone.scale);\n bone.position.copy(frame.position);bone.quaternion.copy(frame.rotation);bone.scale.copy(frame.scale);\n }\n this.scene.updateWorldMatrix(true,true);\n const inverse=this.scene.matrixWorld.clone().invert();\n return this.base.map(pin=>({...pin,pose:pose(inverse.clone().multiply(this.bones.get(pin.id)!.matrixWorld))}));\n }\n private rememberDisplayedAnimationFrame() {\n for (const [bone,frame] of this.animationFrames) {\n frame.displayedPosition.copy(bone.position);frame.displayedRotation.copy(bone.quaternion);frame.displayedScale.copy(bone.scale);\n }\n }\n private apply(pins: readonly PinRecord[], fitted = false) {\n if(this.descriptor.version>=3 && !fitted)pins=driveRig(pins,this.referencePins,this.drivers);\n this.scene.updateWorldMatrix(true, true);\n const desired = new Map(pins.map(p => [this.bones.get(p.id)!, this.scene.matrixWorld.clone().multiply(matrix(p.pose))]));\n // Use desired parent frames, not last frame's bone state (arbitrary order).\n const pending = new Set(desired.keys());\n const apply = (bone: Object3D) => {\n if (!pending.has(bone)) return;\n if (bone.parent && pending.has(bone.parent)) apply(bone.parent);\n bone.parent?.updateWorldMatrix(true, false);\n const local = (bone.parent?.matrixWorld.clone() ?? new Matrix4()).invert().multiply(desired.get(bone)!);\n local.decompose(bone.position, bone.quaternion, bone.scale); bone.updateMatrix(); bone.updateWorldMatrix(false, true); pending.delete(bone);\n };\n for (const bone of desired.keys()) apply(bone);\n // Corrective bones are NOT rigid children of their strongest control.\n // Blend each control's delta using the original harmonic volume binding.\n // Applying a delta to a fitted reference frame preserves the sampled pose\n // exactly, while avoiding hard parent boundaries during new motion.\n const deltas = new Map(this.referencePins.map(reference => {\n const current = pins.find(p => p.id === reference.id)!.pose;\n return [reference.id, { matrix: matrix(current).multiply(matrix(reference.pose).invert()), rotation: new Quaternion().fromArray(current.rotation).multiply(new Quaternion().fromArray(reference.pose.rotation).invert()), scale: new Vector3().fromArray(current.scale).divide(new Vector3().fromArray(reference.pose.scale)) }];\n }));\n for (const helper of this.descriptor.version>=3?[]:this.helpers) {\n const reference = this.helperReferences.get(helper.bone)!;\n const p = new Vector3(), q = new Quaternion(0, 0, 0, 0), s = new Vector3(), ref = new Vector3().fromArray(reference.position);\n const hemisphere = helper.influences.length ? deltas.get(helper.influences[0].id)!.rotation : new Quaternion();\n for (const influence of helper.influences) {\n const delta = deltas.get(influence.id)!, w = influence.weight;\n p.addScaledVector(ref.clone().applyMatrix4(delta.matrix), w); s.addScaledVector(delta.scale, w);\n const sign = hemisphere.dot(delta.rotation) < 0 ? -w : w;\n q.set(q.x + delta.rotation.x*sign, q.y + delta.rotation.y*sign, q.z + delta.rotation.z*sign, q.w + delta.rotation.w*sign);\n }\n if (!helper.influences.length) { p.copy(ref); q.identity(); s.setScalar(1); }\n q.normalize().multiply(new Quaternion().fromArray(reference.rotation)); s.multiply(new Vector3().fromArray(reference.scale));\n const world = this.scene.matrixWorld.clone().multiply(new Matrix4().compose(p, q, s));\n helper.bone.parent?.updateWorldMatrix(true, false);\n const local = (helper.bone.parent?.matrixWorld.clone() ?? new Matrix4()).invert().multiply(world);\n local.decompose(helper.bone.position, helper.bone.quaternion, helper.bone.scale); helper.bone.updateWorldMatrix(false, true);\n }\n this.displayed = pins;\n for(const bone of this.bones.values()){bone.updateMatrix();this.localFrames.set(bone,[...bone.matrix.elements]);}\n }\n /** Call after an external AnimationMixer/TransformControls, before rendering.\n * Targets are scene-local Object3Ds; moving an independent bone never moves them. */\n update(seconds: number) {\n if (this.disposed) return;\n const fitted=this.animationFrame();\n if(fitted){this.base=fitted;this.displayed=fitted;this.dirty=false;}\n else this.furSurface?.update(seconds, this.windStrength);\n this.scene.updateWorldMatrix(true, true);\n const inverse = this.scene.matrixWorld.clone().invert();\n // Accept external bone edits, but never feed our spring output back as input.\n const edited = fitted ? this.base : this.base.map((pin, i) => {\n const driver=this.drivers.find(d=>d.id===pin.id);\n if(driver){\n const bone=this.bones.get(pin.id)!;bone.updateMatrix();\n if(!bone.matrix.elements.some((v,k)=>Math.abs(v-(this.localFrames.get(bone)?.[k]??v))>1e-6))return pin;\n return {...pin,pose:referencePose(pose(inverse.clone().multiply(bone.matrixWorld)),driver,this.base,this.referencePins)};\n }\n const current = pose(inverse.clone().multiply(this.bones.get(pin.id)!.matrixWorld));\n const previous = this.displayed[i].pose;\n const previousMatrix = matrix(previous);\n const changed = matrix(current).elements.some((v, k) => Math.abs(v - previousMatrix.elements[k]) > 1e-6);\n if (changed) this.dirty = true;\n return changed ? { ...pin, pose: current } : pin;\n });\n const bonesEdited=edited.some((p,i)=>p!==this.base[i]);\n if (bonesEdited) this.base = edited;\n const movedTargets = new Set<string>();\n for (const [id, target] of this.targets) {\n const signature = JSON.stringify([target.position.toArray(), target.quaternion.toArray()]);\n if (this.targetFrames.get(id) !== signature) { movedTargets.add(id); this.dirty = true; this.targetFrames.set(id, signature); }\n }\n for (const id of movedTargets) this.editedTargets.add(id);\n const goalTargets = fitted ? this.editedTargets : movedTargets;\n if (fitted && goalTargets.size) this.dirty = true;\n // A secondary root target is a direct hierarchy transform, not a zero-\n // length IK chain. Carry its descendants before solving other fixed goals.\n for (const root of this.base.filter(p => (p.wiggle || p.cloth || p.fur) && goalTargets.has(p.id) && !this.parents.has(p.id))) {\n const target = this.targets.get(root.id)!;\n const delta = matrix({ ...root.pose, position: target.position.toArray(), rotation: target.quaternion.toArray() }).multiply(matrix(root.pose).invert());\n const affected = new Set([root.id]);\n for (let added = true; added;) { added = false; for (const [child, parent] of this.parents) if (affected.has(parent) && !affected.has(child)) { affected.add(child); added = true; } }\n this.base = this.base.map(p => affected.has(p.id) && !this.drivers.some(d=>d.id===p.id) ? { ...p, pose: pose(delta.clone().multiply(matrix(p.pose))) } : p);\n }\n const goals = this.base.filter(p => (p.ik || ((p.wiggle || p.cloth || p.fur) && goalTargets.has(p.id))) && !p.guide && this.chain(p.id).length > 1).map(p => {\n const target = this.targets.get(p.id)!;\n const goal = { id: p.id, position: target.position.toArray(), rotation: target.quaternion.toArray() };\n if (!fitted && (!p.ikTarget || goal.position.some((v, i) => Math.abs(v - p.ikTarget!.position[i]) > 1e-8) || goal.rotation.some((v, i) => Math.abs(v - p.ikTarget!.rotation[i]) > 1e-8))) this.dirty = true;\n return fitted && !goalTargets.has(p.id) ? {id:p.id,position:[...p.pose.position] as PinPose['position'],rotation:[...p.pose.rotation] as PinPose['rotation']} : goal;\n });\n if (this.dirty) {\n const localGoal=!bonesEdited && goalTargets.size===1 ? goals.find(g=>goalTargets.has(g.id)):undefined;\n const articulated=this.articulated(this.base);\n const solved = new Map((localGoal?solveLocalPinIK(articulated,this.parents,localGoal,this.masses):solvePlantedPinIKGoals(articulated, this.parents, goals, this.masses, new Set(articulated.filter(p => p.independent).map(p => p.id)))).map(p => [p.id, p.pose]));\n this.base = this.base.map(p => ({ ...p, pose: solved.get(p.id) ?? p.pose, ikTarget: p.ik ? goals.find(g => g.id === p.id) ?? p.ikTarget : p.ikTarget }));\n this.dirty = false;\n }\n if(fitted && !goalTargets.size && !fitted.some(pin=>pin.wiggle||pin.cloth||pin.fur)) {\n // Ordinary clips already provide exact local TRS, including scaled\n // parent frames which cannot be reconstructed from world TRS alone.\n this.displayed=this.base;\n for(const bone of this.bones.values()){bone.updateMatrix();this.localFrames.set(bone,[...bone.matrix.elements]);}\n } else this.advanceSecondary(seconds,fitted??undefined);\n this.rememberDisplayedAnimationFrame();\n }\n private advanceSecondary(seconds: number, fitted?: readonly PinRecord[]) {\n if (fitted) this.furSurface?.update(seconds, this.windStrength);\n const secondary=this.springs.step(this.articulated(this.base), this.parents, seconds, this.masses, this.windStrength).pins;\n const byId = new Map(secondary.map(p => [p.id, p]));\n const colliders: ClothCollider[] = (this.descriptor.cloth?.colliders ?? []).map(collider => {\n const driver = byId.get(collider.driver!);\n if (!driver) return collider;\n const rest = { position: driver.rest, rotation: [0, 0, 0, 1] as const, scale: [1, 1, 1] as const };\n const position = new Vector3().fromArray(collider.position).applyMatrix4(matrix(driver.pose).multiply(matrix(rest).invert()));\n return { ...collider, position: position.toArray() };\n });\n const cloth = this.cloth.step(secondary, this.parents, seconds, this.descriptor.cloth?.links ?? [], colliders, this.windStrength).pins;\n const displayed=this.base.map(p=>cloth.find(q=>q.id===p.id)??p);\n this.apply(fitted&&this.descriptor.version>=3?driveRig(displayed,fitted,this.drivers):displayed,Boolean(fitted));\n this.updateClothMeshes(seconds, colliders);\n }\n dispose() {\n this.disposed = true; this.mixer.stopAllAction(); this.mixer.uncacheRoot(this.scene); this.resetSecondary();\n this.furSurface?.dispose();\n for (const entry of this.clothMeshes) { entry.mesh.geometry.dispose(); entry.mesh.geometry = entry.original; }\n this.clothMeshes = [];\n for (const target of this.targets.values()) target.removeFromParent(); this.targets.clear(); runtimes.delete(this.scene);\n }\n}\n\n/** GLTFLoader plugin that validates a rig extension and binds its scene runtime. */\nexport class NeedleDeformationRigLoaderPlugin {\n readonly name = NEEDLE_DEFORMATION_RIG;\n constructor(readonly parser: GLTFParser) {}\n async afterRoot(gltf: GLTF) {\n const json = this.parser.json as { nodes?: unknown[]; textures?: unknown[]; scenes?: { extensions?: Record<string, unknown> }[] };\n for (const [i, scene] of gltf.scenes.entries()) {\n const raw = json.scenes?.[i]?.extensions?.[this.name]; if (!raw) continue;\n const descriptor = parseRigDescriptor(raw, json.nodes?.length ?? 0, json.textures?.length ?? 0);\n const nodes: Object3D[] = await Promise.all(descriptor.joints.map(j => this.parser.getDependency('node', j.node)));\n const helpers: Object3D[] = await Promise.all((descriptor.helpers ?? []).map(h => this.parser.getDependency('node', h.node)));\n for (const node of [...nodes, ...helpers]) { let parent: Object3D | null = node; while (parent && parent !== scene) parent = parent.parent; if (!parent) throw new Error('Rig bone is outside its scene.'); }\n const runtime = new DeformationRigRuntime(scene, descriptor, nodes, gltf.animations, helpers);\n if (descriptor.furSurface) {\n const height = await this.parser.getDependency('texture', descriptor.furSurface.heightTexture);\n height.channel = descriptor.furSurface.texCoord ?? 0;\n runtime.setFurHeightMap(height);\n }\n runtimes.set(scene, runtime);\n }\n }\n}\n/** Register the rig plugin before loading a GLB. Returns the same loader. */\nexport function registerNeedleDeformationRigLoader(loader: GLTFLoader) {\n loader.register(parser => new NeedleDeformationRigLoaderPlugin(parser)); return loader;\n}\n/** Return the runtime attached to a loaded glTF scene, if it has the extension. */\nexport function getDeformationRig(scene: Object3D) { return runtimes.get(scene); }\n", "import type { IKConstraint } from './ik-constraints.js';\nimport type { MotionSettings } from './motion-settings.js';\n\n/** Shared data contract; deliberately independent of editor history and GPU types. */\nexport type Point = readonly [number, number, number];\nexport type Rotation = readonly [number, number, number, number];\nexport type PinPose = { readonly position: Point; readonly rotation: Rotation; readonly scale: Point };\nexport type PinParents = ReadonlyMap<string, string>;\nexport type HierarchyEdge = {from:string;to:string;cost:number;geodesic?:number};\nexport type PinMotion = 'none' | 'ik' | 'wiggle' | 'cloth' | 'fur';\nexport const DEFAULT_FUR_DEPTH = .1;\nexport const MAX_FUR_DEPTH = .5;\nexport type IKTarget = { readonly position: Point; readonly rotation: Rotation };\nexport const IK_CHAIN_KINDS = ['leg','arm','head','tail','wing','fin','tentacle','spine'] as const;\nexport type IKChainRole = { readonly kind: typeof IK_CHAIN_KINDS[number]; readonly side: 'center'|'left'|'right'; readonly position?: 'front'|'hind' };\nexport type PinRecord = { readonly id: string; readonly rest: Point; readonly pose: PinPose; readonly rigidGroup: string | null; readonly independent: boolean;\n /** This pose was set on purpose in the slot now open, rather than reached by\n * being carried by a parent or swept along by an IK solve. A slot still\n * stores an unauthored pose it could not otherwise reproduce \u2014 an IK chain\n * does not come back the same way twice \u2014 but only an authored one is shown\n * as deliberate and only an authored one can be released. */\n readonly authored?: boolean; readonly guide?: boolean; readonly ik?: boolean; readonly wiggle?: boolean; readonly cloth?: boolean; readonly fur?: boolean; readonly furDepth?: number; readonly motion?: MotionSettings; readonly ikTarget?: IKTarget; readonly ikConstraint?: IKConstraint; readonly chainRole?: IKChainRole };\n", "/** Shared document, import, UI and GPU capacity. Pin records are 64 bytes. */\nexport const MAX_DEFORMATION_PINS = 128;\n/** What one sweep of the Suggested pins slider will place. Well short of the\n * document cap: past this the slider stops placing body anchors and starts\n * splitting fine branches, which is hand work rather than a slider's job. */\nexport const MAX_SUGGESTED_PINS = 64;\n\n/** Cells along the longest axis of the solver lattice.\n *\n * The lattice is N by N by N over the model's bounds, and everything the solver\n * measures \u2014 how thick a part is, how far a contact reaches, how much an\n * element is strained \u2014 is in units of those cells. What a grid can represent\n * is what it can resolve: on a posed arm a finger is 2.7 cells across at 32 and\n * 3.5 at 40, which is a rod three nodes thick.\n *\n * The ceiling is a memory bound rather than a speed one. Node buffers are 16\n * bytes each and there are about ten of them, so 64 costs roughly 42 MB of\n * those; the harmonic weights are the one that hurts, at four bytes per node\n * per pin slot, which for a full 128 pins is 268 MB at 64 against 67 MB at 40. */\nexport const MIN_DEFORMATION_RESOLUTION = 16;\nexport const MAX_DEFORMATION_RESOLUTION = 64;\n\n/** Bones the skeleton solver turns on its own: every part of the body no pin\n * drives, cut along the curve skeleton. 132 bytes of GPU state each. */\nexport const MAX_SKELETON_BONES = 2048;\n", "export type MotionSettings = { reach: number; frequency: number; damping: number; massInfluence:number; strength:number };\nexport const DEFAULT_MOTION: Readonly<MotionSettings> = { reach: .5, frequency: 14 / (2*Math.PI), damping: .28, massInfluence:1,strength:1 };\nexport function validateMotionSettings(value: MotionSettings) {\n if (!value || !Number.isFinite(value.reach) || value.reach < 0 || value.reach > 1\n || !Number.isFinite(value.frequency) || value.frequency < .25 || value.frequency > 8\n || !Number.isFinite(value.damping) || value.damping < .05 || value.damping > 1\n || !Number.isFinite(value.massInfluence) || value.massInfluence<0 || value.massInfluence>2\n || !Number.isFinite(value.strength) || value.strength<0 || value.strength>3) throw new Error('Invalid motion settings.');\n}\n", "import { Quaternion, Vector3 } from 'three';\nexport type IKConstraint = { mode:'free'|'cone'|'hinge'|'locked'; axis:'auto'|'x'|'y'|'z'; min:number; max:number; orientation?:[number,number,number,number]; maxY?:number };\nexport const DEFAULT_IK_CONSTRAINT:Readonly<IKConstraint> = {mode:'free',axis:'auto',min:-120,max:120};\nexport function validateIKConstraint(value:IKConstraint) {\n if(value?.maxY!==undefined && (!Number.isFinite(value.maxY)||value.maxY<0||value.maxY>180))throw new Error('Invalid IK cone aperture.');\n if(value?.orientation!==undefined && (!Array.isArray(value.orientation)||value.orientation.length!==4||!value.orientation.every(Number.isFinite)||Math.abs(Math.hypot(...value.orientation)-1)>1e-4))throw new Error('Invalid IK cone orientation.');\n if (!value || !['free','cone','hinge','locked'].includes(value.mode) || !['auto','x','y','z'].includes(value.axis)\n || !Number.isFinite(value.min) || !Number.isFinite(value.max) || value.min < -180 || value.max > 180 || value.min > value.max || (value.mode==='cone' && value.max<0)) throw new Error('Invalid IK joint constraint.');\n}\n/** Stable parent-local cone frame. Z follows the rest bone; X/Y are aperture axes. */\nexport function coneFrame(axis:Vector3,constraint:Readonly<IKConstraint>){\n return new Quaternion().fromArray(constraint.orientation??[0,0,0,1]).multiply(new Quaternion().setFromUnitVectors(new Vector3(0,0,1),axis.clone().normalize()));\n}\n/** Angular ellipse (also valid beyond 90 degrees), rather than a tangent-plane box. */\nexport function coneAngle(constraint:Readonly<IKConstraint>,azimuth:number){\n const x=(constraint.mode==='cone'?constraint.max:90)*Math.PI/180,y=(constraint.mode==='cone'?(constraint.maxY??constraint.max):90)*Math.PI/180;\n const c=Math.cos(azimuth),s=Math.sin(azimuth);\n if((x===0&&Math.abs(c)>1e-8)||(y===0&&Math.abs(s)>1e-8))return 0;\n return 1/Math.sqrt((Math.abs(c)<1e-8?0:c/Math.max(x,1e-12))**2+(Math.abs(s)<1e-8?0:s/Math.max(y,1e-12))**2);\n}\nexport function constrainCone(rotation:Quaternion,axis:Vector3,constraint:Readonly<IKConstraint>,movingAxis:Vector3=axis){\n const frame=coneFrame(axis,constraint),direction=movingAxis.clone().normalize().applyQuaternion(rotation);\n const local=direction.clone().applyQuaternion(frame.clone().invert()),azimuth=Math.atan2(local.y,local.x);\n const angle=Math.atan2(Math.hypot(local.x,local.y),local.z),limit=coneAngle(constraint,azimuth);\n if(angle<=limit+1e-8)return rotation.clone();\n const target=new Vector3(Math.sin(limit)*Math.cos(azimuth),Math.sin(limit)*Math.sin(azimuth),Math.cos(limit)).applyQuaternion(frame);\n return new Quaternion().setFromUnitVectors(direction,target).multiply(rotation).normalize();\n}\n/** Circular swing cone, not an Euler-angle box. Twist remains free. */\nexport function constrainSwing(rotation: Quaternion, axis: Vector3, degrees: number) {\n const direction=axis.clone().normalize(), rotated=direction.clone().applyQuaternion(rotation);\n const angle=direction.angleTo(rotated), limit=degrees*Math.PI/180;\n if(angle<=limit+1e-8)return rotation.clone();\n const normal=new Vector3().crossVectors(direction,rotated);\n if(normal.lengthSq()<1e-12)normal.crossVectors(direction,Math.abs(direction.x)<.8?new Vector3(1,0,0):new Vector3(0,1,0));\n return new Quaternion().setFromAxisAngle(normal.normalize(),limit-angle).multiply(rotation).normalize();\n}\n", "import type { IKTarget, PinPose, PinRecord, Point, Rotation } from './pin-types.js';\nimport type { PinParents } from './pin-types.js';\n\nexport type StoredPose = { readonly id:string; readonly pose:PinPose; readonly ikTarget?:IKTarget; readonly authored?:boolean };\nexport type PoseSlot = { readonly slot:number; readonly poses:readonly StoredPose[] };\nexport const POSE_SLOTS=9;\n/** Below any edit a hand can make, and far above the drift of composing one\n * carried transform after another. */\nconst AUTHORED_EPSILON=1e-6;\n\nexport function capturePose(pins:readonly PinRecord[]):readonly StoredPose[]{\n return pins.map(pin=>({id:pin.id,pose:pin.pose,...(pin.authored?{authored:true}:{}),...(pin.ikTarget?{ikTarget:pin.ikTarget}:{})}));\n}\n\nconst restPoseOf=(rest:Point):PinPose=>({position:[rest[0],rest[1],rest[2]],rotation:[0,0,0,1],scale:[1,1,1]});\n\n/** Where a pin lands when its parent carries it from rest. A parent's pose IS\n * a similarity out of its own rest frame, so the child keeps its rest offset\n * through that same rotation and scale \u2014 the transform hierarchy posing applies\n * when a parent moves, written as one step from rest instead of accumulated. */\nexport function carriedPose(rest:Point,parentRest:Point,parent:PinPose):PinPose{\n const [qx,qy,qz,qw]=parent.rotation;\n const x=(rest[0]-parentRest[0])*parent.scale[0],y=(rest[1]-parentRest[1])*parent.scale[1],z=(rest[2]-parentRest[2])*parent.scale[2];\n const tx=2*(qy*z-qz*y),ty=2*(qz*x-qx*z),tz=2*(qx*y-qy*x);\n const position:Point=[parent.position[0]+x+qw*tx+(qy*tz-qz*ty),parent.position[1]+y+qw*ty+(qz*tx-qx*tz),parent.position[2]+z+qw*tz+(qx*ty-qy*tx)];\n const rotation:Rotation=[qx,qy,qz,qw],scale:Point=[parent.scale[0],parent.scale[1],parent.scale[2]];\n return {position,rotation,scale};\n}\n\nconst samePose=(a:PinPose,b:PinPose)=>\n a.position.every((v,i)=>Math.abs(v-b.position[i])<=AUTHORED_EPSILON)\n && a.scale.every((v,i)=>Math.abs(v-b.scale[i])<=AUTHORED_EPSILON)\n && a.rotation.every((v,i)=>Math.abs(v-b.rotation[i])<=AUTHORED_EPSILON);\n\n/** What a slot would place a pin at if it said nothing about it. */\nfunction inheritedPose(pin:PinRecord,parent:PinRecord|undefined,parentPose:PinPose|undefined):PinPose{\n return parent&&parentPose?carriedPose(pin.rest,parent.rest,parentPose):restPoseOf(pin.rest);\n}\n\n/** Only the poses a slot actually authors. A pin the hierarchy already places\n * is left out, so a point added while another pose was open keeps following its\n * parent everywhere else until it is deliberately posed there. */\nexport function authoredPoses(pins:readonly PinRecord[],parents:PinParents=new Map()):readonly StoredPose[]{\n const byId=new Map(pins.map(pin=>[pin.id,pin]));\n return capturePose(pins).filter(stored=>{\n const pin=byId.get(stored.id)!;\n // Deliberate, or a goal, which is deliberate by definition.\n if(pin.authored||pin.ikTarget)return true;\n // Otherwise it is only kept because it could not be worked out again. A\n // joint the IK solve swept along is not reproducible \u2014 the same goal\n // reached from a different bend gives a different arm \u2014 so the value stays\n // even though nobody posed it.\n const parent=byId.get(parents.get(pin.id)??'');\n return !samePose(pin.pose,inheritedPose(pin,parent,parent?.pose));\n });\n}\n\n/** Active pins are the edit register. Inactive slots contain transforms only;\n * topology, rest positions and settings remain shared and action-owned. A pin\n * the slot does not mention inherits through the hierarchy rather than dropping\n * to rest, which is what keeps a newly placed point attached to its parent in\n * every other pose. */\nexport function resolvePose(pins:readonly PinRecord[],slot:PoseSlot,parents:PinParents=new Map()):readonly PinRecord[]{\n const saved=new Map(slot.poses.map(p=>[p.id,p]));\n const byId=new Map(pins.map(pin=>[pin.id,pin]));\n const memo=new Map<string,PinPose>(),visiting=new Set<string>();\n const poseOf=(pin:PinRecord):PinPose=>{\n const cached=memo.get(pin.id);if(cached)return cached;\n const stored=saved.get(pin.id);\n let pose:PinPose;\n if(stored)pose=stored.pose;\n else{\n const parentId=parents.get(pin.id);\n // A parent already on the stack means a cycle in a derived hierarchy;\n // rest is the only answer that terminates.\n const parent=parentId&&!visiting.has(parentId)?byId.get(parentId):undefined;\n if(!parent)pose=restPoseOf(pin.rest);\n else{visiting.add(pin.id);pose=carriedPose(pin.rest,parent.rest,poseOf(parent));visiting.delete(pin.id);}\n }\n memo.set(pin.id,pose);return pose;\n };\n const resolved:PinRecord[]=pins.map(pin=>{\n const stored=saved.get(pin.id),{ikTarget:_target,authored:_authored,...base}=pin;\n return {...base,pose:poseOf(pin),...(stored?.authored?{authored:true}:{}),...(stored?.ikTarget?{ikTarget:stored.ikTarget}:{})};\n });\n // Group membership is shared. A group created after another pose was saved\n // still has one rotation/uniform scale when that pose is opened. Positions\n // stay authored; subsequent rigid edits preserve that arrangement.\n return resolved.map(pin=>{\n if(!pin.rigidGroup)return pin;const anchor=resolved.find(p=>p.rigidGroup===pin.rigidGroup)!;\n return {...pin,pose:{...pin.pose,rotation:anchor.pose.rotation,scale:[anchor.pose.scale[0],anchor.pose.scale[0],anchor.pose.scale[0]]}};\n });\n}\nexport function definedPoses(model:{readonly pins:readonly PinRecord[];readonly poseSlots:readonly PoseSlot[];readonly activePose:number}):PoseSlot[]{\n const slots=model.poseSlots.filter(p=>p.slot!==model.activePose);\n return [...slots,...(model.activePose === 0 ? [] : [{slot:model.activePose,poses:capturePose(model.pins)}])].sort((a,b)=>a.slot-b.slot);\n}\n\n/** Pose 0 is derived from shared rest positions, never an editable pose slot. */\nexport function restPoseSlot(pins:readonly PinRecord[]):PoseSlot{\n return {slot:0,poses:pins.map(pin=>({id:pin.id,pose:restPoseOf(pin.rest)}))};\n}\n\nexport function playablePoses(model:{readonly pins:readonly PinRecord[];readonly poseSlots:readonly PoseSlot[];readonly activePose:number}):PoseSlot[]{\n return [restPoseSlot(model.pins),...definedPoses(model)];\n}\n", "import type { PinPose, PinRecord, Point, Rotation } from './pin-types.js';\nimport type { PinParents } from './pin-types.js';\n\n/** A pose slot's time controls its share of the loop around its own moment.\n * The transition settles at each authored pose without holding a flat frame. */\nexport const DEFAULT_POSE_SECONDS = 0.7;\nexport const MIN_POSE_SECONDS = 0.05;\nexport const MAX_POSE_SECONDS = 60;\n/** Travel kept below the longest pose so a slider dragged to the bottom can\n * always be dragged further on the next pass, and shrinks back when shortened. */\nexport const POSE_TIME_HEADROOM = 0.5;\n\nexport type PoseTiming = { readonly slot: number; readonly seconds: number };\nexport type PoseTimeline = readonly PoseTiming[];\n\nexport function poseTimeScale(timeline: PoseTimeline): number {\n return Math.max(DEFAULT_POSE_SECONDS, ...timeline.map(entry => entry.seconds)) + POSE_TIME_HEADROOM;\n}\n\n/** The strip reads downwards: zero at the top, the scale at the bottom, which\n * is what makes \"drag down\" mean \"stay longer\". */\nexport function poseSecondsAt(offset: number, height: number, scale: number): number {\n if (!(height > 0)) return MIN_POSE_SECONDS;\n return Math.min(1, Math.max(0, offset / height)) * scale;\n}\n\n/** How far down the strip a time sits, as a percentage for the fill and handle. */\nexport function poseTimeOffset(seconds: number, scale: number): number {\n if (!(scale > 0)) return 0;\n return Math.min(100, Math.max(0, (seconds / scale) * 100));\n}\n\nexport function poseLoopSeconds(timeline: PoseTimeline): number {\n return timeline.reduce((total, entry) => total + Math.max(0, entry.seconds), 0);\n}\n\n/** The moment each pose is reached. Neighbours split the gap between them in\n * proportion to their own times, which is what makes a time an ownership share\n * rather than the length of one arc. */\nexport function poseKnots(timeline: PoseTimeline): number[] {\n const knots = [0];\n for (let i = 1; i < timeline.length; i++) {\n knots.push(knots[i - 1] + (Math.max(0, timeline[i - 1].seconds) + Math.max(0, timeline[i].seconds)) / 2);\n }\n return knots;\n}\n\n/** How long one pass takes: the first pose's moment to the last one's.\n * Looping playback adds the closing transition up to poseLoopSeconds. */\nexport function posePassSeconds(timeline: PoseTimeline): number {\n const knots = poseKnots(timeline);\n return knots.length ? knots[knots.length - 1] : 0;\n}\n\nexport function poseTimeOf(timeline: PoseTimeline, slot: number): number {\n const index = timeline.findIndex(entry => entry.slot === slot);\n return index < 0 ? 0 : poseKnots(timeline)[index];\n}\n\n/** Septic: zero first, second AND third derivative at both ends, so a one-shot\n * move away from rest and back to rest is G3 at the moment it starts and the\n * moment it settles. A cubic smoothstep leaves a jerk step at both. */\nexport function smoothStep(t: number): number {\n const x = Math.min(1, Math.max(0, t));\n return x ** 4 * (35 + x * (-84 + x * (70 - 20 * x)));\n}\n\nexport interface PoseSpline {\n readonly slots: readonly number[];\n readonly loop: number;\n /** How much each pose owns of the frame at this moment; sums to one, and is\n * one on a pose exactly at its own moment. */\n weightsAt(time: number): number[];\n}\n\n/** A periodic C2 interpolant of the authored poses. Its weights are shared by\n * rig playback, GLB clip mixing and trajectory sampling, so the visible path\n * is the path the animation actually follows. */\nexport function preparePoseSpline(timeline: PoseTimeline): PoseSpline {\n const n = timeline.length, slots = timeline.map(entry => entry.slot);\n const loop = poseLoopSeconds(timeline), knots = poseKnots(timeline);\n if (n < 2 || !(loop > 0)) {\n const fixed = timeline.map((_, i) => (i === 0 ? 1 : 0));\n return { slots, loop: Math.max(loop, 0), weightsAt: () => [...fixed] };\n }\n return { slots, loop, weightsAt: time => splineWeights(knots,loop,n,time) };\n}\n\nfunction splineWeights(knots: readonly number[], loop: number, n: number, time: number): number[] {\n const cursor = ((time % loop) + loop) % loop, weights = new Array<number>(n).fill(0);\n let k = n - 1; while (k > 0 && cursor < knots[k]) k--;\n const start = knots[k], end = k + 1 < n ? knots[k + 1] : loop;\n const h=end-start,t=h>0?(cursor-start)/h:0,next=(k+1)%n;\n if(n<3||!(h>0)){weights[k]=1-smoothStep(t);weights[next]+=smoothStep(t);return weights;}\n const coordinate=(i:number)=>i<0?knots[i+n]-loop:i>=n?knots[i-n]+loop:knots[i];\n const unit=(i:number)=>{const result=new Array<number>(n).fill(0);result[(i+n)%n]=1;return result;};\n const subtract=(a:readonly number[],b:readonly number[],scale:number)=>a.map((v,j)=>(v-b[j])/scale);\n const derivatives=(i:number)=>{\n const before=coordinate(i)-coordinate(i-1),after=coordinate(i+1)-coordinate(i);\n const previous=subtract(unit(i),unit(i-1),Math.max(before,1e-8));\n const following=subtract(unit(i+1),unit(i),Math.max(after,1e-8));\n // Full centered tangents round a three-pose corner visibly. Reducing them\n // to a quarter left a mathematically C2 but visibly triangular path.\n return {velocity:previous.map((v,j)=>(v*after+following[j]*before)/(before+after)),\n acceleration:previous.map((v,j)=>2*(following[j]-v)/(before+after))};\n };\n const a=derivatives(k),b=derivatives(k+1),p=unit(k),q=unit(k+1);\n for(let j=0;j<n;j++){\n const v0=h*a.velocity[j],v1=h*b.velocity[j],a0=h*h*a.acceleration[j],a1=h*h*b.acceleration[j];\n const d=q[j]-p[j]-v0-a0/2,v=v1-v0-a0,acc=a1-a0;\n weights[j]=p[j]+t*(v0+t*(a0/2+t*((10*d-4*v+acc/2)+t*((-15*d+7*v-acc)+t*(6*d-3*v+acc/2)))));\n }\n return weights;\n}\n\nconst conjugate = (q: Rotation): Rotation => [-q[0], -q[1], -q[2], q[3]];\nconst multiply = (a: Rotation, b: Rotation): Rotation => [\n a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],\n a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],\n a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],\n a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2],\n];\nfunction rotate(q: Rotation, v: Point): Point {\n const tx = 2 * (q[1] * v[2] - q[2] * v[1]), ty = 2 * (q[2] * v[0] - q[0] * v[2]), tz = 2 * (q[0] * v[1] - q[1] * v[0]);\n return [v[0] + q[3] * tx + (q[1] * tz - q[2] * ty), v[1] + q[3] * ty + (q[2] * tx - q[0] * tz), v[2] + q[3] * tz + (q[0] * ty - q[1] * tx)];\n}\nconst safeScale = (v: number) => (Math.abs(v) > 1e-8 ? v : 1e-8);\n\n/** A pose in its parent's frame. */\nfunction localPose(pose: PinPose, parent: PinPose | undefined): PinPose {\n if (!parent) return pose;\n const inverse = conjugate(parent.rotation);\n const offset = rotate(inverse, [pose.position[0] - parent.position[0], pose.position[1] - parent.position[1], pose.position[2] - parent.position[2]]);\n return {\n position: [offset[0] / safeScale(parent.scale[0]), offset[1] / safeScale(parent.scale[1]), offset[2] / safeScale(parent.scale[2])],\n rotation: multiply(inverse, pose.rotation),\n scale: [pose.scale[0] / safeScale(parent.scale[0]), pose.scale[1] / safeScale(parent.scale[1]), pose.scale[2] / safeScale(parent.scale[2])],\n };\n}\n\n/** The inverse of localPose: a local transform read back out into the world. */\nfunction worldPose(local: PinPose, parent: PinPose | undefined): PinPose {\n if (!parent) return local;\n const scaled: Point = [local.position[0] * parent.scale[0], local.position[1] * parent.scale[1], local.position[2] * parent.scale[2]];\n const offset = rotate(parent.rotation, scaled);\n return {\n position: [parent.position[0] + offset[0], parent.position[1] + offset[1], parent.position[2] + offset[2]],\n rotation: multiply(parent.rotation, local.rotation),\n scale: [local.scale[0] * parent.scale[0], local.scale[1] * parent.scale[1], local.scale[2] * parent.scale[2]],\n };\n}\n\n/** Parents before children, with any cycle in a derived hierarchy broken by\n * treating the pin that closes it as a root. */\nfunction hierarchyOrder(pins: readonly PinRecord[], parents: PinParents): { order: number[]; parentOf: (number | undefined)[] } {\n const index = new Map(pins.map((pin, i) => [pin.id, i]));\n const parentOf = pins.map(pin => { const p = index.get(parents.get(pin.id) ?? ''); return p === index.get(pin.id) ? undefined : p; });\n const order: number[] = [], state = new Uint8Array(pins.length);\n const visit = (i: number) => {\n if (state[i]) { if (state[i] === 1) parentOf[i] = undefined; return; }\n state[i] = 1;\n const parent = parentOf[i];\n if (parent !== undefined) visit(parent);\n state[i] = 2; order.push(i);\n };\n for (let i = 0; i < pins.length; i++) visit(i);\n return { order, parentOf };\n}\n\n\n/** The active pair shares one hemisphere, including the last-to-first seam. */\nexport function blendRotations(rotations: readonly Rotation[], weights: readonly number[]): Rotation {\n let [x, y, z, w] = [0, 0, 0, 0];\n const reference=rotations[weights.findIndex(weight=>weight>1e-12)]??rotations[0];\n let dominant = reference, best = -Infinity;\n for (let i = 0; i < rotations.length; i++) {\n const q = rotations[i];\n if(weights[i]===0)continue;\n const aligned: Rotation = q[0] * reference[0] + q[1] * reference[1] + q[2] * reference[2] + q[3] * reference[3] < 0\n ? [-q[0], -q[1], -q[2], -q[3]] : q;\n if (weights[i] > best) { best = weights[i]; dominant = aligned; }\n x += aligned[0] * weights[i]; y += aligned[1] * weights[i];\n z += aligned[2] * weights[i]; w += aligned[3] * weights[i];\n }\n const length = Math.hypot(x, y, z, w);\n // Opposed rotations at equal weight cancel and name no orientation at all.\n return length > 1e-6 ? [x / length, y / length, z / length, w / length] : dominant;\n}\n\n/** Blends by id, so a pin missing from either side simply keeps its own pose \u2014\n * it appears on both sides of the blend and cannot move. Everything but the\n * transform comes from the destination: ids, rest positions and flags are\n * shared between slots and are not animated. */\nexport function blendPins(from: readonly PinRecord[], to: readonly PinRecord[], t: number, parents: PinParents = new Map()): readonly PinRecord[] {\n if (t <= 0 && from.length === to.length && to.every((pin, i) => from[i]?.id === pin.id)) return from;\n const aligned = to.map(pin => from.find(other => other.id === pin.id) ?? pin);\n return blendPoses(to, [aligned, to], [1 - t, t], parents);\n}\n\n/** Every pose at once, by weight. `poses` are the same pins in the same order\n * as `base` \u2014 they all come from resolving one document \u2014 so this walks them by\n * index rather than searching per pin per frame.\n *\n * The blend happens in each pin's PARENT frame, never in world space. A chain\n * posed two ways differs mostly in its joints' rotations, and averaging world\n * positions cuts the chord between them: the limb shortens in the middle of\n * every transition and lengthens again at each pose. In the parent's frame only\n * the joint's own rotation and offset move, so the chain keeps its shape, and a\n * pin's transform stays relative to whatever IK did to its parent \u2014 which is\n * what makes moving an IK target interpolate as one arc rather than dragging\n * every pin along a straight line of its own. */\nexport function blendPoses(base: readonly PinRecord[], poses: readonly (readonly PinRecord[])[], weights: readonly number[], parents: PinParents = new Map()): readonly PinRecord[] {\n if (!poses.length || poses.some(pose => pose.length !== base.length)) return base;\n const { order, parentOf } = hierarchyOrder(base, parents);\n const world = new Array<PinPose>(base.length), blended = new Array<PinRecord>(base.length);\n for (const i of order) {\n const parent = parentOf[i], parentWorld = parent === undefined ? undefined : world[parent];\n const locals = poses.map((pose, k) => localPose(pose[i].pose, parent === undefined ? undefined : poses[k][parent].pose));\n world[i] = worldPose(weightedPose(locals, weights), parentWorld);\n const pin: PinRecord = { ...base[i], pose: world[i] };\n // A goal is an anchor in the world, not a point on its parent. A planted\n // foot has the same goal in every pose, and must come out of the blend as\n // that goal exactly however the body above it moves.\n if (!poses.every(pose => pose[i].ikTarget)) { blended[i] = pin; continue; }\n const targets = poses.map(pose => pose[i].ikTarget!);\n blended[i] = { ...pin, ikTarget: {\n position: [0, 1, 2].map(axis => targets.reduce((sum, target, k) => sum + target.position[axis] * weights[k], 0)) as unknown as Point,\n rotation: blendRotations(targets.map(target => target.rotation), weights),\n } };\n }\n return blended;\n}\n\n/** One pose out of many, by weight. */\nfunction weightedPose(poses: readonly PinPose[], weights: readonly number[]): PinPose {\n const position: [number, number, number] = [0, 0, 0], scale: [number, number, number] = [0, 0, 0];\n for (let k = 0; k < poses.length; k++) for (let axis = 0; axis < 3; axis++) {\n position[axis] += poses[k].position[axis] * weights[k];\n scale[axis] += poses[k].scale[axis] * weights[k];\n }\n return { position, rotation: blendRotations(poses.map(pose => pose.rotation), weights), scale };\n}\n", "import { Vector3 } from 'three';\n\nexport const MAX_WIND_STRENGTH = 4;\n\n/** A single weather control drives pin motion and surface pressure. Sparse pin\n * loads stay bounded; fabric pressure has room to grow through a storm. */\nexport function windProfile(strength: number) {\n const level = Math.max(0, Math.min(MAX_WIND_STRENGTH, strength));\n const label = level === 0 ? 'Off' : level < .75 ? 'Breeze' : level < 1.5 ? 'Windy' : level < 2.5 ? 'Strong wind' : level < 3.3 ? 'Gale' : 'Storm';\n return {\n label,\n load: 30 * level * level / (.8 + level * level),\n surfaceLoad: 4 * level * level,\n gust: .14 + .12 * level,\n crosswind: .05 + .07 * level,\n gustRate: .42 + .12 * level,\n };\n}\n\n/** Deterministic scene-local prevailing wind with slow gusts and spatially\n * varying eddies. Force is an acceleration scaled to the model's size, so a\n * tiny prop and a large character respond comparably at the same setting. */\nexport function windAcceleration(seconds: number, strength: number, scale: number, position: readonly number[]) {\n if (strength <= 0) return new Vector3();\n const size = Math.max(1e-4, scale);\n const profile = windProfile(strength);\n // Advect the gust bands along +X. Nearby controls see related wind, while\n // their phase delay keeps a large sheet or branch hierarchy from moving as\n // one perfectly synchronized rigid object.\n const along = position[0] / size, lateral = (position[1] * .67 + position[2] * .33) / size;\n const slow = seconds * profile.gustRate - along * .55;\n const fast = seconds * (profile.gustRate * 2.7) - along * 1.4 + lateral * .4;\n const gust = Math.max(.2, 1 + profile.gust * (.7 * Math.sin(slow) + .3 * Math.sin(fast + 1.3)));\n const cross = profile.crosswind * (.65 * Math.sin(fast + lateral) + .35 * Math.sin(slow * .73 - lateral * .6));\n return new Vector3(1, cross * .35, cross).normalize().multiplyScalar(profile.load * size * gust);\n}\n", "import { IK_CHAIN_KINDS, MAX_FUR_DEPTH, type IKChainRole, type PinRecord, type Point, type Rotation } from './pin-types.js';\nimport { MAX_DEFORMATION_PINS } from './limits.js';\nimport { DEFAULT_MOTION, validateMotionSettings } from './motion-settings.js';\nimport { validateIKConstraint, type IKConstraint } from './ik-constraints.js';\nimport { capturePose, POSE_SLOTS, resolvePose, type PoseSlot } from './pose-slots.js';\nimport type { PinParents } from './pin-types.js';\nimport { MAX_POSE_SECONDS, MIN_POSE_SECONDS, type PoseTiming } from './pose-timeline.js';\nimport { MAX_WIND_STRENGTH } from './wind.js';\n\nfunction record(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid joints JSON object.');\n return value as Record<string, unknown>;\n}\nfunction numbers(value: unknown, length: number): number[] {\n if (!Array.isArray(value) || value.length !== length || !value.every(v => typeof v === 'number' && Number.isFinite(v))) throw new Error('Invalid joint coordinates.');\n return [...value];\n}\nfunction point(value: unknown): Point { const v = numbers(value, 3); return [v[0], v[1], v[2]]; }\nfunction quaternion(value: unknown): Rotation { const v = numbers(value, 4); return [v[0], v[1], v[2], v[3]]; }\nexport function validateJoints(value: unknown, maximum = MAX_DEFORMATION_PINS): readonly PinRecord[] {\n if (!Array.isArray(value) || value.length > maximum) throw new Error(`Joints JSON must contain at most ${maximum} joints.`);\n const ids = new Set<string>();\n const pins = value.map(item => {\n const pin = record(item), pose = record(pin.pose);\n if (typeof pin.id !== 'string' || !pin.id || ids.has(pin.id)) throw new Error('Joint IDs must be unique non-empty strings.');\n ids.add(pin.id);\n if (typeof pin.independent !== 'boolean' || (pin.rigidGroup !== null && (typeof pin.rigidGroup !== 'string' || !pin.rigidGroup))) throw new Error('Invalid joint membership.');\n if (pin.guide !== undefined && typeof pin.guide !== 'boolean') throw new Error('Invalid guide flag.');\n if (pin.authored !== undefined && typeof pin.authored !== 'boolean') throw new Error('Invalid authored flag.');\n if (pin.ik !== undefined && typeof pin.ik !== 'boolean') throw new Error('Invalid IK flag.');\n if (pin.wiggle !== undefined && typeof pin.wiggle !== 'boolean') throw new Error('Invalid Wiggle flag.');\n if (pin.cloth !== undefined && typeof pin.cloth !== 'boolean') throw new Error('Invalid Cloth flag.');\n if (pin.fur !== undefined && typeof pin.fur !== 'boolean') throw new Error('Invalid Fur flag.');\n if (pin.furDepth !== undefined && (typeof pin.furDepth !== 'number' || !Number.isFinite(pin.furDepth) || pin.furDepth < 0 || pin.furDepth > MAX_FUR_DEPTH)) throw new Error('Invalid Fur depth.');\n const chainRole=pin.chainRole===undefined?undefined:(()=>{\n const value=record(pin.chainRole);\n if(!IK_CHAIN_KINDS.includes(value.kind as IKChainRole['kind'])||!['center','left','right'].includes(value.side as string)||\n (value.position!==undefined&&!['front','hind'].includes(value.position as string)))throw new Error('Invalid IK chain role.');\n return {kind:value.kind as IKChainRole['kind'],side:value.side as IKChainRole['side'],...(value.position?{position:value.position as 'front'|'hind'}:{})};\n })();\n if (Number(Boolean(pin.ik)) + Number(Boolean(pin.wiggle)) + Number(Boolean(pin.cloth)) + Number(Boolean(pin.fur)) > 1) throw new Error('Choose IK, Wiggle, Cloth or Fur.');\n const motion = pin.motion === undefined ? undefined : (()=>{\n const raw=record(pin.motion), result={reach:Number(raw.reach),frequency:Number(raw.frequency),damping:Number(raw.damping),massInfluence:raw.massInfluence===undefined?DEFAULT_MOTION.massInfluence:Number(raw.massInfluence),strength:raw.strength===undefined?DEFAULT_MOTION.strength:Number(raw.strength)};\n for(const key of ['massInfluence','strength']) if(raw[key]!==undefined && typeof raw[key]!=='number') throw new Error('Invalid motion settings.');\n if (typeof raw.reach!=='number' || typeof raw.frequency!=='number' || typeof raw.damping!=='number') throw new Error('Invalid motion settings.');\n validateMotionSettings(result); return result;\n })();\n const ikConstraint=pin.ikConstraint===undefined?undefined:(()=>{const raw=record(pin.ikConstraint);const value={mode:raw.mode,axis:raw.axis,min:raw.min,max:raw.max,...(raw.orientation!==undefined?{orientation:quaternion(raw.orientation)}:{}),...(raw.maxY!==undefined?{maxY:raw.maxY}:{})} as IKConstraint;validateIKConstraint(value);return value;})();\n const ikTarget=pin.ikTarget === undefined ? undefined : (()=>{\n const raw=record(pin.ikTarget),rotation=quaternion(raw.rotation);\n if (Math.abs(Math.hypot(...rotation)-1)>1e-4) throw new Error('Invalid IK target rotation.');\n return {position:point(raw.position),rotation};\n })();\n if (pin.guide && (pin.rigidGroup || pin.independent)) throw new Error('Guides cannot be rigid members or roots.');\n const scale = point(pose.scale), rotation = quaternion(pose.rotation);\n if (scale.some(v => v < 0.01 || v > 100) || Math.abs(Math.hypot(...rotation) - 1) > 1e-4) throw new Error('Invalid joint rotation or scale.');\n return { id: pin.id, independent: pin.independent, rigidGroup: pin.rigidGroup, ...(pin.authored === true ? { authored: true } : {}), ...(typeof pin.guide === 'boolean' ? { guide: pin.guide } : {}), ...(typeof pin.ik === 'boolean' ? { ik: pin.ik } : {}),\n ...(ikConstraint?{ikConstraint}:{}),...(chainRole?{chainRole}:{}),...(motion ? {motion}:{}),...(ikTarget ? {ikTarget}:{}),...(typeof pin.wiggle === 'boolean' ? {wiggle:pin.wiggle} : {}),...(typeof pin.cloth === 'boolean' ? {cloth:pin.cloth} : {}),...(typeof pin.fur === 'boolean' ? {fur:pin.fur} : {}),...(pin.furDepth !== undefined ? {furDepth:pin.furDepth as number} : {}), rest: point(pin.rest), pose: { position: point(pose.position), rotation, scale } };\n });\n for (const pin of pins) if (pin.rigidGroup) {\n const anchor = pins.find(other => other.rigidGroup === pin.rigidGroup)!;\n const dot = pin.pose.rotation.reduce((sum, v, i) => sum + v * anchor.pose.rotation[i], 0);\n if (pin.pose.scale.some(v => Math.abs(v - anchor.pose.scale[0]) > 1e-5) || 1 - Math.abs(dot) > 1e-5) throw new Error('Rigid joints must share rotation and uniform scale.');\n }\n return pins;\n}\nexport interface JointsRig { pins:readonly PinRecord[];activePose:number;poseSlots:readonly PoseSlot[];poseTimes:readonly PoseTiming[];windStrength?:number }\nfunction validatePoseTimes(value:unknown):readonly PoseTiming[]{\n if(!Array.isArray(value)||value.length>POSE_SLOTS)throw new Error('Invalid pose times.');\n const slots=new Set<number>();\n return value.map(item=>{\n const entry=record(item);\n if(!Number.isInteger(entry.slot)||(entry.slot as number)<0||(entry.slot as number)>POSE_SLOTS||slots.has(entry.slot as number))throw new Error('Invalid pose time slot.');\n slots.add(entry.slot as number);\n if(typeof entry.seconds!=='number'||!Number.isFinite(entry.seconds)||entry.seconds<MIN_POSE_SECONDS||entry.seconds>MAX_POSE_SECONDS)throw new Error('Invalid pose time.');\n return {slot:entry.slot as number,seconds:entry.seconds};\n }).sort((a,b)=>a.slot-b.slot);\n}\n/** Slots are written out in full. A pin the hierarchy places is left unsaid in\n * the editor so it keeps following its parent, but a file has no voxel field to\n * rebuild that hierarchy from and older readers would drop it to rest, so the\n * inherited pose is resolved here and stored. */\nexport function validateRig(value:JointsRig, maximum = MAX_DEFORMATION_PINS, parents:PinParents = new Map()):JointsRig{\n const pins=validateJoints(value.pins,maximum);\n if (value.windStrength !== undefined && (!Number.isFinite(value.windStrength) || value.windStrength < 0 || value.windStrength > MAX_WIND_STRENGTH)) throw new Error('Invalid wind strength.');\n if(!Number.isInteger(value.activePose)||value.activePose<0||value.activePose>POSE_SLOTS||!Array.isArray(value.poseSlots)||value.poseSlots.length>POSE_SLOTS)throw new Error('Invalid pose slots.');\n const slots=new Set<number>(),ids=new Set(pins.map(p=>p.id));\n const poseSlots=value.poseSlots.map(slot=>{\n if(!slot||!Number.isInteger(slot.slot)||slot.slot<1||slot.slot>POSE_SLOTS||slots.has(slot.slot)||!Array.isArray(slot.poses))throw new Error('Invalid pose slot.');slots.add(slot.slot);\n const pinIds=new Set<string>();for(const p of slot.poses){if(!p||!ids.has(p.id)||pinIds.has(p.id))throw new Error('Invalid pose pin.');pinIds.add(p.id);}\n return {slot:slot.slot,poses:capturePose(validateJoints(resolvePose(pins,slot,parents),maximum))};\n }).filter(slot=>slot.slot!==value.activePose);\n return {pins,activePose:value.activePose,poseSlots,poseTimes:validatePoseTimes(value.poseTimes??[]),...(value.windStrength !== undefined ? {windStrength:value.windStrength} : {})};\n}\n", "import { Goal, Joint, Link, Solver } from 'closed-chain-ik/core';\nimport { Euler, Matrix4, Quaternion, Vector3 } from 'three';\nimport type { PinRecord, PinPose, Point, Rotation } from './pin-types.js';\nimport { DEFAULT_MOTION } from './motion-settings.js';\nimport type { PinParents } from './pin-types.js';\nimport { DEFAULT_IK_CONSTRAINT, constrainCone } from './ik-constraints.js';\n\nconst POSE_CONTINUITY_WEIGHT=1e-4;\n\n/** A routing guide is not a limb. Only guides leading to real joints create\n * an articulated branch; dangling guidance must not lock an IK pivot. */\nfunction articulatedNodes(pins: readonly PinRecord[], parents: PinParents) {\n const nodes = new Set<string>();\n for (const pin of pins) if (!pin.guide) {\n let id: string | undefined = pin.id;\n while (id && !nodes.has(id)) { nodes.add(id); id = parents.get(id); }\n }\n return nodes;\n}\n\n/** IDs are derived each time; no stale authored chain survives topology edits. */\nexport function ikChain(pins: readonly PinRecord[], parents: PinParents, id: string, mass: ReadonlyMap<string, number> = new Map()): PinRecord[] {\n const byId = new Map(pins.map(pin => [pin.id, pin]));\n const element = (pin: PinRecord) => pin.rigidGroup ?? pin.id;\n const articulated = articulatedNodes(pins, parents);\n const children = new Map<string, Set<string>>();\n const supportLength=new Map<string,number>();\n for (const pin of pins) {\n if (!articulated.has(pin.id)) continue;\n const parent = byId.get(parents.get(pin.id) ?? '');\n if (!parent) continue;\n const length=Math.hypot(...pin.rest.map((x,i)=>x-parent.rest[i]))*.5;\n supportLength.set(pin.id,(supportLength.get(pin.id)??0)+length);\n supportLength.set(parent.id,(supportLength.get(parent.id)??0)+length);\n const set = children.get(element(parent)) ?? new Set<string>(); set.add(element(pin)); children.set(element(parent), set);\n }\n const chain: PinRecord[] = [], seen = new Set<string>();\n let pin = byId.get(id);\n const reach = pin?.motion?.reach ?? DEFAULT_MOTION.reach;\n let automatic:string|undefined;\n // Mass per supported rest length approximates cross-section, unlike raw\n // per-pin mass which shrinks simply because a limb gained more joints.\n const density=(p:PinRecord)=>mass.has(p.id)?mass.get(p.id)!/Math.max(supportLength.get(p.id)??0,1e-12):undefined;\n while (pin && !seen.has(element(pin))) {\n chain.unshift(pin); seen.add(element(pin));\n if (pin.independent) break;\n const parent = byId.get(parents.get(pin.id) ?? '');\n if (!parent) break;\n // Keep the body/other limbs stationary. An immediate parent is still\n // needed as the pivot for a single-link chain.\n if (!automatic && ((children.get(element(parent))?.size ?? 0) > 1\n || (!pin.guide && !parent.guide && (density(parent) ?? 0) > 8 * Math.max(density(pin) ?? Infinity, 1e-12)))) automatic=parent.id;\n pin = parent;\n }\n if(chain.length<2)return chain;\n const distance=new Float64Array(chain.length);\n for(let i=chain.length-2;i>=0;i--)distance[i]=distance[i+1]+Math.hypot(...chain[i].rest.map((x,k)=>x-chain[i+1].rest[k]));\n const boundary=automatic?chain.findIndex(p=>p.id===automatic):-1;\n const automaticDistance=distance[Math.max(0,boundary)];\n // Reach measures REST arc length, not node count or posed/chord distance.\n // Zero starts at the endpoint (clamped to one link); subdivision must not\n // move the slider's origin by changing that first link's length.\n const budget=reach<=.5?automaticDistance*reach*2:automaticDistance+(distance[0]-automaticDistance)*(reach-.5)*2;\n const first=reach<=.5&&boundary>=0?Math.min(boundary+1,chain.length-2):0;\n let start=chain.length-2;\n for(let i=start-1;i>=first;i--)if(Math.abs(distance[i]-budget)<Math.abs(distance[start]-budget))start=i;\n if(reach===1)start=0;\n return chain.slice(start);\n}\n\nexport function solvePinIK(pins: readonly PinRecord[], parents: PinParents, id: string, target: Point,\n mass?: ReadonlyMap<string, number>, targetRotation?: Rotation): { id: string; pose: PinPose }[] {\n const pin=pins.find(p=>p.id===id)!;\n return solvePinIKGoals(pins,parents,[{id,position:target,rotation:targetRotation ?? pin.ikTarget?.rotation ?? pin.pose.rotation}],mass);\n}\n\nexport type IKGoal = {id:string;position:Point;rotation:Rotation};\n\n/** Endpoint editing is local. Shared body frames and sibling branches retain\n * their authored poses; root/body edits use the separate multi-goal solve. */\nexport function solveLocalPinIK(pins:readonly PinRecord[],parents:PinParents,goal:IKGoal,mass?:ReadonlyMap<string,number>,floor=-Infinity){\n const chain=ikChain(pins,parents,goal.id,mass),key=(p:PinRecord)=>p.rigidGroup??p.id;\n const keys=new Set(chain.map(key)),byId=new Map(pins.map(p=>[p.id,p]));\n const articulated = articulatedNodes(pins, parents);\n let boundary=-1;\n // Children below the endpoint are followers, never competing side branches.\n for(let i=0;i<chain.length-1;i++)if(chain[i].independent || pins.some(p=>{\n if (!articulated.has(p.id)) return false;\n const parent=byId.get(parents.get(p.id)??'');return parent&&key(parent)===key(chain[i])&&!keys.has(key(p));\n }))boundary=i;\n const shared=boundary>=0&&pins.some(p=>{\n if(!articulated.has(p.id))return false;\n const parent=byId.get(parents.get(p.id)??'');\n return parent&&key(parent)===key(chain[boundary])&&!keys.has(key(p));\n });\n // A shared attachment fixes the body. The outgoing limb gets a separate\n // zero-length branch pivot in the solver, so the first link can still swing.\n // A lone independent root has no sibling to disturb and retains the exact\n // two-link analytic solve through its temporary root rotation.\n const fixed=new Set(chain.slice(0,shared?boundary+1:Math.max(0,boundary)).flatMap(p=>pins.filter(q=>key(q)===key(p)).map(q=>q.id)));\n const moving=new Set(chain.slice(boundary+1).map(key));\n for(let added=true;added;){added=false;for(const p of pins){const parent=byId.get(parents.get(p.id)??'');if(parent&&moving.has(key(parent))&&!moving.has(key(p))){moving.add(key(p));added=true;}}}\n const retained=new Set(boundary>=0?[key(chain[boundary])]:[]);\n return solvePinIKGoals(pins,parents,[goal],mass,fixed,retained,floor).filter(p=>moving.has(key(byId.get(p.id)!)));\n}\n\n/** Solve separate planted limbs against the same body pose. Their temporary\n * attachment rotations must not become rotations of the shared torso frame. */\nexport function solvePlantedPinIKGoals(pins:readonly PinRecord[],parents:PinParents,goals:readonly IKGoal[],mass?:ReadonlyMap<string,number>,fixed:ReadonlySet<string>=new Set(),floor=-Infinity){\n if(!goals.length)return [];\n const edits=new Map<string,{id:string;pose:PinPose}>();\n let independent=true;\n for(const goal of goals){\n const limb=solveLocalPinIK(pins,parents,goal,mass,floor);\n for(const edit of limb){\n if(fixed.has(edit.id)||edits.has(edit.id)){independent=false;break;}\n edits.set(edit.id,edit);\n }\n if(!independent)break;\n }\n return independent?[...edits.values()]:solvePinIKGoals(pins,parents,goals,mass,fixed,new Set(),floor);\n}\n\n/** Body motion and imported-pose reconstruction use the same full-chain solve.\n * Shared attachment frames are held; each limb gets its own branch pivot. */\nexport function solveBodyIKGoals(pins:readonly PinRecord[],parents:PinParents,goals:readonly IKGoal[],mass:ReadonlyMap<string,number>,fixed:ReadonlySet<string>,floor=-Infinity){\n const poleChains=new Map(goals.map(goal=>[goal.id,ikChain(pins,parents,goal.id,mass)]));\n const full=pins.map(pin=>pin.ik?{...pin,motion:{...DEFAULT_MOTION,...pin.motion,reach:1}}:pin);\n const uses=new Map<string,number>();\n for(const goal of goals)for(const pin of ikChain(full,parents,goal.id,mass))uses.set(pin.id,(uses.get(pin.id)??0)+1);\n const anchors=new Set([...fixed,...[...uses].filter(([,count])=>count>1).map(([id])=>id)]);\n return solvePinIKGoals(full,parents,goals,mass,anchors,new Set(),floor,poleChains);\n}\n\n/** One articulated forest, one joint solve. Shared joints are never overwritten\n * by a later endpoint, and every child offset retains its authored length. */\nexport function solvePinIKGoals(pins:readonly PinRecord[],parents:PinParents,goals:readonly IKGoal[],mass?:ReadonlyMap<string,number>,fixed:ReadonlySet<string>=new Set(),retained:ReadonlySet<string>=new Set(),floor=-Infinity,poleChains:ReadonlyMap<string,readonly PinRecord[]> = new Map()):{id:string;pose:PinPose}[] {\n if (!goals.length) return [];\n const byId=new Map(pins.map(p=>[p.id,p])),key=(p:PinRecord)=>p.rigidGroup ?? p.id;\n const groups=new Map<string,PinRecord[]>();\n for(const pin of pins){const group=groups.get(key(pin)) ?? [];group.push(pin);groups.set(key(pin),group);}\n const active=new Set<string>(), roots=new Set<string>();\n const bendSeeds=new Map<string,Vector3>();\n let size=0;\n for(const goal of goals){\n const chain=ikChain(pins,parents,goal.id,mass);\n if(chain.length<2) throw new Error('IK needs a parent chain. Add a parent pin or remove Independent from this endpoint.');\n for(const p of chain) active.add(key(p));\n roots.add(key(chain[0]));\n // Only a straight, contracting chain needs a perturbation: at full\n // extension its positional Jacobian cannot discover a bend. Seeding an\n // already bent chain injects rotation on every drag sample and accumulates\n // drift despite a nearly stationary target.\n const start=new Vector3().fromArray(chain[0].pose.position),direction=new Vector3().fromArray(chain.at(-1)!.pose.position).sub(start);\n const span=direction.length();\n if(span>1e-8 && new Vector3().fromArray(goal.position).distanceTo(start)<span*(1-1e-6)){\n direction.divideScalar(span);\n const straight=chain.every(p=>new Vector3().fromArray(p.pose.position).sub(start).cross(direction).lengthSq()<span*span*1e-12);\n const candidate=straight?chain.slice(1,-1).find(p=>!groups.get(key(p))!.some(q=>fixed.has(q.id)) && ['free','cone'].includes((p.ikConstraint??DEFAULT_IK_CONSTRAINT).mode)):undefined;\n if(candidate){\n // Bend in the plane the goal is actually in: perpendicular to both the\n // chain and the way it has to reach. Seeding off the chain's smallest\n // world component instead picks a plane with no relation to the goal,\n // and a straight arm pulled sideways swings out of the screen on its\n // way there \u2014 deterministic, but not a bend anyone asked for.\n const axis=new Vector3().crossVectors(direction,new Vector3().fromArray(goal.position).sub(start));\n if(axis.lengthSq()<1e-12){\n // The goal lies along the chain, so no plane is implied by it; any\n // axis across the chain will do, chosen the same way every time.\n const components=direction.toArray().map(Math.abs);\n axis.setComponent(components.indexOf(Math.min(...components)),1).addScaledVector(direction,-axis.dot(direction));\n }\n bendSeeds.set(key(candidate),axis.normalize());\n }\n }\n size=Math.max(size,chain.slice(1).reduce((sum,p,i)=>sum+new Vector3().fromArray(p.pose.position).distanceTo(new Vector3().fromArray(chain[i].pose.position)),0));\n }\n if(size<1e-8) throw new Error('IK chain has no length. Separate its rest pins first.');\n const parentGroup=new Map<string,string>();\n for(const [id,members] of groups){\n const parent=members.map(p=>byId.get(parents.get(p.id) ?? '')).find(p=>p && key(p)!==id);\n if(parent) parentGroup.set(id,key(parent));\n }\n // Include followers in the graph so branch attachments keep their lengths too.\n const affected=new Set(active);\n for(let changed=true;changed;){changed=false;for(const [id,parent] of parentGroup) if(affected.has(parent)&&!affected.has(id)){affected.add(id);changed=true;}}\n const unchanged=goals.every(g=>{const p=byId.get(g.id)!;return new Vector3().fromArray(g.position).distanceToSquared(new Vector3().fromArray(p.pose.position))<1e-20 && new Quaternion().fromArray(g.rotation).angleTo(new Quaternion().fromArray(p.pose.rotation))<1e-10;});\n if(unchanged && !pins.some(p=>p.ikConstraint && p.ikConstraint.mode!=='free')) return pins.filter(p=>affected.has(key(p))).map(p=>({id:p.id,pose:p.pose}));\n const origin=new Vector3().fromArray(byId.get(goals[0].id)!.pose.position);\n const frames=new Map<string,Link>(), forest:Link[]=[], building=new Set<string>();\n const coneJoints=new Map<string,Joint>();\n const freeJoints=new Map<string,Joint>();\n const branchJoints=new Map<string,{joint:Joint;frame:Link}>();\n const build=(id:string):Link=>{\n const cached=frames.get(id);if(cached) return cached;\n if(building.has(id)) throw new Error('Cyclic IK hierarchy.');building.add(id);\n const pin=groups.get(id)![0],parentId=parentGroup.get(id),parent=parentId ? groups.get(parentId)![0] : undefined;\n const parentFrame=parentId ? build(parentId) : new Link();\n let attachment=parentFrame;\n if(parentId&&active.has(id)&&!groups.get(id)!.some(p=>fixed.has(p.id))&&groups.get(parentId)!.some(p=>fixed.has(p.id))){\n const pivot=new Joint();pivot.setDoF(3,4,5);pivot.setDoFValues(0,0,0);pivot.setRestPoseValues(0,0,0);\n parentFrame.addChild(pivot);attachment=new Link();pivot.addChild(attachment);\n branchJoints.set(id,{joint:pivot,frame:attachment});\n }\n const parentRotation=parent ? new Quaternion().fromArray(parent.pose.rotation) : new Quaternion();\n const position=new Vector3().fromArray(pin.pose.position).sub(parent ? new Vector3().fromArray(parent.pose.position):origin).applyQuaternion(parentRotation.clone().invert()).divideScalar(size);\n const relative=parentRotation.clone().invert().multiply(new Quaternion().fromArray(pin.pose.rotation)).normalize();\n const joint=new Joint();joint.setPosition(position.x,position.y,position.z);attachment.addChild(joint);\n const link=new Link(),constraint=pin.ikConstraint ?? DEFAULT_IK_CONSTRAINT;\n const movable=active.has(id)&&!groups.get(id)!.some(p=>fixed.has(p.id));\n if(!movable || constraint.mode==='locked') joint.setQuaternion(...relative.toArray());\n else if(constraint.mode==='hinge') {\n let axis=new Vector3();\n if(constraint.axis!=='auto') axis.setComponent(['x','y','z'].indexOf(constraint.axis),1);\n else {\n const child=pins.find(p=>parents.get(p.id)===pin.id && active.has(key(p)));\n if(parent&&child) axis.crossVectors(new Vector3().fromArray(pin.rest).sub(new Vector3().fromArray(parent.rest)),new Vector3().fromArray(child.rest).sub(new Vector3().fromArray(pin.rest)));\n if(axis.lengthSq()<1e-10) {const direction=child ? new Vector3().fromArray(child.rest).sub(new Vector3().fromArray(pin.rest)).normalize():new Vector3(0,1,0);axis.crossVectors(direction,Math.abs(direction.z)<.9 ? new Vector3(0,0,1):new Vector3(1,0,0));}\n axis.normalize();\n }\n const basis=new Quaternion().setFromUnitVectors(new Vector3(0,0,1),axis);\n joint.setQuaternion(...basis.toArray());link.setQuaternion(...basis.clone().invert().toArray());\n joint.setDoF(5);joint.setMinLimits(constraint.min*Math.PI/180);joint.setMaxLimits(constraint.max*Math.PI/180);\n const twist=2*Math.atan2(new Vector3(relative.x,relative.y,relative.z).dot(axis),relative.w);\n joint.setDoFValues(Math.atan2(Math.sin(twist),Math.cos(twist)));joint.setRestPoseValues(0);\n } else {\n if(constraint.mode==='cone')coneJoints.set(id,joint);\n else freeJoints.set(id,joint);\n joint.setDoF(3,4,5);\n const euler=new Euler().setFromQuaternion(relative,'ZYX');joint.setDoFValues(euler.x,euler.y,euler.z);joint.setRestPoseValues(euler.x,euler.y,euler.z);\n const seed=bendSeeds.get(id);\n if(seed && !roots.has(id) && !goals.some(g=>key(byId.get(g.id)!)===id)){\n const axis=seed.clone().applyQuaternion(parentRotation.clone().invert());\n const seeded=new Euler().setFromQuaternion(new Quaternion().setFromAxisAngle(axis,.03).multiply(relative),'ZYX');\n joint.setDoFValues(seeded.x,seeded.y,seeded.z);\n }\n }\n joint.addChild(link);frames.set(id,link);building.delete(id);if(!parentId) forest.push(parentFrame);return link;\n };\n for(const id of groups.keys()) build(id);\n // Limits describe the visible segment in the committed parent's frame, not\n // a shared attachment's temporary solver rotation or a stale inserted frame.\n const limitRotation=(id:string,rotation:Quaternion,parentRotation:Quaternion)=>{\n const pin=groups.get(id)![0];if(pin.ikConstraint?.mode!=='cone')return rotation;\n const parentId=parentGroup.get(id),parent=parentId?groups.get(parentId)![0]:undefined;\n const child=pins.find(p=>parents.get(p.id)===pin.id);\n if(retained.has(id)&&child&&!active.has(key(child)))return rotation;\n const axis=child?new Vector3().fromArray(child.rest).sub(new Vector3().fromArray(pin.rest)):parent?new Vector3().fromArray(pin.rest).sub(new Vector3().fromArray(parent.rest)):new Vector3(0,1,0);\n if(axis.lengthSq()<1e-12)axis.set(0,1,0);\n const movingAxis=child?new Vector3().fromArray(child.pose.position).sub(new Vector3().fromArray(pin.pose.position)).applyQuaternion(new Quaternion().fromArray(pin.pose.rotation).invert()):axis;\n if(movingAxis.lengthSq()<1e-12)movingAxis.copy(axis);\n const reference=parentId&&retained.has(parentId)?new Quaternion().fromArray(parent!.pose.rotation):parentRotation;\n const relative=reference.clone().invert().multiply(parentRotation).multiply(rotation);\n return parentRotation.clone().invert().multiply(reference).multiply(constrainCone(relative,axis,pin.ikConstraint,movingAxis));\n };\n // Continuity refers to the pose on screen, before analytic initialization\n // or cone projection chooses a candidate. Include temporary body pivots.\n const priorRotations=new Map([...frames.values(),...[...branchJoints.values()].map(branch=>branch.frame)].map(frame=>{\n frame.updateMatrixWorld();return [frame,new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(frame.matrixWorld))] as const;\n }));\n const closures:Goal[]=[];\n for(const target of goals){\n const pin=byId.get(target.id)!,anchor=groups.get(key(pin))![0];\n const offset=new Vector3().fromArray(pin.pose.position).sub(new Vector3().fromArray(anchor.pose.position)).applyQuaternion(new Quaternion().fromArray(anchor.pose.rotation).invert()).divideScalar(size);\n const attachment=new Joint();attachment.setPosition(...offset.toArray());frames.get(key(pin))!.addChild(attachment);\n const tip=new Link();attachment.addChild(tip);\n const goal=new Goal();\n const freeEndpoint=groups.get(key(pin))!.length===1 && (!pin.ikConstraint || pin.ikConstraint.mode==='free');\n if(freeEndpoint) goal.setGoalDoF(0,1,2);else goal.setGoalDoF(0,1,2,3,4,5);\n goal.makeClosure(tip);\n const requested=new Vector3().fromArray(target.position);\n if(goals.length===1 && freeEndpoint){\n const chain=ikChain(pins,parents,target.id,mass);\n const first=chain.findIndex(p=>!groups.get(key(p))!.some(q=>fixed.has(q.id)) && (p.ikConstraint??DEFAULT_IK_CONSTRAINT).mode!=='locked');\n const moving=first<0?[]:chain.slice(branchJoints.has(key(chain[first]))?Math.max(0,first-1):first);\n // For an unconstrained ball-joint chain its link lengths define a\n // reachable spherical shell. Solve against that shell, not an impossible\n // residual which can stall the iterative solver away from the closest\n // pose. The authored world target is deliberately left unchanged.\n if(moving.length>1 && moving.every((p,i)=>(i===0&&branchJoints.has(key(moving[1])))||(!fixed.has(p.id) && groups.get(key(p))!.length===1 && (p.ikConstraint??DEFAULT_IK_CONSTRAINT).mode==='free'))){\n const pivot=new Vector3().fromArray(moving[0].pose.position);\n const lengths=moving.slice(1).map((p,i)=>new Vector3().fromArray(p.pose.position).distanceTo(new Vector3().fromArray(moving[i].pose.position)));\n const outer=lengths.reduce((a,b)=>a+b,0),inner=Math.max(0,2*Math.max(...lengths)-outer),delta=requested.clone().sub(pivot),distance=delta.length();\n if(distance<inner || distance>outer){\n if(distance<1e-12)delta.fromArray(moving.at(-1)!.pose.position).sub(pivot);\n if(delta.lengthSq()>1e-24)requested.copy(pivot).add(delta.setLength(Math.max(inner,Math.min(outer,distance))));\n }\n if(moving.length===2){\n // One free link has a closed-form minimum-rotation solution. Its\n // positional Jacobian is rank deficient (twist is unobservable), so\n // initialize it analytically instead of relying on an arbitrary seed.\n const before=new Vector3().fromArray(moving[1].pose.position).sub(pivot),after=requested.clone().sub(pivot);\n if(before.lengthSq()>1e-24 && after.lengthSq()>1e-24){\n const branch=branchJoints.get(key(moving[1])),parent=branch?moving[0]:byId.get(parents.get(moving[0].id)??'');\n const local=parent?new Quaternion().fromArray(parent.pose.rotation).invert():new Quaternion();\n local.multiply(new Quaternion().setFromUnitVectors(before.normalize(),after.normalize())).multiply(new Quaternion().fromArray(moving[0].pose.rotation));\n const euler=new Euler().setFromQuaternion(local,'ZYX');(branch?.joint??freeJoints.get(key(moving[0])))!.setDoFValues(euler.x,euler.y,euler.z);\n }\n }\n }\n }\n goal.setPosition(...requested.sub(origin).divideScalar(size).toArray());goal.setQuaternion(...target.rotation);\n closures.push(goal);\n }\n // Two-link limbs have an exact positional solution. Keep their existing bend\n // plane and transport each frame by the minimum swing: an Euler/SVD solve can\n // choose a different elbow branch or arbitrary axial twist near singularity.\n // Cone projection + constrained refinement below still enforce authored limits.\n let analytic=false;\n if(goals.length===1){\n const goal=goals[0],chain=ikChain(pins,parents,goal.id,mass);\n const first=chain.findIndex((p,i)=>coneJoints.has(key(p))||freeJoints.has(key(p))||(i+1<chain.length&&branchJoints.has(key(chain[i+1]))));\n const limb=first<0?[]:chain.slice(first),tipPin=byId.get(goal.id)!;\n if(limb.length===3&&limb.every(p=>groups.get(key(p))!.length===1)\n &&limb.slice(0,2).every((p,i)=>coneJoints.has(key(p))||freeJoints.has(key(p))||branchJoints.has(key(limb[i+1])))\n &&(!tipPin.ikConstraint||tipPin.ikConstraint.mode==='free')){\n const world=(p:PinRecord)=>{const frame=frames.get(key(p))!;frame.updateMatrixWorld();return new Matrix4().fromArray(frame.matrixWorld);};\n const matrices=limb.map(world),points=matrices.map(m=>new Vector3().setFromMatrixPosition(m));\n const [base,knee,tip]=points,a=base.distanceTo(knee),b=knee.distanceTo(tip);\n const direction=new Vector3().fromArray(closures[0].position).sub(base);\n if(a>1e-10&&b>1e-10&&direction.lengthSq()>1e-20){\n const distance=Math.max(Math.abs(a-b)+1e-9,Math.min(a+b-1e-9,direction.length()));direction.normalize();\n const oldAxis=tip.clone().sub(base).normalize();\n const bend=knee.clone().sub(base).addScaledVector(oldAxis,-knee.clone().sub(base).dot(oldAxis));\n // Transport the previous pole with the target, instead of projecting it\n // against the new axis (which can flip the knee on a large target move).\n bend.applyQuaternion(new Quaternion().setFromUnitVectors(oldAxis,direction));\n if(bend.lengthSq()<1e-16){\n bend.fromArray(limb[1].rest).sub(new Vector3().fromArray(limb[0].rest));\n const restAxis=new Vector3().fromArray(limb[2].rest).sub(new Vector3().fromArray(limb[0].rest)).normalize();\n bend.addScaledVector(restAxis,-bend.dot(restAxis)).applyQuaternion(new Quaternion().setFromRotationMatrix(matrices[0]));\n bend.addScaledVector(direction,-bend.dot(direction));\n }\n if(bend.lengthSq()<1e-16){bend.set(Math.abs(direction.x)<.8?1:0,Math.abs(direction.x)<.8?0:1,0);bend.addScaledVector(direction,-bend.dot(direction));}\n const along=(a*a-b*b+distance*distance)/(2*distance);\n const desiredKnee=base.clone().addScaledVector(direction,along).addScaledVector(bend.normalize(),Math.sqrt(Math.max(0,a*a-along*along)));\n const desiredTip=base.clone().addScaledVector(direction,distance);\n for(const [i,end] of [desiredKnee,desiredTip].entries()){\n const pin=limb[i],branch=branchJoints.get(key(limb[i+1])),frame=branch?.frame??frames.get(key(pin))!;\n frame.updateMatrixWorld();\n const matrix=new Matrix4().fromArray(frame.matrixWorld),pivot=new Vector3().setFromMatrixPosition(matrix);\n const before=new Vector3().setFromMatrixPosition(world(limb[i+1])).sub(pivot),after=end.clone().sub(pivot);\n const parentId=parentGroup.get(key(pin)),parentFrame=branch?frames.get(key(pin)):branchJoints.get(key(pin))?.frame??(parentId?frames.get(parentId):undefined);parentFrame?.updateMatrixWorld();\n const parentRotation=parentFrame?new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(parentFrame.matrixWorld)):new Quaternion();\n const rotation=parentRotation.invert().multiply(new Quaternion().setFromUnitVectors(before.normalize(),after.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\n const euler=new Euler().setFromQuaternion(rotation,'ZYX');(branch?.joint??coneJoints.get(key(pin))??freeJoints.get(key(pin)))!.setDoFValues(euler.x,euler.y,euler.z);\n }\n analytic=true;\n }\n }\n }\n const positionOnlyGoal=goals.length===1&&groups.get(key(byId.get(goals[0].id)!))!.length===1\n &&(!byId.get(goals[0].id)!.ikConstraint||byId.get(goals[0].id)!.ikConstraint!.mode==='free');\n const positionOnlyGoals=goals.every(goal=>groups.get(key(byId.get(goal.id)!))!.length===1\n &&(!byId.get(goal.id)!.ikConstraint||byId.get(goal.id)!.ikConstraint!.mode==='free'));\n // A lone planted foot has a prior bend in the current frame. Starting a\n // global SVD solve there can choose another elbow branch on a tiny edit;\n // the constrained descent below instead continues that bend.\n if(!analytic&&!positionOnlyGoal&&!positionOnlyGoals){\n const solver=new Solver([...forest,...closures]);solver.useSVD=true;solver.maxIterations=48;solver.restPoseFactor=.001;\n solver.translationConvergeThreshold=1e-6;solver.rotationConvergeThreshold=1e-6;solver.translationErrorClamp=.2;\n solver.solve();\n }\n // Project oriented elliptical swing limits in parent-to-child order. Updating the joint\n // frame carries descendants rigidly, so limiting a cone never stretches links.\n const projectCones=()=>{for(const [id,joint] of coneJoints){\n const parentId=parentGroup.get(id), frame=frames.get(id)!;\n frame.updateMatrixWorld();\n const parentFrame=branchJoints.get(id)?.frame??(parentId?frames.get(parentId):undefined);\n const parentRotation=parentFrame?new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(parentFrame.matrixWorld)):new Quaternion();\n const relative=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(frame.matrixWorld)));\n const limited=limitRotation(id,relative,parentRotation),euler=new Euler().setFromQuaternion(limited,'ZYX');\n joint.setDoFValues(euler.x,euler.y,euler.z);frame.updateMatrixWorld();\n }\n };\n if(goals.length===1||!positionOnlyGoals)projectCones();\n if(goals.length>1&&positionOnlyGoals){\n const world=(frame:Link)=>{frame.updateMatrixWorld();return new Matrix4().fromArray(frame.matrixWorld);};\n const tips=goals.map(goal=>({goal,frame:frames.get(key(byId.get(goal.id)!))!,desired:new Vector3().fromArray(closures[goals.indexOf(goal)].position),chain:ikChain(pins,parents,goal.id,mass).slice(0,-1).reverse()}));\n const poles=tips.flatMap(tip=>{\n const chain=poleChains.get(tip.goal.id);\n if(!chain||chain.length<3)return [];\n const base=chain[0],knee=chain[Math.floor((chain.length-1)/2)],end=chain.at(-1)!;\n const restAxis=new Vector3().fromArray(end.rest).sub(new Vector3().fromArray(base.rest));\n const restBend=new Vector3().fromArray(knee.rest).sub(new Vector3().fromArray(base.rest));\n if(restAxis.lengthSq()<1e-16)return [];\n restBend.addScaledVector(restAxis,-restBend.dot(restAxis)/restAxis.lengthSq());\n if(restBend.length()<restAxis.length()*.02)return [];\n const minBend=Math.min(.03,restBend.length()/size*.5);\n return [{base,knee,chain,tip,minBend,restAxis:restAxis.normalize(),restPole:restBend.normalize()}];\n });\n const poleState=(pole:typeof poles[number])=>{\n const base=new Vector3().setFromMatrixPosition(world(frames.get(key(pole.base))!));\n const knee=new Vector3().setFromMatrixPosition(world(frames.get(key(pole.knee))!));\n const axis=pole.tip.desired.clone().sub(base).normalize();\n const preferred=pole.restPole.clone().applyQuaternion(new Quaternion().setFromUnitVectors(pole.restAxis,axis));\n preferred.addScaledVector(axis,-preferred.dot(axis)).normalize();\n const bend=knee.sub(base);bend.addScaledVector(axis,-bend.dot(axis));\n return {base,axis,preferred,bend};\n };\n const initial=[...new Set(tips.flatMap(tip=>tip.chain.flatMap(pin=>[frames.get(key(pin)),branchJoints.get(key(pin))?.frame]).filter((frame):frame is Link=>Boolean(frame))))]\n .map(frame=>({frame,rotation:new Quaternion().setFromRotationMatrix(world(frame))}));\n const cost=()=>tips.reduce((sum,tip)=>sum+new Vector3().setFromMatrixPosition(world(tip.frame)).distanceToSquared(tip.desired),0)\n +POSE_CONTINUITY_WEIGHT*initial.reduce((sum,{frame,rotation})=>sum+new Quaternion().setFromRotationMatrix(world(frame)).angleTo(rotation)**2,0)\n +10*poles.reduce((sum,pole)=>{const {preferred,bend}=poleState(pole);\n return sum+Math.max(0,pole.minBend-bend.dot(preferred))**2;},0);\n for(let sweep=0;sweep<96;sweep++){\n if(cost()<1e-12)break;\n let largestChange=0;\n for(const tip of tips)for(const pin of tip.chain){\n const id=key(pin),joints=[coneJoints.get(id)??freeJoints.get(id),branchJoints.get(id)?.joint];\n for(const [index,joint] of joints.entries()){\n if(!joint)continue;\n const branch=index===1,frame=branch?branchJoints.get(id)!.frame:frames.get(id)!;\n const matrix=world(frame),pivot=new Vector3().setFromMatrixPosition(matrix),end=new Vector3().setFromMatrixPosition(world(tip.frame));\n const a=end.sub(pivot),b=tip.desired.clone().sub(pivot);\n if(a.lengthSq()<1e-20||b.lengthSq()<1e-20)continue;\n const parentId=parentGroup.get(id),localParent=branch?(parentId?frames.get(parentId):undefined):branchJoints.get(id)?.frame??(parentId?frames.get(parentId):undefined);\n const parentRotation=localParent?new Quaternion().setFromRotationMatrix(world(localParent)):new Quaternion();\n const old=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(matrix));\n let rotation=parentRotation.clone().invert().multiply(new Quaternion().setFromUnitVectors(a.normalize(),b.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\n if(!branch)rotation=limitRotation(id,rotation,parentRotation);\n const before=cost(),set=(q:Quaternion)=>{const e=new Euler().setFromQuaternion(q,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frame.updateMatrixWorld();};\n for(let fraction=1;fraction>=1/32;fraction/=2){\n const attempt=old.clone().slerp(rotation,fraction);set(attempt);\n if(cost()<before-1e-14){largestChange=Math.max(largestChange,old.angleTo(attempt));break;}\n set(old);\n }\n }\n }\n for(const pole of poles){\n const {base,preferred,bend}=poleState(pole),along=bend.dot(preferred);\n if(along>=pole.minBend)continue;\n const baseId=key(pole.base),nextId=key(pole.chain[1]);\n const branch=branchJoints.get(nextId),joint=branch?.joint??coneJoints.get(baseId)??freeJoints.get(baseId);\n const frame=branch?.frame??frames.get(baseId);\n if(!joint||!frame)continue;\n const knee=new Vector3().setFromMatrixPosition(world(frames.get(key(pole.knee))!));\n const arm=knee.sub(base),aim=arm.clone().addScaledVector(preferred,Math.min(.01,pole.minBend-along));\n if(arm.lengthSq()<1e-20||aim.lengthSq()<1e-20)continue;\n const parentId=branch?baseId:parentGroup.get(baseId),parentFrame=parentId?frames.get(parentId):undefined;\n const parentRotation=parentFrame?new Quaternion().setFromRotationMatrix(world(parentFrame)):new Quaternion();\n const matrix=world(frame),old=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(matrix));\n let proposal=parentRotation.clone().invert().multiply(new Quaternion().setFromUnitVectors(arm.normalize(),aim.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\n if(!branch)proposal=limitRotation(baseId,proposal,parentRotation);\n const before=cost(),set=(q:Quaternion)=>{const e=new Euler().setFromQuaternion(q,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frame.updateMatrixWorld();};\n for(let fraction=1;fraction>=1/32;fraction/=2){\n const attempt=old.clone().slerp(proposal,fraction);set(attempt);\n if(cost()<before-1e-14){largestChange=Math.max(largestChange,old.angleTo(attempt));break;}\n set(old);\n }\n }\n if(largestChange<1e-5)break;\n }\n }\n // Projecting cones only AFTER the unconstrained solve leaves the endpoint\n // stranded, even when another joint could reach it. Finish positional chains\n // with constrained coordinate descent: every accepted step obeys its cone\n // and reduces the residual. Siblings/fixed roots never enter this joint list.\n if(goals.length===1){\n const target=goals[0],tipPin=byId.get(target.id)!;\n if(groups.get(key(tipPin))!.length===1&&(!tipPin.ikConstraint||tipPin.ikConstraint.mode==='free')){\n const tip=frames.get(key(tipPin))!,desired=new Vector3().fromArray(closures[0].position);\n const ordered=ikChain(pins,parents,target.id,mass),chain=ordered.slice(0,-1).reverse();\n const world=(frame:Link)=>{frame.updateMatrixWorld();return new Matrix4().fromArray(frame.matrixWorld);};\n const ground=tipPin.chainRole?.kind==='leg'&&Number.isFinite(floor)?(floor-origin.y)/size:-Infinity;\n const point=(pin:PinRecord)=>new Vector3().setFromMatrixPosition(world(frames.get(key(pin))!));\n const initial=[...new Set(chain.flatMap(pin=>[frames.get(key(pin))!,branchJoints.get(key(pin))?.frame].filter((frame):frame is Link=>Boolean(frame))))].map(frame=>({frame,rotation:priorRotations.get(frame)!}));\n // Endpoint distance has mirrored solutions. Carry each visible bend's\n // pole into the new chord frame instead of letting descent change sides.\n const poles=ordered.slice(1,-1).flatMap((knee,i)=>{\n const base=ordered[i],end=ordered[i+2];\n const chord=new Vector3().fromArray(end.pose.position).sub(new Vector3().fromArray(base.pose.position)),span=chord.length(),axis=chord.normalize();\n const bend=new Vector3().fromArray(knee.pose.position).sub(new Vector3().fromArray(base.pose.position));\n bend.addScaledVector(axis,-bend.dot(axis));\n // Near extension the positional pole is numerical noise; the rest\n // bend carried by the current base frame still defines its side.\n if(bend.length()<span*.02){\n const restAxis=new Vector3().fromArray(end.rest).sub(new Vector3().fromArray(base.rest)).normalize();\n bend.fromArray(knee.rest).sub(new Vector3().fromArray(base.rest));\n bend.addScaledVector(restAxis,-bend.dot(restAxis));\n const rotation=new Quaternion().fromArray(base.pose.rotation);\n bend.applyQuaternion(rotation);\n restAxis.applyQuaternion(rotation);\n bend.applyQuaternion(new Quaternion().setFromUnitVectors(restAxis,axis));\n }\n return bend.length()<span*.02?[]:[{base,knee,end,axis,pole:bend.normalize()}];\n });\n const poleCost=()=>poles.reduce((sum,pole)=>{\n const base=point(pole.base),axis=point(pole.end).sub(base).normalize();\n const preferred=pole.pole.clone().applyQuaternion(new Quaternion().setFromUnitVectors(pole.axis,axis));\n const bend=point(pole.knee).sub(base);bend.addScaledVector(axis,-bend.dot(axis));\n return sum+Math.max(0,-bend.dot(preferred))**2;\n },0);\n // Position alone does not determine every joint frame. Keep the nearest\n // solution to the pose on screen when a controller moves a tiny amount.\n const cost=()=>{\n const error=new Vector3().setFromMatrixPosition(world(tip)).distanceToSquared(desired);\n let penetration=0;\n if(Number.isFinite(ground))for(const pin of ordered.slice(1,-1))penetration+=Math.max(0,ground-point(pin).y)**2;\n const drift=initial.reduce((sum,{frame,rotation})=>sum+new Quaternion().setFromRotationMatrix(world(frame)).angleTo(rotation)**2,0);\n return error+16*penetration+100*poleCost()+POSE_CONTINUITY_WEIGHT*drift;\n };\n // Near a tight cone the last few sweeps are small but visible. Stop only\n // once the pose itself has settled, not merely when the goal is close.\n for(let sweep=0;sweep<128;sweep++){\n if(cost()<1e-12)break;\n let largestChange=0;\n for(const pin of chain){\n const id=key(pin);\n const joints=[coneJoints.get(id)??freeJoints.get(id),branchJoints.get(id)?.joint];\n for(const [jointIndex,joint] of joints.entries()){\n if(!joint)continue;\n const branch=jointIndex===1,frame=branch?branchJoints.get(id)!.frame:frames.get(id)!;\n const matrix=world(frame),pivot=new Vector3().setFromMatrixPosition(matrix);\n const end=new Vector3().setFromMatrixPosition(world(tip)),before=cost();\n const a=end.clone().sub(pivot),b=desired.clone().sub(pivot);if(a.lengthSq()<1e-20||b.lengthSq()<1e-20)continue;\n const parentId=parentGroup.get(id),localParent=branch?parentId?frames.get(parentId):undefined:branchJoints.get(id)?.frame??(parentId?frames.get(parentId):undefined);\n const parentRotation=localParent?new Quaternion().setFromRotationMatrix(world(localParent)):new Quaternion();\n const old=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(matrix));\n let rotation=parentRotation.clone().invert().multiply(new Quaternion().setFromUnitVectors(a.normalize(),b.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\n if(!branch)rotation=limitRotation(id,rotation,parentRotation);\n const set=(q:Quaternion)=>{const e=new Euler().setFromQuaternion(q,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frame.updateMatrixWorld();};\n let accepted=false;\n for(let fraction=1;fraction>=1/32;fraction/=2){\n let attempt=old.clone().slerp(rotation,fraction);\n if(!branch)attempt=limitRotation(id,attempt,parentRotation);\n set(attempt);\n if(cost()<=before+1e-14){largestChange=Math.max(largestChange,old.angleTo(attempt));accepted=true;break;}\n }\n if(!accepted)set(old);\n if(Number.isFinite(ground))for(const descendant of ordered.slice(ordered.indexOf(pin)+1,-1)){\n const lower=point(descendant);if(lower.y>=ground)continue;\n const current=point(pin),arm=lower.clone().sub(current),raised=lower.clone();raised.y=ground;\n const aim=raised.sub(current);if(arm.lengthSq()<1e-20||aim.lengthSq()<1e-20)continue;\n const parentNow=localParent?new Quaternion().setFromRotationMatrix(world(localParent)):new Quaternion();\n const previous=parentNow.clone().invert().multiply(new Quaternion().setFromRotationMatrix(world(frame)));\n let proposal=parentNow.clone().invert().multiply(new Quaternion().setFromUnitVectors(arm.normalize(),aim.normalize())).multiply(new Quaternion().setFromRotationMatrix(world(frame)));\n if(!branch)proposal=limitRotation(id,proposal,parentNow);\n const start=cost();\n for(let fraction=1;fraction>=1/16;fraction/=2){\n const attempt=previous.clone().slerp(proposal,fraction);set(attempt);\n if(cost()<start-1e-14){largestChange=Math.max(largestChange,previous.angleTo(attempt));break;}\n set(previous);\n }\n }\n }\n }\n if(largestChange<1e-5)break;\n }\n }\n }\n // Ancestor refinement must not leave a cone outside its committed frame.\n if(goals.length===1||!positionOnlyGoals)projectCones();\n // A free goal's orientation is independent of its position, including when\n // extra toe/follower joints are added below it. Carry those followers through\n // the frame, rather than only overwriting the endpoint's returned quaternion.\n for(const goal of goals){\n const id=key(byId.get(goal.id)!),joint=freeJoints.get(id);if(!joint||groups.get(id)!.length!==1)continue;\n const parentId=parentGroup.get(id),parent=parentId?frames.get(parentId):undefined;parent?.updateMatrixWorld();\n const rotation=parent?new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(parent.matrixWorld)).invert():new Quaternion();\n rotation.multiply(new Quaternion().fromArray(goal.rotation));\n const e=new Euler().setFromQuaternion(rotation,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frames.get(id)!.updateMatrixWorld();\n }\n const result=pins.filter(p=>affected.has(key(p))).map(pin=>{\n if(fixed.has(pin.id)) return {id:pin.id,pose:pin.pose};\n const anchor=groups.get(key(pin))![0],frame=frames.get(key(pin))!;frame.updateMatrixWorld();\n const matrix=new Matrix4().fromArray(frame.matrixWorld),rotation=new Quaternion().setFromRotationMatrix(matrix).normalize();\n const position=new Vector3().setFromMatrixPosition(matrix).multiplyScalar(size).add(origin);\n const delta=rotation.clone().multiply(new Quaternion().fromArray(anchor.pose.rotation).invert());\n const goal=goals.find(g=>key(byId.get(g.id)!)===key(pin));\n const terminal=![...parentGroup.values()].includes(key(pin));\n if(goal&&terminal&&(!pin.ikConstraint || pin.ikConstraint.mode==='free')) rotation.fromArray(goal.rotation);\n const offset=new Vector3().fromArray(pin.pose.position).sub(new Vector3().fromArray(anchor.pose.position));\n if(goal&&terminal&&(!pin.ikConstraint || pin.ikConstraint.mode==='free')) delta.copy(rotation).multiply(new Quaternion().fromArray(anchor.pose.rotation).invert());\n position.add(offset.applyQuaternion(delta));\n if(!parentGroup.has(key(pin)) && pin.id===anchor.id) position.fromArray(pin.pose.position);\n if(![...position.toArray(),...rotation.toArray()].every(Number.isFinite)) throw new Error('IK produced an invalid pose.');\n return {id:pin.id,pose:{position:position.toArray(),rotation:rotation.toArray(),scale:pin.pose.scale}};\n });\n return result;\n}\n", "import { validateRig, type JointsRig } from './joints-json.js';\nimport { ikChain } from './pin-ik.js';\nimport {DEFAULT_MOTION} from './motion-settings.js';\nimport type { ClothCollider, ClothLink } from './pin-cloth.js';\n\nexport const NEEDLE_DEFORMATION_RIG = 'NEEDLE_deformation_rig';\nexport interface RigDescriptor extends JointsRig {\n version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;\n joints: { node: number; parent: number | null; mass: number }[];\n chains: { endpoint: number; joints: number[]; mode: 'ik' | 'secondary' | 'cloth' | 'fur' }[];\n helpers?: { node: number; influences: { node: number; weight: number }[] }[];\n cloth?: { links: ClothLink[]; colliders: ClothCollider[] };\n furSurface?: { heightTexture: number; texCoord?: number };\n}\n/** Validate before allocating runtime objects or accepting node references. */\nexport function parseRigDescriptor(value: unknown, nodeCount: number, textureCount = Infinity): RigDescriptor {\n if (!value || typeof value !== 'object') throw new Error('Invalid deformation rig.');\n const raw = value as RigDescriptor;\n if (raw.version !== 1 && raw.version !== 2 && raw.version !== 3 && raw.version !== 4 && raw.version !== 5 && raw.version !== 6 && raw.version !== 7 && raw.version !== 8 && raw.version !== 9) throw new Error('Unsupported NEEDLE_deformation_rig version.');\n if (raw.furSurface?.texCoord !== undefined && (raw.version < 8 || !Number.isInteger(raw.furSurface.texCoord) || raw.furSurface.texCoord < 0 || raw.furSurface.texCoord > 1)) throw new Error('Invalid Fur height texture coordinates.');\n if (raw.furSurface && (raw.version < 6 || !Number.isInteger(raw.furSurface.heightTexture) || raw.furSurface.heightTexture < 0 || raw.furSurface.heightTexture >= textureCount)) throw new Error('Invalid Fur height texture.');\n if (raw.version < 5 && raw.windStrength !== undefined) throw new Error('Wind requires NEEDLE_deformation_rig version 5.');\n if (raw.activePose === 0 && raw.version < 9) throw new Error('An unselected authored pose requires NEEDLE_deformation_rig version 9.');\n const restSlot=raw.poseSlots?.find(slot=>slot.slot===0);\n if(restSlot && raw.version<7)throw new Error('Pose 0 requires NEEDLE_deformation_rig version 7.');\n const rig = validateRig({...raw,poseSlots:raw.poseSlots?.filter(slot=>slot.slot!==0)}, raw.version>=3?256:128);\n if(restSlot){\n if(raw.poseSlots.filter(slot=>slot.slot===0).length!==1 || !Array.isArray(restSlot.poses) || restSlot.poses.length!==rig.pins.length ||\n new Set(restSlot.poses.map(p=>p.id)).size!==rig.pins.length || restSlot.poses.some(p=>!rig.pins.some(pin=>pin.id===p.id)))throw new Error('Invalid rest pose clip.');\n validateRig({pins:rig.pins,activePose:1,poseSlots:[{slot:1,poses:restSlot.poses}],poseTimes:[]},raw.version>=3?256:128);\n }\n if (raw.version < 5 && rig.pins.some(pin=>pin.fur)) throw new Error('Fur requires NEEDLE_deformation_rig version 5.');\n if (raw.furSurface && !rig.pins.some(pin => pin.fur)) throw new Error('Fur height requires a Fur rig.');\n const node = (n: number) => Number.isInteger(n) && n >= 0 && n < nodeCount;\n if (!Array.isArray(raw.joints) || raw.joints.length !== rig.pins.length) throw new Error('Invalid rig joint bindings.');\n const indices = new Set<number>();\n for (const joint of raw.joints) {\n if (!joint || !node(joint.node) || indices.has(joint.node) || (joint.parent !== null && !node(joint.parent)) || !Number.isFinite(joint.mass) || joint.mass < 0) throw new Error('Invalid rig node or mass.');\n indices.add(joint.node);\n }\n const parents = new Map(raw.joints.map(j => [j.node, j.parent]));\n for (const joint of raw.joints) {\n const seen = new Set<number>(); let cursor: number | null = joint.node;\n while (cursor !== null) {\n if (!indices.has(cursor) || seen.has(cursor)) throw new Error('Invalid or cyclic rig hierarchy.');\n seen.add(cursor); cursor = parents.get(cursor)!;\n }\n }\n if (!Array.isArray(raw.chains) || raw.chains.length > rig.pins.length) throw new Error('Invalid motion chains.');\n const endpoints = new Set<number>();\n for (const chain of raw.chains) {\n if (!chain || !indices.has(chain.endpoint) || endpoints.has(chain.endpoint) || !['ik', 'secondary', 'cloth', 'fur'].includes(chain.mode) || !Array.isArray(chain.joints) || !chain.joints.length || chain.joints.length > rig.pins.length || chain.joints.at(-1) !== chain.endpoint || new Set(chain.joints).size !== chain.joints.length || chain.joints.some(n => !indices.has(n))) throw new Error('Invalid motion chain.');\n endpoints.add(chain.endpoint);\n }\n const pinParents = new Map<string, string>(), masses = new Map<string, number>();\n raw.joints.forEach((j, i) => { masses.set(rig.pins[i].id, j.mass); if (j.parent !== null) pinParents.set(rig.pins[i].id, rig.pins[raw.joints.findIndex(p => p.node === j.parent)].id); });\n for (const [i, pin] of rig.pins.entries()) {\n const chain = raw.chains.find(c => c.endpoint === raw.joints[i].node);\n const mode = !pin.guide && (pin.ik ? 'ik' : pin.wiggle ? 'secondary' : pin.cloth ? 'cloth' : pin.fur ? 'fur' : null);\n if (!mode && chain) throw new Error('Unexpected motion chain.');\n if (!mode) continue;\n const articulated=raw.version>=3?rig.pins.filter((_,i)=>!raw.helpers?.some(h=>h.node===raw.joints[i].node)):rig.pins;\n const expected = ikChain(articulated.map(p=>p.id===pin.id?{...p,motion:{...(p.motion??DEFAULT_MOTION),reach:1}}:p), pinParents, pin.id, masses).map(p => raw.joints[rig.pins.findIndex(pin => pin.id === p.id)].node);\n // Chains are derived caches, not authoritative authored topology. Older\n // writers used discontinuous reach gates; accept any valid ancestor suffix\n // and rebuild the current extent from the saved reach in the runtime.\n if (!chain || chain.mode !== mode || chain.joints.length > expected.length || chain.joints.some((n, i) => n !== expected[expected.length - chain.joints.length + i])) throw new Error('Motion chain does not match its hierarchy and reach.');\n }\n if (raw.helpers !== undefined && (!Array.isArray(raw.helpers) || raw.helpers.length > 256)) throw new Error('Invalid helper bindings.');\n const helpers = raw.helpers?.map(helper => {\n if (!node(helper.node) || (raw.version<3&&indices.has(helper.node)) || (raw.version>=3&&!parents.has(helper.node)) || !Array.isArray(helper.influences) || helper.influences.length > rig.pins.length) throw new Error('Invalid helper node.');\n const seen = new Set<number>(); let sum = 0;\n for (const influence of helper.influences) {\n if (!parents.has(influence.node) || (raw.version>=3&&raw.helpers?.some(h=>h.node===influence.node)) || seen.has(influence.node) || !Number.isFinite(influence.weight) || influence.weight <= 0) throw new Error('Invalid helper influence.');\n seen.add(influence.node); sum += influence.weight;\n }\n if (helper.influences.length && Math.abs(sum - 1) > 1e-4) throw new Error('Helper weights must sum to one.');\n indices.add(helper.node); return { node: helper.node, influences: helper.influences.map(i => ({ ...i })) };\n });\n if (raw.version >= 2 && !helpers) throw new Error('Rig requires helper bindings.');\n if (helpers && new Set(helpers.map(h=>h.node)).size!==helpers.length) throw new Error('Duplicate helper bone.');\n if ((raw.version < 4 && (raw.cloth !== undefined || rig.pins.some(p => p.cloth))) || (raw.version === 4 && !raw.cloth) || (rig.pins.some(p => p.cloth) && !raw.cloth) || (raw.cloth && (!Array.isArray(raw.cloth.links) || !Array.isArray(raw.cloth.colliders) || raw.cloth.links.length > 512 || raw.cloth.colliders.length > 4096))) throw new Error('Invalid cloth simulation data.');\n const pinById = new Map(rig.pins.map(p => [p.id, p]));\n for (const link of raw.cloth?.links ?? []) if (!link || !pinById.has(link.a) || !pinById.has(link.b) || link.a === link.b || !(pinById.get(link.a)?.cloth || pinById.get(link.b)?.cloth) || !Number.isFinite(link.length) || link.length < 0) throw new Error('Invalid cloth link.');\n for (const collider of raw.cloth?.colliders ?? []) if (!collider || !Array.isArray(collider.position) || collider.position.length !== 3 || !collider.position.every(Number.isFinite) || !Number.isFinite(collider.radius) || collider.radius <= 0 || !collider.driver || !pinById.has(collider.driver) || pinById.get(collider.driver)?.cloth) throw new Error('Invalid cloth collider.');\n return { ...rig,poseSlots:restSlot?[restSlot,...rig.poseSlots]:rig.poseSlots, version: raw.version, joints: raw.joints.map(j => ({ ...j })), chains: raw.chains.map(c => ({ ...c, joints: [...c.joints] })), ...(helpers ? { helpers } : {}), ...(raw.cloth ? { cloth: { links: raw.cloth.links.map(l => ({ ...l })), colliders: raw.cloth.colliders.map(c => ({ ...c, position: [...c.position] as [number,number,number] })) } } : {}), ...(raw.furSurface ? { furSurface: { ...raw.furSurface } } : {}) };\n}\n", "import { Quaternion, Vector3 } from 'three';\nimport { DEFAULT_FUR_DEPTH, type PinPose, type PinRecord } from './pin-types.js';\nimport type { PinParents } from './pin-types.js';\nimport { DEFAULT_MOTION, type MotionSettings } from './motion-settings.js';\nimport { ikChain } from './pin-ik.js';\nimport { windAcceleration } from './wind.js';\n\n/** Disposable secondary motion. Never writes authored pins or history. */\nexport class PinWiggle {\n private springs = new Map<string, { position: Vector3; velocity: Vector3; target:Vector3 }>();\n private topology = '';\n private lastPins: readonly PinRecord[] | null = null;\n private lastParents: PinParents | null = null;\n private awake = false;\n private windTime = 0;\n reset() { this.springs.clear(); this.topology = ''; this.lastPins = null; this.lastParents = null; this.awake = false; this.windTime = 0; }\n\n step(pins: readonly PinRecord[], parents: PinParents, seconds: number, masses?:ReadonlyMap<string,number>, windStrength = 0): { pins: readonly PinRecord[]; active: boolean } {\n if (windStrength <= 0 && !this.awake && pins === this.lastPins && parents === this.lastParents) return {pins,active:false};\n const topology = JSON.stringify(pins.map(p => [p.id,p.rest,p.rigidGroup,p.independent,p.guide,p.wiggle,p.fur,p.furDepth,p.motion,parents.get(p.id)]));\n if (topology !== this.topology) { this.reset(); this.topology = topology; }\n const groups = new Map<string, PinRecord[]>(), byId = new Map(pins.map(p => [p.id,p]));\n const key = (p: PinRecord) => p.rigidGroup ?? p.id;\n for (const pin of pins) { const group = groups.get(key(pin)) ?? []; group.push(pin); groups.set(key(pin),group); }\n const settings = new Map<string,Readonly<MotionSettings>>();\n const volumes=[...groups.values()].filter(group=>!group.every(p=>p.guide)).map(group=>Math.max(1e-9,masses?.get(group[0].id)??1)).sort((a,b)=>a-b);\n const typicalVolume=volumes[Math.floor(volumes.length/2)]??1;\n for (const pin of pins.filter(p=>p.wiggle && !p.guide)) {\n const chain=ikChain(pins,parents,pin.id,masses);\n for (const node of chain.length>1 ? chain.slice(1) : chain) if (!settings.has(key(node))) settings.set(key(node),pin.motion ?? DEFAULT_MOTION);\n }\n for (const pin of pins.filter(p=>p.wiggle && !p.guide)) settings.set(key(pin),pin.motion ?? DEFAULT_MOTION);\n // Fur belongs to the outer shell: unlike Wiggle it must not make the\n // articulated core's ancestor chain into springs.\n for (const pin of pins.filter(p=>p.fur && !p.guide)) settings.set(key(pin),pin.motion ?? DEFAULT_MOTION);\n const output = new Map<string, PinPose>(), visiting = new Set<string>();\n let active = false;\n // Exact underdamped spring integration, stable across variable frame times.\n // Clamp background-tab gaps rather than simulating missed seconds.\n const dt = Math.min(Math.max(seconds,0),.05);\n this.windTime += dt;\n const visit = (id: string) => {\n const group = groups.get(id)!;\n if (output.has(group[0].id)) return;\n if (visiting.has(id)) { for (const pin of group) output.set(pin.id,pin.pose); return; }\n visiting.add(id);\n const parent = group.map(p => byId.get(parents.get(p.id) ?? '')).find(p => p && key(p) !== id);\n if (parent) visit(key(parent));\n const parentPose = parent ? output.get(parent.id)! : undefined;\n const inherited = parent && parentPose ? new Quaternion().fromArray(parentPose.rotation).multiply(new Quaternion().fromArray(parent.pose.rotation).invert()) : new Quaternion();\n const targets = group.map(pin => {\n const position = new Vector3().fromArray(pin.pose.position);\n if (!pin.ik && parent && parentPose) position.sub(new Vector3().fromArray(parent.pose.position)).applyQuaternion(inherited).add(new Vector3().fromArray(parentPose.position));\n return { pin, position, rotation: (pin.ik ? new Quaternion() : inherited.clone()).multiply(new Quaternion().fromArray(pin.pose.rotation)) };\n });\n const center = targets.reduce((sum,p) => sum.add(p.position),new Vector3()).divideScalar(group.length);\n let position = center, rotation = new Quaternion();\n const motion=settings.get(id);\n if (motion && !group.every(p=>p.guide) && !group.some(p=>p.ik)) {\n const ratio=Math.max(.125,Math.min(8,(masses?.get(group[0].id)??typicalVolume)/typicalVolume));\n const gain=motion.strength*Math.max(.25,Math.min(4,Math.pow(1/ratio,.5*motion.massInfluence)));\n const frequency=motion.frequency*2*Math.PI, damping=Math.max(.05,Math.min(1,motion.damping*Math.pow(ratio,.25*motion.massInfluence)));\n const decay = damping * frequency, oscillation = frequency * Math.sqrt(1-damping*damping);\n const e = Math.exp(-decay*dt), c = Math.cos(oscillation*dt), s = oscillation > 1e-8 ? Math.sin(oscillation*dt)/oscillation : dt;\n let spring = this.springs.get(id);\n if (!spring) { spring = { position:center.clone(),velocity:new Vector3(),target:center.clone() }; this.springs.set(id,spring); }\n spring.position.addScaledVector(center.clone().sub(spring.target),1-gain);spring.target.copy(center);\n if(motion.strength===0){spring.position.copy(center);spring.velocity.set(0,0,0);}\n else if (windStrength > 0) spring.velocity.addScaledVector(windAcceleration(this.windTime, windStrength,\n parentPose ? Math.max(center.distanceTo(new Vector3().fromArray(parentPose.position)), 1e-3) : 1, center.toArray()), motion.strength * dt);\n const offset = spring.position.clone().sub(center), velocity = spring.velocity.clone();\n spring.position.copy(offset).multiplyScalar(c).addScaledVector(velocity.clone().addScaledVector(offset,decay),s).multiplyScalar(e).add(center);\n spring.velocity.copy(velocity).multiplyScalar(c).sub(velocity.clone().multiplyScalar(decay).addScaledVector(offset,frequency*frequency).multiplyScalar(s)).multiplyScalar(e);\n const fur = group.find(p=>p.fur), furDepth=fur?.furDepth??DEFAULT_FUR_DEPTH;\n let radius = 1;\n if (parentPose) {\n const pivot = new Vector3().fromArray(parentPose.position), desired = center.clone().sub(pivot);\n radius = desired.length();\n const direction = spring.position.clone().sub(pivot);\n if (radius > 1e-8) {\n if (direction.lengthSq() < 1e-16) direction.copy(desired);\n const length=direction.length();direction.divideScalar(length);\n const coreRadius=radius*(1-furDepth),outerRadius=radius*(1+furDepth);\n const projected=fur?Math.max(coreRadius,Math.min(outerRadius,length)):radius;\n spring.position.copy(pivot).addScaledVector(direction,projected);\n if(!fur||length<coreRadius||length>outerRadius)spring.velocity.addScaledVector(direction,-spring.velocity.dot(direction));\n rotation.setFromUnitVectors(desired.normalize(),direction);\n } else { spring.position.copy(center); spring.velocity.set(0,0,0); }\n }\n if (fur) {\n const shell = Math.max(1e-4, radius) * furDepth;\n if (shell === 0) { spring.position.copy(center); spring.velocity.set(0,0,0); rotation.identity(); }\n const displacement = spring.position.clone().sub(center);\n if (displacement.length() > shell) {\n displacement.setLength(shell); spring.position.copy(center).add(displacement);\n const outward=displacement.normalize();spring.velocity.addScaledVector(outward,-Math.max(0,spring.velocity.dot(outward)));\n }\n if(parentPose&&radius>1e-8){\n const pivot=new Vector3().fromArray(parentPose.position),desired=center.clone().sub(pivot).normalize(),direction=spring.position.clone().sub(pivot).normalize();\n rotation.setFromUnitVectors(desired,direction);\n }\n }\n const epsilon = Math.max(radius,1e-3)*1e-5;\n if (spring.position.distanceToSquared(center) < epsilon*epsilon && spring.velocity.lengthSq() < epsilon*epsilon*frequency*frequency) {\n spring.position.copy(center); spring.velocity.set(0,0,0); rotation.identity();\n } else active = true;\n position = spring.position;\n }\n for (const target of targets) output.set(target.pin.id, {\n position:target.position.sub(center).applyQuaternion(rotation).add(position).toArray(),\n rotation:rotation.clone().multiply(target.rotation).normalize().toArray(),scale:target.pin.pose.scale,\n });\n visiting.delete(id);\n };\n for (const id of groups.keys()) visit(id);\n this.lastPins = pins; this.lastParents = parents; this.awake = active;\n return { pins: active ? pins.map(pin => ({...pin,pose:output.get(pin.id)!})) : pins, active };\n }\n}\n", "import { Quaternion, Vector3 } from 'three';\nimport type { PinRecord, Point } from './pin-types.js';\nimport type { PinParents, HierarchyEdge } from './pin-types.js';\nimport { windAcceleration } from './wind.js';\nimport { DEFAULT_MOTION } from './motion-settings.js';\n\nexport type ClothLink = { a: string; b: string; length: number };\nexport type ClothCollider = { position: Point; radius: number; driver?: string };\n\n/** Connect authored cloth controls along the occupied-volume geodesic, not\n * across the shortest line through empty space. The tree is a coarse fabric\n * constraint network; the ordinary skin remains its portable GLB fallback. */\nexport function clothLinks(pins: readonly PinRecord[], parents: PinParents, edges: readonly HierarchyEdge[] = [], components?: ReadonlyMap<string, number>): ClothLink[] {\n const cloth = pins.filter(p => p.cloth && !p.guide), byId = new Map(pins.map(p => [p.id, p]));\n const result: ClothLink[] = [], seen = new Set<string>();\n const add = (a: string, b: string) => {\n if (a === b || !byId.has(a) || !byId.has(b)) return;\n const key = [a, b].sort().join('\\0'); if (seen.has(key)) return;\n seen.add(key); result.push({ a, b, length: new Vector3().fromArray(byId.get(a)!.rest).distanceTo(new Vector3().fromArray(byId.get(b)!.rest)) });\n };\n for (const pin of cloth) {\n let parent = parents.get(pin.id);\n const visited = new Set<string>();\n while (parent && byId.get(parent)?.guide && !visited.has(parent)) { visited.add(parent); parent = parents.get(parent); }\n if (parent) add(pin.id, parent);\n }\n // A topology hierarchy may root a sheet at one of its free corners. Cloth\n // still needs body attachments there; otherwise the entire sheet falls as\n // one unconstrained pair or chain despite nearby non-cloth controls.\n for (const pin of cloth) {\n const parent = byId.get(parents.get(pin.id) ?? '');\n if (parent && !parent.cloth && !parent.guide) continue;\n const anchors = edges.filter(edge => (edge.from === pin.id || edge.to === pin.id) &&\n !byId.get(edge.from === pin.id ? edge.to : edge.from)?.cloth &&\n !byId.get(edge.from === pin.id ? edge.to : edge.from)?.guide &&\n Number.isFinite(edge.geodesic ?? edge.cost));\n const same = anchors.filter(edge => !components || components.get(pin.id) === components.get(edge.from === pin.id ? edge.to : edge.from));\n const best = (same.length ? same : anchors).sort((a, b) => (a.geodesic ?? a.cost) - (b.geodesic ?? b.cost))[0];\n if (best) add(pin.id, best.from === pin.id ? best.to : best.from);\n }\n const candidates = edges.filter(e => cloth.some(p => p.id === e.from) && cloth.some(p => p.id === e.to) && Number.isFinite(e.geodesic ?? e.cost)\n && (!components || components.get(e.from) === components.get(e.to)))\n .sort((a, b) => (a.geodesic ?? a.cost) - (b.geodesic ?? b.cost));\n const root = new Map(cloth.map(p => [p.id, p.id]));\n const find = (id: string): string => { const parent = root.get(id)!; if (parent === id) return id; const top = find(parent); root.set(id, top); return top; };\n for (const edge of candidates) {\n const a = find(edge.from), b = find(edge.to); if (a === b) continue;\n root.set(a, b); add(edge.from, edge.to);\n }\n return result;\n}\n\n/** Small, fixed-step Verlet graph. The editor passes deformed voxel centers;\n * the GLB loader passes the same collider proxy driven by its joint graph. */\nexport class PinCloth {\n private particles = new Map<string, { position: Vector3; previous: Vector3 }>();\n private layout = '';\n private windTime = 0;\n private accumulator = 0;\n reset() { this.particles.clear(); this.layout = ''; this.windTime = 0; this.accumulator = 0; }\n step(pins: readonly PinRecord[], parents: PinParents, seconds: number, links: readonly ClothLink[], colliders: readonly ClothCollider[] = [], windStrength = 0): { pins: readonly PinRecord[]; active: boolean } {\n const cloth = pins.filter(p => p.cloth && !p.guide);\n if (!cloth.length) { this.reset(); return { pins, active: false }; }\n const layout = JSON.stringify([cloth.map(p => [p.id, p.rest]), links]);\n if (layout !== this.layout) { this.reset(); this.layout = layout; }\n const byId = new Map(pins.map(p => [p.id, p]));\n for (const pin of cloth) if (!this.particles.has(pin.id)) {\n const position = new Vector3().fromArray(pin.pose.position);\n this.particles.set(pin.id, { position, previous: position.clone() });\n }\n // Verlet stores displacement per step. Changing the step with render\n // timing changes its velocity and keeps a calm sheet moving.\n const h = 1 / 60;\n this.accumulator += Math.min(Math.max(seconds, 0), .05);\n const steps = Math.floor((this.accumulator + 1e-12) / h);\n this.accumulator = Math.max(0, this.accumulator - steps * h);\n const scale = Math.max(1e-4, ...links.map(link => link.length));\n // A sampled voxel shell can contain thousands of spheres. Bin it once\n // per frame, then refresh each particle's nearby set after integration so\n // a fast-moving cloth point cannot retain last frame's collision region.\n let maxRadius = 0;\n for (const collider of colliders) maxRadius = Math.max(maxRadius, collider.radius);\n const cell = Math.max(1e-4, scale * 2 + maxRadius);\n const spatial = cloth.length > 4 && colliders.length > 128;\n const bins = new Map<string, ClothCollider[]>();\n const key = (x: number, y: number, z: number) => `${x},${y},${z}`;\n if (spatial) for (const collider of colliders) {\n const p = collider.position, id = key(Math.floor(p[0] / cell), Math.floor(p[1] / cell), Math.floor(p[2] / cell));\n const bin = bins.get(id) ?? []; bin.push(collider); bins.set(id, bin);\n }\n const candidates = (position: Vector3) => {\n const found: ClothCollider[] = [];\n const search = (collider: ClothCollider) => {\n const p = collider.position, dx = position.x - p[0], dy = position.y - p[1], dz = position.z - p[2], reach = collider.radius + scale * 2;\n if (dx * dx + dy * dy + dz * dz < reach * reach) found.push(collider);\n };\n if (spatial) {\n const x = Math.floor(position.x / cell), y = Math.floor(position.y / cell), z = Math.floor(position.z / cell);\n for (let dz = -1; dz <= 1; dz++) for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++)\n for (const collider of bins.get(key(x + dx, y + dy, z + dz)) ?? []) search(collider);\n } else for (const collider of colliders) search(collider);\n return found;\n };\n for (let substep = 0; substep < steps; substep++) {\n this.windTime += h;\n for (const pin of cloth) {\n const particle = this.particles.get(pin.id)!;\n const motion = pin.motion ?? DEFAULT_MOTION;\n const velocity = particle.position.clone().sub(particle.previous).multiplyScalar(Math.exp(-motion.damping * 3 * h));\n particle.previous.copy(particle.position);\n particle.position.add(velocity).y -= 2.5 * scale * h * h;\n if (windStrength > 0 && motion.strength > 0) particle.position.addScaledVector(windAcceleration(this.windTime, windStrength, scale, particle.position.toArray()), motion.strength * h * h);\n // Pins are sparse controls, not free particles. A soft return to their\n // authored positions keeps broad sheets from drifting indefinitely.\n particle.position.lerp(new Vector3().fromArray(pin.pose.position), 1 - Math.exp(-2 * Math.PI * motion.frequency * h));\n }\n const nearby = new Map(cloth.map(pin => [pin.id, candidates(this.particles.get(pin.id)!.position)]));\n for (let iteration = 0; iteration < 6; iteration++) {\n for (const link of links) {\n const a = this.particles.get(link.a), b = this.particles.get(link.b);\n const pa = a?.position ?? new Vector3().fromArray(byId.get(link.a)?.pose.position ?? [0, 0, 0]);\n const pb = b?.position ?? new Vector3().fromArray(byId.get(link.b)?.pose.position ?? [0, 0, 0]);\n const delta = pa.clone().sub(pb), distance = delta.length(); if (distance < 1e-8) continue;\n const correction = delta.multiplyScalar((distance - link.length) / distance);\n if (a && b) { a.position.addScaledVector(correction, -.5); b.position.addScaledVector(correction, .5); }\n else if (a) a.position.sub(correction); else if (b) b.position.add(correction);\n }\n for (const [id, particle] of this.particles) for (const collider of nearby.get(id) ?? []) {\n const center = collider.position, dx = particle.position.x - center[0], dy = particle.position.y - center[1], dz = particle.position.z - center[2];\n const squared = dx * dx + dy * dy + dz * dz;\n if (squared >= collider.radius * collider.radius) continue;\n if (squared < 1e-16) particle.position.set(center[0], center[1] + collider.radius, center[2]);\n else {\n const factor = collider.radius / Math.sqrt(squared);\n particle.position.set(center[0] + dx * factor, center[1] + dy * factor, center[2] + dz * factor);\n }\n }\n }\n }\n let active = false;\n const result = pins.map(pin => {\n const particle = this.particles.get(pin.id); if (!particle) return pin;\n const target = new Vector3().fromArray(pin.pose.position), offset = particle.position.clone().sub(target);\n const velocity = particle.position.clone().sub(particle.previous);\n if (offset.lengthSq() > scale * scale * 1e-10 || velocity.lengthSq() > scale * scale * 1e-10) active = true;\n const parent = byId.get(parents.get(pin.id) ?? '');\n const rotation = parent ? new Quaternion().setFromUnitVectors(\n target.clone().sub(new Vector3().fromArray(parent.pose.position)).normalize(),\n particle.position.clone().sub(new Vector3().fromArray(parent.pose.position)).normalize()) : new Quaternion();\n return { ...pin, pose: { ...pin.pose, position: particle.position.toArray() as Point,\n rotation: rotation.multiply(new Quaternion().fromArray(pin.pose.rotation)).normalize().toArray() as [number, number, number, number] } };\n });\n return { pins: active ? result : pins, active };\n }\n}\n", "import { Vector3 } from 'three';\nimport type { PinRecord, Point } from './pin-types.js';\nimport type { ClothCollider } from './pin-cloth.js';\nimport { DEFAULT_MOTION, type MotionSettings } from './motion-settings.js';\nimport { windAcceleration, windProfile } from './wind.js';\n\ntype Edge = { a: number; b: number; length: number; bend: boolean };\ntype Triangle = { a: number; b: number; c: number };\ntype Particle = { position: Vector3; previous: Vector3; base: Vector3; share: number; anchor: number };\n\nexport function clothSurfaceMotion(pins: readonly PinRecord[]): MotionSettings {\n if (!pins.length) return { ...DEFAULT_MOTION };\n const values = pins.map(pin => pin.motion ?? DEFAULT_MOTION);\n return { ...DEFAULT_MOTION,\n damping: values.reduce((sum, motion) => sum + motion.damping, 0) / values.length,\n strength: values.reduce((sum, motion) => sum + motion.strength, 0) / values.length };\n}\n\nfunction distances(graph: readonly { to: number; length: number }[][], seeds: readonly number[]) {\n const distance = new Float64Array(graph.length).fill(Infinity);\n const heap: { node: number; distance: number }[] = [];\n const push = (node: number, value: number) => {\n let i = heap.length; heap.push({ node, distance: value });\n while (i) { const parent = (i - 1) >> 1; if (heap[parent].distance <= value) break; heap[i] = heap[parent]; i = parent; }\n heap[i] = { node, distance: value };\n };\n const pop = () => {\n const top = heap[0], last = heap.pop()!;\n if (heap.length) {\n let i = 0;\n for (;;) {\n let child = i * 2 + 1; if (child >= heap.length) break;\n if (child + 1 < heap.length && heap[child + 1].distance < heap[child].distance) child++;\n if (last.distance <= heap[child].distance) break;\n heap[i] = heap[child]; i = child;\n }\n heap[i] = last;\n }\n return top;\n };\n for (const seed of seeds) if (distance[seed] > 0) { distance[seed] = 0; push(seed, 0); }\n while (heap.length) {\n const next = pop(); if (next.distance !== distance[next.node]) continue;\n for (const edge of graph[next.node]) {\n const value = next.distance + edge.length;\n if (value < distance[edge.to]) { distance[edge.to] = value; push(edge.to, value); }\n }\n }\n return distance;\n}\n\n/** A topology-connected fabric layer over the portable skinned/voxel result.\n * Vertices at UV seams share one particle; all other vertices keep the source\n * triangle topology. Body controls attach the sheet, cloth controls release it. */\nexport class ClothSurface {\n readonly particles: Particle[];\n readonly vertexParticle: Uint32Array;\n readonly triangles: Triangle[];\n readonly edges: Edge[];\n readonly scale: number;\n private time = 0;\n private accumulator = 0;\n\n constructor(restVertices: Float32Array, indices: ArrayLike<number>, pins: readonly PinRecord[]) {\n const vertexCount = restVertices.length / 3;\n const min = new Vector3(Infinity, Infinity, Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity);\n for (let i = 0; i < vertexCount; i++) {\n const p = new Vector3().fromArray(restVertices, i * 3); min.min(p); max.max(p);\n }\n this.scale = Math.max(1e-4, max.clone().sub(min).length());\n const tolerance = this.scale * 1e-6;\n const welded = new Map<string, number>(), particles: Particle[] = [];\n this.vertexParticle = new Uint32Array(vertexCount);\n for (let i = 0; i < vertexCount; i++) {\n const p = new Vector3().fromArray(restVertices, i * 3);\n const key = p.toArray().map(value => Math.round(value / tolerance)).join(',');\n let node = welded.get(key);\n if (node === undefined) {\n node = particles.length; welded.set(key, node);\n particles.push({ position: p.clone(), previous: p.clone(), base: p, share: 0, anchor: 0 });\n }\n this.vertexParticle[i] = node;\n }\n const edgeMap = new Map<string, { a: number; b: number; opposites: number[] }>();\n const graph: { to: number; length: number }[][] = particles.map(() => []);\n const triangles: Triangle[] = [];\n const edge = (a: number, b: number, opposite: number) => {\n if (a === b) return;\n const key = a < b ? `${a}:${b}` : `${b}:${a}`;\n const existing = edgeMap.get(key);\n if (existing) existing.opposites.push(opposite);\n else edgeMap.set(key, { a, b, opposites: [opposite] });\n };\n for (let i = 0; i + 2 < indices.length; i += 3) {\n const a = this.vertexParticle[indices[i]], b = this.vertexParticle[indices[i + 1]], c = this.vertexParticle[indices[i + 2]];\n if (a === b || b === c || c === a) continue;\n triangles.push({ a, b, c }); edge(a, b, c); edge(b, c, a); edge(c, a, b);\n }\n this.triangles = triangles;\n const edges: Edge[] = [];\n for (const value of edgeMap.values()) {\n const length = particles[value.a].base.distanceTo(particles[value.b].base);\n edges.push({ a: value.a, b: value.b, length, bend: false });\n graph[value.a].push({ to: value.b, length }); graph[value.b].push({ to: value.a, length });\n if (value.opposites.length === 2 && value.opposites[0] !== value.opposites[1]) {\n const a = value.opposites[0], b = value.opposites[1];\n edges.push({ a, b, length: particles[a].base.distanceTo(particles[b].base), bend: true });\n }\n }\n this.edges = edges;\n const nearest = (point: Point) => {\n const p = new Vector3().fromArray(point); let found = 0, best = Infinity;\n for (let i = 0; i < particles.length; i++) {\n const d = particles[i].base.distanceToSquared(p); if (d < best) { best = d; found = i; }\n }\n return found;\n };\n const cloth = pins.filter(pin => pin.cloth && !pin.guide).map(pin => nearest(pin.rest));\n const body = pins.filter(pin => !pin.cloth && !pin.guide).map(pin => nearest(pin.rest));\n const clothDistance = distances(graph, cloth), bodyDistance = distances(graph, body);\n for (let i = 0; i < particles.length; i++) {\n const a = clothDistance[i], b = bodyDistance[i];\n particles[i].share = Number.isFinite(a) && Number.isFinite(b) ? b / Math.max(1e-6, a + b) : Number.isFinite(a) ? 1 : 0;\n particles[i].anchor = Number.isFinite(b) ? Math.exp(-b / (.12 * this.scale)) : 0;\n }\n this.particles = particles;\n }\n\n get movableCount() { return this.particles.filter(p => p.share > .25).length; }\n\n reset() {\n this.time = 0;\n this.accumulator = 0;\n for (const particle of this.particles) particle.position.copy(particle.base), particle.previous.copy(particle.base);\n }\n\n step(baseVertices: Float32Array, seconds: number, windStrength: number, colliders: readonly ClothCollider[] = [], motion: Readonly<MotionSettings> = DEFAULT_MOTION) {\n const count = this.particles.length, base = Array.from({ length: count }, () => new Vector3()), samples = new Uint32Array(count);\n for (let i = 0; i < this.vertexParticle.length; i++) {\n const node = this.vertexParticle[i]; base[node].add(new Vector3().fromArray(baseVertices, i * 3)); samples[node]++;\n }\n for (let i = 0; i < count; i++) {\n base[i].divideScalar(samples[i] || 1);\n const particle = this.particles[i], delta = base[i].clone().sub(particle.base);\n particle.position.add(delta); particle.previous.add(delta); particle.base.copy(base[i]);\n }\n // Keep Verlet displacement in one time unit even when GPU frames arrive\n // unevenly; carry unused time rather than changing the integration step.\n const h = 1 / 60;\n this.accumulator += Math.min(Math.max(seconds, 0), .05);\n const steps = Math.floor((this.accumulator + 1e-12) / h);\n this.accumulator = Math.max(0, this.accumulator - steps * h);\n const profile = windProfile(windStrength), pressureScale = profile.load ? .025 * profile.surfaceLoad / profile.load : 0;\n const radius = Math.max(1e-4, ...colliders.map(collider => collider.radius));\n const cell = radius * 2;\n const bins = new Map<number, ClothCollider[]>();\n // Hash collisions only add candidates; the distance test below remains exact.\n const key = (x: number, y: number, z: number) => (Math.imul(x, 73856093) ^ Math.imul(y, 19349663) ^ Math.imul(z, 83492791)) | 0;\n for (const collider of colliders) {\n const p = collider.position, id = key(Math.floor(p[0] / cell), Math.floor(p[1] / cell), Math.floor(p[2] / cell));\n const bin = bins.get(id) ?? []; bin.push(collider); bins.set(id, bin);\n }\n for (let step = 0; step < steps; step++) {\n this.time += h;\n const force = Array.from({ length: count }, () => new Vector3());\n const area = new Float32Array(count);\n if (pressureScale && motion.strength) for (const triangle of this.triangles) {\n const a = this.particles[triangle.a].position, b = this.particles[triangle.b].position, c = this.particles[triangle.c].position;\n const normal = b.clone().sub(a).cross(c.clone().sub(a));\n const surface = normal.length(); if (surface < 1e-10) continue;\n normal.divideScalar(surface);\n const center = a.clone().add(b).add(c).divideScalar(3);\n const wind = windAcceleration(this.time, windStrength, this.scale, center.toArray());\n // Normal pressure bends the sheet; a small tangential drag carries\n // near-parallel fabric rather than letting it ignore the wind entirely.\n const pressure = normal.multiplyScalar(wind.dot(normal)).addScaledVector(wind, .12)\n .multiplyScalar(pressureScale);\n for (const node of [triangle.a, triangle.b, triangle.c]) { force[node].addScaledVector(pressure, surface); area[node] += surface; }\n }\n for (let i = 0; i < count; i++) {\n const particle = this.particles[i], share = particle.share;\n if (share < 1e-4) { particle.position.copy(particle.base); particle.previous.copy(particle.base); continue; }\n const velocity = particle.position.clone().sub(particle.previous).multiplyScalar(Math.exp(-motion.damping * 3 * h));\n particle.previous.copy(particle.position);\n particle.position.add(velocity).y -= 2.5 * this.scale * share * h * h;\n if (area[i]) particle.position.addScaledVector(force[i], motion.strength * share * h * h / area[i]);\n const anchor = 1 - Math.exp(-(1.5 + 60 * particle.anchor ** 2) * h);\n particle.position.lerp(particle.base, anchor);\n }\n for (let iteration = 0; iteration < 5; iteration++) {\n for (const edge of this.edges) {\n const a = this.particles[edge.a], b = this.particles[edge.b];\n const difference = b.position.clone().sub(a.position), length = difference.length();\n if (length < 1e-8) continue;\n const wa = a.share * a.share, wb = b.share * b.share, total = wa + wb;\n if (total < 1e-8) continue;\n const strength = edge.bend ? .14 : .72;\n difference.multiplyScalar((length - edge.length) * strength / (length * total));\n a.position.addScaledVector(difference, wa); b.position.addScaledVector(difference, -wb);\n }\n }\n if (colliders.length) for (const particle of this.particles) {\n if (particle.share < .35) continue;\n // A point projected out of one proxy sphere can still be inside its\n // neighbor. Resolve that overlap here instead of alternating contacts\n // on successive animation frames.\n for (let contact = 0; contact < 8; contact++) {\n const p = particle.position, px = p.x / cell, py = p.y / cell, pz = p.z / cell;\n const x = Math.floor(px), y = Math.floor(py), z = Math.floor(pz);\n const sx = px - x < .5 ? -1 : 1, sy = py - y < .5 ? -1 : 1, sz = pz - z < .5 ? -1 : 1;\n let chosen: ClothCollider | undefined, penetration = 0;\n // Cell width is twice the largest radius, so only the nearest neighbor\n // on each axis can contain a sphere reaching this particle.\n for (let iz = 0; iz < 2; iz++) for (let iy = 0; iy < 2; iy++) for (let ix = 0; ix < 2; ix++) {\n for (const collider of bins.get(key(x + ix * sx, y + iy * sy, z + iz * sz)) ?? []) {\n const center = collider.position, bx = particle.base.x - center[0], by = particle.base.y - center[1], bz = particle.base.z - center[2];\n if (bx * bx + by * by + bz * bz < collider.radius * collider.radius * 1.04) continue;\n const vx = p.x - center[0], vy = p.y - center[1], vz = p.z - center[2];\n const depth = collider.radius - Math.hypot(vx, vy, vz);\n if (depth > penetration) { penetration = depth; chosen = collider; }\n }\n }\n if (!chosen || penetration < this.scale * 1e-7) break;\n const center = chosen.position, delta = p.clone().sub(new Vector3().fromArray(center));\n if (delta.lengthSq() < 1e-12) delta.copy(particle.base).sub(new Vector3().fromArray(center));\n p.copy(new Vector3().fromArray(center).add(delta.setLength(chosen.radius)));\n }\n }\n }\n const result = new Float32Array(baseVertices.length);\n for (let i = 0; i < this.vertexParticle.length; i++) result.set(this.particles[this.vertexParticle[i]].position.toArray(), i * 3);\n return result;\n }\n}\n", "import { Matrix4, Quaternion, Vector3 } from 'three';\nimport type { PinPose, PinRecord } from './pin-types.js';\nexport interface BoneDriver { id:string; influences:readonly {id:string;weight:number}[] }\nconst matrix=(pose:PinPose)=>new Matrix4().compose(new Vector3().fromArray(pose.position),new Quaternion().fromArray(pose.rotation),new Vector3().fromArray(pose.scale));\n/** Drivers reference actual fitted bones, never hidden authoring nodes. The\n * driven bone's reference frame remains independently FK editable. */\nexport function driverDelta(driver:BoneDriver,pins:readonly PinRecord[],reference:readonly PinRecord[]){\n const affine=new Matrix4();affine.elements.fill(0);\n const rotation=new Quaternion(0,0,0,0),scale=new Vector3();let hemisphere:Quaternion|undefined;\n for(const influence of driver.influences){\n const current=pins.find(p=>p.id===influence.id)!.pose,rest=reference.find(p=>p.id===influence.id)!.pose,w=influence.weight;\n const delta=matrix(current).multiply(matrix(rest).invert()),q=new Quaternion().fromArray(current.rotation).multiply(new Quaternion().fromArray(rest.rotation).invert());\n hemisphere??=q;const sign=hemisphere.dot(q)<0?-w:w;\n delta.elements.forEach((value,i)=>affine.elements[i]+=value*w);\n rotation.set(rotation.x+q.x*sign,rotation.y+q.y*sign,rotation.z+q.z*sign,rotation.w+q.w*sign);\n scale.addScaledVector(new Vector3().fromArray(current.scale).divide(new Vector3().fromArray(rest.scale)),w);\n }\n if(!driver.influences.length){affine.identity();rotation.identity();scale.setScalar(1);}\n return {affine,rotation:rotation.normalize(),scale};\n}\nexport function drivenPose(pose:PinPose,driver:BoneDriver,pins:readonly PinRecord[],reference:readonly PinRecord[]):PinPose{\n const delta=driverDelta(driver,pins,reference);\n return {position:new Vector3().fromArray(pose.position).applyMatrix4(delta.affine).toArray(),rotation:delta.rotation.multiply(new Quaternion().fromArray(pose.rotation)).normalize().toArray(),scale:delta.scale.multiply(new Vector3().fromArray(pose.scale)).toArray()};\n}\nexport function referencePose(pose:PinPose,driver:BoneDriver,pins:readonly PinRecord[],reference:readonly PinRecord[]):PinPose{\n const delta=driverDelta(driver,pins,reference);\n if(Math.abs(delta.affine.determinant())<1e-10)throw new Error('This blended bone frame is singular. Adjust its driving bones before editing its position.');\n return {position:new Vector3().fromArray(pose.position).applyMatrix4(delta.affine.invert()).toArray(),rotation:delta.rotation.invert().multiply(new Quaternion().fromArray(pose.rotation)).normalize().toArray(),scale:new Vector3().fromArray(pose.scale).divide(delta.scale).toArray()};\n}\nexport function driveRig(pins:readonly PinRecord[],reference:readonly PinRecord[],drivers:readonly BoneDriver[]){\n return pins.map(pin=>{const driver=drivers.find(d=>d.id===pin.id);return driver?{...pin,pose:drivenPose(pin.pose,driver,pins,reference)}:pin;});\n}\n", "import { BufferAttribute, MeshPhysicalMaterial, MeshStandardMaterial, SkinnedMesh, Vector2, type BufferGeometry, type Material, type Object3D, type Texture } from 'three';\nimport { MeshPhysicalNodeMaterial, MeshStandardNodeMaterial, type Node } from 'three/webgpu';\nimport { attribute, float, mix, normalMap, positionLocal, texture, uniform, uv, varying, vec2, vec3, vec4 } from 'three/tsl';\nimport { bindTextureSlot } from '../rendering/texture-slot.js';\nimport type { RigDescriptor } from './rig-extension.js';\n\ninterface Surface { mesh: SkinnedMesh; geometry: BufferGeometry; modified: BufferGeometry; material: Material | Material[]; variants: MeshStandardNodeMaterial[] }\n\n/** Optional GPU detail for a portable skinned GLB. Nothing is written into its\n * fallback material or geometry, and the variant is absent without Fur pins. */\nexport class FurSurface {\n readonly surfaces: Surface[] = [];\n private height: Texture | null = null;\n private clock = uniform(0);\n private wind = uniform(0);\n\n constructor(scene: Object3D, descriptor: RigDescriptor, nodes: readonly Object3D[], helpers: readonly Object3D[]) {\n const depth = new Map<Object3D, number>();\n descriptor.pins.forEach((pin, i) => depth.set(nodes[i], pin.fur ? (pin.furDepth ?? .1) : 0));\n descriptor.helpers?.forEach((helper, i) => depth.set(helpers[i], helper.influences.reduce((sum, influence) => {\n const index = descriptor.joints.findIndex(joint => joint.node === influence.node);\n const pin = descriptor.pins[index];\n return sum + (pin?.fur ? (pin.furDepth ?? .1) * influence.weight : 0);\n }, 0)));\n scene.traverse(object => {\n if (!(object instanceof SkinnedMesh)) return;\n const geometry = object.geometry, indices = geometry.getAttribute('skinIndex'), weights = geometry.getAttribute('skinWeight');\n if (!indices || !weights || !geometry.getAttribute('uv') || !geometry.getAttribute('normal')) return;\n if ((Array.isArray(object.material) ? object.material : [object.material]).some(material => !(material instanceof MeshStandardMaterial))) return;\n const values = new Float32Array(indices.count);\n for (let v = 0; v < values.length; v++) for (let lane = 0; lane < 4; lane++) {\n values[v] += (depth.get(object.skeleton.bones[indices.getComponent(v, lane)]) ?? 0) * weights.getComponent(v, lane);\n }\n if (!values.some(value => value > 1e-5)) return;\n const modified = geometry.clone();\n modified.setAttribute('furDepth', new BufferAttribute(values, 1));\n const surface: Surface = { mesh: object, geometry, modified, material: object.material, variants: [] };\n object.geometry = modified;\n this.surfaces.push(surface);\n });\n this.rebuild();\n }\n\n setHeightMap(height: Texture | null) { if (this.height !== height) { this.height = height; this.rebuild(); } }\n update(seconds: number, windStrength: number) {\n this.clock.value += Math.max(0, Math.min(seconds, .1));\n this.wind.value = windStrength;\n }\n /** GLTFExporter must only see standard portable materials and attributes. */\n setPortable(portable: boolean) {\n for (const surface of this.surfaces) {\n surface.mesh.geometry = portable ? surface.geometry : surface.modified;\n surface.mesh.material = portable ? surface.material : Array.isArray(surface.material) ? surface.variants : surface.variants[0];\n }\n }\n dispose() {\n this.setPortable(true);\n for (const surface of this.surfaces) {\n surface.modified.dispose(); surface.mesh.geometry = surface.geometry;\n for (const variant of surface.variants) variant.dispose();\n }\n this.surfaces.length = 0;\n }\n private rebuild() {\n for (const surface of this.surfaces) {\n const sources = Array.isArray(surface.material) ? surface.material : [surface.material];\n const variants = sources.map(source => this.material(source as MeshStandardMaterial));\n this.setPortable(true);\n for (const old of surface.variants) old.dispose();\n surface.variants = variants;\n }\n this.setPortable(false);\n }\n private material(source: MeshStandardMaterial) {\n const material = source instanceof MeshPhysicalMaterial ? new MeshPhysicalNodeMaterial() : new MeshStandardNodeMaterial();\n material.copy(source);\n material.name = `${source.name || 'Material'} \u00B7 Fur texture motion`;\n const coordinates = uv();\n const signal = source.map ?? source.normalMap ?? source.roughnessMap ?? source.metalnessMap ?? source.emissiveMap ?? source.aoMap ?? source.alphaMap ?? this.height;\n if (!signal) return material;\n const depth = attribute('furDepth', 'float' as const).mul(5).clamp(0, 1);\n const skinnedDelta = varying(positionLocal.sub(attribute('position', 'vec3' as const)), 'furSkinDelta') as Node<'vec3'>;\n const signalSlot = ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'aoMap', 'alphaMap'].find(slot => Reflect.get(source, slot) === signal) ?? 'furHeightMap';\n const pixel = uniform(new Vector2());\n const updatePixel = (map: Texture) => {\n const dimensions = map.image as { width?: number; height?: number } | undefined;\n pixel.value.set(1 / Math.max(1, dimensions?.width ?? 1024), 1 / Math.max(1, dimensions?.height ?? 1024));\n };\n updatePixel(signal);\n const movement = projectMotionToUv(skinnedDelta, coordinates).clamp(pixel.mul(-1.5), pixel.mul(1.5));\n const heightNode = this.height ? texture(this.height, uv(this.height.channel)) : null;\n if (heightNode && this.height) bindTextureSlot(material, 'furHeightMap', this.height,\n [heightNode], value => { this.height = value; if (signalSlot === 'furHeightMap') updatePixel(value); });\n const height = heightNode ? heightNode.r : float(.5);\n const raised = mix(.65, 1.35, height);\n const phase = coordinates.dot(vec2(31, 43)).add(height.sub(.5).mul(2.4)).add(this.clock.mul(this.wind).mul(1.7));\n const gust = vec2(phase.sin(), phase.mul(1.31).cos()).mul(pixel).mul(this.wind.mul(.65));\n // A shared subpixel-to-two-pixel UV flow keeps color, normal, ORM, AO and\n // opacity aligned. The field follows the skinned surface and can shimmer\n // with wind; height modulates movement rather than drawing synthetic hair.\n const shift = movement.add(gust).mul(depth).mul(raised)\n .clamp(pixel.mul(-2), pixel.mul(2)).toVar('furTextureShift');\n const sample = (map: Texture, slot: string) => {\n const node = texture(map, uv(map.channel).add(shift));\n node.updateMatrix = true;\n bindTextureSlot(material, slot, map, [node], value => { Reflect.set(source, slot, value); if (signalSlot === slot) updatePixel(value); });\n return node;\n };\n const base = source.map ? sample(source.map, 'map') : vec4(1);\n material.colorNode = base.mul(vec4(source.color.r, source.color.g, source.color.b, 1));\n if (source.alphaMap) material.opacityNode = sample(source.alphaMap, 'alphaMap').g;\n if (source.normalMap) material.normalNode = normalMap(sample(source.normalMap, 'normalMap').xyz,\n vec2(source.normalScale.x, source.normalScale.y));\n material.roughnessNode = source.roughnessMap ? sample(source.roughnessMap, 'roughnessMap').g.mul(source.roughness) : float(source.roughness);\n material.metalnessNode = source.metalnessMap ? sample(source.metalnessMap, 'metalnessMap').b.mul(source.metalness) : float(source.metalness);\n if (source.aoMap) material.aoNode = float(1).sub(float(1).sub(sample(source.aoMap, 'aoMap').r).mul(source.aoMapIntensity));\n if (source.emissiveMap) material.emissiveNode = sample(source.emissiveMap, 'emissiveMap').rgb.mul(vec3(\n source.emissive.r * source.emissiveIntensity,\n source.emissive.g * source.emissiveIntensity,\n source.emissive.b * source.emissiveIntensity));\n material.userData.furSurface = { heightMapped: Boolean(this.height), motionMapped: true };\n return material;\n }\n}\n\n/** Convert the current skin displacement into a local UV offset. The metric\n * inversion avoids assuming that U/V align with world X/Y or have equal scale. */\nfunction projectMotionToUv(movement: Node<'vec3'>, coordinates: Node<'vec2'>) {\n const dUvDx = coordinates.dFdx(), dUvDy = coordinates.dFdy();\n const dPosDx = positionLocal.dFdx(), dPosDy = positionLocal.dFdy();\n const determinant = dUvDx.x.mul(dUvDy.y).sub(dUvDx.y.mul(dUvDy.x));\n const safe = determinant.abs().max(1e-10).mul(determinant.lessThan(0).select(-1, 1));\n const dPosDu = dPosDx.mul(dUvDy.y).sub(dPosDy.mul(dUvDx.y)).div(safe);\n const dPosDv = dPosDy.mul(dUvDx.x).sub(dPosDx.mul(dUvDx.y)).div(safe);\n const uu = dPosDu.dot(dPosDu), vv = dPosDv.dot(dPosDv), uvMetric = dPosDu.dot(dPosDv);\n const metric = uu.mul(vv).sub(uvMetric.mul(uvMetric)).max(1e-12);\n const u = movement.dot(dPosDu), v = movement.dot(dPosDv);\n return vec2(vv.mul(u).sub(uvMetric.mul(v)).div(metric), uu.mul(v).sub(uvMetric.mul(u)).div(metric));\n}\n", "// @ts-check\n\n/** Keep material-slot texture replacement connected to the shader nodes.\n * @param {import('three').Material} material\n * @param {string} slot\n * @param {import('three').Texture} initial\n * @param {{value: import('three').Texture}[]} nodes\n * @param {((value: import('three').Texture) => void)=} onChange\n */\nexport function bindTextureSlot(material, slot, initial, nodes, onChange) {\n let current = initial;\n Object.defineProperty(material, slot, {\n configurable: true, enumerable: true,\n get: () => current,\n set: (/** @type {import('three').Texture} */ value) => {\n value.channel = current.channel;\n value.offset = current.offset;\n value.repeat = current.repeat;\n value.center = current.center;\n value.rotation = current.rotation;\n current = value;\n for (const node of nodes) node.value = value;\n onChange?.(value);\n material.needsUpdate = true;\n },\n });\n}\n"],
|
|
5
|
-
"mappings": ";;;AAAA,SAAS,gBAAgB,iBAAiB,WAAAA,UAAS,UAAU,cAAAC,aAAY,eAAAC,cAAa,WAAAC,gBAAsE;;;ACUrJ,IAAM,oBAAoB;AAC1B,IAAM,gBAAgB;AAEtB,IAAM,iBAAiB,CAAC,OAAM,OAAM,QAAO,QAAO,QAAO,OAAM,YAAW,OAAO;;;ACZjF,IAAM,uBAAuB;;;ACA7B,IAAM,iBAA2C,EAAE,OAAO,KAAI,WAAW,MAAM,IAAE,KAAK,KAAK,SAAS,MAAK,eAAc,GAAE,UAAS,EAAE;AACpI,SAAS,uBAAuB,OAAuB;AAC5D,MAAI,CAAC,SAAS,CAAC,OAAO,SAAS,MAAM,KAAK,KAAK,MAAM,QAAQ,KAAK,MAAM,QAAQ,KAC3E,CAAC,OAAO,SAAS,MAAM,SAAS,KAAK,MAAM,YAAY,QAAO,MAAM,YAAY,KAChF,CAAC,OAAO,SAAS,MAAM,OAAO,KAAK,MAAM,UAAU,QAAO,MAAM,UAAU,KAC1E,CAAC,OAAO,SAAS,MAAM,aAAa,KAAK,MAAM,gBAAc,KAAK,MAAM,gBAAc,KACtF,CAAC,OAAO,SAAS,MAAM,QAAQ,KAAK,MAAM,WAAS,KAAK,MAAM,WAAS,EAAG,OAAM,IAAI,MAAM,0BAA0B;AAC3H;;;ACRA,SAAS,YAAY,eAAe;AAE7B,IAAM,wBAA+C,EAAC,MAAK,QAAO,MAAK,QAAO,KAAI,MAAK,KAAI,IAAG;AAC9F,SAAS,qBAAqB,OAAoB;AACvD,MAAG,OAAO,SAAO,WAAc,CAAC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AAK,SAAS,CAAC,GAAG,aAAa,KAAK,IAAI;AAAG,UAAI,CAAC,IAAK;AACjE,YAAM,aAAa,mBAAmB,KAAK,KAAK,OAAO,UAAU,GAAG,KAAK,UAAU,UAAU,CAAC;AAC9F,YAAM,QAAoB,MAAM,QAAQ,IAAI,WAAW,OAAO,IAAI,OAAK,KAAK,OAAO,cAAc,QAAQ,EAAE,IAAI,CAAC,CAAC;AACjH,YAAM,UAAsB,MAAM,QAAQ,KAAK,WAAW,WAAW,CAAC,GAAG,IAAI,OAAK,KAAK,OAAO,cAAc,QAAQ,EAAE,IAAI,CAAC,CAAC;AAC5H,iBAAW,QAAQ,CAAC,GAAG,OAAO,GAAG,OAAO,GAAG;AAAE,YAAI,SAA0B;AAAM,eAAO,UAAU,WAAW,MAAO,UAAS,OAAO;AAAQ,YAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,gCAAgC;AAAA,MAAG;AAC5M,YAAM,UAAU,IAAI,sBAAsB,OAAO,YAAY,OAAO,KAAK,YAAY,OAAO;AAC5F,UAAI,WAAW,YAAY;AACzB,cAAM,SAAS,MAAM,KAAK,OAAO,cAAc,WAAW,WAAW,WAAW,aAAa;AAC7F,eAAO,UAAU,WAAW,WAAW,YAAY;AACnD,gBAAQ,gBAAgB,MAAM;AAAA,MAChC;AACA,eAAS,IAAI,OAAO,OAAO;AAAA,IAC7B;AAAA,EACF;AACF;AAEO,SAAS,mCAAmC,QAAoB;AACrE,SAAO,SAAS,YAAU,IAAI,iCAAiC,MAAM,CAAC;AAAG,SAAO;AAClF;AAEO,SAAS,kBAAkB,OAAiB;AAAE,SAAO,SAAS,IAAI,KAAK;AAAG;",
|
|
4
|
+
"sourcesContent": ["import { AnimationMixer, PropertyBinding, Matrix4, Object3D, Quaternion, SkinnedMesh, Vector3, type AnimationClip, type BufferGeometry, type Texture } from 'three';\nimport type { GLTF, GLTFLoader, GLTFParser } from 'three/addons/loaders/GLTFLoader.js';\nimport type { PinRecord, PinPose } from './pin-types.js';\nimport { NEEDLE_DEFORMATION_RIG, parseRigDescriptor, type RigDescriptor } from './rig-extension.js';\nimport { definedPoses, restPoseSlot, resolvePose } from './pose-slots.js';\nimport { solvePlantedPinIKGoals, solveLocalPinIK, ikChain } from './pin-ik.js';\nimport { PinWiggle } from './pin-wiggle.js';\nimport { PinCloth, type ClothCollider } from './pin-cloth.js';\nimport { ClothSurface, clothSurfaceMotion } from './cloth-surface.js';\nimport { driveRig, referencePose, type BoneDriver } from './rig-drivers.js';\nimport { FurSurface } from './fur-surface.js';\n\nconst runtimes = new WeakMap<Object3D, DeformationRigRuntime>();\nconst matrix = (pose: PinPose) => new Matrix4().compose(new Vector3().fromArray(pose.position), new Quaternion().fromArray(pose.rotation), new Vector3().fromArray(pose.scale));\nfunction pose(matrix: Matrix4): PinPose {\n const p = new Vector3(), q = new Quaternion(), s = new Vector3(); matrix.decompose(p, q, s);\n return { position: p.toArray(), rotation: q.normalize().toArray(), scale: s.toArray() };\n}\n\ntype RuntimeClothMesh = { mesh: SkinnedMesh; original: BufferGeometry; positions: Float32Array; surface: ClothSurface; clothIds: string[]; elapsed: number };\n\n/** Lightweight articulated runtime. Skinning stays on the renderer's GPU;\n * only the small joint graph is solved on the CPU, with no voxel dependency. */\nexport class DeformationRigRuntime {\n /** Stable pin IDs mapped to the glTF bone nodes. Edit a bone for FK. */\n readonly bones = new Map<string, Object3D>();\n /** Scene-local goal objects for IK and secondary controls. Move one before `update()`. */\n readonly targets = new Map<string, Object3D>();\n readonly parents = new Map<string, string>();\n readonly masses = new Map<string, number>();\n readonly helpers: { bone: Object3D; influences: { id: string; weight: number }[] }[] = [];\n private helperReferences = new Map<Object3D, PinPose>();\n private referencePins: readonly PinRecord[] = [];\n private localFrames = new Map<Object3D, number[]>();\n private fittedDrivers:BoneDriver[]=[];\n get drivers(): readonly BoneDriver[] { return this.fittedDrivers; }\n private articulated(pins:readonly PinRecord[]) { const helpers=new Set(this.drivers.map(d=>d.id));return pins.filter(p=>!helpers.has(p.id)); }\n private springs = new PinWiggle();\n private cloth = new PinCloth();\n private clothMeshes: RuntimeClothMesh[] = [];\n readonly furSurface: FurSurface | null;\n private mixer: AnimationMixer;\n private base: readonly PinRecord[];\n private displayed: readonly PinRecord[];\n private disposed = false;\n private dirty = true;\n private targetFrames = new Map<string, string>();\n private editedTargets = new Set<string>();\n private mixedPoseWeights = new Map<number, number>();\n private mixingStaticPoses = false;\n private animationFrames = new Map<Object3D, {position:Vector3;rotation:Quaternion;scale:Vector3;displayedPosition:Vector3;displayedRotation:Quaternion;displayedScale:Vector3}>();\n windStrength:number;\n activePose: number;\n constructor(readonly scene: Object3D, readonly descriptor: RigDescriptor, nodes: readonly Object3D[], readonly clips: readonly AnimationClip[], helperNodes: readonly Object3D[] = []) {\n this.base = descriptor.pins; this.displayed = this.base; this.activePose = descriptor.activePose;this.windStrength=descriptor.windStrength??0;\n descriptor.joints.forEach((joint, i) => {\n const pin = descriptor.pins[i]; this.bones.set(pin.id, nodes[i]); this.masses.set(pin.id, joint.mass);\n if (joint.parent !== null) this.parents.set(pin.id, descriptor.pins[descriptor.joints.findIndex(j => j.node === joint.parent)].id);\n if (pin.ik || pin.wiggle || pin.cloth || pin.fur) { const target = new Object3D(); target.name = `${pin.id} target`; target.visible = false; scene.add(target); this.targets.set(pin.id, target); }\n });\n descriptor.helpers?.forEach((h, i) => this.helpers.push({ bone: helperNodes[i], influences: h.influences.map(w => ({ id: descriptor.pins[descriptor.joints.findIndex(j => j.node === w.node)].id, weight: w.weight })) }));\n if(descriptor.version>=3)this.fittedDrivers=this.helpers.map(h=>({id:[...this.bones].find(([,bone])=>bone===h.bone)![0],influences:h.influences}));\n this.furSurface = descriptor.pins.some(pin => pin.fur) ? new FurSurface(scene, descriptor, nodes, helperNodes) : null;\n this.mixer = new AnimationMixer(scene);\n const bones = [...this.bones.values()];\n const animated = clips.some(clip => clip.tracks.some(track => {\n const node = PropertyBinding.findNode(scene, PropertyBinding.parseTrackName(track.name).nodeName);\n return bones.some(bone => bone === node);\n }));\n if (animated) for (const bone of bones) this.animationFrames.set(bone, this.localFrame(bone));\n this.selectPose(this.activePose);\n if (descriptor.pins.some(pin => pin.cloth)) this.prepareClothMeshes();\n }\n /** Supply a Fur height atlas. The loader calls this for embedded atlases. */\n setFurHeightMap(texture: Texture | null) { this.furSurface?.setHeightMap(texture); }\n /** Keep ordinary glTF materials on renderers without the Fur node shader. */\n setPortableMaterials(portable: boolean) { this.furSurface?.setPortable(portable); }\n /** Joint records in the last displayed frame, including secondary motion. */\n get pins() { return this.displayed; }\n /** Return stable pin IDs from the root of the selected chain to its endpoint. */\n chain(id: string) { return ikChain(this.articulated(this.base), this.parents, id, this.masses).map(p => p.id); }\n /** Clear accumulated spring and Cloth motion after a pose or editor reset. */\n resetSecondary() { this.springs.reset(); this.cloth.reset(); for (const entry of this.clothMeshes) { entry.surface.reset(); entry.elapsed = 0; } }\n\n private prepareClothMeshes() {\n this.scene.updateWorldMatrix(true, true);\n const inverse = this.scene.matrixWorld.clone().invert();\n const candidates: { mesh: SkinnedMesh; original: BufferGeometry; positions: Float32Array; rest: Float32Array; indices: ArrayLike<number> }[] = [];\n this.scene.traverse(object => {\n if (!(object instanceof SkinnedMesh)) return;\n const mesh = object, position = mesh.geometry.getAttribute('position');\n if (!position) return;\n const original = mesh.geometry, positions = new Float32Array(position.count * 3), rest = new Float32Array(position.count * 3);\n for (let i = 0; i < position.count; i++) {\n const point = new Vector3().fromBufferAttribute(position, i);\n positions.set(point.toArray(), i * 3);\n rest.set(mesh.applyBoneTransform(i, point).applyMatrix4(mesh.matrixWorld).applyMatrix4(inverse).toArray(), i * 3);\n }\n candidates.push({ mesh, original, positions, rest,\n indices: original.index?.array ?? Uint32Array.from({ length: position.count }, (_, i) => i) });\n });\n const assigned = new Map<SkinnedMesh, PinRecord[]>();\n for (const pin of this.descriptor.pins.filter(record => record.cloth && !record.guide)) {\n const point = new Vector3().fromArray(pin.pose.position);\n let best = Infinity, owner: SkinnedMesh | null = null;\n for (const candidate of candidates) for (let i = 0; i < candidate.rest.length; i += 3) {\n const dx = candidate.rest[i] - point.x, dy = candidate.rest[i + 1] - point.y, dz = candidate.rest[i + 2] - point.z;\n const distance = dx * dx + dy * dy + dz * dz;\n if (distance < best) { best = distance; owner = candidate.mesh; }\n }\n if (owner) assigned.set(owner, [...assigned.get(owner) ?? [], pin]);\n }\n for (const candidate of candidates) {\n const cloth = assigned.get(candidate.mesh); if (!cloth?.length) continue;\n const fitted = new Set(this.drivers.map(driver => driver.id));\n const pins = [...this.descriptor.pins.filter(pin => !pin.cloth && !pin.guide && !fitted.has(pin.id)), ...cloth]\n .map(pin => ({ ...pin, rest: pin.pose.position }));\n candidate.mesh.geometry = candidate.original.clone();\n this.clothMeshes.push({ mesh: candidate.mesh, original: candidate.original, positions: candidate.positions,\n surface: new ClothSurface(candidate.rest, candidate.indices, pins), clothIds: cloth.map(pin => pin.id), elapsed: 0 });\n }\n }\n\n private updateClothMeshes(seconds: number, colliders: readonly ClothCollider[]) {\n if (!this.clothMeshes.length) return;\n this.scene.updateWorldMatrix(true, true);\n const sceneInverse = this.scene.matrixWorld.clone().invert();\n for (const entry of this.clothMeshes) {\n // Bones still render every frame; the coarse fabric solve runs at 30 Hz.\n entry.elapsed += Math.max(0, seconds);\n if (entry.elapsed < 1 / 30) continue;\n const step = Math.min(entry.elapsed, .05); entry.elapsed = 0;\n const { mesh, positions, surface } = entry, target = mesh.geometry.getAttribute('position');\n mesh.skeleton.update();\n const base = new Float32Array(positions.length);\n for (let i = 0; i < positions.length / 3; i++) {\n const point = new Vector3().fromArray(positions, i * 3);\n base.set(mesh.applyBoneTransform(i, point).applyMatrix4(mesh.matrixWorld).applyMatrix4(sceneInverse).toArray(), i * 3);\n }\n const moved = surface.step(base, step, this.windStrength, colliders,\n clothSurfaceMotion(this.base.filter(pin => entry.clothIds.includes(pin.id))));\n const skinIndex = mesh.geometry.getAttribute('skinIndex'), skinWeight = mesh.geometry.getAttribute('skinWeight');\n const meshInverse = mesh.matrixWorld.clone().invert().multiply(this.scene.matrixWorld);\n const bone = new Matrix4(), blended = new Matrix4(), skin = new Matrix4();\n for (let i = 0; i < positions.length / 3; i++) {\n const elements = blended.elements; elements.fill(0);\n for (let j = 0; j < 4; j++) {\n const weight = skinWeight.getComponent(i, j); if (!weight) continue;\n bone.fromArray(mesh.skeleton.boneMatrices!, skinIndex.getComponent(i, j) * 16);\n for (let k = 0; k < 16; k++) elements[k] += bone.elements[k] * weight;\n }\n skin.copy(mesh.bindMatrixInverse).multiply(blended).multiply(mesh.bindMatrix).invert();\n const local = new Vector3().fromArray(moved, i * 3).applyMatrix4(meshInverse).applyMatrix4(skin);\n target.setXYZ(i, local.x, local.y, local.z);\n }\n target.needsUpdate = true; mesh.geometry.computeVertexNormals();\n mesh.geometry.computeBoundingSphere(); mesh.frustumCulled = false;\n }\n }\n /** Select an exported `Pose N` clip and reset its IK goals and secondary motion. */\n selectPose(slot: number) {\n const stored = slot === 0 ? this.descriptor.poseSlots.find(p=>p.slot===0) ?? (this.descriptor.activePose===0 ? restPoseSlot(this.descriptor.pins) : undefined) : definedPoses(this.descriptor).find(p => p.slot === slot);\n if (!stored) throw new Error(`Pose ${slot} is not included in this GLB.`);\n this.mixer.stopAllAction();\n this.mixingStaticPoses = false;\n const clip = this.clips.find(c => c.name === `Pose ${slot}`);\n if (clip) { this.mixer.clipAction(clip).play(); this.mixer.update(0); }\n this.mixedPoseWeights = new Map([[slot, 1]]);\n this.scene.updateWorldMatrix(true, true);\n const inverse = this.scene.matrixWorld.clone().invert();\n this.referencePins = resolvePose(this.descriptor.pins, stored, this.parents);\n this.helperReferences = new Map(this.helpers.map(h => [h.bone, pose(inverse.clone().multiply(h.bone.matrixWorld))]));\n this.activePose = slot; this.resetSecondary(); this.setPins(resolvePose(this.descriptor.pins, stored, this.parents));\n }\n get poseWeights(): ReadonlyMap<number, number> { return this.mixedPoseWeights; }\n /** Change the editable reference pose without interrupting secondary motion. */\n preparePose(slot: number) {\n const stored = slot === 0 ? this.descriptor.poseSlots.find(p=>p.slot===0) ?? (this.descriptor.activePose===0 ? restPoseSlot(this.descriptor.pins) : undefined) : definedPoses(this.descriptor).find(p => p.slot === slot);\n if (!stored) throw new Error(`Pose ${slot} is not included in this GLB.`);\n this.referencePins = resolvePose(this.descriptor.pins, stored, this.parents);\n this.activePose = slot;\n }\n /** Mix the GLB's standard static pose clips, then simulate on that fitted frame. */\n previewPoseWeights(weights: ReadonlyMap<number, number>, seconds: number) {\n if (this.disposed) return;\n this.mixedPoseWeights = new Map(weights);\n const starting = !this.mixingStaticPoses;\n if (starting) {\n this.mixer.stopAllAction();\n for (const clip of this.clips) if (/^Pose \\d+$/.test(clip.name)) this.mixer.clipAction(clip).play();\n this.mixingStaticPoses = true;\n }\n // Secondary motion changed the same bones after the previous mixer tick.\n // PropertyMixer skips an unchanged clip value, so put its last clip-only\n // frame back before evaluating the next one.\n if (!starting) this.apply(this.base, true);\n for (const clip of this.clips) {\n const match = /^Pose (\\d+)$/.exec(clip.name);\n if (match) this.mixer.clipAction(clip).setEffectiveWeight(weights.get(Number(match[1])) ?? 0);\n }\n this.mixer.update(0);\n this.scene.updateWorldMatrix(true, true);\n const inverse = this.scene.matrixWorld.clone().invert();\n const fitted = this.base.map(pin => ({ ...pin, pose: pose(inverse.clone().multiply(this.bones.get(pin.id)!.matrixWorld)) }));\n this.base = fitted; this.dirty = false;\n this.rememberAnimationFrame(); this.advanceSecondary(seconds, fitted); this.rememberDisplayedAnimationFrame();\n }\n /** Adapter for editors: authored state stays in the caller's action history. */\n setPins(pins: readonly PinRecord[]) {\n if (pins.length !== this.bones.size || pins.some(p => !this.bones.has(p.id))) throw new Error('Rig layout changed; rebuild the GLB.');\n if (this.mixingStaticPoses) { this.mixer.stopAllAction(); this.mixingStaticPoses = false; }\n // These poses already passed the author's solve. In particular, an\n // unreachable IK goal must not perturb that solve again on load/replay.\n this.base = pins; this.dirty = false; this.editedTargets.clear(); this.mixedPoseWeights = new Map([[this.activePose, 1]]);\n for (const [id, target] of this.targets) if (!pins.some(p => p.id === id && (p.ik || p.wiggle || p.cloth || p.fur) && !p.guide)) { target.removeFromParent(); this.targets.delete(id); this.targetFrames.delete(id); }\n for (const pin of pins) {\n if (pin.guide || (!pin.ik && !pin.wiggle && !pin.cloth && !pin.fur)) continue;\n let target = this.targets.get(pin.id);\n if (!target) { target = new Object3D(); target.name = `${pin.id} target`; target.visible = false; this.scene.add(target); this.targets.set(pin.id, target); }\n target.position.fromArray(pin.ikTarget?.position ?? pin.pose.position); target.quaternion.fromArray(pin.ikTarget?.rotation ?? pin.pose.rotation);\n this.targetFrames.set(pin.id, JSON.stringify([target.position.toArray(), target.quaternion.toArray()]));\n }\n this.apply(pins); this.rememberAnimationFrame();\n }\n /** Display a caller-supplied fitted frame. Workbench playback uses the clips. */\n previewPins(pins: readonly PinRecord[]) {\n if (pins.length !== this.bones.size || pins.some(p => !this.bones.has(p.id))) throw new Error('Rig layout changed; rebuild the GLB.');\n if (this.mixingStaticPoses) { this.mixer.stopAllAction(); this.mixingStaticPoses = false; }\n this.base = pins; this.dirty = false;\n this.apply(pins, true); this.rememberAnimationFrame();\n }\n private localFrame(bone: Object3D) {\n return {position:bone.position.clone(),rotation:bone.quaternion.clone(),scale:bone.scale.clone(),\n displayedPosition:bone.position.clone(),displayedRotation:bone.quaternion.clone(),displayedScale:bone.scale.clone()};\n }\n private rememberAnimationFrame() {\n for (const bone of this.animationFrames.keys()) this.animationFrames.set(bone,this.localFrame(bone));\n }\n /** PropertyMixer skips unchanged values. Recover their clip-only components\n * rather than feeding last frame's secondary motion back into animation. */\n private animationFrame() {\n if (!this.animationFrames.size) return null;\n for (const [bone,frame] of this.animationFrames) {\n if (!bone.position.equals(frame.displayedPosition)) frame.position.copy(bone.position);\n if (!bone.quaternion.equals(frame.displayedRotation)) frame.rotation.copy(bone.quaternion);\n if (!bone.scale.equals(frame.displayedScale)) frame.scale.copy(bone.scale);\n bone.position.copy(frame.position);bone.quaternion.copy(frame.rotation);bone.scale.copy(frame.scale);\n }\n this.scene.updateWorldMatrix(true,true);\n const inverse=this.scene.matrixWorld.clone().invert();\n return this.base.map(pin=>({...pin,pose:pose(inverse.clone().multiply(this.bones.get(pin.id)!.matrixWorld))}));\n }\n private rememberDisplayedAnimationFrame() {\n for (const [bone,frame] of this.animationFrames) {\n frame.displayedPosition.copy(bone.position);frame.displayedRotation.copy(bone.quaternion);frame.displayedScale.copy(bone.scale);\n }\n }\n private apply(pins: readonly PinRecord[], fitted = false) {\n if(this.descriptor.version>=3 && !fitted)pins=driveRig(pins,this.referencePins,this.drivers);\n this.scene.updateWorldMatrix(true, true);\n const desired = new Map(pins.map(p => [this.bones.get(p.id)!, this.scene.matrixWorld.clone().multiply(matrix(p.pose))]));\n // Use desired parent frames, not last frame's bone state (arbitrary order).\n const pending = new Set(desired.keys());\n const apply = (bone: Object3D) => {\n if (!pending.has(bone)) return;\n if (bone.parent && pending.has(bone.parent)) apply(bone.parent);\n bone.parent?.updateWorldMatrix(true, false);\n const local = (bone.parent?.matrixWorld.clone() ?? new Matrix4()).invert().multiply(desired.get(bone)!);\n local.decompose(bone.position, bone.quaternion, bone.scale); bone.updateMatrix(); bone.updateWorldMatrix(false, true); pending.delete(bone);\n };\n for (const bone of desired.keys()) apply(bone);\n // Corrective bones are NOT rigid children of their strongest control.\n // Blend each control's delta using the original harmonic volume binding.\n // Applying a delta to a fitted reference frame preserves the sampled pose\n // exactly, while avoiding hard parent boundaries during new motion.\n const deltas = new Map(this.referencePins.map(reference => {\n const current = pins.find(p => p.id === reference.id)!.pose;\n return [reference.id, { matrix: matrix(current).multiply(matrix(reference.pose).invert()), rotation: new Quaternion().fromArray(current.rotation).multiply(new Quaternion().fromArray(reference.pose.rotation).invert()), scale: new Vector3().fromArray(current.scale).divide(new Vector3().fromArray(reference.pose.scale)) }];\n }));\n for (const helper of this.descriptor.version>=3?[]:this.helpers) {\n const reference = this.helperReferences.get(helper.bone)!;\n const p = new Vector3(), q = new Quaternion(0, 0, 0, 0), s = new Vector3(), ref = new Vector3().fromArray(reference.position);\n const hemisphere = helper.influences.length ? deltas.get(helper.influences[0].id)!.rotation : new Quaternion();\n for (const influence of helper.influences) {\n const delta = deltas.get(influence.id)!, w = influence.weight;\n p.addScaledVector(ref.clone().applyMatrix4(delta.matrix), w); s.addScaledVector(delta.scale, w);\n const sign = hemisphere.dot(delta.rotation) < 0 ? -w : w;\n q.set(q.x + delta.rotation.x*sign, q.y + delta.rotation.y*sign, q.z + delta.rotation.z*sign, q.w + delta.rotation.w*sign);\n }\n if (!helper.influences.length) { p.copy(ref); q.identity(); s.setScalar(1); }\n q.normalize().multiply(new Quaternion().fromArray(reference.rotation)); s.multiply(new Vector3().fromArray(reference.scale));\n const world = this.scene.matrixWorld.clone().multiply(new Matrix4().compose(p, q, s));\n helper.bone.parent?.updateWorldMatrix(true, false);\n const local = (helper.bone.parent?.matrixWorld.clone() ?? new Matrix4()).invert().multiply(world);\n local.decompose(helper.bone.position, helper.bone.quaternion, helper.bone.scale); helper.bone.updateWorldMatrix(false, true);\n }\n this.displayed = pins;\n for(const bone of this.bones.values()){bone.updateMatrix();this.localFrames.set(bone,[...bone.matrix.elements]);}\n }\n /** Call after an external AnimationMixer/TransformControls, before rendering.\n * Targets are scene-local Object3Ds; moving an independent bone never moves them. */\n update(seconds: number) {\n if (this.disposed) return;\n const fitted=this.animationFrame();\n if(fitted){this.base=fitted;this.displayed=fitted;this.dirty=false;}\n else this.furSurface?.update(seconds, this.windStrength);\n this.scene.updateWorldMatrix(true, true);\n const inverse = this.scene.matrixWorld.clone().invert();\n // Accept external bone edits, but never feed our spring output back as input.\n const edited = fitted ? this.base : this.base.map((pin, i) => {\n const driver=this.drivers.find(d=>d.id===pin.id);\n if(driver){\n const bone=this.bones.get(pin.id)!;bone.updateMatrix();\n if(!bone.matrix.elements.some((v,k)=>Math.abs(v-(this.localFrames.get(bone)?.[k]??v))>1e-6))return pin;\n return {...pin,pose:referencePose(pose(inverse.clone().multiply(bone.matrixWorld)),driver,this.base,this.referencePins)};\n }\n const current = pose(inverse.clone().multiply(this.bones.get(pin.id)!.matrixWorld));\n const previous = this.displayed[i].pose;\n const previousMatrix = matrix(previous);\n const changed = matrix(current).elements.some((v, k) => Math.abs(v - previousMatrix.elements[k]) > 1e-6);\n if (changed) this.dirty = true;\n return changed ? { ...pin, pose: current } : pin;\n });\n const bonesEdited=edited.some((p,i)=>p!==this.base[i]);\n if (bonesEdited) this.base = edited;\n const movedTargets = new Set<string>();\n for (const [id, target] of this.targets) {\n const signature = JSON.stringify([target.position.toArray(), target.quaternion.toArray()]);\n if (this.targetFrames.get(id) !== signature) { movedTargets.add(id); this.dirty = true; this.targetFrames.set(id, signature); }\n }\n for (const id of movedTargets) this.editedTargets.add(id);\n const goalTargets = fitted ? this.editedTargets : movedTargets;\n if (fitted && goalTargets.size) this.dirty = true;\n // A secondary root target is a direct hierarchy transform, not a zero-\n // length IK chain. Carry its descendants before solving other fixed goals.\n for (const root of this.base.filter(p => (p.wiggle || p.cloth || p.fur) && goalTargets.has(p.id) && !this.parents.has(p.id))) {\n const target = this.targets.get(root.id)!;\n const delta = matrix({ ...root.pose, position: target.position.toArray(), rotation: target.quaternion.toArray() }).multiply(matrix(root.pose).invert());\n const affected = new Set([root.id]);\n for (let added = true; added;) { added = false; for (const [child, parent] of this.parents) if (affected.has(parent) && !affected.has(child)) { affected.add(child); added = true; } }\n this.base = this.base.map(p => affected.has(p.id) && !this.drivers.some(d=>d.id===p.id) ? { ...p, pose: pose(delta.clone().multiply(matrix(p.pose))) } : p);\n }\n const goals = this.base.filter(p => (p.ik || ((p.wiggle || p.cloth || p.fur) && goalTargets.has(p.id))) && !p.guide && this.chain(p.id).length > 1).map(p => {\n const target = this.targets.get(p.id)!;\n const goal = { id: p.id, position: target.position.toArray(), rotation: target.quaternion.toArray() };\n if (!fitted && (!p.ikTarget || goal.position.some((v, i) => Math.abs(v - p.ikTarget!.position[i]) > 1e-8) || goal.rotation.some((v, i) => Math.abs(v - p.ikTarget!.rotation[i]) > 1e-8))) this.dirty = true;\n return fitted && !goalTargets.has(p.id) ? {id:p.id,position:[...p.pose.position] as PinPose['position'],rotation:[...p.pose.rotation] as PinPose['rotation']} : goal;\n });\n if (this.dirty) {\n const localGoal=!bonesEdited && goalTargets.size===1 ? goals.find(g=>goalTargets.has(g.id)):undefined;\n const articulated=this.articulated(this.base);\n const solved = new Map((localGoal?solveLocalPinIK(articulated,this.parents,localGoal,this.masses):solvePlantedPinIKGoals(articulated, this.parents, goals, this.masses, new Set(articulated.filter(p => p.independent).map(p => p.id)))).map(p => [p.id, p.pose]));\n this.base = this.base.map(p => ({ ...p, pose: solved.get(p.id) ?? p.pose, ikTarget: p.ik ? goals.find(g => g.id === p.id) ?? p.ikTarget : p.ikTarget }));\n this.dirty = false;\n }\n if(fitted && !goalTargets.size && !fitted.some(pin=>pin.wiggle||pin.cloth||pin.fur)) {\n // Ordinary clips already provide exact local TRS, including scaled\n // parent frames which cannot be reconstructed from world TRS alone.\n this.displayed=this.base;\n for(const bone of this.bones.values()){bone.updateMatrix();this.localFrames.set(bone,[...bone.matrix.elements]);}\n } else this.advanceSecondary(seconds,fitted??undefined);\n this.rememberDisplayedAnimationFrame();\n }\n private advanceSecondary(seconds: number, fitted?: readonly PinRecord[]) {\n if (fitted) this.furSurface?.update(seconds, this.windStrength);\n const secondary=this.springs.step(this.articulated(this.base), this.parents, seconds, this.masses, this.windStrength).pins;\n const byId = new Map(secondary.map(p => [p.id, p]));\n const colliders: ClothCollider[] = (this.descriptor.cloth?.colliders ?? []).map(collider => {\n const driver = byId.get(collider.driver!);\n if (!driver) return collider;\n const rest = { position: driver.rest, rotation: [0, 0, 0, 1] as const, scale: [1, 1, 1] as const };\n const position = new Vector3().fromArray(collider.position).applyMatrix4(matrix(driver.pose).multiply(matrix(rest).invert()));\n return { ...collider, position: position.toArray() };\n });\n const cloth = this.cloth.step(secondary, this.parents, seconds, this.descriptor.cloth?.links ?? [], colliders, this.windStrength).pins;\n const displayed=this.base.map(p=>cloth.find(q=>q.id===p.id)??p);\n this.apply(fitted&&this.descriptor.version>=3?driveRig(displayed,fitted,this.drivers):displayed,Boolean(fitted));\n this.updateClothMeshes(seconds, colliders);\n }\n dispose() {\n this.disposed = true; this.mixer.stopAllAction(); this.mixer.uncacheRoot(this.scene); this.resetSecondary();\n this.furSurface?.dispose();\n for (const entry of this.clothMeshes) { entry.mesh.geometry.dispose(); entry.mesh.geometry = entry.original; }\n this.clothMeshes = [];\n for (const target of this.targets.values()) target.removeFromParent(); this.targets.clear(); runtimes.delete(this.scene);\n }\n}\n\n/** GLTFLoader plugin that validates a rig extension and binds its scene runtime. */\nexport class NeedleDeformationRigLoaderPlugin {\n readonly name = NEEDLE_DEFORMATION_RIG;\n constructor(readonly parser: GLTFParser) {}\n async afterRoot(gltf: GLTF) {\n const json = this.parser.json as { nodes?: unknown[]; textures?: unknown[]; scenes?: { extensions?: Record<string, unknown> }[] };\n for (const [i, scene] of gltf.scenes.entries()) {\n const raw = json.scenes?.[i]?.extensions?.[this.name]; if (!raw) continue;\n const descriptor = parseRigDescriptor(raw, json.nodes?.length ?? 0, json.textures?.length ?? 0);\n const nodes: Object3D[] = await Promise.all(descriptor.joints.map(j => this.parser.getDependency('node', j.node)));\n const helpers: Object3D[] = await Promise.all((descriptor.helpers ?? []).map(h => this.parser.getDependency('node', h.node)));\n for (const node of [...nodes, ...helpers]) { let parent: Object3D | null = node; while (parent && parent !== scene) parent = parent.parent; if (!parent) throw new Error('Rig bone is outside its scene.'); }\n const runtime = new DeformationRigRuntime(scene, descriptor, nodes, gltf.animations, helpers);\n if (descriptor.furSurface) {\n const height = await this.parser.getDependency('texture', descriptor.furSurface.heightTexture);\n height.channel = descriptor.furSurface.texCoord ?? 0;\n runtime.setFurHeightMap(height);\n }\n runtimes.set(scene, runtime);\n }\n }\n}\n/** Register the rig plugin before loading a GLB. Returns the same loader. */\nexport function registerNeedleDeformationRigLoader(loader: GLTFLoader) {\n loader.register(parser => new NeedleDeformationRigLoaderPlugin(parser)); return loader;\n}\n/** Return the runtime attached to a loaded glTF scene, if it has the extension. */\nexport function getDeformationRig(scene: Object3D) { return runtimes.get(scene); }\n", "import type { IKConstraint } from './ik-constraints.js';\nimport type { MotionSettings } from './motion-settings.js';\n\n/** Shared data contract; deliberately independent of editor history and GPU types. */\nexport type Point = readonly [number, number, number];\nexport type Rotation = readonly [number, number, number, number];\nexport type PinPose = { readonly position: Point; readonly rotation: Rotation; readonly scale: Point };\nexport type PinParents = ReadonlyMap<string, string>;\nexport type HierarchyEdge = {from:string;to:string;cost:number;geodesic?:number};\nexport type PinMotion = 'none' | 'ik' | 'wiggle' | 'cloth' | 'fur';\nexport const DEFAULT_FUR_DEPTH = .1;\nexport const MAX_FUR_DEPTH = .5;\nexport type IKTarget = { readonly position: Point; readonly rotation: Rotation };\nexport const IK_CHAIN_KINDS = ['leg','arm','head','tail','wing','fin','tentacle','spine'] as const;\nexport type IKChainRole = { readonly kind: typeof IK_CHAIN_KINDS[number]; readonly side: 'center'|'left'|'right'; readonly position?: 'front'|'hind' };\nexport type PinRecord = { readonly id: string; readonly rest: Point; readonly pose: PinPose; readonly rigidGroup: string | null; readonly independent: boolean;\n /** This pose was set on purpose in the slot now open, rather than reached by\n * being carried by a parent or swept along by an IK solve. A slot still\n * stores an unauthored pose it could not otherwise reproduce \u2014 an IK chain\n * does not come back the same way twice \u2014 but only an authored one is shown\n * as deliberate and only an authored one can be released. */\n readonly authored?: boolean; readonly guide?: boolean; readonly ik?: boolean; readonly wiggle?: boolean; readonly cloth?: boolean; readonly fur?: boolean; readonly furDepth?: number; readonly motion?: MotionSettings; readonly ikTarget?: IKTarget; readonly ikConstraint?: IKConstraint; readonly chainRole?: IKChainRole };\n", "/** Shared document, import, UI and GPU capacity. Pin records are 64 bytes. */\nexport const MAX_DEFORMATION_PINS = 128;\n/** What one sweep of the Suggested pins slider will place. Well short of the\n * document cap: past this the slider stops placing body anchors and starts\n * splitting fine branches, which is hand work rather than a slider's job. */\nexport const MAX_SUGGESTED_PINS = 64;\n\n/** Cells along the longest axis of the solver lattice.\n *\n * The lattice is N by N by N over the model's bounds, and everything the solver\n * measures \u2014 how thick a part is, how far a contact reaches, how much an\n * element is strained \u2014 is in units of those cells. What a grid can represent\n * is what it can resolve: on a posed arm a finger is 2.7 cells across at 32 and\n * 3.5 at 40, which is a rod three nodes thick.\n *\n * The ceiling is a memory bound rather than a speed one. Node buffers are 16\n * bytes each and there are about ten of them, so 64 costs roughly 42 MB of\n * those; the harmonic weights are the one that hurts, at four bytes per node\n * per pin slot, which for a full 128 pins is 268 MB at 64 against 67 MB at 40. */\nexport const MIN_DEFORMATION_RESOLUTION = 16;\nexport const MAX_DEFORMATION_RESOLUTION = 64;\n\n/** Bones the skeleton solver turns on its own: every part of the body no pin\n * drives, cut along the curve skeleton. 132 bytes of GPU state each. */\nexport const MAX_SKELETON_BONES = 2048;\n", "export type MotionSettings = { reach: number; frequency: number; damping: number; massInfluence:number; strength:number };\nexport const DEFAULT_MOTION: Readonly<MotionSettings> = { reach: .5, frequency: 14 / (2*Math.PI), damping: .28, massInfluence:1,strength:1 };\nexport function validateMotionSettings(value: MotionSettings) {\n if (!value || !Number.isFinite(value.reach) || value.reach < 0 || value.reach > 1\n || !Number.isFinite(value.frequency) || value.frequency < .25 || value.frequency > 8\n || !Number.isFinite(value.damping) || value.damping < .05 || value.damping > 1\n || !Number.isFinite(value.massInfluence) || value.massInfluence<0 || value.massInfluence>2\n || !Number.isFinite(value.strength) || value.strength<0 || value.strength>3) throw new Error('Invalid motion settings.');\n}\n", "import { Quaternion, Vector3 } from 'three';\nexport type IKConstraint = { mode:'free'|'cone'|'hinge'|'locked'; axis:'auto'|'x'|'y'|'z'; min:number; max:number; orientation?:[number,number,number,number]; maxY?:number };\nexport const DEFAULT_IK_CONSTRAINT:Readonly<IKConstraint> = {mode:'free',axis:'auto',min:-120,max:120};\nexport function validateIKConstraint(value:IKConstraint) {\n if(value?.maxY!==undefined && (!Number.isFinite(value.maxY)||value.maxY<0||value.maxY>180))throw new Error('Invalid IK cone aperture.');\n if(value?.orientation!==undefined && (!Array.isArray(value.orientation)||value.orientation.length!==4||!value.orientation.every(Number.isFinite)||Math.abs(Math.hypot(...value.orientation)-1)>1e-4))throw new Error('Invalid IK cone orientation.');\n if (!value || !['free','cone','hinge','locked'].includes(value.mode) || !['auto','x','y','z'].includes(value.axis)\n || !Number.isFinite(value.min) || !Number.isFinite(value.max) || value.min < -180 || value.max > 180 || value.min > value.max || (value.mode==='cone' && value.max<0)) throw new Error('Invalid IK joint constraint.');\n}\n/** Stable parent-local cone frame. Z follows the rest bone; X/Y are aperture axes. */\nexport function coneFrame(axis:Vector3,constraint:Readonly<IKConstraint>){\n return new Quaternion().fromArray(constraint.orientation??[0,0,0,1]).multiply(new Quaternion().setFromUnitVectors(new Vector3(0,0,1),axis.clone().normalize()));\n}\n/** Angular ellipse (also valid beyond 90 degrees), rather than a tangent-plane box. */\nexport function coneAngle(constraint:Readonly<IKConstraint>,azimuth:number){\n const x=(constraint.mode==='cone'?constraint.max:90)*Math.PI/180,y=(constraint.mode==='cone'?(constraint.maxY??constraint.max):90)*Math.PI/180;\n const c=Math.cos(azimuth),s=Math.sin(azimuth);\n if((x===0&&Math.abs(c)>1e-8)||(y===0&&Math.abs(s)>1e-8))return 0;\n return 1/Math.sqrt((Math.abs(c)<1e-8?0:c/Math.max(x,1e-12))**2+(Math.abs(s)<1e-8?0:s/Math.max(y,1e-12))**2);\n}\nexport function constrainCone(rotation:Quaternion,axis:Vector3,constraint:Readonly<IKConstraint>,movingAxis:Vector3=axis){\n const frame=coneFrame(axis,constraint),direction=movingAxis.clone().normalize().applyQuaternion(rotation);\n const local=direction.clone().applyQuaternion(frame.clone().invert()),azimuth=Math.atan2(local.y,local.x);\n const angle=Math.atan2(Math.hypot(local.x,local.y),local.z),limit=coneAngle(constraint,azimuth);\n if(angle<=limit+1e-8)return rotation.clone();\n const target=new Vector3(Math.sin(limit)*Math.cos(azimuth),Math.sin(limit)*Math.sin(azimuth),Math.cos(limit)).applyQuaternion(frame);\n return new Quaternion().setFromUnitVectors(direction,target).multiply(rotation).normalize();\n}\n/** Circular swing cone, not an Euler-angle box. Twist remains free. */\nexport function constrainSwing(rotation: Quaternion, axis: Vector3, degrees: number) {\n const direction=axis.clone().normalize(), rotated=direction.clone().applyQuaternion(rotation);\n const angle=direction.angleTo(rotated), limit=degrees*Math.PI/180;\n if(angle<=limit+1e-8)return rotation.clone();\n const normal=new Vector3().crossVectors(direction,rotated);\n if(normal.lengthSq()<1e-12)normal.crossVectors(direction,Math.abs(direction.x)<.8?new Vector3(1,0,0):new Vector3(0,1,0));\n return new Quaternion().setFromAxisAngle(normal.normalize(),limit-angle).multiply(rotation).normalize();\n}\n", "import type { IKTarget, PinPose, PinRecord, Point, Rotation } from './pin-types.js';\nimport type { PinParents } from './pin-types.js';\n\nexport type StoredPose = { readonly id:string; readonly pose:PinPose; readonly ikTarget?:IKTarget; readonly authored?:boolean };\nexport type PoseSlot = { readonly slot:number; readonly poses:readonly StoredPose[] };\nexport const POSE_SLOTS=9;\n/** Below any edit a hand can make, and far above the drift of composing one\n * carried transform after another. */\nconst AUTHORED_EPSILON=1e-6;\n\nexport function capturePose(pins:readonly PinRecord[]):readonly StoredPose[]{\n return pins.map(pin=>({id:pin.id,pose:pin.pose,...(pin.authored?{authored:true}:{}),...(pin.ikTarget?{ikTarget:pin.ikTarget}:{})}));\n}\n\nconst restPoseOf=(rest:Point):PinPose=>({position:[rest[0],rest[1],rest[2]],rotation:[0,0,0,1],scale:[1,1,1]});\n\n/** Where a pin lands when its parent carries it from rest. A parent's pose IS\n * a similarity out of its own rest frame, so the child keeps its rest offset\n * through that same rotation and scale \u2014 the transform hierarchy posing applies\n * when a parent moves, written as one step from rest instead of accumulated. */\nexport function carriedPose(rest:Point,parentRest:Point,parent:PinPose):PinPose{\n const [qx,qy,qz,qw]=parent.rotation;\n const x=(rest[0]-parentRest[0])*parent.scale[0],y=(rest[1]-parentRest[1])*parent.scale[1],z=(rest[2]-parentRest[2])*parent.scale[2];\n const tx=2*(qy*z-qz*y),ty=2*(qz*x-qx*z),tz=2*(qx*y-qy*x);\n const position:Point=[parent.position[0]+x+qw*tx+(qy*tz-qz*ty),parent.position[1]+y+qw*ty+(qz*tx-qx*tz),parent.position[2]+z+qw*tz+(qx*ty-qy*tx)];\n const rotation:Rotation=[qx,qy,qz,qw],scale:Point=[parent.scale[0],parent.scale[1],parent.scale[2]];\n return {position,rotation,scale};\n}\n\nconst samePose=(a:PinPose,b:PinPose)=>\n a.position.every((v,i)=>Math.abs(v-b.position[i])<=AUTHORED_EPSILON)\n && a.scale.every((v,i)=>Math.abs(v-b.scale[i])<=AUTHORED_EPSILON)\n && a.rotation.every((v,i)=>Math.abs(v-b.rotation[i])<=AUTHORED_EPSILON);\n\n/** What a slot would place a pin at if it said nothing about it. */\nfunction inheritedPose(pin:PinRecord,parent:PinRecord|undefined,parentPose:PinPose|undefined):PinPose{\n return parent&&parentPose?carriedPose(pin.rest,parent.rest,parentPose):restPoseOf(pin.rest);\n}\n\n/** Only the poses a slot actually authors. A pin the hierarchy already places\n * is left out, so a point added while another pose was open keeps following its\n * parent everywhere else until it is deliberately posed there. */\nexport function authoredPoses(pins:readonly PinRecord[],parents:PinParents=new Map()):readonly StoredPose[]{\n const byId=new Map(pins.map(pin=>[pin.id,pin]));\n return capturePose(pins).filter(stored=>{\n const pin=byId.get(stored.id)!;\n // Deliberate, or a goal, which is deliberate by definition.\n if(pin.authored||pin.ikTarget)return true;\n // Otherwise it is only kept because it could not be worked out again. A\n // joint the IK solve swept along is not reproducible \u2014 the same goal\n // reached from a different bend gives a different arm \u2014 so the value stays\n // even though nobody posed it.\n const parent=byId.get(parents.get(pin.id)??'');\n return !samePose(pin.pose,inheritedPose(pin,parent,parent?.pose));\n });\n}\n\n/** Active pins are the edit register. Inactive slots contain transforms only;\n * topology, rest positions and settings remain shared and action-owned. A pin\n * the slot does not mention inherits through the hierarchy rather than dropping\n * to rest, which is what keeps a newly placed point attached to its parent in\n * every other pose. */\nexport function resolvePose(pins:readonly PinRecord[],slot:PoseSlot,parents:PinParents=new Map()):readonly PinRecord[]{\n const saved=new Map(slot.poses.map(p=>[p.id,p]));\n const byId=new Map(pins.map(pin=>[pin.id,pin]));\n const memo=new Map<string,PinPose>(),visiting=new Set<string>();\n const poseOf=(pin:PinRecord):PinPose=>{\n const cached=memo.get(pin.id);if(cached)return cached;\n const stored=saved.get(pin.id);\n let pose:PinPose;\n if(stored)pose=stored.pose;\n else{\n const parentId=parents.get(pin.id);\n // A parent already on the stack means a cycle in a derived hierarchy;\n // rest is the only answer that terminates.\n const parent=parentId&&!visiting.has(parentId)?byId.get(parentId):undefined;\n if(!parent)pose=restPoseOf(pin.rest);\n else{visiting.add(pin.id);pose=carriedPose(pin.rest,parent.rest,poseOf(parent));visiting.delete(pin.id);}\n }\n memo.set(pin.id,pose);return pose;\n };\n const resolved:PinRecord[]=pins.map(pin=>{\n const stored=saved.get(pin.id),{ikTarget:_target,authored:_authored,...base}=pin;\n return {...base,pose:poseOf(pin),...(stored?.authored?{authored:true}:{}),...(stored?.ikTarget?{ikTarget:stored.ikTarget}:{})};\n });\n // Group membership is shared. A group created after another pose was saved\n // still has one rotation/uniform scale when that pose is opened. Positions\n // stay authored; subsequent rigid edits preserve that arrangement.\n return resolved.map(pin=>{\n if(!pin.rigidGroup)return pin;const anchor=resolved.find(p=>p.rigidGroup===pin.rigidGroup)!;\n return {...pin,pose:{...pin.pose,rotation:anchor.pose.rotation,scale:[anchor.pose.scale[0],anchor.pose.scale[0],anchor.pose.scale[0]]}};\n });\n}\nexport function definedPoses(model:{readonly pins:readonly PinRecord[];readonly poseSlots:readonly PoseSlot[];readonly activePose:number}):PoseSlot[]{\n const slots=model.poseSlots.filter(p=>p.slot!==model.activePose);\n return [...slots,...(model.activePose === 0 ? [] : [{slot:model.activePose,poses:capturePose(model.pins)}])].sort((a,b)=>a.slot-b.slot);\n}\n\n/** Pose 0 is derived from shared rest positions, never an editable pose slot. */\nexport function restPoseSlot(pins:readonly PinRecord[]):PoseSlot{\n return {slot:0,poses:pins.map(pin=>({id:pin.id,pose:restPoseOf(pin.rest)}))};\n}\n\nexport function playablePoses(model:{readonly pins:readonly PinRecord[];readonly poseSlots:readonly PoseSlot[];readonly activePose:number}):PoseSlot[]{\n return [restPoseSlot(model.pins),...definedPoses(model)];\n}\n", "import type { PinPose, PinRecord, Point, Rotation } from './pin-types.js';\nimport type { PinParents } from './pin-types.js';\n\n/** A pose slot's time controls its share of the loop around its own moment.\n * The transition settles at each authored pose without holding a flat frame. */\nexport const DEFAULT_POSE_SECONDS = 0.7;\nexport const MIN_POSE_SECONDS = 0.05;\nexport const MAX_POSE_SECONDS = 60;\n/** Travel kept below the longest pose so a slider dragged to the bottom can\n * always be dragged further on the next pass, and shrinks back when shortened. */\nexport const POSE_TIME_HEADROOM = 0.5;\n\nexport type PoseTiming = { readonly slot: number; readonly seconds: number };\nexport type PoseTimeline = readonly PoseTiming[];\n\nexport function poseTimeScale(timeline: PoseTimeline): number {\n return Math.max(DEFAULT_POSE_SECONDS, ...timeline.map(entry => entry.seconds)) + POSE_TIME_HEADROOM;\n}\n\n/** The strip reads downwards: zero at the top, the scale at the bottom, which\n * is what makes \"drag down\" mean \"stay longer\". */\nexport function poseSecondsAt(offset: number, height: number, scale: number): number {\n if (!(height > 0)) return MIN_POSE_SECONDS;\n return Math.min(1, Math.max(0, offset / height)) * scale;\n}\n\n/** How far down the strip a time sits, as a percentage for the fill and handle. */\nexport function poseTimeOffset(seconds: number, scale: number): number {\n if (!(scale > 0)) return 0;\n return Math.min(100, Math.max(0, (seconds / scale) * 100));\n}\n\nexport function poseLoopSeconds(timeline: PoseTimeline): number {\n return timeline.reduce((total, entry) => total + Math.max(0, entry.seconds), 0);\n}\n\n/** The moment each pose is reached. Neighbours split the gap between them in\n * proportion to their own times, which is what makes a time an ownership share\n * rather than the length of one arc. */\nexport function poseKnots(timeline: PoseTimeline): number[] {\n const knots = [0];\n for (let i = 1; i < timeline.length; i++) {\n knots.push(knots[i - 1] + (Math.max(0, timeline[i - 1].seconds) + Math.max(0, timeline[i].seconds)) / 2);\n }\n return knots;\n}\n\n/** How long one pass takes: the first pose's moment to the last one's.\n * Looping playback adds the closing transition up to poseLoopSeconds. */\nexport function posePassSeconds(timeline: PoseTimeline): number {\n const knots = poseKnots(timeline);\n return knots.length ? knots[knots.length - 1] : 0;\n}\n\nexport function poseTimeOf(timeline: PoseTimeline, slot: number): number {\n const index = timeline.findIndex(entry => entry.slot === slot);\n return index < 0 ? 0 : poseKnots(timeline)[index];\n}\n\n/** Septic: zero first, second AND third derivative at both ends, so a one-shot\n * move away from rest and back to rest is G3 at the moment it starts and the\n * moment it settles. A cubic smoothstep leaves a jerk step at both. */\nexport function smoothStep(t: number): number {\n const x = Math.min(1, Math.max(0, t));\n return x ** 4 * (35 + x * (-84 + x * (70 - 20 * x)));\n}\n\nexport interface PoseSpline {\n readonly slots: readonly number[];\n readonly loop: number;\n /** How much each pose owns of the frame at this moment; sums to one, and is\n * one on a pose exactly at its own moment. */\n weightsAt(time: number): number[];\n}\n\n/** A periodic C2 interpolant of the authored poses. Its weights are shared by\n * rig playback, GLB clip mixing and trajectory sampling, so the visible path\n * is the path the animation actually follows. */\nexport function preparePoseSpline(timeline: PoseTimeline): PoseSpline {\n const n = timeline.length, slots = timeline.map(entry => entry.slot);\n const loop = poseLoopSeconds(timeline), knots = poseKnots(timeline);\n if (n < 2 || !(loop > 0)) {\n const fixed = timeline.map((_, i) => (i === 0 ? 1 : 0));\n return { slots, loop: Math.max(loop, 0), weightsAt: () => [...fixed] };\n }\n return { slots, loop, weightsAt: time => splineWeights(knots,loop,n,time) };\n}\n\nfunction splineWeights(knots: readonly number[], loop: number, n: number, time: number): number[] {\n const cursor = ((time % loop) + loop) % loop, weights = new Array<number>(n).fill(0);\n let k = n - 1; while (k > 0 && cursor < knots[k]) k--;\n const start = knots[k], end = k + 1 < n ? knots[k + 1] : loop;\n const h=end-start,t=h>0?(cursor-start)/h:0,next=(k+1)%n;\n if(n<3||!(h>0)){weights[k]=1-smoothStep(t);weights[next]+=smoothStep(t);return weights;}\n const coordinate=(i:number)=>i<0?knots[i+n]-loop:i>=n?knots[i-n]+loop:knots[i];\n const unit=(i:number)=>{const result=new Array<number>(n).fill(0);result[(i+n)%n]=1;return result;};\n const subtract=(a:readonly number[],b:readonly number[],scale:number)=>a.map((v,j)=>(v-b[j])/scale);\n const derivatives=(i:number)=>{\n const before=coordinate(i)-coordinate(i-1),after=coordinate(i+1)-coordinate(i);\n const previous=subtract(unit(i),unit(i-1),Math.max(before,1e-8));\n const following=subtract(unit(i+1),unit(i),Math.max(after,1e-8));\n // Full centered tangents round a three-pose corner visibly. Reducing them\n // to a quarter left a mathematically C2 but visibly triangular path.\n return {velocity:previous.map((v,j)=>(v*after+following[j]*before)/(before+after)),\n acceleration:previous.map((v,j)=>2*(following[j]-v)/(before+after))};\n };\n const a=derivatives(k),b=derivatives(k+1),p=unit(k),q=unit(k+1);\n for(let j=0;j<n;j++){\n const v0=h*a.velocity[j],v1=h*b.velocity[j],a0=h*h*a.acceleration[j],a1=h*h*b.acceleration[j];\n const d=q[j]-p[j]-v0-a0/2,v=v1-v0-a0,acc=a1-a0;\n weights[j]=p[j]+t*(v0+t*(a0/2+t*((10*d-4*v+acc/2)+t*((-15*d+7*v-acc)+t*(6*d-3*v+acc/2)))));\n }\n return weights;\n}\n\nconst conjugate = (q: Rotation): Rotation => [-q[0], -q[1], -q[2], q[3]];\nconst multiply = (a: Rotation, b: Rotation): Rotation => [\n a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],\n a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],\n a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],\n a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2],\n];\nfunction rotate(q: Rotation, v: Point): Point {\n const tx = 2 * (q[1] * v[2] - q[2] * v[1]), ty = 2 * (q[2] * v[0] - q[0] * v[2]), tz = 2 * (q[0] * v[1] - q[1] * v[0]);\n return [v[0] + q[3] * tx + (q[1] * tz - q[2] * ty), v[1] + q[3] * ty + (q[2] * tx - q[0] * tz), v[2] + q[3] * tz + (q[0] * ty - q[1] * tx)];\n}\nconst safeScale = (v: number) => (Math.abs(v) > 1e-8 ? v : 1e-8);\n\n/** A pose in its parent's frame. */\nfunction localPose(pose: PinPose, parent: PinPose | undefined): PinPose {\n if (!parent) return pose;\n const inverse = conjugate(parent.rotation);\n const offset = rotate(inverse, [pose.position[0] - parent.position[0], pose.position[1] - parent.position[1], pose.position[2] - parent.position[2]]);\n return {\n position: [offset[0] / safeScale(parent.scale[0]), offset[1] / safeScale(parent.scale[1]), offset[2] / safeScale(parent.scale[2])],\n rotation: multiply(inverse, pose.rotation),\n scale: [pose.scale[0] / safeScale(parent.scale[0]), pose.scale[1] / safeScale(parent.scale[1]), pose.scale[2] / safeScale(parent.scale[2])],\n };\n}\n\n/** The inverse of localPose: a local transform read back out into the world. */\nfunction worldPose(local: PinPose, parent: PinPose | undefined): PinPose {\n if (!parent) return local;\n const scaled: Point = [local.position[0] * parent.scale[0], local.position[1] * parent.scale[1], local.position[2] * parent.scale[2]];\n const offset = rotate(parent.rotation, scaled);\n return {\n position: [parent.position[0] + offset[0], parent.position[1] + offset[1], parent.position[2] + offset[2]],\n rotation: multiply(parent.rotation, local.rotation),\n scale: [local.scale[0] * parent.scale[0], local.scale[1] * parent.scale[1], local.scale[2] * parent.scale[2]],\n };\n}\n\n/** Parents before children, with any cycle in a derived hierarchy broken by\n * treating the pin that closes it as a root. */\nfunction hierarchyOrder(pins: readonly PinRecord[], parents: PinParents): { order: number[]; parentOf: (number | undefined)[] } {\n const index = new Map(pins.map((pin, i) => [pin.id, i]));\n const parentOf = pins.map(pin => { const p = index.get(parents.get(pin.id) ?? ''); return p === index.get(pin.id) ? undefined : p; });\n const order: number[] = [], state = new Uint8Array(pins.length);\n const visit = (i: number) => {\n if (state[i]) { if (state[i] === 1) parentOf[i] = undefined; return; }\n state[i] = 1;\n const parent = parentOf[i];\n if (parent !== undefined) visit(parent);\n state[i] = 2; order.push(i);\n };\n for (let i = 0; i < pins.length; i++) visit(i);\n return { order, parentOf };\n}\n\n\n/** The active pair shares one hemisphere, including the last-to-first seam. */\nexport function blendRotations(rotations: readonly Rotation[], weights: readonly number[]): Rotation {\n let [x, y, z, w] = [0, 0, 0, 0];\n const reference=rotations[weights.findIndex(weight=>weight>1e-12)]??rotations[0];\n let dominant = reference, best = -Infinity;\n for (let i = 0; i < rotations.length; i++) {\n const q = rotations[i];\n if(weights[i]===0)continue;\n const aligned: Rotation = q[0] * reference[0] + q[1] * reference[1] + q[2] * reference[2] + q[3] * reference[3] < 0\n ? [-q[0], -q[1], -q[2], -q[3]] : q;\n if (weights[i] > best) { best = weights[i]; dominant = aligned; }\n x += aligned[0] * weights[i]; y += aligned[1] * weights[i];\n z += aligned[2] * weights[i]; w += aligned[3] * weights[i];\n }\n const length = Math.hypot(x, y, z, w);\n // Opposed rotations at equal weight cancel and name no orientation at all.\n return length > 1e-6 ? [x / length, y / length, z / length, w / length] : dominant;\n}\n\n/** Blends by id, so a pin missing from either side simply keeps its own pose \u2014\n * it appears on both sides of the blend and cannot move. Everything but the\n * transform comes from the destination: ids, rest positions and flags are\n * shared between slots and are not animated. */\nexport function blendPins(from: readonly PinRecord[], to: readonly PinRecord[], t: number, parents: PinParents = new Map()): readonly PinRecord[] {\n if (t <= 0 && from.length === to.length && to.every((pin, i) => from[i]?.id === pin.id)) return from;\n const aligned = to.map(pin => from.find(other => other.id === pin.id) ?? pin);\n return blendPoses(to, [aligned, to], [1 - t, t], parents);\n}\n\n/** Every pose at once, by weight. `poses` are the same pins in the same order\n * as `base` \u2014 they all come from resolving one document \u2014 so this walks them by\n * index rather than searching per pin per frame.\n *\n * The blend happens in each pin's PARENT frame, never in world space. A chain\n * posed two ways differs mostly in its joints' rotations, and averaging world\n * positions cuts the chord between them: the limb shortens in the middle of\n * every transition and lengthens again at each pose. In the parent's frame only\n * the joint's own rotation and offset move, so the chain keeps its shape, and a\n * pin's transform stays relative to whatever IK did to its parent \u2014 which is\n * what makes moving an IK target interpolate as one arc rather than dragging\n * every pin along a straight line of its own. */\nexport function blendPoses(base: readonly PinRecord[], poses: readonly (readonly PinRecord[])[], weights: readonly number[], parents: PinParents = new Map()): readonly PinRecord[] {\n if (!poses.length || poses.some(pose => pose.length !== base.length)) return base;\n const { order, parentOf } = hierarchyOrder(base, parents);\n const world = new Array<PinPose>(base.length), blended = new Array<PinRecord>(base.length);\n for (const i of order) {\n const parent = parentOf[i], parentWorld = parent === undefined ? undefined : world[parent];\n const locals = poses.map((pose, k) => localPose(pose[i].pose, parent === undefined ? undefined : poses[k][parent].pose));\n world[i] = worldPose(weightedPose(locals, weights), parentWorld);\n const pin: PinRecord = { ...base[i], pose: world[i] };\n // A goal is an anchor in the world, not a point on its parent. A planted\n // foot has the same goal in every pose, and must come out of the blend as\n // that goal exactly however the body above it moves.\n if (!poses.every(pose => pose[i].ikTarget)) { blended[i] = pin; continue; }\n const targets = poses.map(pose => pose[i].ikTarget!);\n blended[i] = { ...pin, ikTarget: {\n position: [0, 1, 2].map(axis => targets.reduce((sum, target, k) => sum + target.position[axis] * weights[k], 0)) as unknown as Point,\n rotation: blendRotations(targets.map(target => target.rotation), weights),\n } };\n }\n return blended;\n}\n\n/** One pose out of many, by weight. */\nfunction weightedPose(poses: readonly PinPose[], weights: readonly number[]): PinPose {\n const position: [number, number, number] = [0, 0, 0], scale: [number, number, number] = [0, 0, 0];\n for (let k = 0; k < poses.length; k++) for (let axis = 0; axis < 3; axis++) {\n position[axis] += poses[k].position[axis] * weights[k];\n scale[axis] += poses[k].scale[axis] * weights[k];\n }\n return { position, rotation: blendRotations(poses.map(pose => pose.rotation), weights), scale };\n}\n", "import { Vector3 } from 'three';\n\nexport const MAX_WIND_STRENGTH = 4;\n\n/** A single weather control drives pin motion and surface pressure. Sparse pin\n * loads stay bounded; fabric pressure has room to grow through a storm. */\nexport function windProfile(strength: number) {\n const level = Math.max(0, Math.min(MAX_WIND_STRENGTH, strength));\n const label = level === 0 ? 'Off' : level < .75 ? 'Breeze' : level < 1.5 ? 'Windy' : level < 2.5 ? 'Strong wind' : level < 3.3 ? 'Gale' : 'Storm';\n return {\n label,\n load: 30 * level * level / (.8 + level * level),\n surfaceLoad: 4 * level * level,\n gust: .14 + .12 * level,\n crosswind: .05 + .07 * level,\n gustRate: .42 + .12 * level,\n };\n}\n\n/** Deterministic scene-local prevailing wind with slow gusts and spatially\n * varying eddies. Force is an acceleration scaled to the model's size, so a\n * tiny prop and a large character respond comparably at the same setting. */\nexport function windAcceleration(seconds: number, strength: number, scale: number, position: readonly number[]) {\n if (strength <= 0) return new Vector3();\n const size = Math.max(1e-4, scale);\n const profile = windProfile(strength);\n // Advect the gust bands along +X. Nearby controls see related wind, while\n // their phase delay keeps a large sheet or branch hierarchy from moving as\n // one perfectly synchronized rigid object.\n const along = position[0] / size, lateral = (position[1] * .67 + position[2] * .33) / size;\n const slow = seconds * profile.gustRate - along * .55;\n const fast = seconds * (profile.gustRate * 2.7) - along * 1.4 + lateral * .4;\n const gust = Math.max(.2, 1 + profile.gust * (.7 * Math.sin(slow) + .3 * Math.sin(fast + 1.3)));\n const cross = profile.crosswind * (.65 * Math.sin(fast + lateral) + .35 * Math.sin(slow * .73 - lateral * .6));\n return new Vector3(1, cross * .35, cross).normalize().multiplyScalar(profile.load * size * gust);\n}\n", "import { IK_CHAIN_KINDS, MAX_FUR_DEPTH, type IKChainRole, type PinRecord, type Point, type Rotation } from './pin-types.js';\nimport { MAX_DEFORMATION_PINS } from './limits.js';\nimport { DEFAULT_MOTION, validateMotionSettings } from './motion-settings.js';\nimport { validateIKConstraint, type IKConstraint } from './ik-constraints.js';\nimport { capturePose, POSE_SLOTS, resolvePose, type PoseSlot } from './pose-slots.js';\nimport type { PinParents } from './pin-types.js';\nimport { MAX_POSE_SECONDS, MIN_POSE_SECONDS, type PoseTiming } from './pose-timeline.js';\nimport { MAX_WIND_STRENGTH } from './wind.js';\n\nfunction record(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid joints JSON object.');\n return value as Record<string, unknown>;\n}\nfunction numbers(value: unknown, length: number): number[] {\n if (!Array.isArray(value) || value.length !== length || !value.every(v => typeof v === 'number' && Number.isFinite(v))) throw new Error('Invalid joint coordinates.');\n return [...value];\n}\nfunction point(value: unknown): Point { const v = numbers(value, 3); return [v[0], v[1], v[2]]; }\nfunction quaternion(value: unknown): Rotation { const v = numbers(value, 4); return [v[0], v[1], v[2], v[3]]; }\nexport function validateJoints(value: unknown, maximum = MAX_DEFORMATION_PINS): readonly PinRecord[] {\n if (!Array.isArray(value) || value.length > maximum) throw new Error(`Joints JSON must contain at most ${maximum} joints.`);\n const ids = new Set<string>();\n const pins = value.map(item => {\n const pin = record(item), pose = record(pin.pose);\n if (typeof pin.id !== 'string' || !pin.id || ids.has(pin.id)) throw new Error('Joint IDs must be unique non-empty strings.');\n ids.add(pin.id);\n if (typeof pin.independent !== 'boolean' || (pin.rigidGroup !== null && (typeof pin.rigidGroup !== 'string' || !pin.rigidGroup))) throw new Error('Invalid joint membership.');\n if (pin.guide !== undefined && typeof pin.guide !== 'boolean') throw new Error('Invalid guide flag.');\n if (pin.authored !== undefined && typeof pin.authored !== 'boolean') throw new Error('Invalid authored flag.');\n if (pin.ik !== undefined && typeof pin.ik !== 'boolean') throw new Error('Invalid IK flag.');\n if (pin.wiggle !== undefined && typeof pin.wiggle !== 'boolean') throw new Error('Invalid Wiggle flag.');\n if (pin.cloth !== undefined && typeof pin.cloth !== 'boolean') throw new Error('Invalid Cloth flag.');\n if (pin.fur !== undefined && typeof pin.fur !== 'boolean') throw new Error('Invalid Fur flag.');\n if (pin.furDepth !== undefined && (typeof pin.furDepth !== 'number' || !Number.isFinite(pin.furDepth) || pin.furDepth < 0 || pin.furDepth > MAX_FUR_DEPTH)) throw new Error('Invalid Fur depth.');\n const chainRole=pin.chainRole===undefined?undefined:(()=>{\n const value=record(pin.chainRole);\n if(!IK_CHAIN_KINDS.includes(value.kind as IKChainRole['kind'])||!['center','left','right'].includes(value.side as string)||\n (value.position!==undefined&&!['front','hind'].includes(value.position as string)))throw new Error('Invalid IK chain role.');\n return {kind:value.kind as IKChainRole['kind'],side:value.side as IKChainRole['side'],...(value.position?{position:value.position as 'front'|'hind'}:{})};\n })();\n if (Number(Boolean(pin.ik)) + Number(Boolean(pin.wiggle)) + Number(Boolean(pin.cloth)) + Number(Boolean(pin.fur)) > 1) throw new Error('Choose IK, Wiggle, Cloth or Fur.');\n const motion = pin.motion === undefined ? undefined : (()=>{\n const raw=record(pin.motion), result={reach:Number(raw.reach),frequency:Number(raw.frequency),damping:Number(raw.damping),massInfluence:raw.massInfluence===undefined?DEFAULT_MOTION.massInfluence:Number(raw.massInfluence),strength:raw.strength===undefined?DEFAULT_MOTION.strength:Number(raw.strength)};\n for(const key of ['massInfluence','strength']) if(raw[key]!==undefined && typeof raw[key]!=='number') throw new Error('Invalid motion settings.');\n if (typeof raw.reach!=='number' || typeof raw.frequency!=='number' || typeof raw.damping!=='number') throw new Error('Invalid motion settings.');\n validateMotionSettings(result); return result;\n })();\n const ikConstraint=pin.ikConstraint===undefined?undefined:(()=>{const raw=record(pin.ikConstraint);const value={mode:raw.mode,axis:raw.axis,min:raw.min,max:raw.max,...(raw.orientation!==undefined?{orientation:quaternion(raw.orientation)}:{}),...(raw.maxY!==undefined?{maxY:raw.maxY}:{})} as IKConstraint;validateIKConstraint(value);return value;})();\n const ikTarget=pin.ikTarget === undefined ? undefined : (()=>{\n const raw=record(pin.ikTarget),rotation=quaternion(raw.rotation);\n if (Math.abs(Math.hypot(...rotation)-1)>1e-4) throw new Error('Invalid IK target rotation.');\n return {position:point(raw.position),rotation};\n })();\n if (pin.guide && (pin.rigidGroup || pin.independent)) throw new Error('Guides cannot be rigid members or roots.');\n const scale = point(pose.scale), rotation = quaternion(pose.rotation);\n if (scale.some(v => v < 0.01 || v > 100) || Math.abs(Math.hypot(...rotation) - 1) > 1e-4) throw new Error('Invalid joint rotation or scale.');\n return { id: pin.id, independent: pin.independent, rigidGroup: pin.rigidGroup, ...(pin.authored === true ? { authored: true } : {}), ...(typeof pin.guide === 'boolean' ? { guide: pin.guide } : {}), ...(typeof pin.ik === 'boolean' ? { ik: pin.ik } : {}),\n ...(ikConstraint?{ikConstraint}:{}),...(chainRole?{chainRole}:{}),...(motion ? {motion}:{}),...(ikTarget ? {ikTarget}:{}),...(typeof pin.wiggle === 'boolean' ? {wiggle:pin.wiggle} : {}),...(typeof pin.cloth === 'boolean' ? {cloth:pin.cloth} : {}),...(typeof pin.fur === 'boolean' ? {fur:pin.fur} : {}),...(pin.furDepth !== undefined ? {furDepth:pin.furDepth as number} : {}), rest: point(pin.rest), pose: { position: point(pose.position), rotation, scale } };\n });\n for (const pin of pins) if (pin.rigidGroup) {\n const anchor = pins.find(other => other.rigidGroup === pin.rigidGroup)!;\n const dot = pin.pose.rotation.reduce((sum, v, i) => sum + v * anchor.pose.rotation[i], 0);\n if (pin.pose.scale.some(v => Math.abs(v - anchor.pose.scale[0]) > 1e-5) || 1 - Math.abs(dot) > 1e-5) throw new Error('Rigid joints must share rotation and uniform scale.');\n }\n return pins;\n}\nexport interface JointsRig { pins:readonly PinRecord[];activePose:number;poseSlots:readonly PoseSlot[];poseTimes:readonly PoseTiming[];windStrength?:number }\nfunction validatePoseTimes(value:unknown):readonly PoseTiming[]{\n if(!Array.isArray(value)||value.length>POSE_SLOTS)throw new Error('Invalid pose times.');\n const slots=new Set<number>();\n return value.map(item=>{\n const entry=record(item);\n if(!Number.isInteger(entry.slot)||(entry.slot as number)<0||(entry.slot as number)>POSE_SLOTS||slots.has(entry.slot as number))throw new Error('Invalid pose time slot.');\n slots.add(entry.slot as number);\n if(typeof entry.seconds!=='number'||!Number.isFinite(entry.seconds)||entry.seconds<MIN_POSE_SECONDS||entry.seconds>MAX_POSE_SECONDS)throw new Error('Invalid pose time.');\n return {slot:entry.slot as number,seconds:entry.seconds};\n }).sort((a,b)=>a.slot-b.slot);\n}\n/** Slots are written out in full. A pin the hierarchy places is left unsaid in\n * the editor so it keeps following its parent, but a file has no voxel field to\n * rebuild that hierarchy from and older readers would drop it to rest, so the\n * inherited pose is resolved here and stored. */\nexport function validateRig(value:JointsRig, maximum = MAX_DEFORMATION_PINS, parents:PinParents = new Map()):JointsRig{\n const pins=validateJoints(value.pins,maximum);\n if (value.windStrength !== undefined && (!Number.isFinite(value.windStrength) || value.windStrength < 0 || value.windStrength > MAX_WIND_STRENGTH)) throw new Error('Invalid wind strength.');\n if(!Number.isInteger(value.activePose)||value.activePose<0||value.activePose>POSE_SLOTS||!Array.isArray(value.poseSlots)||value.poseSlots.length>POSE_SLOTS)throw new Error('Invalid pose slots.');\n const slots=new Set<number>(),ids=new Set(pins.map(p=>p.id));\n const poseSlots=value.poseSlots.map(slot=>{\n if(!slot||!Number.isInteger(slot.slot)||slot.slot<1||slot.slot>POSE_SLOTS||slots.has(slot.slot)||!Array.isArray(slot.poses))throw new Error('Invalid pose slot.');slots.add(slot.slot);\n const pinIds=new Set<string>();for(const p of slot.poses){if(!p||!ids.has(p.id)||pinIds.has(p.id))throw new Error('Invalid pose pin.');pinIds.add(p.id);}\n return {slot:slot.slot,poses:capturePose(validateJoints(resolvePose(pins,slot,parents),maximum))};\n }).filter(slot=>slot.slot!==value.activePose);\n return {pins,activePose:value.activePose,poseSlots,poseTimes:validatePoseTimes(value.poseTimes??[]),...(value.windStrength !== undefined ? {windStrength:value.windStrength} : {})};\n}\n", "import { Goal, Joint, Link, Solver } from 'closed-chain-ik/core';\nimport { Euler, Matrix4, Quaternion, Vector3 } from 'three';\nimport type { PinRecord, PinPose, Point, Rotation } from './pin-types.js';\nimport { DEFAULT_MOTION } from './motion-settings.js';\nimport type { PinParents } from './pin-types.js';\nimport { DEFAULT_IK_CONSTRAINT, constrainCone } from './ik-constraints.js';\n\nconst POSE_CONTINUITY_WEIGHT=1e-4;\n\n/** A routing guide is not a limb. Only guides leading to real joints create\n * an articulated branch; dangling guidance must not lock an IK pivot. */\nfunction articulatedNodes(pins: readonly PinRecord[], parents: PinParents) {\n const nodes = new Set<string>();\n for (const pin of pins) if (!pin.guide) {\n let id: string | undefined = pin.id;\n while (id && !nodes.has(id)) { nodes.add(id); id = parents.get(id); }\n }\n return nodes;\n}\n\n/** IDs are derived each time; no stale authored chain survives topology edits. */\nexport function ikChain(pins: readonly PinRecord[], parents: PinParents, id: string, mass: ReadonlyMap<string, number> = new Map()): PinRecord[] {\n const byId = new Map(pins.map(pin => [pin.id, pin]));\n const element = (pin: PinRecord) => pin.rigidGroup ?? pin.id;\n const articulated = articulatedNodes(pins, parents);\n const children = new Map<string, Set<string>>();\n const supportLength=new Map<string,number>();\n for (const pin of pins) {\n if (!articulated.has(pin.id)) continue;\n const parent = byId.get(parents.get(pin.id) ?? '');\n if (!parent) continue;\n const length=Math.hypot(...pin.rest.map((x,i)=>x-parent.rest[i]))*.5;\n supportLength.set(pin.id,(supportLength.get(pin.id)??0)+length);\n supportLength.set(parent.id,(supportLength.get(parent.id)??0)+length);\n const set = children.get(element(parent)) ?? new Set<string>(); set.add(element(pin)); children.set(element(parent), set);\n }\n const chain: PinRecord[] = [], seen = new Set<string>();\n let pin = byId.get(id);\n const reach = pin?.motion?.reach ?? DEFAULT_MOTION.reach;\n let automatic:string|undefined;\n // Mass per supported rest length approximates cross-section, unlike raw\n // per-pin mass which shrinks simply because a limb gained more joints.\n const density=(p:PinRecord)=>mass.has(p.id)?mass.get(p.id)!/Math.max(supportLength.get(p.id)??0,1e-12):undefined;\n while (pin && !seen.has(element(pin))) {\n chain.unshift(pin); seen.add(element(pin));\n if (pin.independent) break;\n const parent = byId.get(parents.get(pin.id) ?? '');\n if (!parent) break;\n // Keep the body/other limbs stationary. An immediate parent is still\n // needed as the pivot for a single-link chain.\n if (!automatic && ((children.get(element(parent))?.size ?? 0) > 1\n || (!pin.guide && !parent.guide && (density(parent) ?? 0) > 8 * Math.max(density(pin) ?? Infinity, 1e-12)))) automatic=parent.id;\n pin = parent;\n }\n if(chain.length<2)return chain;\n const distance=new Float64Array(chain.length);\n for(let i=chain.length-2;i>=0;i--)distance[i]=distance[i+1]+Math.hypot(...chain[i].rest.map((x,k)=>x-chain[i+1].rest[k]));\n const boundary=automatic?chain.findIndex(p=>p.id===automatic):-1;\n const automaticDistance=distance[Math.max(0,boundary)];\n // Reach measures REST arc length, not node count or posed/chord distance.\n // Zero starts at the endpoint (clamped to one link); subdivision must not\n // move the slider's origin by changing that first link's length.\n const budget=reach<=.5?automaticDistance*reach*2:automaticDistance+(distance[0]-automaticDistance)*(reach-.5)*2;\n const first=reach<=.5&&boundary>=0?Math.min(boundary+1,chain.length-2):0;\n let start=chain.length-2;\n for(let i=start-1;i>=first;i--)if(Math.abs(distance[i]-budget)<Math.abs(distance[start]-budget))start=i;\n if(reach===1)start=0;\n return chain.slice(start);\n}\n\nexport function solvePinIK(pins: readonly PinRecord[], parents: PinParents, id: string, target: Point,\n mass?: ReadonlyMap<string, number>, targetRotation?: Rotation): { id: string; pose: PinPose }[] {\n const pin=pins.find(p=>p.id===id)!;\n return solvePinIKGoals(pins,parents,[{id,position:target,rotation:targetRotation ?? pin.ikTarget?.rotation ?? pin.pose.rotation}],mass);\n}\n\nexport type IKGoal = {id:string;position:Point;rotation:Rotation};\n\n/** Endpoint editing is local. Shared body frames and sibling branches retain\n * their authored poses; root/body edits use the separate multi-goal solve. */\nexport function solveLocalPinIK(pins:readonly PinRecord[],parents:PinParents,goal:IKGoal,mass?:ReadonlyMap<string,number>,floor=-Infinity){\n const chain=ikChain(pins,parents,goal.id,mass),key=(p:PinRecord)=>p.rigidGroup??p.id;\n const keys=new Set(chain.map(key)),byId=new Map(pins.map(p=>[p.id,p]));\n const articulated = articulatedNodes(pins, parents);\n let boundary=-1;\n // Children below the endpoint are followers, never competing side branches.\n for(let i=0;i<chain.length-1;i++)if(chain[i].independent || pins.some(p=>{\n if (!articulated.has(p.id)) return false;\n const parent=byId.get(parents.get(p.id)??'');return parent&&key(parent)===key(chain[i])&&!keys.has(key(p));\n }))boundary=i;\n const shared=boundary>=0&&pins.some(p=>{\n if(!articulated.has(p.id))return false;\n const parent=byId.get(parents.get(p.id)??'');\n return parent&&key(parent)===key(chain[boundary])&&!keys.has(key(p));\n });\n // A shared attachment fixes the body. The outgoing limb gets a separate\n // zero-length branch pivot in the solver, so the first link can still swing.\n // A lone independent root has no sibling to disturb and retains the exact\n // two-link analytic solve through its temporary root rotation.\n const fixed=new Set(chain.slice(0,shared?boundary+1:Math.max(0,boundary)).flatMap(p=>pins.filter(q=>key(q)===key(p)).map(q=>q.id)));\n const moving=new Set(chain.slice(boundary+1).map(key));\n for(let added=true;added;){added=false;for(const p of pins){const parent=byId.get(parents.get(p.id)??'');if(parent&&moving.has(key(parent))&&!moving.has(key(p))){moving.add(key(p));added=true;}}}\n const retained=new Set(boundary>=0?[key(chain[boundary])]:[]);\n return solvePinIKGoals(pins,parents,[goal],mass,fixed,retained,floor).filter(p=>moving.has(key(byId.get(p.id)!)));\n}\n\n/** Solve separate planted limbs against the same body pose. Their temporary\n * attachment rotations must not become rotations of the shared torso frame. */\nexport function solvePlantedPinIKGoals(pins:readonly PinRecord[],parents:PinParents,goals:readonly IKGoal[],mass?:ReadonlyMap<string,number>,fixed:ReadonlySet<string>=new Set(),floor=-Infinity){\n if(!goals.length)return [];\n const edits=new Map<string,{id:string;pose:PinPose}>();\n let independent=true;\n for(const goal of goals){\n const limb=solveLocalPinIK(pins,parents,goal,mass,floor);\n for(const edit of limb){\n if(fixed.has(edit.id)||edits.has(edit.id)){independent=false;break;}\n edits.set(edit.id,edit);\n }\n if(!independent)break;\n }\n return independent?[...edits.values()]:solvePinIKGoals(pins,parents,goals,mass,fixed,new Set(),floor);\n}\n\n/** Body motion and imported-pose reconstruction use the same full-chain solve.\n * Shared attachment frames are held; each limb gets its own branch pivot. */\nexport function solveBodyIKGoals(pins:readonly PinRecord[],parents:PinParents,goals:readonly IKGoal[],mass:ReadonlyMap<string,number>,fixed:ReadonlySet<string>,floor=-Infinity){\n const poleChains=new Map(goals.map(goal=>[goal.id,ikChain(pins,parents,goal.id,mass)]));\n const full=pins.map(pin=>pin.ik?{...pin,motion:{...DEFAULT_MOTION,...pin.motion,reach:1}}:pin);\n const uses=new Map<string,number>();\n for(const goal of goals)for(const pin of ikChain(full,parents,goal.id,mass))uses.set(pin.id,(uses.get(pin.id)??0)+1);\n const anchors=new Set([...fixed,...[...uses].filter(([,count])=>count>1).map(([id])=>id)]);\n return solvePinIKGoals(full,parents,goals,mass,anchors,new Set(),floor,poleChains);\n}\n\n/** One articulated forest, one joint solve. Shared joints are never overwritten\n * by a later endpoint, and every child offset retains its authored length. */\nexport function solvePinIKGoals(pins:readonly PinRecord[],parents:PinParents,goals:readonly IKGoal[],mass?:ReadonlyMap<string,number>,fixed:ReadonlySet<string>=new Set(),retained:ReadonlySet<string>=new Set(),floor=-Infinity,poleChains:ReadonlyMap<string,readonly PinRecord[]> = new Map()):{id:string;pose:PinPose}[] {\n if (!goals.length) return [];\n const byId=new Map(pins.map(p=>[p.id,p])),key=(p:PinRecord)=>p.rigidGroup ?? p.id;\n const groups=new Map<string,PinRecord[]>();\n for(const pin of pins){const group=groups.get(key(pin)) ?? [];group.push(pin);groups.set(key(pin),group);}\n const parentGroup=new Map<string,string>();\n for(const [id,members] of groups){\n const parent=members.map(p=>byId.get(parents.get(p.id) ?? '')).find(p=>p && key(p)!==id);\n if(parent) parentGroup.set(id,key(parent));\n }\n // A joint carries every pin below it, so a joint above a fixed pin holds\n // still too; otherwise the fixed pin would swing about that ancestor.\n const holding=new Set<string>();\n for(const [id,members] of groups) if(members.some(p=>fixed.has(p.id))) for(let at:string|undefined=id;at&&!holding.has(at);at=parentGroup.get(at)) holding.add(at);\n const active=new Set<string>(), roots=new Set<string>();\n const bendSeeds=new Map<string,Vector3>();\n let size=0;\n for(const goal of goals){\n const chain=ikChain(pins,parents,goal.id,mass);\n if(chain.length<2) throw new Error('IK needs a parent chain. Add a parent pin or remove Independent from this endpoint.');\n for(const p of chain) active.add(key(p));\n roots.add(key(chain[0]));\n // Only a straight, contracting chain needs a perturbation: at full\n // extension its positional Jacobian cannot discover a bend. Seeding an\n // already bent chain injects rotation on every drag sample and accumulates\n // drift despite a nearly stationary target.\n const start=new Vector3().fromArray(chain[0].pose.position),direction=new Vector3().fromArray(chain.at(-1)!.pose.position).sub(start);\n const span=direction.length();\n if(span>1e-8 && new Vector3().fromArray(goal.position).distanceTo(start)<span*(1-1e-6)){\n direction.divideScalar(span);\n const straight=chain.every(p=>new Vector3().fromArray(p.pose.position).sub(start).cross(direction).lengthSq()<span*span*1e-12);\n const candidate=straight?chain.slice(1,-1).find(p=>!holding.has(key(p)) && ['free','cone'].includes((p.ikConstraint??DEFAULT_IK_CONSTRAINT).mode)):undefined;\n if(candidate){\n // Bend in the plane the goal is actually in: perpendicular to both the\n // chain and the way it has to reach. Seeding off the chain's smallest\n // world component instead picks a plane with no relation to the goal,\n // and a straight arm pulled sideways swings out of the screen on its\n // way there \u2014 deterministic, but not a bend anyone asked for.\n const axis=new Vector3().crossVectors(direction,new Vector3().fromArray(goal.position).sub(start));\n if(axis.lengthSq()<1e-12){\n // The goal lies along the chain, so no plane is implied by it; any\n // axis across the chain will do, chosen the same way every time.\n const components=direction.toArray().map(Math.abs);\n axis.setComponent(components.indexOf(Math.min(...components)),1).addScaledVector(direction,-axis.dot(direction));\n }\n bendSeeds.set(key(candidate),axis.normalize());\n }\n }\n size=Math.max(size,chain.slice(1).reduce((sum,p,i)=>sum+new Vector3().fromArray(p.pose.position).distanceTo(new Vector3().fromArray(chain[i].pose.position)),0));\n }\n if(size<1e-8) throw new Error('IK chain has no length. Separate its rest pins first.');\n // Include followers in the graph so branch attachments keep their lengths too.\n const affected=new Set(active);\n for(let changed=true;changed;){changed=false;for(const [id,parent] of parentGroup) if(affected.has(parent)&&!affected.has(id)){affected.add(id);changed=true;}}\n const unchanged=goals.every(g=>{const p=byId.get(g.id)!;return new Vector3().fromArray(g.position).distanceToSquared(new Vector3().fromArray(p.pose.position))<1e-20 && new Quaternion().fromArray(g.rotation).angleTo(new Quaternion().fromArray(p.pose.rotation))<1e-10;});\n if(unchanged && !pins.some(p=>p.ikConstraint && p.ikConstraint.mode!=='free')) return pins.filter(p=>affected.has(key(p))).map(p=>({id:p.id,pose:p.pose}));\n const origin=new Vector3().fromArray(byId.get(goals[0].id)!.pose.position);\n const frames=new Map<string,Link>(), forest:Link[]=[], building=new Set<string>();\n const coneJoints=new Map<string,Joint>();\n const freeJoints=new Map<string,Joint>();\n const branchJoints=new Map<string,{joint:Joint;frame:Link}>();\n const build=(id:string):Link=>{\n const cached=frames.get(id);if(cached) return cached;\n if(building.has(id)) throw new Error('Cyclic IK hierarchy.');building.add(id);\n const pin=groups.get(id)![0],parentId=parentGroup.get(id),parent=parentId ? groups.get(parentId)![0] : undefined;\n const parentFrame=parentId ? build(parentId) : new Link();\n let attachment=parentFrame;\n if(parentId&&active.has(id)&&!holding.has(id)&&holding.has(parentId)){\n const pivot=new Joint();pivot.setDoF(3,4,5);pivot.setDoFValues(0,0,0);pivot.setRestPoseValues(0,0,0);\n parentFrame.addChild(pivot);attachment=new Link();pivot.addChild(attachment);\n branchJoints.set(id,{joint:pivot,frame:attachment});\n }\n const parentRotation=parent ? new Quaternion().fromArray(parent.pose.rotation) : new Quaternion();\n const position=new Vector3().fromArray(pin.pose.position).sub(parent ? new Vector3().fromArray(parent.pose.position):origin).applyQuaternion(parentRotation.clone().invert()).divideScalar(size);\n const relative=parentRotation.clone().invert().multiply(new Quaternion().fromArray(pin.pose.rotation)).normalize();\n const joint=new Joint();joint.setPosition(position.x,position.y,position.z);attachment.addChild(joint);\n const link=new Link(),constraint=pin.ikConstraint ?? DEFAULT_IK_CONSTRAINT;\n const movable=active.has(id)&&!holding.has(id);\n if(!movable || constraint.mode==='locked') joint.setQuaternion(...relative.toArray());\n else if(constraint.mode==='hinge') {\n let axis=new Vector3();\n if(constraint.axis!=='auto') axis.setComponent(['x','y','z'].indexOf(constraint.axis),1);\n else {\n const child=pins.find(p=>parents.get(p.id)===pin.id && active.has(key(p)));\n if(parent&&child) axis.crossVectors(new Vector3().fromArray(pin.rest).sub(new Vector3().fromArray(parent.rest)),new Vector3().fromArray(child.rest).sub(new Vector3().fromArray(pin.rest)));\n if(axis.lengthSq()<1e-10) {const direction=child ? new Vector3().fromArray(child.rest).sub(new Vector3().fromArray(pin.rest)).normalize():new Vector3(0,1,0);axis.crossVectors(direction,Math.abs(direction.z)<.9 ? new Vector3(0,0,1):new Vector3(1,0,0));}\n axis.normalize();\n }\n const basis=new Quaternion().setFromUnitVectors(new Vector3(0,0,1),axis);\n joint.setQuaternion(...basis.toArray());link.setQuaternion(...basis.clone().invert().toArray());\n joint.setDoF(5);joint.setMinLimits(constraint.min*Math.PI/180);joint.setMaxLimits(constraint.max*Math.PI/180);\n const twist=2*Math.atan2(new Vector3(relative.x,relative.y,relative.z).dot(axis),relative.w);\n joint.setDoFValues(Math.atan2(Math.sin(twist),Math.cos(twist)));joint.setRestPoseValues(0);\n } else {\n if(constraint.mode==='cone')coneJoints.set(id,joint);\n else freeJoints.set(id,joint);\n joint.setDoF(3,4,5);\n const euler=new Euler().setFromQuaternion(relative,'ZYX');joint.setDoFValues(euler.x,euler.y,euler.z);joint.setRestPoseValues(euler.x,euler.y,euler.z);\n const seed=bendSeeds.get(id);\n if(seed && !roots.has(id) && !goals.some(g=>key(byId.get(g.id)!)===id)){\n const axis=seed.clone().applyQuaternion(parentRotation.clone().invert());\n const seeded=new Euler().setFromQuaternion(new Quaternion().setFromAxisAngle(axis,.03).multiply(relative),'ZYX');\n joint.setDoFValues(seeded.x,seeded.y,seeded.z);\n }\n }\n joint.addChild(link);frames.set(id,link);building.delete(id);if(!parentId) forest.push(parentFrame);return link;\n };\n for(const id of groups.keys()) build(id);\n // Limits describe the visible segment in the committed parent's frame, not\n // a shared attachment's temporary solver rotation or a stale inserted frame.\n const limitRotation=(id:string,rotation:Quaternion,parentRotation:Quaternion)=>{\n const pin=groups.get(id)![0];if(pin.ikConstraint?.mode!=='cone')return rotation;\n const parentId=parentGroup.get(id),parent=parentId?groups.get(parentId)![0]:undefined;\n const child=pins.find(p=>parents.get(p.id)===pin.id);\n if(retained.has(id)&&child&&!active.has(key(child)))return rotation;\n const axis=child?new Vector3().fromArray(child.rest).sub(new Vector3().fromArray(pin.rest)):parent?new Vector3().fromArray(pin.rest).sub(new Vector3().fromArray(parent.rest)):new Vector3(0,1,0);\n if(axis.lengthSq()<1e-12)axis.set(0,1,0);\n const movingAxis=child?new Vector3().fromArray(child.pose.position).sub(new Vector3().fromArray(pin.pose.position)).applyQuaternion(new Quaternion().fromArray(pin.pose.rotation).invert()):axis;\n if(movingAxis.lengthSq()<1e-12)movingAxis.copy(axis);\n const reference=parentId&&retained.has(parentId)?new Quaternion().fromArray(parent!.pose.rotation):parentRotation;\n const relative=reference.clone().invert().multiply(parentRotation).multiply(rotation);\n return parentRotation.clone().invert().multiply(reference).multiply(constrainCone(relative,axis,pin.ikConstraint,movingAxis));\n };\n // Continuity refers to the pose on screen, before analytic initialization\n // or cone projection chooses a candidate. Include temporary body pivots.\n const priorRotations=new Map([...frames.values(),...[...branchJoints.values()].map(branch=>branch.frame)].map(frame=>{\n frame.updateMatrixWorld();return [frame,new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(frame.matrixWorld))] as const;\n }));\n const closures:Goal[]=[];\n for(const target of goals){\n const pin=byId.get(target.id)!,anchor=groups.get(key(pin))![0];\n const offset=new Vector3().fromArray(pin.pose.position).sub(new Vector3().fromArray(anchor.pose.position)).applyQuaternion(new Quaternion().fromArray(anchor.pose.rotation).invert()).divideScalar(size);\n const attachment=new Joint();attachment.setPosition(...offset.toArray());frames.get(key(pin))!.addChild(attachment);\n const tip=new Link();attachment.addChild(tip);\n const goal=new Goal();\n const freeEndpoint=groups.get(key(pin))!.length===1 && (!pin.ikConstraint || pin.ikConstraint.mode==='free');\n if(freeEndpoint) goal.setGoalDoF(0,1,2);else goal.setGoalDoF(0,1,2,3,4,5);\n goal.makeClosure(tip);\n const requested=new Vector3().fromArray(target.position);\n if(goals.length===1 && freeEndpoint){\n const chain=ikChain(pins,parents,target.id,mass);\n const first=chain.findIndex(p=>!holding.has(key(p)) && (p.ikConstraint??DEFAULT_IK_CONSTRAINT).mode!=='locked');\n const moving=first<0?[]:chain.slice(branchJoints.has(key(chain[first]))?Math.max(0,first-1):first);\n // For an unconstrained ball-joint chain its link lengths define a\n // reachable spherical shell. Solve against that shell, not an impossible\n // residual which can stall the iterative solver away from the closest\n // pose. The authored world target is deliberately left unchanged.\n if(moving.length>1 && moving.every((p,i)=>(i===0&&branchJoints.has(key(moving[1])))||(!fixed.has(p.id) && groups.get(key(p))!.length===1 && (p.ikConstraint??DEFAULT_IK_CONSTRAINT).mode==='free'))){\n const pivot=new Vector3().fromArray(moving[0].pose.position);\n const lengths=moving.slice(1).map((p,i)=>new Vector3().fromArray(p.pose.position).distanceTo(new Vector3().fromArray(moving[i].pose.position)));\n const outer=lengths.reduce((a,b)=>a+b,0),inner=Math.max(0,2*Math.max(...lengths)-outer),delta=requested.clone().sub(pivot),distance=delta.length();\n if(distance<inner || distance>outer){\n if(distance<1e-12)delta.fromArray(moving.at(-1)!.pose.position).sub(pivot);\n if(delta.lengthSq()>1e-24)requested.copy(pivot).add(delta.setLength(Math.max(inner,Math.min(outer,distance))));\n }\n if(moving.length===2){\n // One free link has a closed-form minimum-rotation solution. Its\n // positional Jacobian is rank deficient (twist is unobservable), so\n // initialize it analytically instead of relying on an arbitrary seed.\n const before=new Vector3().fromArray(moving[1].pose.position).sub(pivot),after=requested.clone().sub(pivot);\n if(before.lengthSq()>1e-24 && after.lengthSq()>1e-24){\n const branch=branchJoints.get(key(moving[1])),parent=branch?moving[0]:byId.get(parents.get(moving[0].id)??'');\n const local=parent?new Quaternion().fromArray(parent.pose.rotation).invert():new Quaternion();\n local.multiply(new Quaternion().setFromUnitVectors(before.normalize(),after.normalize())).multiply(new Quaternion().fromArray(moving[0].pose.rotation));\n const euler=new Euler().setFromQuaternion(local,'ZYX');(branch?.joint??freeJoints.get(key(moving[0])))!.setDoFValues(euler.x,euler.y,euler.z);\n }\n }\n }\n }\n goal.setPosition(...requested.sub(origin).divideScalar(size).toArray());goal.setQuaternion(...target.rotation);\n closures.push(goal);\n }\n // Two-link limbs have an exact positional solution. Keep their existing bend\n // plane and transport each frame by the minimum swing: an Euler/SVD solve can\n // choose a different elbow branch or arbitrary axial twist near singularity.\n // Cone projection + constrained refinement below still enforce authored limits.\n let analytic=false;\n if(goals.length===1){\n const goal=goals[0],chain=ikChain(pins,parents,goal.id,mass);\n const first=chain.findIndex((p,i)=>coneJoints.has(key(p))||freeJoints.has(key(p))||(i+1<chain.length&&branchJoints.has(key(chain[i+1]))));\n const limb=first<0?[]:chain.slice(first),tipPin=byId.get(goal.id)!;\n if(limb.length===3&&limb.every(p=>groups.get(key(p))!.length===1)\n &&limb.slice(0,2).every((p,i)=>coneJoints.has(key(p))||freeJoints.has(key(p))||branchJoints.has(key(limb[i+1])))\n &&(!tipPin.ikConstraint||tipPin.ikConstraint.mode==='free')){\n const world=(p:PinRecord)=>{const frame=frames.get(key(p))!;frame.updateMatrixWorld();return new Matrix4().fromArray(frame.matrixWorld);};\n const matrices=limb.map(world),points=matrices.map(m=>new Vector3().setFromMatrixPosition(m));\n const [base,knee,tip]=points,a=base.distanceTo(knee),b=knee.distanceTo(tip);\n const direction=new Vector3().fromArray(closures[0].position).sub(base);\n if(a>1e-10&&b>1e-10&&direction.lengthSq()>1e-20){\n const distance=Math.max(Math.abs(a-b)+1e-9,Math.min(a+b-1e-9,direction.length()));direction.normalize();\n const oldAxis=tip.clone().sub(base).normalize();\n const bend=knee.clone().sub(base).addScaledVector(oldAxis,-knee.clone().sub(base).dot(oldAxis));\n // Transport the previous pole with the target, instead of projecting it\n // against the new axis (which can flip the knee on a large target move).\n bend.applyQuaternion(new Quaternion().setFromUnitVectors(oldAxis,direction));\n if(bend.lengthSq()<1e-16){\n bend.fromArray(limb[1].rest).sub(new Vector3().fromArray(limb[0].rest));\n const restAxis=new Vector3().fromArray(limb[2].rest).sub(new Vector3().fromArray(limb[0].rest)).normalize();\n bend.addScaledVector(restAxis,-bend.dot(restAxis)).applyQuaternion(new Quaternion().setFromRotationMatrix(matrices[0]));\n bend.addScaledVector(direction,-bend.dot(direction));\n }\n if(bend.lengthSq()<1e-16){bend.set(Math.abs(direction.x)<.8?1:0,Math.abs(direction.x)<.8?0:1,0);bend.addScaledVector(direction,-bend.dot(direction));}\n const along=(a*a-b*b+distance*distance)/(2*distance);\n const desiredKnee=base.clone().addScaledVector(direction,along).addScaledVector(bend.normalize(),Math.sqrt(Math.max(0,a*a-along*along)));\n const desiredTip=base.clone().addScaledVector(direction,distance);\n for(const [i,end] of [desiredKnee,desiredTip].entries()){\n const pin=limb[i],branch=branchJoints.get(key(limb[i+1])),frame=branch?.frame??frames.get(key(pin))!;\n frame.updateMatrixWorld();\n const matrix=new Matrix4().fromArray(frame.matrixWorld),pivot=new Vector3().setFromMatrixPosition(matrix);\n const before=new Vector3().setFromMatrixPosition(world(limb[i+1])).sub(pivot),after=end.clone().sub(pivot);\n const parentId=parentGroup.get(key(pin)),parentFrame=branch?frames.get(key(pin)):branchJoints.get(key(pin))?.frame??(parentId?frames.get(parentId):undefined);parentFrame?.updateMatrixWorld();\n const parentRotation=parentFrame?new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(parentFrame.matrixWorld)):new Quaternion();\n const rotation=parentRotation.invert().multiply(new Quaternion().setFromUnitVectors(before.normalize(),after.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\n const euler=new Euler().setFromQuaternion(rotation,'ZYX');(branch?.joint??coneJoints.get(key(pin))??freeJoints.get(key(pin)))!.setDoFValues(euler.x,euler.y,euler.z);\n }\n analytic=true;\n }\n }\n }\n const positionOnlyGoal=goals.length===1&&groups.get(key(byId.get(goals[0].id)!))!.length===1\n &&(!byId.get(goals[0].id)!.ikConstraint||byId.get(goals[0].id)!.ikConstraint!.mode==='free');\n const positionOnlyGoals=goals.every(goal=>groups.get(key(byId.get(goal.id)!))!.length===1\n &&(!byId.get(goal.id)!.ikConstraint||byId.get(goal.id)!.ikConstraint!.mode==='free'));\n // A lone planted foot has a prior bend in the current frame. Starting a\n // global SVD solve there can choose another elbow branch on a tiny edit;\n // the constrained descent below instead continues that bend.\n if(!analytic&&!positionOnlyGoal&&!positionOnlyGoals){\n const solver=new Solver([...forest,...closures]);solver.useSVD=true;solver.maxIterations=48;solver.restPoseFactor=.001;\n solver.translationConvergeThreshold=1e-6;solver.rotationConvergeThreshold=1e-6;solver.translationErrorClamp=.2;\n solver.solve();\n }\n // Project oriented elliptical swing limits in parent-to-child order. Updating the joint\n // frame carries descendants rigidly, so limiting a cone never stretches links.\n const projectCones=()=>{for(const [id,joint] of coneJoints){\n const parentId=parentGroup.get(id), frame=frames.get(id)!;\n frame.updateMatrixWorld();\n const parentFrame=branchJoints.get(id)?.frame??(parentId?frames.get(parentId):undefined);\n const parentRotation=parentFrame?new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(parentFrame.matrixWorld)):new Quaternion();\n const relative=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(frame.matrixWorld)));\n const limited=limitRotation(id,relative,parentRotation),euler=new Euler().setFromQuaternion(limited,'ZYX');\n joint.setDoFValues(euler.x,euler.y,euler.z);frame.updateMatrixWorld();\n }\n };\n if(goals.length===1||!positionOnlyGoals)projectCones();\n if(goals.length>1&&positionOnlyGoals){\n const world=(frame:Link)=>{frame.updateMatrixWorld();return new Matrix4().fromArray(frame.matrixWorld);};\n const tips=goals.map(goal=>({goal,frame:frames.get(key(byId.get(goal.id)!))!,desired:new Vector3().fromArray(closures[goals.indexOf(goal)].position),chain:ikChain(pins,parents,goal.id,mass).slice(0,-1).reverse()}));\n const poles=tips.flatMap(tip=>{\n const chain=poleChains.get(tip.goal.id);\n if(!chain||chain.length<3)return [];\n const base=chain[0],knee=chain[Math.floor((chain.length-1)/2)],end=chain.at(-1)!;\n const restAxis=new Vector3().fromArray(end.rest).sub(new Vector3().fromArray(base.rest));\n const restBend=new Vector3().fromArray(knee.rest).sub(new Vector3().fromArray(base.rest));\n if(restAxis.lengthSq()<1e-16)return [];\n restBend.addScaledVector(restAxis,-restBend.dot(restAxis)/restAxis.lengthSq());\n if(restBend.length()<restAxis.length()*.02)return [];\n const minBend=Math.min(.03,restBend.length()/size*.5);\n return [{base,knee,chain,tip,minBend,restAxis:restAxis.normalize(),restPole:restBend.normalize()}];\n });\n const poleState=(pole:typeof poles[number])=>{\n const base=new Vector3().setFromMatrixPosition(world(frames.get(key(pole.base))!));\n const knee=new Vector3().setFromMatrixPosition(world(frames.get(key(pole.knee))!));\n const axis=pole.tip.desired.clone().sub(base).normalize();\n const preferred=pole.restPole.clone().applyQuaternion(new Quaternion().setFromUnitVectors(pole.restAxis,axis));\n preferred.addScaledVector(axis,-preferred.dot(axis)).normalize();\n const bend=knee.sub(base);bend.addScaledVector(axis,-bend.dot(axis));\n return {base,axis,preferred,bend};\n };\n const initial=[...new Set(tips.flatMap(tip=>tip.chain.flatMap(pin=>[frames.get(key(pin)),branchJoints.get(key(pin))?.frame]).filter((frame):frame is Link=>Boolean(frame))))]\n .map(frame=>({frame,rotation:new Quaternion().setFromRotationMatrix(world(frame))}));\n const cost=()=>tips.reduce((sum,tip)=>sum+new Vector3().setFromMatrixPosition(world(tip.frame)).distanceToSquared(tip.desired),0)\n +POSE_CONTINUITY_WEIGHT*initial.reduce((sum,{frame,rotation})=>sum+new Quaternion().setFromRotationMatrix(world(frame)).angleTo(rotation)**2,0)\n +10*poles.reduce((sum,pole)=>{const {preferred,bend}=poleState(pole);\n return sum+Math.max(0,pole.minBend-bend.dot(preferred))**2;},0);\n for(let sweep=0;sweep<96;sweep++){\n if(cost()<1e-12)break;\n let largestChange=0;\n for(const tip of tips)for(const pin of tip.chain){\n const id=key(pin),joints=[coneJoints.get(id)??freeJoints.get(id),branchJoints.get(id)?.joint];\n for(const [index,joint] of joints.entries()){\n if(!joint)continue;\n const branch=index===1,frame=branch?branchJoints.get(id)!.frame:frames.get(id)!;\n const matrix=world(frame),pivot=new Vector3().setFromMatrixPosition(matrix),end=new Vector3().setFromMatrixPosition(world(tip.frame));\n const a=end.sub(pivot),b=tip.desired.clone().sub(pivot);\n if(a.lengthSq()<1e-20||b.lengthSq()<1e-20)continue;\n const parentId=parentGroup.get(id),localParent=branch?(parentId?frames.get(parentId):undefined):branchJoints.get(id)?.frame??(parentId?frames.get(parentId):undefined);\n const parentRotation=localParent?new Quaternion().setFromRotationMatrix(world(localParent)):new Quaternion();\n const old=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(matrix));\n let rotation=parentRotation.clone().invert().multiply(new Quaternion().setFromUnitVectors(a.normalize(),b.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\n if(!branch)rotation=limitRotation(id,rotation,parentRotation);\n const before=cost(),set=(q:Quaternion)=>{const e=new Euler().setFromQuaternion(q,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frame.updateMatrixWorld();};\n for(let fraction=1;fraction>=1/32;fraction/=2){\n const attempt=old.clone().slerp(rotation,fraction);set(attempt);\n if(cost()<before-1e-14){largestChange=Math.max(largestChange,old.angleTo(attempt));break;}\n set(old);\n }\n }\n }\n for(const pole of poles){\n const {base,preferred,bend}=poleState(pole),along=bend.dot(preferred);\n if(along>=pole.minBend)continue;\n const baseId=key(pole.base),nextId=key(pole.chain[1]);\n const branch=branchJoints.get(nextId),joint=branch?.joint??coneJoints.get(baseId)??freeJoints.get(baseId);\n const frame=branch?.frame??frames.get(baseId);\n if(!joint||!frame)continue;\n const knee=new Vector3().setFromMatrixPosition(world(frames.get(key(pole.knee))!));\n const arm=knee.sub(base),aim=arm.clone().addScaledVector(preferred,Math.min(.01,pole.minBend-along));\n if(arm.lengthSq()<1e-20||aim.lengthSq()<1e-20)continue;\n const parentId=branch?baseId:parentGroup.get(baseId),parentFrame=parentId?frames.get(parentId):undefined;\n const parentRotation=parentFrame?new Quaternion().setFromRotationMatrix(world(parentFrame)):new Quaternion();\n const matrix=world(frame),old=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(matrix));\n let proposal=parentRotation.clone().invert().multiply(new Quaternion().setFromUnitVectors(arm.normalize(),aim.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\n if(!branch)proposal=limitRotation(baseId,proposal,parentRotation);\n const before=cost(),set=(q:Quaternion)=>{const e=new Euler().setFromQuaternion(q,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frame.updateMatrixWorld();};\n for(let fraction=1;fraction>=1/32;fraction/=2){\n const attempt=old.clone().slerp(proposal,fraction);set(attempt);\n if(cost()<before-1e-14){largestChange=Math.max(largestChange,old.angleTo(attempt));break;}\n set(old);\n }\n }\n if(largestChange<1e-5)break;\n }\n }\n // Projecting cones only AFTER the unconstrained solve leaves the endpoint\n // stranded, even when another joint could reach it. Finish positional chains\n // with constrained coordinate descent: every accepted step obeys its cone\n // and reduces the residual. Siblings/fixed roots never enter this joint list.\n if(goals.length===1){\n const target=goals[0],tipPin=byId.get(target.id)!;\n if(groups.get(key(tipPin))!.length===1&&(!tipPin.ikConstraint||tipPin.ikConstraint.mode==='free')){\n const tip=frames.get(key(tipPin))!,desired=new Vector3().fromArray(closures[0].position);\n const ordered=ikChain(pins,parents,target.id,mass),chain=ordered.slice(0,-1).reverse();\n const world=(frame:Link)=>{frame.updateMatrixWorld();return new Matrix4().fromArray(frame.matrixWorld);};\n const ground=tipPin.chainRole?.kind==='leg'&&Number.isFinite(floor)?(floor-origin.y)/size:-Infinity;\n const point=(pin:PinRecord)=>new Vector3().setFromMatrixPosition(world(frames.get(key(pin))!));\n const initial=[...new Set(chain.flatMap(pin=>[frames.get(key(pin))!,branchJoints.get(key(pin))?.frame].filter((frame):frame is Link=>Boolean(frame))))].map(frame=>({frame,rotation:priorRotations.get(frame)!}));\n // Endpoint distance has mirrored solutions. Carry each visible bend's\n // pole into the new chord frame instead of letting descent change sides.\n const poles=ordered.slice(1,-1).flatMap((knee,i)=>{\n const base=ordered[i],end=ordered[i+2];\n const chord=new Vector3().fromArray(end.pose.position).sub(new Vector3().fromArray(base.pose.position)),span=chord.length(),axis=chord.normalize();\n const bend=new Vector3().fromArray(knee.pose.position).sub(new Vector3().fromArray(base.pose.position));\n bend.addScaledVector(axis,-bend.dot(axis));\n // Near extension the positional pole is numerical noise; the rest\n // bend carried by the current base frame still defines its side.\n if(bend.length()<span*.02){\n const restAxis=new Vector3().fromArray(end.rest).sub(new Vector3().fromArray(base.rest)).normalize();\n bend.fromArray(knee.rest).sub(new Vector3().fromArray(base.rest));\n bend.addScaledVector(restAxis,-bend.dot(restAxis));\n const rotation=new Quaternion().fromArray(base.pose.rotation);\n bend.applyQuaternion(rotation);\n restAxis.applyQuaternion(rotation);\n bend.applyQuaternion(new Quaternion().setFromUnitVectors(restAxis,axis));\n }\n return bend.length()<span*.02?[]:[{base,knee,end,axis,pole:bend.normalize()}];\n });\n const poleCost=()=>poles.reduce((sum,pole)=>{\n const base=point(pole.base),axis=point(pole.end).sub(base).normalize();\n const preferred=pole.pole.clone().applyQuaternion(new Quaternion().setFromUnitVectors(pole.axis,axis));\n const bend=point(pole.knee).sub(base);bend.addScaledVector(axis,-bend.dot(axis));\n return sum+Math.max(0,-bend.dot(preferred))**2;\n },0);\n // Position alone does not determine every joint frame. Keep the nearest\n // solution to the pose on screen when a controller moves a tiny amount.\n const cost=()=>{\n const error=new Vector3().setFromMatrixPosition(world(tip)).distanceToSquared(desired);\n let penetration=0;\n if(Number.isFinite(ground))for(const pin of ordered.slice(1,-1))penetration+=Math.max(0,ground-point(pin).y)**2;\n const drift=initial.reduce((sum,{frame,rotation})=>sum+new Quaternion().setFromRotationMatrix(world(frame)).angleTo(rotation)**2,0);\n return error+16*penetration+100*poleCost()+POSE_CONTINUITY_WEIGHT*drift;\n };\n // Near a tight cone the last few sweeps are small but visible. Stop only\n // once the pose itself has settled, not merely when the goal is close.\n for(let sweep=0;sweep<128;sweep++){\n if(cost()<1e-12)break;\n let largestChange=0;\n for(const pin of chain){\n const id=key(pin);\n const joints=[coneJoints.get(id)??freeJoints.get(id),branchJoints.get(id)?.joint];\n for(const [jointIndex,joint] of joints.entries()){\n if(!joint)continue;\n const branch=jointIndex===1,frame=branch?branchJoints.get(id)!.frame:frames.get(id)!;\n const matrix=world(frame),pivot=new Vector3().setFromMatrixPosition(matrix);\n const end=new Vector3().setFromMatrixPosition(world(tip)),before=cost();\n const a=end.clone().sub(pivot),b=desired.clone().sub(pivot);if(a.lengthSq()<1e-20||b.lengthSq()<1e-20)continue;\n const parentId=parentGroup.get(id),localParent=branch?parentId?frames.get(parentId):undefined:branchJoints.get(id)?.frame??(parentId?frames.get(parentId):undefined);\n const parentRotation=localParent?new Quaternion().setFromRotationMatrix(world(localParent)):new Quaternion();\n const old=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(matrix));\n let rotation=parentRotation.clone().invert().multiply(new Quaternion().setFromUnitVectors(a.normalize(),b.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\n if(!branch)rotation=limitRotation(id,rotation,parentRotation);\n const set=(q:Quaternion)=>{const e=new Euler().setFromQuaternion(q,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frame.updateMatrixWorld();};\n let accepted=false;\n for(let fraction=1;fraction>=1/32;fraction/=2){\n let attempt=old.clone().slerp(rotation,fraction);\n if(!branch)attempt=limitRotation(id,attempt,parentRotation);\n set(attempt);\n if(cost()<=before+1e-14){largestChange=Math.max(largestChange,old.angleTo(attempt));accepted=true;break;}\n }\n if(!accepted)set(old);\n if(Number.isFinite(ground))for(const descendant of ordered.slice(ordered.indexOf(pin)+1,-1)){\n const lower=point(descendant);if(lower.y>=ground)continue;\n const current=point(pin),arm=lower.clone().sub(current),raised=lower.clone();raised.y=ground;\n const aim=raised.sub(current);if(arm.lengthSq()<1e-20||aim.lengthSq()<1e-20)continue;\n const parentNow=localParent?new Quaternion().setFromRotationMatrix(world(localParent)):new Quaternion();\n const previous=parentNow.clone().invert().multiply(new Quaternion().setFromRotationMatrix(world(frame)));\n let proposal=parentNow.clone().invert().multiply(new Quaternion().setFromUnitVectors(arm.normalize(),aim.normalize())).multiply(new Quaternion().setFromRotationMatrix(world(frame)));\n if(!branch)proposal=limitRotation(id,proposal,parentNow);\n const start=cost();\n for(let fraction=1;fraction>=1/16;fraction/=2){\n const attempt=previous.clone().slerp(proposal,fraction);set(attempt);\n if(cost()<start-1e-14){largestChange=Math.max(largestChange,previous.angleTo(attempt));break;}\n set(previous);\n }\n }\n }\n }\n if(largestChange<1e-5)break;\n }\n }\n }\n // Ancestor refinement must not leave a cone outside its committed frame.\n if(goals.length===1||!positionOnlyGoals)projectCones();\n // A free goal's orientation is independent of its position, including when\n // extra toe/follower joints are added below it. Carry those followers through\n // the frame, rather than only overwriting the endpoint's returned quaternion.\n for(const goal of goals){\n const id=key(byId.get(goal.id)!),joint=freeJoints.get(id);if(!joint||groups.get(id)!.length!==1)continue;\n const parentId=parentGroup.get(id),parent=parentId?frames.get(parentId):undefined;parent?.updateMatrixWorld();\n const rotation=parent?new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(parent.matrixWorld)).invert():new Quaternion();\n rotation.multiply(new Quaternion().fromArray(goal.rotation));\n const e=new Euler().setFromQuaternion(rotation,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frames.get(id)!.updateMatrixWorld();\n }\n const result=pins.filter(p=>affected.has(key(p))).map(pin=>{\n if(fixed.has(pin.id)) return {id:pin.id,pose:pin.pose};\n const anchor=groups.get(key(pin))![0],frame=frames.get(key(pin))!;frame.updateMatrixWorld();\n const matrix=new Matrix4().fromArray(frame.matrixWorld),rotation=new Quaternion().setFromRotationMatrix(matrix).normalize();\n const position=new Vector3().setFromMatrixPosition(matrix).multiplyScalar(size).add(origin);\n const delta=rotation.clone().multiply(new Quaternion().fromArray(anchor.pose.rotation).invert());\n const goal=goals.find(g=>key(byId.get(g.id)!)===key(pin));\n const terminal=![...parentGroup.values()].includes(key(pin));\n if(goal&&terminal&&(!pin.ikConstraint || pin.ikConstraint.mode==='free')) rotation.fromArray(goal.rotation);\n const offset=new Vector3().fromArray(pin.pose.position).sub(new Vector3().fromArray(anchor.pose.position));\n if(goal&&terminal&&(!pin.ikConstraint || pin.ikConstraint.mode==='free')) delta.copy(rotation).multiply(new Quaternion().fromArray(anchor.pose.rotation).invert());\n position.add(offset.applyQuaternion(delta));\n if(!parentGroup.has(key(pin)) && pin.id===anchor.id) position.fromArray(pin.pose.position);\n if(![...position.toArray(),...rotation.toArray()].every(Number.isFinite)) throw new Error('IK produced an invalid pose.');\n return {id:pin.id,pose:{position:position.toArray(),rotation:rotation.toArray(),scale:pin.pose.scale}};\n });\n return result;\n}\n", "import { validateRig, type JointsRig } from './joints-json.js';\nimport { ikChain } from './pin-ik.js';\nimport {DEFAULT_MOTION} from './motion-settings.js';\nimport type { ClothCollider, ClothLink } from './pin-cloth.js';\n\nexport const NEEDLE_DEFORMATION_RIG = 'NEEDLE_deformation_rig';\nexport interface RigDescriptor extends JointsRig {\n version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;\n joints: { node: number; parent: number | null; mass: number }[];\n chains: { endpoint: number; joints: number[]; mode: 'ik' | 'secondary' | 'cloth' | 'fur' }[];\n helpers?: { node: number; influences: { node: number; weight: number }[] }[];\n cloth?: { links: ClothLink[]; colliders: ClothCollider[] };\n furSurface?: { heightTexture: number; texCoord?: number };\n}\n/** Validate before allocating runtime objects or accepting node references. */\nexport function parseRigDescriptor(value: unknown, nodeCount: number, textureCount = Infinity): RigDescriptor {\n if (!value || typeof value !== 'object') throw new Error('Invalid deformation rig.');\n const raw = value as RigDescriptor;\n if (raw.version !== 1 && raw.version !== 2 && raw.version !== 3 && raw.version !== 4 && raw.version !== 5 && raw.version !== 6 && raw.version !== 7 && raw.version !== 8 && raw.version !== 9) throw new Error('Unsupported NEEDLE_deformation_rig version.');\n if (raw.furSurface?.texCoord !== undefined && (raw.version < 8 || !Number.isInteger(raw.furSurface.texCoord) || raw.furSurface.texCoord < 0 || raw.furSurface.texCoord > 1)) throw new Error('Invalid Fur height texture coordinates.');\n if (raw.furSurface && (raw.version < 6 || !Number.isInteger(raw.furSurface.heightTexture) || raw.furSurface.heightTexture < 0 || raw.furSurface.heightTexture >= textureCount)) throw new Error('Invalid Fur height texture.');\n if (raw.version < 5 && raw.windStrength !== undefined) throw new Error('Wind requires NEEDLE_deformation_rig version 5.');\n if (raw.activePose === 0 && raw.version < 9) throw new Error('An unselected authored pose requires NEEDLE_deformation_rig version 9.');\n const restSlot=raw.poseSlots?.find(slot=>slot.slot===0);\n if(restSlot && raw.version<7)throw new Error('Pose 0 requires NEEDLE_deformation_rig version 7.');\n const rig = validateRig({...raw,poseSlots:raw.poseSlots?.filter(slot=>slot.slot!==0)}, raw.version>=3?256:128);\n if(restSlot){\n if(raw.poseSlots.filter(slot=>slot.slot===0).length!==1 || !Array.isArray(restSlot.poses) || restSlot.poses.length!==rig.pins.length ||\n new Set(restSlot.poses.map(p=>p.id)).size!==rig.pins.length || restSlot.poses.some(p=>!rig.pins.some(pin=>pin.id===p.id)))throw new Error('Invalid rest pose clip.');\n validateRig({pins:rig.pins,activePose:1,poseSlots:[{slot:1,poses:restSlot.poses}],poseTimes:[]},raw.version>=3?256:128);\n }\n if (raw.version < 5 && rig.pins.some(pin=>pin.fur)) throw new Error('Fur requires NEEDLE_deformation_rig version 5.');\n if (raw.furSurface && !rig.pins.some(pin => pin.fur)) throw new Error('Fur height requires a Fur rig.');\n const node = (n: number) => Number.isInteger(n) && n >= 0 && n < nodeCount;\n if (!Array.isArray(raw.joints) || raw.joints.length !== rig.pins.length) throw new Error('Invalid rig joint bindings.');\n const indices = new Set<number>();\n for (const joint of raw.joints) {\n if (!joint || !node(joint.node) || indices.has(joint.node) || (joint.parent !== null && !node(joint.parent)) || !Number.isFinite(joint.mass) || joint.mass < 0) throw new Error('Invalid rig node or mass.');\n indices.add(joint.node);\n }\n const parents = new Map(raw.joints.map(j => [j.node, j.parent]));\n for (const joint of raw.joints) {\n const seen = new Set<number>(); let cursor: number | null = joint.node;\n while (cursor !== null) {\n if (!indices.has(cursor) || seen.has(cursor)) throw new Error('Invalid or cyclic rig hierarchy.');\n seen.add(cursor); cursor = parents.get(cursor)!;\n }\n }\n if (!Array.isArray(raw.chains) || raw.chains.length > rig.pins.length) throw new Error('Invalid motion chains.');\n const endpoints = new Set<number>();\n for (const chain of raw.chains) {\n if (!chain || !indices.has(chain.endpoint) || endpoints.has(chain.endpoint) || !['ik', 'secondary', 'cloth', 'fur'].includes(chain.mode) || !Array.isArray(chain.joints) || !chain.joints.length || chain.joints.length > rig.pins.length || chain.joints.at(-1) !== chain.endpoint || new Set(chain.joints).size !== chain.joints.length || chain.joints.some(n => !indices.has(n))) throw new Error('Invalid motion chain.');\n endpoints.add(chain.endpoint);\n }\n const pinParents = new Map<string, string>(), masses = new Map<string, number>();\n raw.joints.forEach((j, i) => { masses.set(rig.pins[i].id, j.mass); if (j.parent !== null) pinParents.set(rig.pins[i].id, rig.pins[raw.joints.findIndex(p => p.node === j.parent)].id); });\n for (const [i, pin] of rig.pins.entries()) {\n const chain = raw.chains.find(c => c.endpoint === raw.joints[i].node);\n const mode = !pin.guide && (pin.ik ? 'ik' : pin.wiggle ? 'secondary' : pin.cloth ? 'cloth' : pin.fur ? 'fur' : null);\n if (!mode && chain) throw new Error('Unexpected motion chain.');\n if (!mode) continue;\n const articulated=raw.version>=3?rig.pins.filter((_,i)=>!raw.helpers?.some(h=>h.node===raw.joints[i].node)):rig.pins;\n const expected = ikChain(articulated.map(p=>p.id===pin.id?{...p,motion:{...(p.motion??DEFAULT_MOTION),reach:1}}:p), pinParents, pin.id, masses).map(p => raw.joints[rig.pins.findIndex(pin => pin.id === p.id)].node);\n // Chains are derived caches, not authoritative authored topology. Older\n // writers used discontinuous reach gates; accept any valid ancestor suffix\n // and rebuild the current extent from the saved reach in the runtime.\n if (!chain || chain.mode !== mode || chain.joints.length > expected.length || chain.joints.some((n, i) => n !== expected[expected.length - chain.joints.length + i])) throw new Error('Motion chain does not match its hierarchy and reach.');\n }\n if (raw.helpers !== undefined && (!Array.isArray(raw.helpers) || raw.helpers.length > 256)) throw new Error('Invalid helper bindings.');\n const helpers = raw.helpers?.map(helper => {\n if (!node(helper.node) || (raw.version<3&&indices.has(helper.node)) || (raw.version>=3&&!parents.has(helper.node)) || !Array.isArray(helper.influences) || helper.influences.length > rig.pins.length) throw new Error('Invalid helper node.');\n const seen = new Set<number>(); let sum = 0;\n for (const influence of helper.influences) {\n if (!parents.has(influence.node) || (raw.version>=3&&raw.helpers?.some(h=>h.node===influence.node)) || seen.has(influence.node) || !Number.isFinite(influence.weight) || influence.weight <= 0) throw new Error('Invalid helper influence.');\n seen.add(influence.node); sum += influence.weight;\n }\n if (helper.influences.length && Math.abs(sum - 1) > 1e-4) throw new Error('Helper weights must sum to one.');\n indices.add(helper.node); return { node: helper.node, influences: helper.influences.map(i => ({ ...i })) };\n });\n if (raw.version >= 2 && !helpers) throw new Error('Rig requires helper bindings.');\n if (helpers && new Set(helpers.map(h=>h.node)).size!==helpers.length) throw new Error('Duplicate helper bone.');\n if ((raw.version < 4 && (raw.cloth !== undefined || rig.pins.some(p => p.cloth))) || (raw.version === 4 && !raw.cloth) || (rig.pins.some(p => p.cloth) && !raw.cloth) || (raw.cloth && (!Array.isArray(raw.cloth.links) || !Array.isArray(raw.cloth.colliders) || raw.cloth.links.length > 512 || raw.cloth.colliders.length > 4096))) throw new Error('Invalid cloth simulation data.');\n const pinById = new Map(rig.pins.map(p => [p.id, p]));\n for (const link of raw.cloth?.links ?? []) if (!link || !pinById.has(link.a) || !pinById.has(link.b) || link.a === link.b || !(pinById.get(link.a)?.cloth || pinById.get(link.b)?.cloth) || !Number.isFinite(link.length) || link.length < 0) throw new Error('Invalid cloth link.');\n for (const collider of raw.cloth?.colliders ?? []) if (!collider || !Array.isArray(collider.position) || collider.position.length !== 3 || !collider.position.every(Number.isFinite) || !Number.isFinite(collider.radius) || collider.radius <= 0 || !collider.driver || !pinById.has(collider.driver) || pinById.get(collider.driver)?.cloth) throw new Error('Invalid cloth collider.');\n return { ...rig,poseSlots:restSlot?[restSlot,...rig.poseSlots]:rig.poseSlots, version: raw.version, joints: raw.joints.map(j => ({ ...j })), chains: raw.chains.map(c => ({ ...c, joints: [...c.joints] })), ...(helpers ? { helpers } : {}), ...(raw.cloth ? { cloth: { links: raw.cloth.links.map(l => ({ ...l })), colliders: raw.cloth.colliders.map(c => ({ ...c, position: [...c.position] as [number,number,number] })) } } : {}), ...(raw.furSurface ? { furSurface: { ...raw.furSurface } } : {}) };\n}\n", "import { Quaternion, Vector3 } from 'three';\nimport { DEFAULT_FUR_DEPTH, type PinPose, type PinRecord } from './pin-types.js';\nimport type { PinParents } from './pin-types.js';\nimport { DEFAULT_MOTION, type MotionSettings } from './motion-settings.js';\nimport { ikChain } from './pin-ik.js';\nimport { windAcceleration } from './wind.js';\n\n/** Disposable secondary motion. Never writes authored pins or history. */\nexport class PinWiggle {\n private springs = new Map<string, { position: Vector3; velocity: Vector3; target:Vector3 }>();\n private topology = '';\n private lastPins: readonly PinRecord[] | null = null;\n private lastParents: PinParents | null = null;\n private awake = false;\n private windTime = 0;\n reset() { this.springs.clear(); this.topology = ''; this.lastPins = null; this.lastParents = null; this.awake = false; this.windTime = 0; }\n\n step(pins: readonly PinRecord[], parents: PinParents, seconds: number, masses?:ReadonlyMap<string,number>, windStrength = 0): { pins: readonly PinRecord[]; active: boolean } {\n if (windStrength <= 0 && !this.awake && pins === this.lastPins && parents === this.lastParents) return {pins,active:false};\n const topology = JSON.stringify(pins.map(p => [p.id,p.rest,p.rigidGroup,p.independent,p.guide,p.wiggle,p.fur,p.furDepth,p.motion,parents.get(p.id)]));\n if (topology !== this.topology) { this.reset(); this.topology = topology; }\n const groups = new Map<string, PinRecord[]>(), byId = new Map(pins.map(p => [p.id,p]));\n const key = (p: PinRecord) => p.rigidGroup ?? p.id;\n for (const pin of pins) { const group = groups.get(key(pin)) ?? []; group.push(pin); groups.set(key(pin),group); }\n const settings = new Map<string,Readonly<MotionSettings>>();\n const volumes=[...groups.values()].filter(group=>!group.every(p=>p.guide)).map(group=>Math.max(1e-9,masses?.get(group[0].id)??1)).sort((a,b)=>a-b);\n const typicalVolume=volumes[Math.floor(volumes.length/2)]??1;\n for (const pin of pins.filter(p=>p.wiggle && !p.guide)) {\n const chain=ikChain(pins,parents,pin.id,masses);\n for (const node of chain.length>1 ? chain.slice(1) : chain) if (!settings.has(key(node))) settings.set(key(node),pin.motion ?? DEFAULT_MOTION);\n }\n for (const pin of pins.filter(p=>p.wiggle && !p.guide)) settings.set(key(pin),pin.motion ?? DEFAULT_MOTION);\n // Fur belongs to the outer shell: unlike Wiggle it must not make the\n // articulated core's ancestor chain into springs.\n for (const pin of pins.filter(p=>p.fur && !p.guide)) settings.set(key(pin),pin.motion ?? DEFAULT_MOTION);\n const output = new Map<string, PinPose>(), visiting = new Set<string>();\n let active = false;\n // Exact underdamped spring integration, stable across variable frame times.\n // Clamp background-tab gaps rather than simulating missed seconds.\n const dt = Math.min(Math.max(seconds,0),.05);\n this.windTime += dt;\n const visit = (id: string) => {\n const group = groups.get(id)!;\n if (output.has(group[0].id)) return;\n if (visiting.has(id)) { for (const pin of group) output.set(pin.id,pin.pose); return; }\n visiting.add(id);\n const parent = group.map(p => byId.get(parents.get(p.id) ?? '')).find(p => p && key(p) !== id);\n if (parent) visit(key(parent));\n const parentPose = parent ? output.get(parent.id)! : undefined;\n const inherited = parent && parentPose ? new Quaternion().fromArray(parentPose.rotation).multiply(new Quaternion().fromArray(parent.pose.rotation).invert()) : new Quaternion();\n const targets = group.map(pin => {\n const position = new Vector3().fromArray(pin.pose.position);\n if (!pin.ik && parent && parentPose) position.sub(new Vector3().fromArray(parent.pose.position)).applyQuaternion(inherited).add(new Vector3().fromArray(parentPose.position));\n return { pin, position, rotation: (pin.ik ? new Quaternion() : inherited.clone()).multiply(new Quaternion().fromArray(pin.pose.rotation)) };\n });\n const center = targets.reduce((sum,p) => sum.add(p.position),new Vector3()).divideScalar(group.length);\n let position = center, rotation = new Quaternion();\n const motion=settings.get(id);\n if (motion && !group.every(p=>p.guide) && !group.some(p=>p.ik)) {\n const ratio=Math.max(.125,Math.min(8,(masses?.get(group[0].id)??typicalVolume)/typicalVolume));\n const gain=motion.strength*Math.max(.25,Math.min(4,Math.pow(1/ratio,.5*motion.massInfluence)));\n const frequency=motion.frequency*2*Math.PI, damping=Math.max(.05,Math.min(1,motion.damping*Math.pow(ratio,.25*motion.massInfluence)));\n const decay = damping * frequency, oscillation = frequency * Math.sqrt(1-damping*damping);\n const e = Math.exp(-decay*dt), c = Math.cos(oscillation*dt), s = oscillation > 1e-8 ? Math.sin(oscillation*dt)/oscillation : dt;\n let spring = this.springs.get(id);\n if (!spring) { spring = { position:center.clone(),velocity:new Vector3(),target:center.clone() }; this.springs.set(id,spring); }\n spring.position.addScaledVector(center.clone().sub(spring.target),1-gain);spring.target.copy(center);\n if(motion.strength===0){spring.position.copy(center);spring.velocity.set(0,0,0);}\n else if (windStrength > 0) spring.velocity.addScaledVector(windAcceleration(this.windTime, windStrength,\n parentPose ? Math.max(center.distanceTo(new Vector3().fromArray(parentPose.position)), 1e-3) : 1, center.toArray()), motion.strength * dt);\n const offset = spring.position.clone().sub(center), velocity = spring.velocity.clone();\n spring.position.copy(offset).multiplyScalar(c).addScaledVector(velocity.clone().addScaledVector(offset,decay),s).multiplyScalar(e).add(center);\n spring.velocity.copy(velocity).multiplyScalar(c).sub(velocity.clone().multiplyScalar(decay).addScaledVector(offset,frequency*frequency).multiplyScalar(s)).multiplyScalar(e);\n const fur = group.find(p=>p.fur), furDepth=fur?.furDepth??DEFAULT_FUR_DEPTH;\n let radius = 1;\n if (parentPose) {\n const pivot = new Vector3().fromArray(parentPose.position), desired = center.clone().sub(pivot);\n radius = desired.length();\n const direction = spring.position.clone().sub(pivot);\n if (radius > 1e-8) {\n if (direction.lengthSq() < 1e-16) direction.copy(desired);\n const length=direction.length();direction.divideScalar(length);\n const coreRadius=radius*(1-furDepth),outerRadius=radius*(1+furDepth);\n const projected=fur?Math.max(coreRadius,Math.min(outerRadius,length)):radius;\n spring.position.copy(pivot).addScaledVector(direction,projected);\n if(!fur||length<coreRadius||length>outerRadius)spring.velocity.addScaledVector(direction,-spring.velocity.dot(direction));\n rotation.setFromUnitVectors(desired.normalize(),direction);\n } else { spring.position.copy(center); spring.velocity.set(0,0,0); }\n }\n if (fur) {\n const shell = Math.max(1e-4, radius) * furDepth;\n if (shell === 0) { spring.position.copy(center); spring.velocity.set(0,0,0); rotation.identity(); }\n const displacement = spring.position.clone().sub(center);\n if (displacement.length() > shell) {\n displacement.setLength(shell); spring.position.copy(center).add(displacement);\n const outward=displacement.normalize();spring.velocity.addScaledVector(outward,-Math.max(0,spring.velocity.dot(outward)));\n }\n if(parentPose&&radius>1e-8){\n const pivot=new Vector3().fromArray(parentPose.position),desired=center.clone().sub(pivot).normalize(),direction=spring.position.clone().sub(pivot).normalize();\n rotation.setFromUnitVectors(desired,direction);\n }\n }\n const epsilon = Math.max(radius,1e-3)*1e-5;\n if (spring.position.distanceToSquared(center) < epsilon*epsilon && spring.velocity.lengthSq() < epsilon*epsilon*frequency*frequency) {\n spring.position.copy(center); spring.velocity.set(0,0,0); rotation.identity();\n } else active = true;\n position = spring.position;\n }\n for (const target of targets) output.set(target.pin.id, {\n position:target.position.sub(center).applyQuaternion(rotation).add(position).toArray(),\n rotation:rotation.clone().multiply(target.rotation).normalize().toArray(),scale:target.pin.pose.scale,\n });\n visiting.delete(id);\n };\n for (const id of groups.keys()) visit(id);\n this.lastPins = pins; this.lastParents = parents; this.awake = active;\n return { pins: active ? pins.map(pin => ({...pin,pose:output.get(pin.id)!})) : pins, active };\n }\n}\n", "import { Quaternion, Vector3 } from 'three';\nimport type { PinRecord, Point } from './pin-types.js';\nimport type { PinParents, HierarchyEdge } from './pin-types.js';\nimport { windAcceleration } from './wind.js';\nimport { DEFAULT_MOTION } from './motion-settings.js';\n\nexport type ClothLink = { a: string; b: string; length: number };\nexport type ClothCollider = { position: Point; radius: number; driver?: string };\n\n/** Connect authored cloth controls along the occupied-volume geodesic, not\n * across the shortest line through empty space. The tree is a coarse fabric\n * constraint network; the ordinary skin remains its portable GLB fallback. */\nexport function clothLinks(pins: readonly PinRecord[], parents: PinParents, edges: readonly HierarchyEdge[] = [], components?: ReadonlyMap<string, number>): ClothLink[] {\n const cloth = pins.filter(p => p.cloth && !p.guide), byId = new Map(pins.map(p => [p.id, p]));\n const result: ClothLink[] = [], seen = new Set<string>();\n const add = (a: string, b: string) => {\n if (a === b || !byId.has(a) || !byId.has(b)) return;\n const key = [a, b].sort().join('\\0'); if (seen.has(key)) return;\n seen.add(key); result.push({ a, b, length: new Vector3().fromArray(byId.get(a)!.rest).distanceTo(new Vector3().fromArray(byId.get(b)!.rest)) });\n };\n for (const pin of cloth) {\n let parent = parents.get(pin.id);\n const visited = new Set<string>();\n while (parent && byId.get(parent)?.guide && !visited.has(parent)) { visited.add(parent); parent = parents.get(parent); }\n if (parent) add(pin.id, parent);\n }\n // A topology hierarchy may root a sheet at one of its free corners. Cloth\n // still needs body attachments there; otherwise the entire sheet falls as\n // one unconstrained pair or chain despite nearby non-cloth controls.\n for (const pin of cloth) {\n const parent = byId.get(parents.get(pin.id) ?? '');\n if (parent && !parent.cloth && !parent.guide) continue;\n const anchors = edges.filter(edge => (edge.from === pin.id || edge.to === pin.id) &&\n !byId.get(edge.from === pin.id ? edge.to : edge.from)?.cloth &&\n !byId.get(edge.from === pin.id ? edge.to : edge.from)?.guide &&\n Number.isFinite(edge.geodesic ?? edge.cost));\n const same = anchors.filter(edge => !components || components.get(pin.id) === components.get(edge.from === pin.id ? edge.to : edge.from));\n const best = (same.length ? same : anchors).sort((a, b) => (a.geodesic ?? a.cost) - (b.geodesic ?? b.cost))[0];\n if (best) add(pin.id, best.from === pin.id ? best.to : best.from);\n }\n const candidates = edges.filter(e => cloth.some(p => p.id === e.from) && cloth.some(p => p.id === e.to) && Number.isFinite(e.geodesic ?? e.cost)\n && (!components || components.get(e.from) === components.get(e.to)))\n .sort((a, b) => (a.geodesic ?? a.cost) - (b.geodesic ?? b.cost));\n const root = new Map(cloth.map(p => [p.id, p.id]));\n const find = (id: string): string => { const parent = root.get(id)!; if (parent === id) return id; const top = find(parent); root.set(id, top); return top; };\n for (const edge of candidates) {\n const a = find(edge.from), b = find(edge.to); if (a === b) continue;\n root.set(a, b); add(edge.from, edge.to);\n }\n return result;\n}\n\n/** Small, fixed-step Verlet graph. The editor passes deformed voxel centers;\n * the GLB loader passes the same collider proxy driven by its joint graph. */\nexport class PinCloth {\n private particles = new Map<string, { position: Vector3; previous: Vector3 }>();\n private layout = '';\n private windTime = 0;\n private accumulator = 0;\n reset() { this.particles.clear(); this.layout = ''; this.windTime = 0; this.accumulator = 0; }\n step(pins: readonly PinRecord[], parents: PinParents, seconds: number, links: readonly ClothLink[], colliders: readonly ClothCollider[] = [], windStrength = 0): { pins: readonly PinRecord[]; active: boolean } {\n const cloth = pins.filter(p => p.cloth && !p.guide);\n if (!cloth.length) { this.reset(); return { pins, active: false }; }\n const layout = JSON.stringify([cloth.map(p => [p.id, p.rest]), links]);\n if (layout !== this.layout) { this.reset(); this.layout = layout; }\n const byId = new Map(pins.map(p => [p.id, p]));\n for (const pin of cloth) if (!this.particles.has(pin.id)) {\n const position = new Vector3().fromArray(pin.pose.position);\n this.particles.set(pin.id, { position, previous: position.clone() });\n }\n // Verlet stores displacement per step. Changing the step with render\n // timing changes its velocity and keeps a calm sheet moving.\n const h = 1 / 60;\n this.accumulator += Math.min(Math.max(seconds, 0), .05);\n const steps = Math.floor((this.accumulator + 1e-12) / h);\n this.accumulator = Math.max(0, this.accumulator - steps * h);\n const scale = Math.max(1e-4, ...links.map(link => link.length));\n // A sampled voxel shell can contain thousands of spheres. Bin it once\n // per frame, then refresh each particle's nearby set after integration so\n // a fast-moving cloth point cannot retain last frame's collision region.\n let maxRadius = 0;\n for (const collider of colliders) maxRadius = Math.max(maxRadius, collider.radius);\n const cell = Math.max(1e-4, scale * 2 + maxRadius);\n const spatial = cloth.length > 4 && colliders.length > 128;\n const bins = new Map<string, ClothCollider[]>();\n const key = (x: number, y: number, z: number) => `${x},${y},${z}`;\n if (spatial) for (const collider of colliders) {\n const p = collider.position, id = key(Math.floor(p[0] / cell), Math.floor(p[1] / cell), Math.floor(p[2] / cell));\n const bin = bins.get(id) ?? []; bin.push(collider); bins.set(id, bin);\n }\n const candidates = (position: Vector3) => {\n const found: ClothCollider[] = [];\n const search = (collider: ClothCollider) => {\n const p = collider.position, dx = position.x - p[0], dy = position.y - p[1], dz = position.z - p[2], reach = collider.radius + scale * 2;\n if (dx * dx + dy * dy + dz * dz < reach * reach) found.push(collider);\n };\n if (spatial) {\n const x = Math.floor(position.x / cell), y = Math.floor(position.y / cell), z = Math.floor(position.z / cell);\n for (let dz = -1; dz <= 1; dz++) for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++)\n for (const collider of bins.get(key(x + dx, y + dy, z + dz)) ?? []) search(collider);\n } else for (const collider of colliders) search(collider);\n return found;\n };\n for (let substep = 0; substep < steps; substep++) {\n this.windTime += h;\n for (const pin of cloth) {\n const particle = this.particles.get(pin.id)!;\n const motion = pin.motion ?? DEFAULT_MOTION;\n const velocity = particle.position.clone().sub(particle.previous).multiplyScalar(Math.exp(-motion.damping * 3 * h));\n particle.previous.copy(particle.position);\n particle.position.add(velocity).y -= 2.5 * scale * h * h;\n if (windStrength > 0 && motion.strength > 0) particle.position.addScaledVector(windAcceleration(this.windTime, windStrength, scale, particle.position.toArray()), motion.strength * h * h);\n // Pins are sparse controls, not free particles. A soft return to their\n // authored positions keeps broad sheets from drifting indefinitely.\n particle.position.lerp(new Vector3().fromArray(pin.pose.position), 1 - Math.exp(-2 * Math.PI * motion.frequency * h));\n }\n const nearby = new Map(cloth.map(pin => [pin.id, candidates(this.particles.get(pin.id)!.position)]));\n for (let iteration = 0; iteration < 6; iteration++) {\n for (const link of links) {\n const a = this.particles.get(link.a), b = this.particles.get(link.b);\n const pa = a?.position ?? new Vector3().fromArray(byId.get(link.a)?.pose.position ?? [0, 0, 0]);\n const pb = b?.position ?? new Vector3().fromArray(byId.get(link.b)?.pose.position ?? [0, 0, 0]);\n const delta = pa.clone().sub(pb), distance = delta.length(); if (distance < 1e-8) continue;\n const correction = delta.multiplyScalar((distance - link.length) / distance);\n if (a && b) { a.position.addScaledVector(correction, -.5); b.position.addScaledVector(correction, .5); }\n else if (a) a.position.sub(correction); else if (b) b.position.add(correction);\n }\n for (const [id, particle] of this.particles) for (const collider of nearby.get(id) ?? []) {\n const center = collider.position, dx = particle.position.x - center[0], dy = particle.position.y - center[1], dz = particle.position.z - center[2];\n const squared = dx * dx + dy * dy + dz * dz;\n if (squared >= collider.radius * collider.radius) continue;\n if (squared < 1e-16) particle.position.set(center[0], center[1] + collider.radius, center[2]);\n else {\n const factor = collider.radius / Math.sqrt(squared);\n particle.position.set(center[0] + dx * factor, center[1] + dy * factor, center[2] + dz * factor);\n }\n }\n }\n }\n let active = false;\n const result = pins.map(pin => {\n const particle = this.particles.get(pin.id); if (!particle) return pin;\n const target = new Vector3().fromArray(pin.pose.position), offset = particle.position.clone().sub(target);\n const velocity = particle.position.clone().sub(particle.previous);\n if (offset.lengthSq() > scale * scale * 1e-10 || velocity.lengthSq() > scale * scale * 1e-10) active = true;\n const parent = byId.get(parents.get(pin.id) ?? '');\n const rotation = parent ? new Quaternion().setFromUnitVectors(\n target.clone().sub(new Vector3().fromArray(parent.pose.position)).normalize(),\n particle.position.clone().sub(new Vector3().fromArray(parent.pose.position)).normalize()) : new Quaternion();\n return { ...pin, pose: { ...pin.pose, position: particle.position.toArray() as Point,\n rotation: rotation.multiply(new Quaternion().fromArray(pin.pose.rotation)).normalize().toArray() as [number, number, number, number] } };\n });\n return { pins: active ? result : pins, active };\n }\n}\n", "import { Vector3 } from 'three';\nimport type { PinRecord, Point } from './pin-types.js';\nimport type { ClothCollider } from './pin-cloth.js';\nimport { DEFAULT_MOTION, type MotionSettings } from './motion-settings.js';\nimport { windAcceleration, windProfile } from './wind.js';\n\ntype Edge = { a: number; b: number; length: number; bend: boolean };\ntype Triangle = { a: number; b: number; c: number };\ntype Particle = { position: Vector3; previous: Vector3; base: Vector3; share: number; anchor: number };\n\nexport function clothSurfaceMotion(pins: readonly PinRecord[]): MotionSettings {\n if (!pins.length) return { ...DEFAULT_MOTION };\n const values = pins.map(pin => pin.motion ?? DEFAULT_MOTION);\n return { ...DEFAULT_MOTION,\n damping: values.reduce((sum, motion) => sum + motion.damping, 0) / values.length,\n strength: values.reduce((sum, motion) => sum + motion.strength, 0) / values.length };\n}\n\nfunction distances(graph: readonly { to: number; length: number }[][], seeds: readonly number[]) {\n const distance = new Float64Array(graph.length).fill(Infinity);\n const heap: { node: number; distance: number }[] = [];\n const push = (node: number, value: number) => {\n let i = heap.length; heap.push({ node, distance: value });\n while (i) { const parent = (i - 1) >> 1; if (heap[parent].distance <= value) break; heap[i] = heap[parent]; i = parent; }\n heap[i] = { node, distance: value };\n };\n const pop = () => {\n const top = heap[0], last = heap.pop()!;\n if (heap.length) {\n let i = 0;\n for (;;) {\n let child = i * 2 + 1; if (child >= heap.length) break;\n if (child + 1 < heap.length && heap[child + 1].distance < heap[child].distance) child++;\n if (last.distance <= heap[child].distance) break;\n heap[i] = heap[child]; i = child;\n }\n heap[i] = last;\n }\n return top;\n };\n for (const seed of seeds) if (distance[seed] > 0) { distance[seed] = 0; push(seed, 0); }\n while (heap.length) {\n const next = pop(); if (next.distance !== distance[next.node]) continue;\n for (const edge of graph[next.node]) {\n const value = next.distance + edge.length;\n if (value < distance[edge.to]) { distance[edge.to] = value; push(edge.to, value); }\n }\n }\n return distance;\n}\n\n/** A topology-connected fabric layer over the portable skinned/voxel result.\n * Vertices at UV seams share one particle; all other vertices keep the source\n * triangle topology. Body controls attach the sheet, cloth controls release it. */\nexport class ClothSurface {\n readonly particles: Particle[];\n readonly vertexParticle: Uint32Array;\n readonly triangles: Triangle[];\n readonly edges: Edge[];\n readonly scale: number;\n private time = 0;\n private accumulator = 0;\n\n constructor(restVertices: Float32Array, indices: ArrayLike<number>, pins: readonly PinRecord[]) {\n const vertexCount = restVertices.length / 3;\n const min = new Vector3(Infinity, Infinity, Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity);\n for (let i = 0; i < vertexCount; i++) {\n const p = new Vector3().fromArray(restVertices, i * 3); min.min(p); max.max(p);\n }\n this.scale = Math.max(1e-4, max.clone().sub(min).length());\n const tolerance = this.scale * 1e-6;\n const welded = new Map<string, number>(), particles: Particle[] = [];\n this.vertexParticle = new Uint32Array(vertexCount);\n for (let i = 0; i < vertexCount; i++) {\n const p = new Vector3().fromArray(restVertices, i * 3);\n const key = p.toArray().map(value => Math.round(value / tolerance)).join(',');\n let node = welded.get(key);\n if (node === undefined) {\n node = particles.length; welded.set(key, node);\n particles.push({ position: p.clone(), previous: p.clone(), base: p, share: 0, anchor: 0 });\n }\n this.vertexParticle[i] = node;\n }\n const edgeMap = new Map<string, { a: number; b: number; opposites: number[] }>();\n const graph: { to: number; length: number }[][] = particles.map(() => []);\n const triangles: Triangle[] = [];\n const edge = (a: number, b: number, opposite: number) => {\n if (a === b) return;\n const key = a < b ? `${a}:${b}` : `${b}:${a}`;\n const existing = edgeMap.get(key);\n if (existing) existing.opposites.push(opposite);\n else edgeMap.set(key, { a, b, opposites: [opposite] });\n };\n for (let i = 0; i + 2 < indices.length; i += 3) {\n const a = this.vertexParticle[indices[i]], b = this.vertexParticle[indices[i + 1]], c = this.vertexParticle[indices[i + 2]];\n if (a === b || b === c || c === a) continue;\n triangles.push({ a, b, c }); edge(a, b, c); edge(b, c, a); edge(c, a, b);\n }\n this.triangles = triangles;\n const edges: Edge[] = [];\n for (const value of edgeMap.values()) {\n const length = particles[value.a].base.distanceTo(particles[value.b].base);\n edges.push({ a: value.a, b: value.b, length, bend: false });\n graph[value.a].push({ to: value.b, length }); graph[value.b].push({ to: value.a, length });\n if (value.opposites.length === 2 && value.opposites[0] !== value.opposites[1]) {\n const a = value.opposites[0], b = value.opposites[1];\n edges.push({ a, b, length: particles[a].base.distanceTo(particles[b].base), bend: true });\n }\n }\n this.edges = edges;\n const nearest = (point: Point) => {\n const p = new Vector3().fromArray(point); let found = 0, best = Infinity;\n for (let i = 0; i < particles.length; i++) {\n const d = particles[i].base.distanceToSquared(p); if (d < best) { best = d; found = i; }\n }\n return found;\n };\n const cloth = pins.filter(pin => pin.cloth && !pin.guide).map(pin => nearest(pin.rest));\n const body = pins.filter(pin => !pin.cloth && !pin.guide).map(pin => nearest(pin.rest));\n const clothDistance = distances(graph, cloth), bodyDistance = distances(graph, body);\n for (let i = 0; i < particles.length; i++) {\n const a = clothDistance[i], b = bodyDistance[i];\n particles[i].share = Number.isFinite(a) && Number.isFinite(b) ? b / Math.max(1e-6, a + b) : Number.isFinite(a) ? 1 : 0;\n particles[i].anchor = Number.isFinite(b) ? Math.exp(-b / (.12 * this.scale)) : 0;\n }\n this.particles = particles;\n }\n\n get movableCount() { return this.particles.filter(p => p.share > .25).length; }\n\n reset() {\n this.time = 0;\n this.accumulator = 0;\n for (const particle of this.particles) particle.position.copy(particle.base), particle.previous.copy(particle.base);\n }\n\n step(baseVertices: Float32Array, seconds: number, windStrength: number, colliders: readonly ClothCollider[] = [], motion: Readonly<MotionSettings> = DEFAULT_MOTION) {\n const count = this.particles.length, base = Array.from({ length: count }, () => new Vector3()), samples = new Uint32Array(count);\n for (let i = 0; i < this.vertexParticle.length; i++) {\n const node = this.vertexParticle[i]; base[node].add(new Vector3().fromArray(baseVertices, i * 3)); samples[node]++;\n }\n for (let i = 0; i < count; i++) {\n base[i].divideScalar(samples[i] || 1);\n const particle = this.particles[i], delta = base[i].clone().sub(particle.base);\n particle.position.add(delta); particle.previous.add(delta); particle.base.copy(base[i]);\n }\n // Keep Verlet displacement in one time unit even when GPU frames arrive\n // unevenly; carry unused time rather than changing the integration step.\n const h = 1 / 60;\n this.accumulator += Math.min(Math.max(seconds, 0), .05);\n const steps = Math.floor((this.accumulator + 1e-12) / h);\n this.accumulator = Math.max(0, this.accumulator - steps * h);\n const profile = windProfile(windStrength), pressureScale = profile.load ? .025 * profile.surfaceLoad / profile.load : 0;\n const radius = Math.max(1e-4, ...colliders.map(collider => collider.radius));\n const cell = radius * 2;\n const bins = new Map<number, ClothCollider[]>();\n // Hash collisions only add candidates; the distance test below remains exact.\n const key = (x: number, y: number, z: number) => (Math.imul(x, 73856093) ^ Math.imul(y, 19349663) ^ Math.imul(z, 83492791)) | 0;\n for (const collider of colliders) {\n const p = collider.position, id = key(Math.floor(p[0] / cell), Math.floor(p[1] / cell), Math.floor(p[2] / cell));\n const bin = bins.get(id) ?? []; bin.push(collider); bins.set(id, bin);\n }\n for (let step = 0; step < steps; step++) {\n this.time += h;\n const force = Array.from({ length: count }, () => new Vector3());\n const area = new Float32Array(count);\n if (pressureScale && motion.strength) for (const triangle of this.triangles) {\n const a = this.particles[triangle.a].position, b = this.particles[triangle.b].position, c = this.particles[triangle.c].position;\n const normal = b.clone().sub(a).cross(c.clone().sub(a));\n const surface = normal.length(); if (surface < 1e-10) continue;\n normal.divideScalar(surface);\n const center = a.clone().add(b).add(c).divideScalar(3);\n const wind = windAcceleration(this.time, windStrength, this.scale, center.toArray());\n // Normal pressure bends the sheet; a small tangential drag carries\n // near-parallel fabric rather than letting it ignore the wind entirely.\n const pressure = normal.multiplyScalar(wind.dot(normal)).addScaledVector(wind, .12)\n .multiplyScalar(pressureScale);\n for (const node of [triangle.a, triangle.b, triangle.c]) { force[node].addScaledVector(pressure, surface); area[node] += surface; }\n }\n for (let i = 0; i < count; i++) {\n const particle = this.particles[i], share = particle.share;\n if (share < 1e-4) { particle.position.copy(particle.base); particle.previous.copy(particle.base); continue; }\n const velocity = particle.position.clone().sub(particle.previous).multiplyScalar(Math.exp(-motion.damping * 3 * h));\n particle.previous.copy(particle.position);\n particle.position.add(velocity).y -= 2.5 * this.scale * share * h * h;\n if (area[i]) particle.position.addScaledVector(force[i], motion.strength * share * h * h / area[i]);\n const anchor = 1 - Math.exp(-(1.5 + 60 * particle.anchor ** 2) * h);\n particle.position.lerp(particle.base, anchor);\n }\n for (let iteration = 0; iteration < 5; iteration++) {\n for (const edge of this.edges) {\n const a = this.particles[edge.a], b = this.particles[edge.b];\n const difference = b.position.clone().sub(a.position), length = difference.length();\n if (length < 1e-8) continue;\n const wa = a.share * a.share, wb = b.share * b.share, total = wa + wb;\n if (total < 1e-8) continue;\n const strength = edge.bend ? .14 : .72;\n difference.multiplyScalar((length - edge.length) * strength / (length * total));\n a.position.addScaledVector(difference, wa); b.position.addScaledVector(difference, -wb);\n }\n }\n if (colliders.length) for (const particle of this.particles) {\n if (particle.share < .35) continue;\n // A point projected out of one proxy sphere can still be inside its\n // neighbor. Resolve that overlap here instead of alternating contacts\n // on successive animation frames.\n for (let contact = 0; contact < 8; contact++) {\n const p = particle.position, px = p.x / cell, py = p.y / cell, pz = p.z / cell;\n const x = Math.floor(px), y = Math.floor(py), z = Math.floor(pz);\n const sx = px - x < .5 ? -1 : 1, sy = py - y < .5 ? -1 : 1, sz = pz - z < .5 ? -1 : 1;\n let chosen: ClothCollider | undefined, penetration = 0;\n // Cell width is twice the largest radius, so only the nearest neighbor\n // on each axis can contain a sphere reaching this particle.\n for (let iz = 0; iz < 2; iz++) for (let iy = 0; iy < 2; iy++) for (let ix = 0; ix < 2; ix++) {\n for (const collider of bins.get(key(x + ix * sx, y + iy * sy, z + iz * sz)) ?? []) {\n const center = collider.position, bx = particle.base.x - center[0], by = particle.base.y - center[1], bz = particle.base.z - center[2];\n if (bx * bx + by * by + bz * bz < collider.radius * collider.radius * 1.04) continue;\n const vx = p.x - center[0], vy = p.y - center[1], vz = p.z - center[2];\n const depth = collider.radius - Math.hypot(vx, vy, vz);\n if (depth > penetration) { penetration = depth; chosen = collider; }\n }\n }\n if (!chosen || penetration < this.scale * 1e-7) break;\n const center = chosen.position, delta = p.clone().sub(new Vector3().fromArray(center));\n if (delta.lengthSq() < 1e-12) delta.copy(particle.base).sub(new Vector3().fromArray(center));\n p.copy(new Vector3().fromArray(center).add(delta.setLength(chosen.radius)));\n }\n }\n }\n const result = new Float32Array(baseVertices.length);\n for (let i = 0; i < this.vertexParticle.length; i++) result.set(this.particles[this.vertexParticle[i]].position.toArray(), i * 3);\n return result;\n }\n}\n", "import { Matrix4, Quaternion, Vector3 } from 'three';\nimport type { PinPose, PinRecord } from './pin-types.js';\nexport interface BoneDriver { id:string; influences:readonly {id:string;weight:number}[] }\nconst matrix=(pose:PinPose)=>new Matrix4().compose(new Vector3().fromArray(pose.position),new Quaternion().fromArray(pose.rotation),new Vector3().fromArray(pose.scale));\n/** Drivers reference actual fitted bones, never hidden authoring nodes. The\n * driven bone's reference frame remains independently FK editable. */\nexport function driverDelta(driver:BoneDriver,pins:readonly PinRecord[],reference:readonly PinRecord[]){\n const affine=new Matrix4();affine.elements.fill(0);\n const rotation=new Quaternion(0,0,0,0),scale=new Vector3();let hemisphere:Quaternion|undefined;\n for(const influence of driver.influences){\n const current=pins.find(p=>p.id===influence.id)!.pose,rest=reference.find(p=>p.id===influence.id)!.pose,w=influence.weight;\n const delta=matrix(current).multiply(matrix(rest).invert()),q=new Quaternion().fromArray(current.rotation).multiply(new Quaternion().fromArray(rest.rotation).invert());\n hemisphere??=q;const sign=hemisphere.dot(q)<0?-w:w;\n delta.elements.forEach((value,i)=>affine.elements[i]+=value*w);\n rotation.set(rotation.x+q.x*sign,rotation.y+q.y*sign,rotation.z+q.z*sign,rotation.w+q.w*sign);\n scale.addScaledVector(new Vector3().fromArray(current.scale).divide(new Vector3().fromArray(rest.scale)),w);\n }\n if(!driver.influences.length){affine.identity();rotation.identity();scale.setScalar(1);}\n return {affine,rotation:rotation.normalize(),scale};\n}\nexport function drivenPose(pose:PinPose,driver:BoneDriver,pins:readonly PinRecord[],reference:readonly PinRecord[]):PinPose{\n const delta=driverDelta(driver,pins,reference);\n return {position:new Vector3().fromArray(pose.position).applyMatrix4(delta.affine).toArray(),rotation:delta.rotation.multiply(new Quaternion().fromArray(pose.rotation)).normalize().toArray(),scale:delta.scale.multiply(new Vector3().fromArray(pose.scale)).toArray()};\n}\nexport function referencePose(pose:PinPose,driver:BoneDriver,pins:readonly PinRecord[],reference:readonly PinRecord[]):PinPose{\n const delta=driverDelta(driver,pins,reference);\n if(Math.abs(delta.affine.determinant())<1e-10)throw new Error('This blended bone frame is singular. Adjust its driving bones before editing its position.');\n return {position:new Vector3().fromArray(pose.position).applyMatrix4(delta.affine.invert()).toArray(),rotation:delta.rotation.invert().multiply(new Quaternion().fromArray(pose.rotation)).normalize().toArray(),scale:new Vector3().fromArray(pose.scale).divide(delta.scale).toArray()};\n}\nexport function driveRig(pins:readonly PinRecord[],reference:readonly PinRecord[],drivers:readonly BoneDriver[]){\n return pins.map(pin=>{const driver=drivers.find(d=>d.id===pin.id);return driver?{...pin,pose:drivenPose(pin.pose,driver,pins,reference)}:pin;});\n}\n", "import { BufferAttribute, MeshPhysicalMaterial, MeshStandardMaterial, SkinnedMesh, Vector2, type BufferGeometry, type Material, type Object3D, type Texture } from 'three';\nimport { MeshPhysicalNodeMaterial, MeshStandardNodeMaterial, type Node } from 'three/webgpu';\nimport { attribute, float, mix, normalMap, positionLocal, texture, uniform, uv, varying, vec2, vec3, vec4 } from 'three/tsl';\nimport { bindTextureSlot } from '../rendering/texture-slot.js';\nimport type { RigDescriptor } from './rig-extension.js';\n\ninterface Surface { mesh: SkinnedMesh; geometry: BufferGeometry; modified: BufferGeometry; material: Material | Material[]; variants: MeshStandardNodeMaterial[] }\n\n/** Optional GPU detail for a portable skinned GLB. Nothing is written into its\n * fallback material or geometry, and the variant is absent without Fur pins. */\nexport class FurSurface {\n readonly surfaces: Surface[] = [];\n private height: Texture | null = null;\n private clock = uniform(0);\n private wind = uniform(0);\n\n constructor(scene: Object3D, descriptor: RigDescriptor, nodes: readonly Object3D[], helpers: readonly Object3D[]) {\n const depth = new Map<Object3D, number>();\n descriptor.pins.forEach((pin, i) => depth.set(nodes[i], pin.fur ? (pin.furDepth ?? .1) : 0));\n descriptor.helpers?.forEach((helper, i) => depth.set(helpers[i], helper.influences.reduce((sum, influence) => {\n const index = descriptor.joints.findIndex(joint => joint.node === influence.node);\n const pin = descriptor.pins[index];\n return sum + (pin?.fur ? (pin.furDepth ?? .1) * influence.weight : 0);\n }, 0)));\n scene.traverse(object => {\n if (!(object instanceof SkinnedMesh)) return;\n const geometry = object.geometry, indices = geometry.getAttribute('skinIndex'), weights = geometry.getAttribute('skinWeight');\n if (!indices || !weights || !geometry.getAttribute('uv') || !geometry.getAttribute('normal')) return;\n if ((Array.isArray(object.material) ? object.material : [object.material]).some(material => !(material instanceof MeshStandardMaterial))) return;\n const values = new Float32Array(indices.count);\n for (let v = 0; v < values.length; v++) for (let lane = 0; lane < 4; lane++) {\n values[v] += (depth.get(object.skeleton.bones[indices.getComponent(v, lane)]) ?? 0) * weights.getComponent(v, lane);\n }\n if (!values.some(value => value > 1e-5)) return;\n const modified = geometry.clone();\n modified.setAttribute('furDepth', new BufferAttribute(values, 1));\n const surface: Surface = { mesh: object, geometry, modified, material: object.material, variants: [] };\n object.geometry = modified;\n this.surfaces.push(surface);\n });\n this.rebuild();\n }\n\n setHeightMap(height: Texture | null) { if (this.height !== height) { this.height = height; this.rebuild(); } }\n update(seconds: number, windStrength: number) {\n this.clock.value += Math.max(0, Math.min(seconds, .1));\n this.wind.value = windStrength;\n }\n /** GLTFExporter must only see standard portable materials and attributes. */\n setPortable(portable: boolean) {\n for (const surface of this.surfaces) {\n surface.mesh.geometry = portable ? surface.geometry : surface.modified;\n surface.mesh.material = portable ? surface.material : Array.isArray(surface.material) ? surface.variants : surface.variants[0];\n }\n }\n dispose() {\n this.setPortable(true);\n for (const surface of this.surfaces) {\n surface.modified.dispose(); surface.mesh.geometry = surface.geometry;\n for (const variant of surface.variants) variant.dispose();\n }\n this.surfaces.length = 0;\n }\n private rebuild() {\n for (const surface of this.surfaces) {\n const sources = Array.isArray(surface.material) ? surface.material : [surface.material];\n const variants = sources.map(source => this.material(source as MeshStandardMaterial));\n this.setPortable(true);\n for (const old of surface.variants) old.dispose();\n surface.variants = variants;\n }\n this.setPortable(false);\n }\n private material(source: MeshStandardMaterial) {\n const material = source instanceof MeshPhysicalMaterial ? new MeshPhysicalNodeMaterial() : new MeshStandardNodeMaterial();\n material.copy(source);\n material.name = `${source.name || 'Material'} \u00B7 Fur texture motion`;\n const coordinates = uv();\n const signal = source.map ?? source.normalMap ?? source.roughnessMap ?? source.metalnessMap ?? source.emissiveMap ?? source.aoMap ?? source.alphaMap ?? this.height;\n if (!signal) return material;\n const depth = attribute('furDepth', 'float' as const).mul(5).clamp(0, 1);\n const skinnedDelta = varying(positionLocal.sub(attribute('position', 'vec3' as const)), 'furSkinDelta') as Node<'vec3'>;\n const signalSlot = ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'aoMap', 'alphaMap'].find(slot => Reflect.get(source, slot) === signal) ?? 'furHeightMap';\n const pixel = uniform(new Vector2());\n const updatePixel = (map: Texture) => {\n const dimensions = map.image as { width?: number; height?: number } | undefined;\n pixel.value.set(1 / Math.max(1, dimensions?.width ?? 1024), 1 / Math.max(1, dimensions?.height ?? 1024));\n };\n updatePixel(signal);\n const movement = projectMotionToUv(skinnedDelta, coordinates).clamp(pixel.mul(-1.5), pixel.mul(1.5));\n const heightNode = this.height ? texture(this.height, uv(this.height.channel)) : null;\n if (heightNode && this.height) bindTextureSlot(material, 'furHeightMap', this.height,\n [heightNode], value => { this.height = value; if (signalSlot === 'furHeightMap') updatePixel(value); });\n const height = heightNode ? heightNode.r : float(.5);\n const raised = mix(.65, 1.35, height);\n const phase = coordinates.dot(vec2(31, 43)).add(height.sub(.5).mul(2.4)).add(this.clock.mul(this.wind).mul(1.7));\n const gust = vec2(phase.sin(), phase.mul(1.31).cos()).mul(pixel).mul(this.wind.mul(.65));\n // A shared subpixel-to-two-pixel UV flow keeps color, normal, ORM, AO and\n // opacity aligned. The field follows the skinned surface and can shimmer\n // with wind; height modulates movement rather than drawing synthetic hair.\n const shift = movement.add(gust).mul(depth).mul(raised)\n .clamp(pixel.mul(-2), pixel.mul(2)).toVar('furTextureShift');\n const sample = (map: Texture, slot: string) => {\n const node = texture(map, uv(map.channel).add(shift));\n node.updateMatrix = true;\n bindTextureSlot(material, slot, map, [node], value => { Reflect.set(source, slot, value); if (signalSlot === slot) updatePixel(value); });\n return node;\n };\n const base = source.map ? sample(source.map, 'map') : vec4(1);\n material.colorNode = base.mul(vec4(source.color.r, source.color.g, source.color.b, 1));\n if (source.alphaMap) material.opacityNode = sample(source.alphaMap, 'alphaMap').g;\n if (source.normalMap) material.normalNode = normalMap(sample(source.normalMap, 'normalMap').xyz,\n vec2(source.normalScale.x, source.normalScale.y));\n material.roughnessNode = source.roughnessMap ? sample(source.roughnessMap, 'roughnessMap').g.mul(source.roughness) : float(source.roughness);\n material.metalnessNode = source.metalnessMap ? sample(source.metalnessMap, 'metalnessMap').b.mul(source.metalness) : float(source.metalness);\n if (source.aoMap) material.aoNode = float(1).sub(float(1).sub(sample(source.aoMap, 'aoMap').r).mul(source.aoMapIntensity));\n if (source.emissiveMap) material.emissiveNode = sample(source.emissiveMap, 'emissiveMap').rgb.mul(vec3(\n source.emissive.r * source.emissiveIntensity,\n source.emissive.g * source.emissiveIntensity,\n source.emissive.b * source.emissiveIntensity));\n material.userData.furSurface = { heightMapped: Boolean(this.height), motionMapped: true };\n return material;\n }\n}\n\n/** Convert the current skin displacement into a local UV offset. The metric\n * inversion avoids assuming that U/V align with world X/Y or have equal scale. */\nfunction projectMotionToUv(movement: Node<'vec3'>, coordinates: Node<'vec2'>) {\n const dUvDx = coordinates.dFdx(), dUvDy = coordinates.dFdy();\n const dPosDx = positionLocal.dFdx(), dPosDy = positionLocal.dFdy();\n const determinant = dUvDx.x.mul(dUvDy.y).sub(dUvDx.y.mul(dUvDy.x));\n const safe = determinant.abs().max(1e-10).mul(determinant.lessThan(0).select(-1, 1));\n const dPosDu = dPosDx.mul(dUvDy.y).sub(dPosDy.mul(dUvDx.y)).div(safe);\n const dPosDv = dPosDy.mul(dUvDx.x).sub(dPosDx.mul(dUvDx.y)).div(safe);\n const uu = dPosDu.dot(dPosDu), vv = dPosDv.dot(dPosDv), uvMetric = dPosDu.dot(dPosDv);\n const metric = uu.mul(vv).sub(uvMetric.mul(uvMetric)).max(1e-12);\n const u = movement.dot(dPosDu), v = movement.dot(dPosDv);\n return vec2(vv.mul(u).sub(uvMetric.mul(v)).div(metric), uu.mul(v).sub(uvMetric.mul(u)).div(metric));\n}\n", "// @ts-check\n\n/** Keep material-slot texture replacement connected to the shader nodes.\n * @param {import('three').Material} material\n * @param {string} slot\n * @param {import('three').Texture} initial\n * @param {{value: import('three').Texture}[]} nodes\n * @param {((value: import('three').Texture) => void)=} onChange\n */\nexport function bindTextureSlot(material, slot, initial, nodes, onChange) {\n let current = initial;\n Object.defineProperty(material, slot, {\n configurable: true, enumerable: true,\n get: () => current,\n set: (/** @type {import('three').Texture} */ value) => {\n value.channel = current.channel;\n value.offset = current.offset;\n value.repeat = current.repeat;\n value.center = current.center;\n value.rotation = current.rotation;\n current = value;\n for (const node of nodes) node.value = value;\n onChange?.(value);\n material.needsUpdate = true;\n },\n });\n}\n"],
|
|
5
|
+
"mappings": ";;;AAAA,SAAS,gBAAgB,iBAAiB,WAAAA,UAAS,UAAU,cAAAC,aAAY,eAAAC,cAAa,WAAAC,gBAAsE;;;ACUrJ,IAAM,oBAAoB;AAC1B,IAAM,gBAAgB;AAEtB,IAAM,iBAAiB,CAAC,OAAM,OAAM,QAAO,QAAO,QAAO,OAAM,YAAW,OAAO;;;ACZjF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UAAU,WAAW,MAAO,UAAS,OAAO;AAAQ,YAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,gCAAgC;AAAA,MAAG;AAC5M,YAAM,UAAU,IAAI,sBAAsB,OAAO,YAAY,OAAO,KAAK,YAAY,OAAO;AAC5F,UAAI,WAAW,YAAY;AACzB,cAAM,SAAS,MAAM,KAAK,OAAO,cAAc,WAAW,WAAW,WAAW,aAAa;AAC7F,eAAO,UAAU,WAAW,WAAW,YAAY;AACnD,gBAAQ,gBAAgB,MAAM;AAAA,MAChC;AACA,eAAS,IAAI,OAAO,OAAO;AAAA,IAC7B;AAAA,EACF;AACF;AAEO,SAAS,mCAAmC,QAAoB;AACrE,SAAO,SAAS,YAAU,IAAI,iCAAiC,MAAM,CAAC;AAAG,SAAO;AAClF;AAEO,SAAS,kBAAkB,OAAiB;AAAE,SAAO,SAAS,IAAI,KAAK;AAAG;",
|
|
6
6
|
"names": ["Matrix4", "Quaternion", "SkinnedMesh", "Vector3", "pose", "Vector3", "pose", "value", "rotation", "Quaternion", "Vector3", "pin", "Vector3", "Quaternion", "matrix", "point", "i", "pin", "Quaternion", "Vector3", "Quaternion", "position", "Vector3", "Quaternion", "Vector3", "Vector3", "Quaternion", "Vector3", "Vector3", "point", "center", "Matrix4", "Quaternion", "Vector3", "pose", "matrix", "pose", "Matrix4", "Vector3", "Quaternion", "texture", "SkinnedMesh", "point", "record"]
|
|
7
7
|
}
|