@needle-tools/three-mesh-effects 0.0.0-stage → 0.1.0-alpha
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/LICENSE +21 -0
- package/README.md +88 -3
- package/build/deformation-runtime.js +2143 -0
- package/build/deformation-runtime.js.map +7 -0
- package/build/impostor-runtime-needle-engine.js +42 -0
- package/build/impostor-runtime-needle-engine.js.map +7 -0
- package/build/impostor-runtime.js +1333 -0
- package/build/impostor-runtime.js.map +7 -0
- package/build/internal/deformation/cloth-surface.js +288 -0
- package/build/internal/deformation/cloth-surface.js.map +7 -0
- package/build/internal/deformation/fur-surface.js +130 -0
- package/build/internal/deformation/fur-surface.js.map +7 -0
- package/build/internal/deformation/ik-constraints.js +44 -0
- package/build/internal/deformation/ik-constraints.js.map +7 -0
- package/build/internal/deformation/joints-json.js +197 -0
- package/build/internal/deformation/joints-json.js.map +7 -0
- package/build/internal/deformation/limits.js +16 -0
- package/build/internal/deformation/limits.js.map +7 -0
- package/build/internal/deformation/motion-settings.js +12 -0
- package/build/internal/deformation/motion-settings.js.map +7 -0
- package/build/internal/deformation/pin-cloth.js +196 -0
- package/build/internal/deformation/pin-cloth.js.map +7 -0
- package/build/internal/deformation/pin-ik.js +650 -0
- package/build/internal/deformation/pin-ik.js.map +7 -0
- package/build/internal/deformation/pin-types.js +12 -0
- package/build/internal/deformation/pin-types.js.map +7 -0
- package/build/internal/deformation/pin-wiggle.js +249 -0
- package/build/internal/deformation/pin-wiggle.js.map +7 -0
- package/build/internal/deformation/pose-slots.js +84 -0
- package/build/internal/deformation/pose-slots.js.map +7 -0
- package/build/internal/deformation/pose-timeline.js +210 -0
- package/build/internal/deformation/pose-timeline.js.map +7 -0
- package/build/internal/deformation/rig-drivers.js +48 -0
- package/build/internal/deformation/rig-drivers.js.map +7 -0
- package/build/internal/deformation/rig-extension.js +334 -0
- package/build/internal/deformation/rig-extension.js.map +7 -0
- package/build/internal/deformation/rig-runtime.js +2141 -0
- package/build/internal/deformation/rig-runtime.js.map +7 -0
- package/build/internal/deformation/wind.js +34 -0
- package/build/internal/deformation/wind.js.map +7 -0
- package/build/internal/impostor/impostor-metadata.js +77 -0
- package/build/internal/impostor/impostor-metadata.js.map +7 -0
- package/build/internal/impostor/impostor-node-material.js +1331 -0
- package/build/internal/impostor/impostor-node-material.js.map +7 -0
- package/build/internal/impostor/impostor-runtime-support.js +162 -0
- package/build/internal/impostor/impostor-runtime-support.js.map +7 -0
- package/build/internal/impostor/octahedral.js +232 -0
- package/build/internal/impostor/octahedral.js.map +7 -0
- package/build/internal/pixel-impostor/pixel-impostor-display.js +728 -0
- package/build/internal/pixel-impostor/pixel-impostor-display.js.map +7 -0
- package/build/internal/pixel-impostor/pixel-impostor-metadata.js +71 -0
- package/build/internal/pixel-impostor/pixel-impostor-metadata.js.map +7 -0
- package/build/internal/pixel-impostor/pixel-impostor-runtime.js +150 -0
- package/build/internal/pixel-impostor/pixel-impostor-runtime.js.map +7 -0
- package/build/internal/public/deformation-runtime.js +2143 -0
- package/build/internal/public/deformation-runtime.js.map +7 -0
- package/build/internal/public/impostor-runtime-needle-engine.js +42 -0
- package/build/internal/public/impostor-runtime-needle-engine.js.map +7 -0
- package/build/internal/public/impostor-runtime.js +1333 -0
- package/build/internal/public/impostor-runtime.js.map +7 -0
- package/build/internal/public/pixel-impostor-runtime.js +876 -0
- package/build/internal/public/pixel-impostor-runtime.js.map +7 -0
- package/build/internal/public/wrap-effects.js +5640 -0
- package/build/internal/public/wrap-effects.js.map +7 -0
- package/build/internal/rendering/skin-projection.js +4630 -0
- package/build/internal/rendering/skin-projection.js.map +7 -0
- package/build/internal/rendering/surface-query.js +4519 -0
- package/build/internal/rendering/surface-query.js.map +7 -0
- package/build/internal/rendering/wireframe.js +112 -0
- package/build/internal/rendering/wireframe.js.map +7 -0
- package/build/internal/rendering/wrap-preview-settings.js +126 -0
- package/build/internal/rendering/wrap-preview-settings.js.map +7 -0
- package/build/internal/rendering/wrap-preview.js +5610 -0
- package/build/internal/rendering/wrap-preview.js.map +7 -0
- package/build/internal/rendering/wrap-skin.js +4746 -0
- package/build/internal/rendering/wrap-skin.js.map +7 -0
- package/build/pixel-impostor-runtime.js +876 -0
- package/build/pixel-impostor-runtime.js.map +7 -0
- package/build/types/deformation/cloth-surface.d.ts +39 -0
- package/build/types/deformation/cloth-surface.js +1 -0
- package/build/types/deformation/fur-surface.d.ts +27 -0
- package/build/types/deformation/fur-surface.js +1 -0
- package/build/types/deformation/ik-constraints.d.ts +18 -0
- package/build/types/deformation/ik-constraints.js +1 -0
- package/build/types/deformation/joints-json.d.ts +17 -0
- package/build/types/deformation/joints-json.js +1 -0
- package/build/types/deformation/limits.d.ts +23 -0
- package/build/types/deformation/limits.js +1 -0
- package/build/types/deformation/motion-settings.d.ts +9 -0
- package/build/types/deformation/motion-settings.js +1 -0
- package/build/types/deformation/pin-cloth.d.ts +28 -0
- package/build/types/deformation/pin-cloth.js +1 -0
- package/build/types/deformation/pin-ik.d.ts +37 -0
- package/build/types/deformation/pin-ik.js +1 -0
- package/build/types/deformation/pin-types.d.ts +53 -0
- package/build/types/deformation/pin-types.js +1 -0
- package/build/types/deformation/pin-wiggle.d.ts +16 -0
- package/build/types/deformation/pin-wiggle.js +1 -0
- package/build/types/deformation/pose-slots.d.ts +41 -0
- package/build/types/deformation/pose-slots.js +1 -0
- package/build/types/deformation/pose-timeline.d.ts +65 -0
- package/build/types/deformation/pose-timeline.js +1 -0
- package/build/types/deformation/rig-drivers.d.ts +19 -0
- package/build/types/deformation/rig-drivers.js +1 -0
- package/build/types/deformation/rig-extension.d.ts +33 -0
- package/build/types/deformation/rig-extension.js +1 -0
- package/build/types/deformation/rig-runtime.d.ts +95 -0
- package/build/types/deformation/rig-runtime.js +1 -0
- package/build/types/deformation/wind.d.ts +16 -0
- package/build/types/deformation/wind.js +1 -0
- package/build/types/impostor/impostor-metadata.d.ts +61 -0
- package/build/types/impostor/impostor-metadata.js +1 -0
- package/build/types/impostor/impostor-node-material.d.ts +140 -0
- package/build/types/impostor/impostor-node-material.js +1 -0
- package/build/types/impostor/impostor-runtime-support.d.ts +52 -0
- package/build/types/impostor/impostor-runtime-support.js +1 -0
- package/build/types/impostor/octahedral.d.ts +84 -0
- package/build/types/impostor/octahedral.js +1 -0
- package/build/types/pixel-impostor/pixel-impostor-display.d.ts +48 -0
- package/build/types/pixel-impostor/pixel-impostor-display.js +1 -0
- package/build/types/pixel-impostor/pixel-impostor-metadata.d.ts +34 -0
- package/build/types/pixel-impostor/pixel-impostor-metadata.js +1 -0
- package/build/types/pixel-impostor/pixel-impostor-runtime.d.ts +18 -0
- package/build/types/pixel-impostor/pixel-impostor-runtime.js +1 -0
- package/build/types/public/deformation-runtime.d.ts +3 -0
- package/build/types/public/deformation-runtime.js +1 -0
- package/build/types/public/impostor-runtime-needle-engine.d.ts +31 -0
- package/build/types/public/impostor-runtime-needle-engine.js +1 -0
- package/build/types/public/impostor-runtime.d.ts +6 -0
- package/build/types/public/impostor-runtime.js +1 -0
- package/build/types/public/pixel-impostor-runtime.d.ts +3 -0
- package/build/types/public/pixel-impostor-runtime.js +1 -0
- package/build/types/public/wrap-effects.d.ts +4 -0
- package/build/types/public/wrap-effects.js +1 -0
- package/build/types/rendering/skin-projection.d.ts +44 -0
- package/build/types/rendering/skin-projection.js +1 -0
- package/build/types/rendering/surface-query.d.ts +66 -0
- package/build/types/rendering/surface-query.js +1 -0
- package/build/types/rendering/wireframe.d.ts +25 -0
- package/build/types/rendering/wireframe.js +1 -0
- package/build/types/rendering/wrap-preview-settings.d.ts +22 -0
- package/build/types/rendering/wrap-preview-settings.js +1 -0
- package/build/types/rendering/wrap-preview.d.ts +39 -0
- package/build/types/rendering/wrap-preview.js +1 -0
- package/build/types/rendering/wrap-skin.d.ts +14 -0
- package/build/types/rendering/wrap-skin.js +1 -0
- package/build/wrap-effects.js +5640 -0
- package/build/wrap-effects.js.map +7 -0
- package/package.json +94 -6
- package/src/deformation/cloth-surface.ts +223 -0
- package/src/deformation/fur-surface.ts +129 -0
- package/src/deformation/ik-constraints.ts +37 -0
- package/src/deformation/joints-json.ts +94 -0
- package/src/deformation/limits.ts +25 -0
- package/src/deformation/motion-settings.ts +9 -0
- package/src/deformation/pin-cloth.ts +149 -0
- package/src/deformation/pin-ik.ts +582 -0
- package/src/deformation/pin-types.ts +22 -0
- package/src/deformation/pin-wiggle.ts +119 -0
- package/src/deformation/pose-slots.ts +106 -0
- package/src/deformation/pose-timeline.ts +242 -0
- package/src/deformation/rig-drivers.ts +32 -0
- package/src/deformation/rig-extension.ts +87 -0
- package/src/deformation/rig-runtime.ts +416 -0
- package/src/deformation/wind.ts +36 -0
- package/src/impostor/impostor-metadata.js +137 -0
- package/src/impostor/impostor-node-material.js +1581 -0
- package/src/impostor/impostor-runtime-support.js +139 -0
- package/src/impostor/octahedral.js +280 -0
- package/src/pixel-impostor/pixel-impostor-display.js +794 -0
- package/src/pixel-impostor/pixel-impostor-metadata.js +74 -0
- package/src/pixel-impostor/pixel-impostor-runtime.js +78 -0
- package/src/public/deformation-runtime.ts +3 -0
- package/src/public/impostor-runtime-needle-engine.js +56 -0
- package/src/public/impostor-runtime.js +21 -0
- package/src/public/pixel-impostor-runtime.js +5 -0
- package/src/public/wrap-effects.js +21 -0
- package/src/rendering/skin-projection.js +113 -0
- package/src/rendering/surface-query.js +88 -0
- package/src/rendering/wireframe.js +115 -0
- package/src/rendering/wrap-preview-settings.js +123 -0
- package/src/rendering/wrap-preview.js +645 -0
- package/src/rendering/wrap-skin.js +109 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/deformation/pin-wiggle.ts", "../../../src/deformation/pin-types.ts", "../../../src/deformation/motion-settings.ts", "../../../src/deformation/pin-ik.ts", "../../../src/deformation/wind.ts"],
|
|
4
|
+
"sourcesContent": ["import { Quaternion, Vector3 } from 'three';\r\nimport { DEFAULT_FUR_DEPTH, type PinPose, type PinRecord } from './pin-types.js';\r\nimport type { PinParents } from './pin-types.js';\r\nimport { DEFAULT_MOTION, type MotionSettings } from './motion-settings.js';\r\nimport { ikChain } from './pin-ik.js';\r\nimport { windAcceleration } from './wind.js';\r\n\r\n/** Disposable secondary motion. Never writes authored pins or history. */\r\nexport class PinWiggle {\r\n private springs = new Map<string, { position: Vector3; velocity: Vector3; target:Vector3 }>();\r\n private topology = '';\r\n private lastPins: readonly PinRecord[] | null = null;\r\n private lastParents: PinParents | null = null;\r\n private awake = false;\r\n private windTime = 0;\r\n reset() { this.springs.clear(); this.topology = ''; this.lastPins = null; this.lastParents = null; this.awake = false; this.windTime = 0; }\r\n\r\n step(pins: readonly PinRecord[], parents: PinParents, seconds: number, masses?:ReadonlyMap<string,number>, windStrength = 0): { pins: readonly PinRecord[]; active: boolean } {\r\n if (windStrength <= 0 && !this.awake && pins === this.lastPins && parents === this.lastParents) return {pins,active:false};\r\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)]));\r\n if (topology !== this.topology) { this.reset(); this.topology = topology; }\r\n const groups = new Map<string, PinRecord[]>(), byId = new Map(pins.map(p => [p.id,p]));\r\n const key = (p: PinRecord) => p.rigidGroup ?? p.id;\r\n for (const pin of pins) { const group = groups.get(key(pin)) ?? []; group.push(pin); groups.set(key(pin),group); }\r\n const settings = new Map<string,Readonly<MotionSettings>>();\r\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);\r\n const typicalVolume=volumes[Math.floor(volumes.length/2)]??1;\r\n for (const pin of pins.filter(p=>p.wiggle && !p.guide)) {\r\n const chain=ikChain(pins,parents,pin.id,masses);\r\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);\r\n }\r\n for (const pin of pins.filter(p=>p.wiggle && !p.guide)) settings.set(key(pin),pin.motion ?? DEFAULT_MOTION);\r\n // Fur belongs to the outer shell: unlike Wiggle it must not make the\r\n // articulated core's ancestor chain into springs.\r\n for (const pin of pins.filter(p=>p.fur && !p.guide)) settings.set(key(pin),pin.motion ?? DEFAULT_MOTION);\r\n const output = new Map<string, PinPose>(), visiting = new Set<string>();\r\n let active = false;\r\n // Exact underdamped spring integration, stable across variable frame times.\r\n // Clamp background-tab gaps rather than simulating missed seconds.\r\n const dt = Math.min(Math.max(seconds,0),.05);\r\n this.windTime += dt;\r\n const visit = (id: string) => {\r\n const group = groups.get(id)!;\r\n if (output.has(group[0].id)) return;\r\n if (visiting.has(id)) { for (const pin of group) output.set(pin.id,pin.pose); return; }\r\n visiting.add(id);\r\n const parent = group.map(p => byId.get(parents.get(p.id) ?? '')).find(p => p && key(p) !== id);\r\n if (parent) visit(key(parent));\r\n const parentPose = parent ? output.get(parent.id)! : undefined;\r\n const inherited = parent && parentPose ? new Quaternion().fromArray(parentPose.rotation).multiply(new Quaternion().fromArray(parent.pose.rotation).invert()) : new Quaternion();\r\n const targets = group.map(pin => {\r\n const position = new Vector3().fromArray(pin.pose.position);\r\n if (!pin.ik && parent && parentPose) position.sub(new Vector3().fromArray(parent.pose.position)).applyQuaternion(inherited).add(new Vector3().fromArray(parentPose.position));\r\n return { pin, position, rotation: (pin.ik ? new Quaternion() : inherited.clone()).multiply(new Quaternion().fromArray(pin.pose.rotation)) };\r\n });\r\n const center = targets.reduce((sum,p) => sum.add(p.position),new Vector3()).divideScalar(group.length);\r\n let position = center, rotation = new Quaternion();\r\n const motion=settings.get(id);\r\n if (motion && !group.every(p=>p.guide) && !group.some(p=>p.ik)) {\r\n const ratio=Math.max(.125,Math.min(8,(masses?.get(group[0].id)??typicalVolume)/typicalVolume));\r\n const gain=motion.strength*Math.max(.25,Math.min(4,Math.pow(1/ratio,.5*motion.massInfluence)));\r\n const frequency=motion.frequency*2*Math.PI, damping=Math.max(.05,Math.min(1,motion.damping*Math.pow(ratio,.25*motion.massInfluence)));\r\n const decay = damping * frequency, oscillation = frequency * Math.sqrt(1-damping*damping);\r\n const e = Math.exp(-decay*dt), c = Math.cos(oscillation*dt), s = oscillation > 1e-8 ? Math.sin(oscillation*dt)/oscillation : dt;\r\n let spring = this.springs.get(id);\r\n if (!spring) { spring = { position:center.clone(),velocity:new Vector3(),target:center.clone() }; this.springs.set(id,spring); }\r\n spring.position.addScaledVector(center.clone().sub(spring.target),1-gain);spring.target.copy(center);\r\n if(motion.strength===0){spring.position.copy(center);spring.velocity.set(0,0,0);}\r\n else if (windStrength > 0) spring.velocity.addScaledVector(windAcceleration(this.windTime, windStrength,\r\n parentPose ? Math.max(center.distanceTo(new Vector3().fromArray(parentPose.position)), 1e-3) : 1, center.toArray()), motion.strength * dt);\r\n const offset = spring.position.clone().sub(center), velocity = spring.velocity.clone();\r\n spring.position.copy(offset).multiplyScalar(c).addScaledVector(velocity.clone().addScaledVector(offset,decay),s).multiplyScalar(e).add(center);\r\n spring.velocity.copy(velocity).multiplyScalar(c).sub(velocity.clone().multiplyScalar(decay).addScaledVector(offset,frequency*frequency).multiplyScalar(s)).multiplyScalar(e);\r\n const fur = group.find(p=>p.fur), furDepth=fur?.furDepth??DEFAULT_FUR_DEPTH;\r\n let radius = 1;\r\n if (parentPose) {\r\n const pivot = new Vector3().fromArray(parentPose.position), desired = center.clone().sub(pivot);\r\n radius = desired.length();\r\n const direction = spring.position.clone().sub(pivot);\r\n if (radius > 1e-8) {\r\n if (direction.lengthSq() < 1e-16) direction.copy(desired);\r\n const length=direction.length();direction.divideScalar(length);\r\n const coreRadius=radius*(1-furDepth),outerRadius=radius*(1+furDepth);\r\n const projected=fur?Math.max(coreRadius,Math.min(outerRadius,length)):radius;\r\n spring.position.copy(pivot).addScaledVector(direction,projected);\r\n if(!fur||length<coreRadius||length>outerRadius)spring.velocity.addScaledVector(direction,-spring.velocity.dot(direction));\r\n rotation.setFromUnitVectors(desired.normalize(),direction);\r\n } else { spring.position.copy(center); spring.velocity.set(0,0,0); }\r\n }\r\n if (fur) {\r\n const shell = Math.max(1e-4, radius) * furDepth;\r\n if (shell === 0) { spring.position.copy(center); spring.velocity.set(0,0,0); rotation.identity(); }\r\n const displacement = spring.position.clone().sub(center);\r\n if (displacement.length() > shell) {\r\n displacement.setLength(shell); spring.position.copy(center).add(displacement);\r\n const outward=displacement.normalize();spring.velocity.addScaledVector(outward,-Math.max(0,spring.velocity.dot(outward)));\r\n }\r\n if(parentPose&&radius>1e-8){\r\n const pivot=new Vector3().fromArray(parentPose.position),desired=center.clone().sub(pivot).normalize(),direction=spring.position.clone().sub(pivot).normalize();\r\n rotation.setFromUnitVectors(desired,direction);\r\n }\r\n }\r\n const epsilon = Math.max(radius,1e-3)*1e-5;\r\n if (spring.position.distanceToSquared(center) < epsilon*epsilon && spring.velocity.lengthSq() < epsilon*epsilon*frequency*frequency) {\r\n spring.position.copy(center); spring.velocity.set(0,0,0); rotation.identity();\r\n } else active = true;\r\n position = spring.position;\r\n }\r\n for (const target of targets) output.set(target.pin.id, {\r\n position:target.position.sub(center).applyQuaternion(rotation).add(position).toArray(),\r\n rotation:rotation.clone().multiply(target.rotation).normalize().toArray(),scale:target.pin.pose.scale,\r\n });\r\n visiting.delete(id);\r\n };\r\n for (const id of groups.keys()) visit(id);\r\n this.lastPins = pins; this.lastParents = parents; this.awake = active;\r\n return { pins: active ? pins.map(pin => ({...pin,pose:output.get(pin.id)!})) : pins, active };\r\n }\r\n}\r\n", "import type { IKConstraint } from './ik-constraints.js';\r\nimport type { MotionSettings } from './motion-settings.js';\r\n\r\n/** Shared data contract; deliberately independent of editor history and GPU types. */\r\nexport type Point = readonly [number, number, number];\r\nexport type Rotation = readonly [number, number, number, number];\r\nexport type PinPose = { readonly position: Point; readonly rotation: Rotation; readonly scale: Point };\r\nexport type PinParents = ReadonlyMap<string, string>;\r\nexport type HierarchyEdge = {from:string;to:string;cost:number;geodesic?:number};\r\nexport type PinMotion = 'none' | 'ik' | 'wiggle' | 'cloth' | 'fur';\r\nexport const DEFAULT_FUR_DEPTH = .1;\r\nexport const MAX_FUR_DEPTH = .5;\r\nexport type IKTarget = { readonly position: Point; readonly rotation: Rotation };\r\nexport const IK_CHAIN_KINDS = ['leg','arm','head','tail','wing','fin','tentacle','spine'] as const;\r\nexport type IKChainRole = { readonly kind: typeof IK_CHAIN_KINDS[number]; readonly side: 'center'|'left'|'right'; readonly position?: 'front'|'hind' };\r\nexport type PinRecord = { readonly id: string; readonly rest: Point; readonly pose: PinPose; readonly rigidGroup: string | null; readonly independent: boolean;\r\n /** This pose was set on purpose in the slot now open, rather than reached by\r\n * being carried by a parent or swept along by an IK solve. A slot still\r\n * stores an unauthored pose it could not otherwise reproduce \u2014 an IK chain\r\n * does not come back the same way twice \u2014 but only an authored one is shown\r\n * as deliberate and only an authored one can be released. */\r\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 };\r\n", "export type MotionSettings = { reach: number; frequency: number; damping: number; massInfluence:number; strength:number };\r\nexport const DEFAULT_MOTION: Readonly<MotionSettings> = { reach: .5, frequency: 14 / (2*Math.PI), damping: .28, massInfluence:1,strength:1 };\r\nexport function validateMotionSettings(value: MotionSettings) {\r\n if (!value || !Number.isFinite(value.reach) || value.reach < 0 || value.reach > 1\r\n || !Number.isFinite(value.frequency) || value.frequency < .25 || value.frequency > 8\r\n || !Number.isFinite(value.damping) || value.damping < .05 || value.damping > 1\r\n || !Number.isFinite(value.massInfluence) || value.massInfluence<0 || value.massInfluence>2\r\n || !Number.isFinite(value.strength) || value.strength<0 || value.strength>3) throw new Error('Invalid motion settings.');\r\n}\r\n", "import { Goal, Joint, Link, Solver } from 'closed-chain-ik/core';\r\nimport { Euler, Matrix4, Quaternion, Vector3 } from 'three';\r\nimport type { PinRecord, PinPose, Point, Rotation } from './pin-types.js';\r\nimport { DEFAULT_MOTION } from './motion-settings.js';\r\nimport type { PinParents } from './pin-types.js';\r\nimport { DEFAULT_IK_CONSTRAINT, constrainCone } from './ik-constraints.js';\r\n\r\nconst POSE_CONTINUITY_WEIGHT=1e-4;\r\n\r\n/** A routing guide is not a limb. Only guides leading to real joints create\r\n * an articulated branch; dangling guidance must not lock an IK pivot. */\r\nfunction articulatedNodes(pins: readonly PinRecord[], parents: PinParents) {\r\n const nodes = new Set<string>();\r\n for (const pin of pins) if (!pin.guide) {\r\n let id: string | undefined = pin.id;\r\n while (id && !nodes.has(id)) { nodes.add(id); id = parents.get(id); }\r\n }\r\n return nodes;\r\n}\r\n\r\n/** IDs are derived each time; no stale authored chain survives topology edits. */\r\nexport function ikChain(pins: readonly PinRecord[], parents: PinParents, id: string, mass: ReadonlyMap<string, number> = new Map()): PinRecord[] {\r\n const byId = new Map(pins.map(pin => [pin.id, pin]));\r\n const element = (pin: PinRecord) => pin.rigidGroup ?? pin.id;\r\n const articulated = articulatedNodes(pins, parents);\r\n const children = new Map<string, Set<string>>();\r\n const supportLength=new Map<string,number>();\r\n for (const pin of pins) {\r\n if (!articulated.has(pin.id)) continue;\r\n const parent = byId.get(parents.get(pin.id) ?? '');\r\n if (!parent) continue;\r\n const length=Math.hypot(...pin.rest.map((x,i)=>x-parent.rest[i]))*.5;\r\n supportLength.set(pin.id,(supportLength.get(pin.id)??0)+length);\r\n supportLength.set(parent.id,(supportLength.get(parent.id)??0)+length);\r\n const set = children.get(element(parent)) ?? new Set<string>(); set.add(element(pin)); children.set(element(parent), set);\r\n }\r\n const chain: PinRecord[] = [], seen = new Set<string>();\r\n let pin = byId.get(id);\r\n const reach = pin?.motion?.reach ?? DEFAULT_MOTION.reach;\r\n let automatic:string|undefined;\r\n // Mass per supported rest length approximates cross-section, unlike raw\r\n // per-pin mass which shrinks simply because a limb gained more joints.\r\n const density=(p:PinRecord)=>mass.has(p.id)?mass.get(p.id)!/Math.max(supportLength.get(p.id)??0,1e-12):undefined;\r\n while (pin && !seen.has(element(pin))) {\r\n chain.unshift(pin); seen.add(element(pin));\r\n if (pin.independent) break;\r\n const parent = byId.get(parents.get(pin.id) ?? '');\r\n if (!parent) break;\r\n // Keep the body/other limbs stationary. An immediate parent is still\r\n // needed as the pivot for a single-link chain.\r\n if (!automatic && ((children.get(element(parent))?.size ?? 0) > 1\r\n || (!pin.guide && !parent.guide && (density(parent) ?? 0) > 8 * Math.max(density(pin) ?? Infinity, 1e-12)))) automatic=parent.id;\r\n pin = parent;\r\n }\r\n if(chain.length<2)return chain;\r\n const distance=new Float64Array(chain.length);\r\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]));\r\n const boundary=automatic?chain.findIndex(p=>p.id===automatic):-1;\r\n const automaticDistance=distance[Math.max(0,boundary)];\r\n // Reach measures REST arc length, not node count or posed/chord distance.\r\n // Zero starts at the endpoint (clamped to one link); subdivision must not\r\n // move the slider's origin by changing that first link's length.\r\n const budget=reach<=.5?automaticDistance*reach*2:automaticDistance+(distance[0]-automaticDistance)*(reach-.5)*2;\r\n const first=reach<=.5&&boundary>=0?Math.min(boundary+1,chain.length-2):0;\r\n let start=chain.length-2;\r\n for(let i=start-1;i>=first;i--)if(Math.abs(distance[i]-budget)<Math.abs(distance[start]-budget))start=i;\r\n if(reach===1)start=0;\r\n return chain.slice(start);\r\n}\r\n\r\nexport function solvePinIK(pins: readonly PinRecord[], parents: PinParents, id: string, target: Point,\r\n mass?: ReadonlyMap<string, number>, targetRotation?: Rotation): { id: string; pose: PinPose }[] {\r\n const pin=pins.find(p=>p.id===id)!;\r\n return solvePinIKGoals(pins,parents,[{id,position:target,rotation:targetRotation ?? pin.ikTarget?.rotation ?? pin.pose.rotation}],mass);\r\n}\r\n\r\nexport type IKGoal = {id:string;position:Point;rotation:Rotation};\r\n\r\n/** Endpoint editing is local. Shared body frames and sibling branches retain\r\n * their authored poses; root/body edits use the separate multi-goal solve. */\r\nexport function solveLocalPinIK(pins:readonly PinRecord[],parents:PinParents,goal:IKGoal,mass?:ReadonlyMap<string,number>,floor=-Infinity){\r\n const chain=ikChain(pins,parents,goal.id,mass),key=(p:PinRecord)=>p.rigidGroup??p.id;\r\n const keys=new Set(chain.map(key)),byId=new Map(pins.map(p=>[p.id,p]));\r\n const articulated = articulatedNodes(pins, parents);\r\n let boundary=-1;\r\n // Children below the endpoint are followers, never competing side branches.\r\n for(let i=0;i<chain.length-1;i++)if(chain[i].independent || pins.some(p=>{\r\n if (!articulated.has(p.id)) return false;\r\n const parent=byId.get(parents.get(p.id)??'');return parent&&key(parent)===key(chain[i])&&!keys.has(key(p));\r\n }))boundary=i;\r\n const shared=boundary>=0&&pins.some(p=>{\r\n if(!articulated.has(p.id))return false;\r\n const parent=byId.get(parents.get(p.id)??'');\r\n return parent&&key(parent)===key(chain[boundary])&&!keys.has(key(p));\r\n });\r\n // A shared attachment fixes the body. The outgoing limb gets a separate\r\n // zero-length branch pivot in the solver, so the first link can still swing.\r\n // A lone independent root has no sibling to disturb and retains the exact\r\n // two-link analytic solve through its temporary root rotation.\r\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)));\r\n const moving=new Set(chain.slice(boundary+1).map(key));\r\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;}}}\r\n const retained=new Set(boundary>=0?[key(chain[boundary])]:[]);\r\n return solvePinIKGoals(pins,parents,[goal],mass,fixed,retained,floor).filter(p=>moving.has(key(byId.get(p.id)!)));\r\n}\r\n\r\n/** Solve separate planted limbs against the same body pose. Their temporary\r\n * attachment rotations must not become rotations of the shared torso frame. */\r\nexport function solvePlantedPinIKGoals(pins:readonly PinRecord[],parents:PinParents,goals:readonly IKGoal[],mass?:ReadonlyMap<string,number>,fixed:ReadonlySet<string>=new Set(),floor=-Infinity){\r\n if(!goals.length)return [];\r\n const edits=new Map<string,{id:string;pose:PinPose}>();\r\n let independent=true;\r\n for(const goal of goals){\r\n const limb=solveLocalPinIK(pins,parents,goal,mass,floor);\r\n for(const edit of limb){\r\n if(fixed.has(edit.id)||edits.has(edit.id)){independent=false;break;}\r\n edits.set(edit.id,edit);\r\n }\r\n if(!independent)break;\r\n }\r\n return independent?[...edits.values()]:solvePinIKGoals(pins,parents,goals,mass,fixed,new Set(),floor);\r\n}\r\n\r\n/** Body motion and imported-pose reconstruction use the same full-chain solve.\r\n * Shared attachment frames are held; each limb gets its own branch pivot. */\r\nexport function solveBodyIKGoals(pins:readonly PinRecord[],parents:PinParents,goals:readonly IKGoal[],mass:ReadonlyMap<string,number>,fixed:ReadonlySet<string>,floor=-Infinity){\r\n const poleChains=new Map(goals.map(goal=>[goal.id,ikChain(pins,parents,goal.id,mass)]));\r\n const full=pins.map(pin=>pin.ik?{...pin,motion:{...DEFAULT_MOTION,...pin.motion,reach:1}}:pin);\r\n const uses=new Map<string,number>();\r\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);\r\n const anchors=new Set([...fixed,...[...uses].filter(([,count])=>count>1).map(([id])=>id)]);\r\n return solvePinIKGoals(full,parents,goals,mass,anchors,new Set(),floor,poleChains);\r\n}\r\n\r\n/** One articulated forest, one joint solve. Shared joints are never overwritten\r\n * by a later endpoint, and every child offset retains its authored length. */\r\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}[] {\r\n if (!goals.length) return [];\r\n const byId=new Map(pins.map(p=>[p.id,p])),key=(p:PinRecord)=>p.rigidGroup ?? p.id;\r\n const groups=new Map<string,PinRecord[]>();\r\n for(const pin of pins){const group=groups.get(key(pin)) ?? [];group.push(pin);groups.set(key(pin),group);}\r\n const active=new Set<string>(), roots=new Set<string>();\r\n const bendSeeds=new Map<string,Vector3>();\r\n let size=0;\r\n for(const goal of goals){\r\n const chain=ikChain(pins,parents,goal.id,mass);\r\n if(chain.length<2) throw new Error('IK needs a parent chain. Add a parent pin or remove Independent from this endpoint.');\r\n for(const p of chain) active.add(key(p));\r\n roots.add(key(chain[0]));\r\n // Only a straight, contracting chain needs a perturbation: at full\r\n // extension its positional Jacobian cannot discover a bend. Seeding an\r\n // already bent chain injects rotation on every drag sample and accumulates\r\n // drift despite a nearly stationary target.\r\n const start=new Vector3().fromArray(chain[0].pose.position),direction=new Vector3().fromArray(chain.at(-1)!.pose.position).sub(start);\r\n const span=direction.length();\r\n if(span>1e-8 && new Vector3().fromArray(goal.position).distanceTo(start)<span*(1-1e-6)){\r\n direction.divideScalar(span);\r\n const straight=chain.every(p=>new Vector3().fromArray(p.pose.position).sub(start).cross(direction).lengthSq()<span*span*1e-12);\r\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;\r\n if(candidate){\r\n // Bend in the plane the goal is actually in: perpendicular to both the\r\n // chain and the way it has to reach. Seeding off the chain's smallest\r\n // world component instead picks a plane with no relation to the goal,\r\n // and a straight arm pulled sideways swings out of the screen on its\r\n // way there \u2014 deterministic, but not a bend anyone asked for.\r\n const axis=new Vector3().crossVectors(direction,new Vector3().fromArray(goal.position).sub(start));\r\n if(axis.lengthSq()<1e-12){\r\n // The goal lies along the chain, so no plane is implied by it; any\r\n // axis across the chain will do, chosen the same way every time.\r\n const components=direction.toArray().map(Math.abs);\r\n axis.setComponent(components.indexOf(Math.min(...components)),1).addScaledVector(direction,-axis.dot(direction));\r\n }\r\n bendSeeds.set(key(candidate),axis.normalize());\r\n }\r\n }\r\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));\r\n }\r\n if(size<1e-8) throw new Error('IK chain has no length. Separate its rest pins first.');\r\n const parentGroup=new Map<string,string>();\r\n for(const [id,members] of groups){\r\n const parent=members.map(p=>byId.get(parents.get(p.id) ?? '')).find(p=>p && key(p)!==id);\r\n if(parent) parentGroup.set(id,key(parent));\r\n }\r\n // Include followers in the graph so branch attachments keep their lengths too.\r\n const affected=new Set(active);\r\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;}}\r\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;});\r\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}));\r\n const origin=new Vector3().fromArray(byId.get(goals[0].id)!.pose.position);\r\n const frames=new Map<string,Link>(), forest:Link[]=[], building=new Set<string>();\r\n const coneJoints=new Map<string,Joint>();\r\n const freeJoints=new Map<string,Joint>();\r\n const branchJoints=new Map<string,{joint:Joint;frame:Link}>();\r\n const build=(id:string):Link=>{\r\n const cached=frames.get(id);if(cached) return cached;\r\n if(building.has(id)) throw new Error('Cyclic IK hierarchy.');building.add(id);\r\n const pin=groups.get(id)![0],parentId=parentGroup.get(id),parent=parentId ? groups.get(parentId)![0] : undefined;\r\n const parentFrame=parentId ? build(parentId) : new Link();\r\n let attachment=parentFrame;\r\n if(parentId&&active.has(id)&&!groups.get(id)!.some(p=>fixed.has(p.id))&&groups.get(parentId)!.some(p=>fixed.has(p.id))){\r\n const pivot=new Joint();pivot.setDoF(3,4,5);pivot.setDoFValues(0,0,0);pivot.setRestPoseValues(0,0,0);\r\n parentFrame.addChild(pivot);attachment=new Link();pivot.addChild(attachment);\r\n branchJoints.set(id,{joint:pivot,frame:attachment});\r\n }\r\n const parentRotation=parent ? new Quaternion().fromArray(parent.pose.rotation) : new Quaternion();\r\n const position=new Vector3().fromArray(pin.pose.position).sub(parent ? new Vector3().fromArray(parent.pose.position):origin).applyQuaternion(parentRotation.clone().invert()).divideScalar(size);\r\n const relative=parentRotation.clone().invert().multiply(new Quaternion().fromArray(pin.pose.rotation)).normalize();\r\n const joint=new Joint();joint.setPosition(position.x,position.y,position.z);attachment.addChild(joint);\r\n const link=new Link(),constraint=pin.ikConstraint ?? DEFAULT_IK_CONSTRAINT;\r\n const movable=active.has(id)&&!groups.get(id)!.some(p=>fixed.has(p.id));\r\n if(!movable || constraint.mode==='locked') joint.setQuaternion(...relative.toArray());\r\n else if(constraint.mode==='hinge') {\r\n let axis=new Vector3();\r\n if(constraint.axis!=='auto') axis.setComponent(['x','y','z'].indexOf(constraint.axis),1);\r\n else {\r\n const child=pins.find(p=>parents.get(p.id)===pin.id && active.has(key(p)));\r\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)));\r\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));}\r\n axis.normalize();\r\n }\r\n const basis=new Quaternion().setFromUnitVectors(new Vector3(0,0,1),axis);\r\n joint.setQuaternion(...basis.toArray());link.setQuaternion(...basis.clone().invert().toArray());\r\n joint.setDoF(5);joint.setMinLimits(constraint.min*Math.PI/180);joint.setMaxLimits(constraint.max*Math.PI/180);\r\n const twist=2*Math.atan2(new Vector3(relative.x,relative.y,relative.z).dot(axis),relative.w);\r\n joint.setDoFValues(Math.atan2(Math.sin(twist),Math.cos(twist)));joint.setRestPoseValues(0);\r\n } else {\r\n if(constraint.mode==='cone')coneJoints.set(id,joint);\r\n else freeJoints.set(id,joint);\r\n joint.setDoF(3,4,5);\r\n const euler=new Euler().setFromQuaternion(relative,'ZYX');joint.setDoFValues(euler.x,euler.y,euler.z);joint.setRestPoseValues(euler.x,euler.y,euler.z);\r\n const seed=bendSeeds.get(id);\r\n if(seed && !roots.has(id) && !goals.some(g=>key(byId.get(g.id)!)===id)){\r\n const axis=seed.clone().applyQuaternion(parentRotation.clone().invert());\r\n const seeded=new Euler().setFromQuaternion(new Quaternion().setFromAxisAngle(axis,.03).multiply(relative),'ZYX');\r\n joint.setDoFValues(seeded.x,seeded.y,seeded.z);\r\n }\r\n }\r\n joint.addChild(link);frames.set(id,link);building.delete(id);if(!parentId) forest.push(parentFrame);return link;\r\n };\r\n for(const id of groups.keys()) build(id);\r\n // Limits describe the visible segment in the committed parent's frame, not\r\n // a shared attachment's temporary solver rotation or a stale inserted frame.\r\n const limitRotation=(id:string,rotation:Quaternion,parentRotation:Quaternion)=>{\r\n const pin=groups.get(id)![0];if(pin.ikConstraint?.mode!=='cone')return rotation;\r\n const parentId=parentGroup.get(id),parent=parentId?groups.get(parentId)![0]:undefined;\r\n const child=pins.find(p=>parents.get(p.id)===pin.id);\r\n if(retained.has(id)&&child&&!active.has(key(child)))return rotation;\r\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);\r\n if(axis.lengthSq()<1e-12)axis.set(0,1,0);\r\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;\r\n if(movingAxis.lengthSq()<1e-12)movingAxis.copy(axis);\r\n const reference=parentId&&retained.has(parentId)?new Quaternion().fromArray(parent!.pose.rotation):parentRotation;\r\n const relative=reference.clone().invert().multiply(parentRotation).multiply(rotation);\r\n return parentRotation.clone().invert().multiply(reference).multiply(constrainCone(relative,axis,pin.ikConstraint,movingAxis));\r\n };\r\n // Continuity refers to the pose on screen, before analytic initialization\r\n // or cone projection chooses a candidate. Include temporary body pivots.\r\n const priorRotations=new Map([...frames.values(),...[...branchJoints.values()].map(branch=>branch.frame)].map(frame=>{\r\n frame.updateMatrixWorld();return [frame,new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(frame.matrixWorld))] as const;\r\n }));\r\n const closures:Goal[]=[];\r\n for(const target of goals){\r\n const pin=byId.get(target.id)!,anchor=groups.get(key(pin))![0];\r\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);\r\n const attachment=new Joint();attachment.setPosition(...offset.toArray());frames.get(key(pin))!.addChild(attachment);\r\n const tip=new Link();attachment.addChild(tip);\r\n const goal=new Goal();\r\n const freeEndpoint=groups.get(key(pin))!.length===1 && (!pin.ikConstraint || pin.ikConstraint.mode==='free');\r\n if(freeEndpoint) goal.setGoalDoF(0,1,2);else goal.setGoalDoF(0,1,2,3,4,5);\r\n goal.makeClosure(tip);\r\n const requested=new Vector3().fromArray(target.position);\r\n if(goals.length===1 && freeEndpoint){\r\n const chain=ikChain(pins,parents,target.id,mass);\r\n const first=chain.findIndex(p=>!groups.get(key(p))!.some(q=>fixed.has(q.id)) && (p.ikConstraint??DEFAULT_IK_CONSTRAINT).mode!=='locked');\r\n const moving=first<0?[]:chain.slice(branchJoints.has(key(chain[first]))?Math.max(0,first-1):first);\r\n // For an unconstrained ball-joint chain its link lengths define a\r\n // reachable spherical shell. Solve against that shell, not an impossible\r\n // residual which can stall the iterative solver away from the closest\r\n // pose. The authored world target is deliberately left unchanged.\r\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'))){\r\n const pivot=new Vector3().fromArray(moving[0].pose.position);\r\n const lengths=moving.slice(1).map((p,i)=>new Vector3().fromArray(p.pose.position).distanceTo(new Vector3().fromArray(moving[i].pose.position)));\r\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();\r\n if(distance<inner || distance>outer){\r\n if(distance<1e-12)delta.fromArray(moving.at(-1)!.pose.position).sub(pivot);\r\n if(delta.lengthSq()>1e-24)requested.copy(pivot).add(delta.setLength(Math.max(inner,Math.min(outer,distance))));\r\n }\r\n if(moving.length===2){\r\n // One free link has a closed-form minimum-rotation solution. Its\r\n // positional Jacobian is rank deficient (twist is unobservable), so\r\n // initialize it analytically instead of relying on an arbitrary seed.\r\n const before=new Vector3().fromArray(moving[1].pose.position).sub(pivot),after=requested.clone().sub(pivot);\r\n if(before.lengthSq()>1e-24 && after.lengthSq()>1e-24){\r\n const branch=branchJoints.get(key(moving[1])),parent=branch?moving[0]:byId.get(parents.get(moving[0].id)??'');\r\n const local=parent?new Quaternion().fromArray(parent.pose.rotation).invert():new Quaternion();\r\n local.multiply(new Quaternion().setFromUnitVectors(before.normalize(),after.normalize())).multiply(new Quaternion().fromArray(moving[0].pose.rotation));\r\n const euler=new Euler().setFromQuaternion(local,'ZYX');(branch?.joint??freeJoints.get(key(moving[0])))!.setDoFValues(euler.x,euler.y,euler.z);\r\n }\r\n }\r\n }\r\n }\r\n goal.setPosition(...requested.sub(origin).divideScalar(size).toArray());goal.setQuaternion(...target.rotation);\r\n closures.push(goal);\r\n }\r\n // Two-link limbs have an exact positional solution. Keep their existing bend\r\n // plane and transport each frame by the minimum swing: an Euler/SVD solve can\r\n // choose a different elbow branch or arbitrary axial twist near singularity.\r\n // Cone projection + constrained refinement below still enforce authored limits.\r\n let analytic=false;\r\n if(goals.length===1){\r\n const goal=goals[0],chain=ikChain(pins,parents,goal.id,mass);\r\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]))));\r\n const limb=first<0?[]:chain.slice(first),tipPin=byId.get(goal.id)!;\r\n if(limb.length===3&&limb.every(p=>groups.get(key(p))!.length===1)\r\n &&limb.slice(0,2).every((p,i)=>coneJoints.has(key(p))||freeJoints.has(key(p))||branchJoints.has(key(limb[i+1])))\r\n &&(!tipPin.ikConstraint||tipPin.ikConstraint.mode==='free')){\r\n const world=(p:PinRecord)=>{const frame=frames.get(key(p))!;frame.updateMatrixWorld();return new Matrix4().fromArray(frame.matrixWorld);};\r\n const matrices=limb.map(world),points=matrices.map(m=>new Vector3().setFromMatrixPosition(m));\r\n const [base,knee,tip]=points,a=base.distanceTo(knee),b=knee.distanceTo(tip);\r\n const direction=new Vector3().fromArray(closures[0].position).sub(base);\r\n if(a>1e-10&&b>1e-10&&direction.lengthSq()>1e-20){\r\n const distance=Math.max(Math.abs(a-b)+1e-9,Math.min(a+b-1e-9,direction.length()));direction.normalize();\r\n const oldAxis=tip.clone().sub(base).normalize();\r\n const bend=knee.clone().sub(base).addScaledVector(oldAxis,-knee.clone().sub(base).dot(oldAxis));\r\n // Transport the previous pole with the target, instead of projecting it\r\n // against the new axis (which can flip the knee on a large target move).\r\n bend.applyQuaternion(new Quaternion().setFromUnitVectors(oldAxis,direction));\r\n if(bend.lengthSq()<1e-16){\r\n bend.fromArray(limb[1].rest).sub(new Vector3().fromArray(limb[0].rest));\r\n const restAxis=new Vector3().fromArray(limb[2].rest).sub(new Vector3().fromArray(limb[0].rest)).normalize();\r\n bend.addScaledVector(restAxis,-bend.dot(restAxis)).applyQuaternion(new Quaternion().setFromRotationMatrix(matrices[0]));\r\n bend.addScaledVector(direction,-bend.dot(direction));\r\n }\r\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));}\r\n const along=(a*a-b*b+distance*distance)/(2*distance);\r\n const desiredKnee=base.clone().addScaledVector(direction,along).addScaledVector(bend.normalize(),Math.sqrt(Math.max(0,a*a-along*along)));\r\n const desiredTip=base.clone().addScaledVector(direction,distance);\r\n for(const [i,end] of [desiredKnee,desiredTip].entries()){\r\n const pin=limb[i],branch=branchJoints.get(key(limb[i+1])),frame=branch?.frame??frames.get(key(pin))!;\r\n frame.updateMatrixWorld();\r\n const matrix=new Matrix4().fromArray(frame.matrixWorld),pivot=new Vector3().setFromMatrixPosition(matrix);\r\n const before=new Vector3().setFromMatrixPosition(world(limb[i+1])).sub(pivot),after=end.clone().sub(pivot);\r\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();\r\n const parentRotation=parentFrame?new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(parentFrame.matrixWorld)):new Quaternion();\r\n const rotation=parentRotation.invert().multiply(new Quaternion().setFromUnitVectors(before.normalize(),after.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\r\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);\r\n }\r\n analytic=true;\r\n }\r\n }\r\n }\r\n const positionOnlyGoal=goals.length===1&&groups.get(key(byId.get(goals[0].id)!))!.length===1\r\n &&(!byId.get(goals[0].id)!.ikConstraint||byId.get(goals[0].id)!.ikConstraint!.mode==='free');\r\n const positionOnlyGoals=goals.every(goal=>groups.get(key(byId.get(goal.id)!))!.length===1\r\n &&(!byId.get(goal.id)!.ikConstraint||byId.get(goal.id)!.ikConstraint!.mode==='free'));\r\n // A lone planted foot has a prior bend in the current frame. Starting a\r\n // global SVD solve there can choose another elbow branch on a tiny edit;\r\n // the constrained descent below instead continues that bend.\r\n if(!analytic&&!positionOnlyGoal&&!positionOnlyGoals){\r\n const solver=new Solver([...forest,...closures]);solver.useSVD=true;solver.maxIterations=48;solver.restPoseFactor=.001;\r\n solver.translationConvergeThreshold=1e-6;solver.rotationConvergeThreshold=1e-6;solver.translationErrorClamp=.2;\r\n solver.solve();\r\n }\r\n // Project oriented elliptical swing limits in parent-to-child order. Updating the joint\r\n // frame carries descendants rigidly, so limiting a cone never stretches links.\r\n const projectCones=()=>{for(const [id,joint] of coneJoints){\r\n const parentId=parentGroup.get(id), frame=frames.get(id)!;\r\n frame.updateMatrixWorld();\r\n const parentFrame=branchJoints.get(id)?.frame??(parentId?frames.get(parentId):undefined);\r\n const parentRotation=parentFrame?new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(parentFrame.matrixWorld)):new Quaternion();\r\n const relative=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(frame.matrixWorld)));\r\n const limited=limitRotation(id,relative,parentRotation),euler=new Euler().setFromQuaternion(limited,'ZYX');\r\n joint.setDoFValues(euler.x,euler.y,euler.z);frame.updateMatrixWorld();\r\n }\r\n };\r\n if(goals.length===1||!positionOnlyGoals)projectCones();\r\n if(goals.length>1&&positionOnlyGoals){\r\n const world=(frame:Link)=>{frame.updateMatrixWorld();return new Matrix4().fromArray(frame.matrixWorld);};\r\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()}));\r\n const poles=tips.flatMap(tip=>{\r\n const chain=poleChains.get(tip.goal.id);\r\n if(!chain||chain.length<3)return [];\r\n const base=chain[0],knee=chain[Math.floor((chain.length-1)/2)],end=chain.at(-1)!;\r\n const restAxis=new Vector3().fromArray(end.rest).sub(new Vector3().fromArray(base.rest));\r\n const restBend=new Vector3().fromArray(knee.rest).sub(new Vector3().fromArray(base.rest));\r\n if(restAxis.lengthSq()<1e-16)return [];\r\n restBend.addScaledVector(restAxis,-restBend.dot(restAxis)/restAxis.lengthSq());\r\n if(restBend.length()<restAxis.length()*.02)return [];\r\n const minBend=Math.min(.03,restBend.length()/size*.5);\r\n return [{base,knee,chain,tip,minBend,restAxis:restAxis.normalize(),restPole:restBend.normalize()}];\r\n });\r\n const poleState=(pole:typeof poles[number])=>{\r\n const base=new Vector3().setFromMatrixPosition(world(frames.get(key(pole.base))!));\r\n const knee=new Vector3().setFromMatrixPosition(world(frames.get(key(pole.knee))!));\r\n const axis=pole.tip.desired.clone().sub(base).normalize();\r\n const preferred=pole.restPole.clone().applyQuaternion(new Quaternion().setFromUnitVectors(pole.restAxis,axis));\r\n preferred.addScaledVector(axis,-preferred.dot(axis)).normalize();\r\n const bend=knee.sub(base);bend.addScaledVector(axis,-bend.dot(axis));\r\n return {base,axis,preferred,bend};\r\n };\r\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))))]\r\n .map(frame=>({frame,rotation:new Quaternion().setFromRotationMatrix(world(frame))}));\r\n const cost=()=>tips.reduce((sum,tip)=>sum+new Vector3().setFromMatrixPosition(world(tip.frame)).distanceToSquared(tip.desired),0)\r\n +POSE_CONTINUITY_WEIGHT*initial.reduce((sum,{frame,rotation})=>sum+new Quaternion().setFromRotationMatrix(world(frame)).angleTo(rotation)**2,0)\r\n +10*poles.reduce((sum,pole)=>{const {preferred,bend}=poleState(pole);\r\n return sum+Math.max(0,pole.minBend-bend.dot(preferred))**2;},0);\r\n for(let sweep=0;sweep<96;sweep++){\r\n if(cost()<1e-12)break;\r\n let largestChange=0;\r\n for(const tip of tips)for(const pin of tip.chain){\r\n const id=key(pin),joints=[coneJoints.get(id)??freeJoints.get(id),branchJoints.get(id)?.joint];\r\n for(const [index,joint] of joints.entries()){\r\n if(!joint)continue;\r\n const branch=index===1,frame=branch?branchJoints.get(id)!.frame:frames.get(id)!;\r\n const matrix=world(frame),pivot=new Vector3().setFromMatrixPosition(matrix),end=new Vector3().setFromMatrixPosition(world(tip.frame));\r\n const a=end.sub(pivot),b=tip.desired.clone().sub(pivot);\r\n if(a.lengthSq()<1e-20||b.lengthSq()<1e-20)continue;\r\n const parentId=parentGroup.get(id),localParent=branch?(parentId?frames.get(parentId):undefined):branchJoints.get(id)?.frame??(parentId?frames.get(parentId):undefined);\r\n const parentRotation=localParent?new Quaternion().setFromRotationMatrix(world(localParent)):new Quaternion();\r\n const old=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(matrix));\r\n let rotation=parentRotation.clone().invert().multiply(new Quaternion().setFromUnitVectors(a.normalize(),b.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\r\n if(!branch)rotation=limitRotation(id,rotation,parentRotation);\r\n const before=cost(),set=(q:Quaternion)=>{const e=new Euler().setFromQuaternion(q,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frame.updateMatrixWorld();};\r\n for(let fraction=1;fraction>=1/32;fraction/=2){\r\n const attempt=old.clone().slerp(rotation,fraction);set(attempt);\r\n if(cost()<before-1e-14){largestChange=Math.max(largestChange,old.angleTo(attempt));break;}\r\n set(old);\r\n }\r\n }\r\n }\r\n for(const pole of poles){\r\n const {base,preferred,bend}=poleState(pole),along=bend.dot(preferred);\r\n if(along>=pole.minBend)continue;\r\n const baseId=key(pole.base),nextId=key(pole.chain[1]);\r\n const branch=branchJoints.get(nextId),joint=branch?.joint??coneJoints.get(baseId)??freeJoints.get(baseId);\r\n const frame=branch?.frame??frames.get(baseId);\r\n if(!joint||!frame)continue;\r\n const knee=new Vector3().setFromMatrixPosition(world(frames.get(key(pole.knee))!));\r\n const arm=knee.sub(base),aim=arm.clone().addScaledVector(preferred,Math.min(.01,pole.minBend-along));\r\n if(arm.lengthSq()<1e-20||aim.lengthSq()<1e-20)continue;\r\n const parentId=branch?baseId:parentGroup.get(baseId),parentFrame=parentId?frames.get(parentId):undefined;\r\n const parentRotation=parentFrame?new Quaternion().setFromRotationMatrix(world(parentFrame)):new Quaternion();\r\n const matrix=world(frame),old=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(matrix));\r\n let proposal=parentRotation.clone().invert().multiply(new Quaternion().setFromUnitVectors(arm.normalize(),aim.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\r\n if(!branch)proposal=limitRotation(baseId,proposal,parentRotation);\r\n const before=cost(),set=(q:Quaternion)=>{const e=new Euler().setFromQuaternion(q,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frame.updateMatrixWorld();};\r\n for(let fraction=1;fraction>=1/32;fraction/=2){\r\n const attempt=old.clone().slerp(proposal,fraction);set(attempt);\r\n if(cost()<before-1e-14){largestChange=Math.max(largestChange,old.angleTo(attempt));break;}\r\n set(old);\r\n }\r\n }\r\n if(largestChange<1e-5)break;\r\n }\r\n }\r\n // Projecting cones only AFTER the unconstrained solve leaves the endpoint\r\n // stranded, even when another joint could reach it. Finish positional chains\r\n // with constrained coordinate descent: every accepted step obeys its cone\r\n // and reduces the residual. Siblings/fixed roots never enter this joint list.\r\n if(goals.length===1){\r\n const target=goals[0],tipPin=byId.get(target.id)!;\r\n if(groups.get(key(tipPin))!.length===1&&(!tipPin.ikConstraint||tipPin.ikConstraint.mode==='free')){\r\n const tip=frames.get(key(tipPin))!,desired=new Vector3().fromArray(closures[0].position);\r\n const ordered=ikChain(pins,parents,target.id,mass),chain=ordered.slice(0,-1).reverse();\r\n const world=(frame:Link)=>{frame.updateMatrixWorld();return new Matrix4().fromArray(frame.matrixWorld);};\r\n const ground=tipPin.chainRole?.kind==='leg'&&Number.isFinite(floor)?(floor-origin.y)/size:-Infinity;\r\n const point=(pin:PinRecord)=>new Vector3().setFromMatrixPosition(world(frames.get(key(pin))!));\r\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)!}));\r\n // Endpoint distance has mirrored solutions. Carry each visible bend's\r\n // pole into the new chord frame instead of letting descent change sides.\r\n const poles=ordered.slice(1,-1).flatMap((knee,i)=>{\r\n const base=ordered[i],end=ordered[i+2];\r\n const chord=new Vector3().fromArray(end.pose.position).sub(new Vector3().fromArray(base.pose.position)),span=chord.length(),axis=chord.normalize();\r\n const bend=new Vector3().fromArray(knee.pose.position).sub(new Vector3().fromArray(base.pose.position));\r\n bend.addScaledVector(axis,-bend.dot(axis));\r\n // Near extension the positional pole is numerical noise; the rest\r\n // bend carried by the current base frame still defines its side.\r\n if(bend.length()<span*.02){\r\n const restAxis=new Vector3().fromArray(end.rest).sub(new Vector3().fromArray(base.rest)).normalize();\r\n bend.fromArray(knee.rest).sub(new Vector3().fromArray(base.rest));\r\n bend.addScaledVector(restAxis,-bend.dot(restAxis));\r\n const rotation=new Quaternion().fromArray(base.pose.rotation);\r\n bend.applyQuaternion(rotation);\r\n restAxis.applyQuaternion(rotation);\r\n bend.applyQuaternion(new Quaternion().setFromUnitVectors(restAxis,axis));\r\n }\r\n return bend.length()<span*.02?[]:[{base,knee,end,axis,pole:bend.normalize()}];\r\n });\r\n const poleCost=()=>poles.reduce((sum,pole)=>{\r\n const base=point(pole.base),axis=point(pole.end).sub(base).normalize();\r\n const preferred=pole.pole.clone().applyQuaternion(new Quaternion().setFromUnitVectors(pole.axis,axis));\r\n const bend=point(pole.knee).sub(base);bend.addScaledVector(axis,-bend.dot(axis));\r\n return sum+Math.max(0,-bend.dot(preferred))**2;\r\n },0);\r\n // Position alone does not determine every joint frame. Keep the nearest\r\n // solution to the pose on screen when a controller moves a tiny amount.\r\n const cost=()=>{\r\n const error=new Vector3().setFromMatrixPosition(world(tip)).distanceToSquared(desired);\r\n let penetration=0;\r\n if(Number.isFinite(ground))for(const pin of ordered.slice(1,-1))penetration+=Math.max(0,ground-point(pin).y)**2;\r\n const drift=initial.reduce((sum,{frame,rotation})=>sum+new Quaternion().setFromRotationMatrix(world(frame)).angleTo(rotation)**2,0);\r\n return error+16*penetration+100*poleCost()+POSE_CONTINUITY_WEIGHT*drift;\r\n };\r\n // Near a tight cone the last few sweeps are small but visible. Stop only\r\n // once the pose itself has settled, not merely when the goal is close.\r\n for(let sweep=0;sweep<128;sweep++){\r\n if(cost()<1e-12)break;\r\n let largestChange=0;\r\n for(const pin of chain){\r\n const id=key(pin);\r\n const joints=[coneJoints.get(id)??freeJoints.get(id),branchJoints.get(id)?.joint];\r\n for(const [jointIndex,joint] of joints.entries()){\r\n if(!joint)continue;\r\n const branch=jointIndex===1,frame=branch?branchJoints.get(id)!.frame:frames.get(id)!;\r\n const matrix=world(frame),pivot=new Vector3().setFromMatrixPosition(matrix);\r\n const end=new Vector3().setFromMatrixPosition(world(tip)),before=cost();\r\n const a=end.clone().sub(pivot),b=desired.clone().sub(pivot);if(a.lengthSq()<1e-20||b.lengthSq()<1e-20)continue;\r\n const parentId=parentGroup.get(id),localParent=branch?parentId?frames.get(parentId):undefined:branchJoints.get(id)?.frame??(parentId?frames.get(parentId):undefined);\r\n const parentRotation=localParent?new Quaternion().setFromRotationMatrix(world(localParent)):new Quaternion();\r\n const old=parentRotation.clone().invert().multiply(new Quaternion().setFromRotationMatrix(matrix));\r\n let rotation=parentRotation.clone().invert().multiply(new Quaternion().setFromUnitVectors(a.normalize(),b.normalize())).multiply(new Quaternion().setFromRotationMatrix(matrix));\r\n if(!branch)rotation=limitRotation(id,rotation,parentRotation);\r\n const set=(q:Quaternion)=>{const e=new Euler().setFromQuaternion(q,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frame.updateMatrixWorld();};\r\n let accepted=false;\r\n for(let fraction=1;fraction>=1/32;fraction/=2){\r\n let attempt=old.clone().slerp(rotation,fraction);\r\n if(!branch)attempt=limitRotation(id,attempt,parentRotation);\r\n set(attempt);\r\n if(cost()<=before+1e-14){largestChange=Math.max(largestChange,old.angleTo(attempt));accepted=true;break;}\r\n }\r\n if(!accepted)set(old);\r\n if(Number.isFinite(ground))for(const descendant of ordered.slice(ordered.indexOf(pin)+1,-1)){\r\n const lower=point(descendant);if(lower.y>=ground)continue;\r\n const current=point(pin),arm=lower.clone().sub(current),raised=lower.clone();raised.y=ground;\r\n const aim=raised.sub(current);if(arm.lengthSq()<1e-20||aim.lengthSq()<1e-20)continue;\r\n const parentNow=localParent?new Quaternion().setFromRotationMatrix(world(localParent)):new Quaternion();\r\n const previous=parentNow.clone().invert().multiply(new Quaternion().setFromRotationMatrix(world(frame)));\r\n let proposal=parentNow.clone().invert().multiply(new Quaternion().setFromUnitVectors(arm.normalize(),aim.normalize())).multiply(new Quaternion().setFromRotationMatrix(world(frame)));\r\n if(!branch)proposal=limitRotation(id,proposal,parentNow);\r\n const start=cost();\r\n for(let fraction=1;fraction>=1/16;fraction/=2){\r\n const attempt=previous.clone().slerp(proposal,fraction);set(attempt);\r\n if(cost()<start-1e-14){largestChange=Math.max(largestChange,previous.angleTo(attempt));break;}\r\n set(previous);\r\n }\r\n }\r\n }\r\n }\r\n if(largestChange<1e-5)break;\r\n }\r\n }\r\n }\r\n // Ancestor refinement must not leave a cone outside its committed frame.\r\n if(goals.length===1||!positionOnlyGoals)projectCones();\r\n // A free goal's orientation is independent of its position, including when\r\n // extra toe/follower joints are added below it. Carry those followers through\r\n // the frame, rather than only overwriting the endpoint's returned quaternion.\r\n for(const goal of goals){\r\n const id=key(byId.get(goal.id)!),joint=freeJoints.get(id);if(!joint||groups.get(id)!.length!==1)continue;\r\n const parentId=parentGroup.get(id),parent=parentId?frames.get(parentId):undefined;parent?.updateMatrixWorld();\r\n const rotation=parent?new Quaternion().setFromRotationMatrix(new Matrix4().fromArray(parent.matrixWorld)).invert():new Quaternion();\r\n rotation.multiply(new Quaternion().fromArray(goal.rotation));\r\n const e=new Euler().setFromQuaternion(rotation,'ZYX');joint.setDoFValues(e.x,e.y,e.z);frames.get(id)!.updateMatrixWorld();\r\n }\r\n const result=pins.filter(p=>affected.has(key(p))).map(pin=>{\r\n if(fixed.has(pin.id)) return {id:pin.id,pose:pin.pose};\r\n const anchor=groups.get(key(pin))![0],frame=frames.get(key(pin))!;frame.updateMatrixWorld();\r\n const matrix=new Matrix4().fromArray(frame.matrixWorld),rotation=new Quaternion().setFromRotationMatrix(matrix).normalize();\r\n const position=new Vector3().setFromMatrixPosition(matrix).multiplyScalar(size).add(origin);\r\n const delta=rotation.clone().multiply(new Quaternion().fromArray(anchor.pose.rotation).invert());\r\n const goal=goals.find(g=>key(byId.get(g.id)!)===key(pin));\r\n const terminal=![...parentGroup.values()].includes(key(pin));\r\n if(goal&&terminal&&(!pin.ikConstraint || pin.ikConstraint.mode==='free')) rotation.fromArray(goal.rotation);\r\n const offset=new Vector3().fromArray(pin.pose.position).sub(new Vector3().fromArray(anchor.pose.position));\r\n if(goal&&terminal&&(!pin.ikConstraint || pin.ikConstraint.mode==='free')) delta.copy(rotation).multiply(new Quaternion().fromArray(anchor.pose.rotation).invert());\r\n position.add(offset.applyQuaternion(delta));\r\n if(!parentGroup.has(key(pin)) && pin.id===anchor.id) position.fromArray(pin.pose.position);\r\n if(![...position.toArray(),...rotation.toArray()].every(Number.isFinite)) throw new Error('IK produced an invalid pose.');\r\n return {id:pin.id,pose:{position:position.toArray(),rotation:rotation.toArray(),scale:pin.pose.scale}};\r\n });\r\n return result;\r\n}\r\n", "import { Vector3 } from 'three';\r\n\r\nexport const MAX_WIND_STRENGTH = 4;\r\n\r\n/** A single weather control drives pin motion and surface pressure. Sparse pin\r\n * loads stay bounded; fabric pressure has room to grow through a storm. */\r\nexport function windProfile(strength: number) {\r\n const level = Math.max(0, Math.min(MAX_WIND_STRENGTH, strength));\r\n const label = level === 0 ? 'Off' : level < .75 ? 'Breeze' : level < 1.5 ? 'Windy' : level < 2.5 ? 'Strong wind' : level < 3.3 ? 'Gale' : 'Storm';\r\n return {\r\n label,\r\n load: 30 * level * level / (.8 + level * level),\r\n surfaceLoad: 4 * level * level,\r\n gust: .14 + .12 * level,\r\n crosswind: .05 + .07 * level,\r\n gustRate: .42 + .12 * level,\r\n };\r\n}\r\n\r\n/** Deterministic scene-local prevailing wind with slow gusts and spatially\r\n * varying eddies. Force is an acceleration scaled to the model's size, so a\r\n * tiny prop and a large character respond comparably at the same setting. */\r\nexport function windAcceleration(seconds: number, strength: number, scale: number, position: readonly number[]) {\r\n if (strength <= 0) return new Vector3();\r\n const size = Math.max(1e-4, scale);\r\n const profile = windProfile(strength);\r\n // Advect the gust bands along +X. Nearby controls see related wind, while\r\n // their phase delay keeps a large sheet or branch hierarchy from moving as\r\n // one perfectly synchronized rigid object.\r\n const along = position[0] / size, lateral = (position[1] * .67 + position[2] * .33) / size;\r\n const slow = seconds * profile.gustRate - along * .55;\r\n const fast = seconds * (profile.gustRate * 2.7) - along * 1.4 + lateral * .4;\r\n const gust = Math.max(.2, 1 + profile.gust * (.7 * Math.sin(slow) + .3 * Math.sin(fast + 1.3)));\r\n const cross = profile.crosswind * (.65 * Math.sin(fast + lateral) + .35 * Math.sin(slow * .73 - lateral * .6));\r\n return new Vector3(1, cross * .35, cross).normalize().multiplyScalar(profile.load * size * gust);\r\n}\r\n"],
|
|
5
|
+
"mappings": ";;;AAAA,SAAS,cAAAA,aAAY,WAAAC,gBAAe;;;ACU7B,IAAM,oBAAoB;;;ACT1B,IAAM,iBAA2C,EAAE,OAAO,KAAI,WAAW,MAAM,IAAE,KAAK,KAAK,SAAS,MAAK,eAAc,GAAE,UAAS,EAAE;;;ACD3I,SAAS,MAAM,OAAO,MAAM,cAAc;AAC1C,SAAS,OAAO,SAAS,YAAY,eAAe;AAUpD,SAAS,iBAAiB,MAA4B,SAAqB;AACzE,QAAM,QAAQ,oBAAI,IAAY;AAC9B,aAAW,OAAO,KAAM,KAAI,CAAC,IAAI,OAAO;AACtC,QAAI,KAAyB,IAAI;AACjC,WAAO,MAAM,CAAC,MAAM,IAAI,EAAE,GAAG;AAAE,YAAM,IAAI,EAAE;AAAG,WAAK,QAAQ,IAAI,EAAE;AAA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AI;AAAA,QACtD,UAAS,OAAO,SAAS,IAAI,MAAM,EAAE,gBAAgB,QAAQ,EAAE,IAAI,QAAQ,EAAE,QAAQ;AAAA,QACrF,UAAS,SAAS,MAAM,EAAE,SAAS,OAAO,QAAQ,EAAE,UAAU,EAAE,QAAQ;AAAA,QAAE,OAAM,OAAO,IAAI,KAAK;AAAA,MAClG,CAAC;AACD,eAAS,OAAO,EAAE;AAAA,IACpB;AACA,eAAW,MAAM,OAAO,KAAK,EAAG,OAAM,EAAE;AACxC,SAAK,WAAW;AAAM,SAAK,cAAc;AAAS,SAAK,QAAQ;AAC/D,WAAO,EAAE,MAAM,SAAS,KAAK,IAAI,UAAQ,EAAC,GAAG,KAAI,MAAK,OAAO,IAAI,IAAI,EAAE,EAAE,EAAE,IAAI,MAAM,OAAO;AAAA,EAC9F;AACF;",
|
|
6
|
+
"names": ["Quaternion", "Vector3", "pin", "Vector3", "Quaternion", "position", "Vector3"]
|
|
7
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// @ts-nocheck
|
|
2
|
+
|
|
3
|
+
// src/deformation/pose-slots.ts
|
|
4
|
+
var POSE_SLOTS = 9;
|
|
5
|
+
var AUTHORED_EPSILON = 1e-6;
|
|
6
|
+
function capturePose(pins) {
|
|
7
|
+
return pins.map((pin) => ({ id: pin.id, pose: pin.pose, ...pin.authored ? { authored: true } : {}, ...pin.ikTarget ? { ikTarget: pin.ikTarget } : {} }));
|
|
8
|
+
}
|
|
9
|
+
var restPoseOf = (rest) => ({ position: [rest[0], rest[1], rest[2]], rotation: [0, 0, 0, 1], scale: [1, 1, 1] });
|
|
10
|
+
function carriedPose(rest, parentRest, parent) {
|
|
11
|
+
const [qx, qy, qz, qw] = parent.rotation;
|
|
12
|
+
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];
|
|
13
|
+
const tx = 2 * (qy * z - qz * y), ty = 2 * (qz * x - qx * z), tz = 2 * (qx * y - qy * x);
|
|
14
|
+
const position = [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)];
|
|
15
|
+
const rotation = [qx, qy, qz, qw], scale = [parent.scale[0], parent.scale[1], parent.scale[2]];
|
|
16
|
+
return { position, rotation, scale };
|
|
17
|
+
}
|
|
18
|
+
var samePose = (a, b) => a.position.every((v, i) => Math.abs(v - b.position[i]) <= AUTHORED_EPSILON) && a.scale.every((v, i) => Math.abs(v - b.scale[i]) <= AUTHORED_EPSILON) && a.rotation.every((v, i) => Math.abs(v - b.rotation[i]) <= AUTHORED_EPSILON);
|
|
19
|
+
function inheritedPose(pin, parent, parentPose) {
|
|
20
|
+
return parent && parentPose ? carriedPose(pin.rest, parent.rest, parentPose) : restPoseOf(pin.rest);
|
|
21
|
+
}
|
|
22
|
+
function authoredPoses(pins, parents = /* @__PURE__ */ new Map()) {
|
|
23
|
+
const byId = new Map(pins.map((pin) => [pin.id, pin]));
|
|
24
|
+
return capturePose(pins).filter((stored) => {
|
|
25
|
+
const pin = byId.get(stored.id);
|
|
26
|
+
if (pin.authored || pin.ikTarget) return true;
|
|
27
|
+
const parent = byId.get(parents.get(pin.id) ?? "");
|
|
28
|
+
return !samePose(pin.pose, inheritedPose(pin, parent, parent?.pose));
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
function resolvePose(pins, slot, parents = /* @__PURE__ */ new Map()) {
|
|
32
|
+
const saved = new Map(slot.poses.map((p) => [p.id, p]));
|
|
33
|
+
const byId = new Map(pins.map((pin) => [pin.id, pin]));
|
|
34
|
+
const memo = /* @__PURE__ */ new Map(), visiting = /* @__PURE__ */ new Set();
|
|
35
|
+
const poseOf = (pin) => {
|
|
36
|
+
const cached = memo.get(pin.id);
|
|
37
|
+
if (cached) return cached;
|
|
38
|
+
const stored = saved.get(pin.id);
|
|
39
|
+
let pose;
|
|
40
|
+
if (stored) pose = stored.pose;
|
|
41
|
+
else {
|
|
42
|
+
const parentId = parents.get(pin.id);
|
|
43
|
+
const parent = parentId && !visiting.has(parentId) ? byId.get(parentId) : void 0;
|
|
44
|
+
if (!parent) pose = restPoseOf(pin.rest);
|
|
45
|
+
else {
|
|
46
|
+
visiting.add(pin.id);
|
|
47
|
+
pose = carriedPose(pin.rest, parent.rest, poseOf(parent));
|
|
48
|
+
visiting.delete(pin.id);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
memo.set(pin.id, pose);
|
|
52
|
+
return pose;
|
|
53
|
+
};
|
|
54
|
+
const resolved = pins.map((pin) => {
|
|
55
|
+
const stored = saved.get(pin.id), { ikTarget: _target, authored: _authored, ...base } = pin;
|
|
56
|
+
return { ...base, pose: poseOf(pin), ...stored?.authored ? { authored: true } : {}, ...stored?.ikTarget ? { ikTarget: stored.ikTarget } : {} };
|
|
57
|
+
});
|
|
58
|
+
return resolved.map((pin) => {
|
|
59
|
+
if (!pin.rigidGroup) return pin;
|
|
60
|
+
const anchor = resolved.find((p) => p.rigidGroup === pin.rigidGroup);
|
|
61
|
+
return { ...pin, pose: { ...pin.pose, rotation: anchor.pose.rotation, scale: [anchor.pose.scale[0], anchor.pose.scale[0], anchor.pose.scale[0]] } };
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
function definedPoses(model) {
|
|
65
|
+
const slots = model.poseSlots.filter((p) => p.slot !== model.activePose);
|
|
66
|
+
return [...slots, ...model.activePose === 0 ? [] : [{ slot: model.activePose, poses: capturePose(model.pins) }]].sort((a, b) => a.slot - b.slot);
|
|
67
|
+
}
|
|
68
|
+
function restPoseSlot(pins) {
|
|
69
|
+
return { slot: 0, poses: pins.map((pin) => ({ id: pin.id, pose: restPoseOf(pin.rest) })) };
|
|
70
|
+
}
|
|
71
|
+
function playablePoses(model) {
|
|
72
|
+
return [restPoseSlot(model.pins), ...definedPoses(model)];
|
|
73
|
+
}
|
|
74
|
+
export {
|
|
75
|
+
POSE_SLOTS,
|
|
76
|
+
authoredPoses,
|
|
77
|
+
capturePose,
|
|
78
|
+
carriedPose,
|
|
79
|
+
definedPoses,
|
|
80
|
+
playablePoses,
|
|
81
|
+
resolvePose,
|
|
82
|
+
restPoseSlot
|
|
83
|
+
};
|
|
84
|
+
//# sourceMappingURL=pose-slots.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/deformation/pose-slots.ts"],
|
|
4
|
+
"sourcesContent": ["import type { IKTarget, PinPose, PinRecord, Point, Rotation } from './pin-types.js';\r\nimport type { PinParents } from './pin-types.js';\r\n\r\nexport type StoredPose = { readonly id:string; readonly pose:PinPose; readonly ikTarget?:IKTarget; readonly authored?:boolean };\r\nexport type PoseSlot = { readonly slot:number; readonly poses:readonly StoredPose[] };\r\nexport const POSE_SLOTS=9;\r\n/** Below any edit a hand can make, and far above the drift of composing one\r\n * carried transform after another. */\r\nconst AUTHORED_EPSILON=1e-6;\r\n\r\nexport function capturePose(pins:readonly PinRecord[]):readonly StoredPose[]{\r\n return pins.map(pin=>({id:pin.id,pose:pin.pose,...(pin.authored?{authored:true}:{}),...(pin.ikTarget?{ikTarget:pin.ikTarget}:{})}));\r\n}\r\n\r\nconst restPoseOf=(rest:Point):PinPose=>({position:[rest[0],rest[1],rest[2]],rotation:[0,0,0,1],scale:[1,1,1]});\r\n\r\n/** Where a pin lands when its parent carries it from rest. A parent's pose IS\r\n * a similarity out of its own rest frame, so the child keeps its rest offset\r\n * through that same rotation and scale \u2014 the transform hierarchy posing applies\r\n * when a parent moves, written as one step from rest instead of accumulated. */\r\nexport function carriedPose(rest:Point,parentRest:Point,parent:PinPose):PinPose{\r\n const [qx,qy,qz,qw]=parent.rotation;\r\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];\r\n const tx=2*(qy*z-qz*y),ty=2*(qz*x-qx*z),tz=2*(qx*y-qy*x);\r\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)];\r\n const rotation:Rotation=[qx,qy,qz,qw],scale:Point=[parent.scale[0],parent.scale[1],parent.scale[2]];\r\n return {position,rotation,scale};\r\n}\r\n\r\nconst samePose=(a:PinPose,b:PinPose)=>\r\n a.position.every((v,i)=>Math.abs(v-b.position[i])<=AUTHORED_EPSILON)\r\n && a.scale.every((v,i)=>Math.abs(v-b.scale[i])<=AUTHORED_EPSILON)\r\n && a.rotation.every((v,i)=>Math.abs(v-b.rotation[i])<=AUTHORED_EPSILON);\r\n\r\n/** What a slot would place a pin at if it said nothing about it. */\r\nfunction inheritedPose(pin:PinRecord,parent:PinRecord|undefined,parentPose:PinPose|undefined):PinPose{\r\n return parent&&parentPose?carriedPose(pin.rest,parent.rest,parentPose):restPoseOf(pin.rest);\r\n}\r\n\r\n/** Only the poses a slot actually authors. A pin the hierarchy already places\r\n * is left out, so a point added while another pose was open keeps following its\r\n * parent everywhere else until it is deliberately posed there. */\r\nexport function authoredPoses(pins:readonly PinRecord[],parents:PinParents=new Map()):readonly StoredPose[]{\r\n const byId=new Map(pins.map(pin=>[pin.id,pin]));\r\n return capturePose(pins).filter(stored=>{\r\n const pin=byId.get(stored.id)!;\r\n // Deliberate, or a goal, which is deliberate by definition.\r\n if(pin.authored||pin.ikTarget)return true;\r\n // Otherwise it is only kept because it could not be worked out again. A\r\n // joint the IK solve swept along is not reproducible \u2014 the same goal\r\n // reached from a different bend gives a different arm \u2014 so the value stays\r\n // even though nobody posed it.\r\n const parent=byId.get(parents.get(pin.id)??'');\r\n return !samePose(pin.pose,inheritedPose(pin,parent,parent?.pose));\r\n });\r\n}\r\n\r\n/** Active pins are the edit register. Inactive slots contain transforms only;\r\n * topology, rest positions and settings remain shared and action-owned. A pin\r\n * the slot does not mention inherits through the hierarchy rather than dropping\r\n * to rest, which is what keeps a newly placed point attached to its parent in\r\n * every other pose. */\r\nexport function resolvePose(pins:readonly PinRecord[],slot:PoseSlot,parents:PinParents=new Map()):readonly PinRecord[]{\r\n const saved=new Map(slot.poses.map(p=>[p.id,p]));\r\n const byId=new Map(pins.map(pin=>[pin.id,pin]));\r\n const memo=new Map<string,PinPose>(),visiting=new Set<string>();\r\n const poseOf=(pin:PinRecord):PinPose=>{\r\n const cached=memo.get(pin.id);if(cached)return cached;\r\n const stored=saved.get(pin.id);\r\n let pose:PinPose;\r\n if(stored)pose=stored.pose;\r\n else{\r\n const parentId=parents.get(pin.id);\r\n // A parent already on the stack means a cycle in a derived hierarchy;\r\n // rest is the only answer that terminates.\r\n const parent=parentId&&!visiting.has(parentId)?byId.get(parentId):undefined;\r\n if(!parent)pose=restPoseOf(pin.rest);\r\n else{visiting.add(pin.id);pose=carriedPose(pin.rest,parent.rest,poseOf(parent));visiting.delete(pin.id);}\r\n }\r\n memo.set(pin.id,pose);return pose;\r\n };\r\n const resolved:PinRecord[]=pins.map(pin=>{\r\n const stored=saved.get(pin.id),{ikTarget:_target,authored:_authored,...base}=pin;\r\n return {...base,pose:poseOf(pin),...(stored?.authored?{authored:true}:{}),...(stored?.ikTarget?{ikTarget:stored.ikTarget}:{})};\r\n });\r\n // Group membership is shared. A group created after another pose was saved\r\n // still has one rotation/uniform scale when that pose is opened. Positions\r\n // stay authored; subsequent rigid edits preserve that arrangement.\r\n return resolved.map(pin=>{\r\n if(!pin.rigidGroup)return pin;const anchor=resolved.find(p=>p.rigidGroup===pin.rigidGroup)!;\r\n return {...pin,pose:{...pin.pose,rotation:anchor.pose.rotation,scale:[anchor.pose.scale[0],anchor.pose.scale[0],anchor.pose.scale[0]]}};\r\n });\r\n}\r\nexport function definedPoses(model:{readonly pins:readonly PinRecord[];readonly poseSlots:readonly PoseSlot[];readonly activePose:number}):PoseSlot[]{\r\n const slots=model.poseSlots.filter(p=>p.slot!==model.activePose);\r\n return [...slots,...(model.activePose === 0 ? [] : [{slot:model.activePose,poses:capturePose(model.pins)}])].sort((a,b)=>a.slot-b.slot);\r\n}\r\n\r\n/** Pose 0 is derived from shared rest positions, never an editable pose slot. */\r\nexport function restPoseSlot(pins:readonly PinRecord[]):PoseSlot{\r\n return {slot:0,poses:pins.map(pin=>({id:pin.id,pose:restPoseOf(pin.rest)}))};\r\n}\r\n\r\nexport function playablePoses(model:{readonly pins:readonly PinRecord[];readonly poseSlots:readonly PoseSlot[];readonly activePose:number}):PoseSlot[]{\r\n return [restPoseSlot(model.pins),...definedPoses(model)];\r\n}\r\n"],
|
|
5
|
+
"mappings": ";;;AAKO,IAAM,aAAW;AAGxB,IAAM,mBAAiB;AAEhB,SAAS,YAAY,MAAgD;AAC1E,SAAO,KAAK,IAAI,UAAM,EAAC,IAAG,IAAI,IAAG,MAAK,IAAI,MAAK,GAAI,IAAI,WAAS,EAAC,UAAS,KAAI,IAAE,CAAC,GAAG,GAAI,IAAI,WAAS,EAAC,UAAS,IAAI,SAAQ,IAAE,CAAC,EAAE,EAAE;AACpI;AAEA,IAAM,aAAW,CAAC,UAAsB,EAAC,UAAS,CAAC,KAAK,CAAC,GAAE,KAAK,CAAC,GAAE,KAAK,CAAC,CAAC,GAAE,UAAS,CAAC,GAAE,GAAE,GAAE,CAAC,GAAE,OAAM,CAAC,GAAE,GAAE,CAAC,EAAC;AAMrG,SAAS,YAAY,MAAW,YAAiB,QAAuB;AAC7E,QAAM,CAAC,IAAG,IAAG,IAAG,EAAE,IAAE,OAAO;AAC3B,QAAM,KAAG,KAAK,CAAC,IAAE,WAAW,CAAC,KAAG,OAAO,MAAM,CAAC,GAAE,KAAG,KAAK,CAAC,IAAE,WAAW,CAAC,KAAG,OAAO,MAAM,CAAC,GAAE,KAAG,KAAK,CAAC,IAAE,WAAW,CAAC,KAAG,OAAO,MAAM,CAAC;AAClI,QAAM,KAAG,KAAG,KAAG,IAAE,KAAG,IAAG,KAAG,KAAG,KAAG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7
|
+
var POSE_TIME_HEADROOM = 0.5;
|
|
8
|
+
function poseTimeScale(timeline) {
|
|
9
|
+
return Math.max(DEFAULT_POSE_SECONDS, ...timeline.map((entry) => entry.seconds)) + POSE_TIME_HEADROOM;
|
|
10
|
+
}
|
|
11
|
+
function poseSecondsAt(offset, height, scale) {
|
|
12
|
+
if (!(height > 0)) return MIN_POSE_SECONDS;
|
|
13
|
+
return Math.min(1, Math.max(0, offset / height)) * scale;
|
|
14
|
+
}
|
|
15
|
+
function poseTimeOffset(seconds, scale) {
|
|
16
|
+
if (!(scale > 0)) return 0;
|
|
17
|
+
return Math.min(100, Math.max(0, seconds / scale * 100));
|
|
18
|
+
}
|
|
19
|
+
function poseLoopSeconds(timeline) {
|
|
20
|
+
return timeline.reduce((total, entry) => total + Math.max(0, entry.seconds), 0);
|
|
21
|
+
}
|
|
22
|
+
function poseKnots(timeline) {
|
|
23
|
+
const knots = [0];
|
|
24
|
+
for (let i = 1; i < timeline.length; i++) {
|
|
25
|
+
knots.push(knots[i - 1] + (Math.max(0, timeline[i - 1].seconds) + Math.max(0, timeline[i].seconds)) / 2);
|
|
26
|
+
}
|
|
27
|
+
return knots;
|
|
28
|
+
}
|
|
29
|
+
function posePassSeconds(timeline) {
|
|
30
|
+
const knots = poseKnots(timeline);
|
|
31
|
+
return knots.length ? knots[knots.length - 1] : 0;
|
|
32
|
+
}
|
|
33
|
+
function poseTimeOf(timeline, slot) {
|
|
34
|
+
const index = timeline.findIndex((entry) => entry.slot === slot);
|
|
35
|
+
return index < 0 ? 0 : poseKnots(timeline)[index];
|
|
36
|
+
}
|
|
37
|
+
function smoothStep(t) {
|
|
38
|
+
const x = Math.min(1, Math.max(0, t));
|
|
39
|
+
return x ** 4 * (35 + x * (-84 + x * (70 - 20 * x)));
|
|
40
|
+
}
|
|
41
|
+
function preparePoseSpline(timeline) {
|
|
42
|
+
const n = timeline.length, slots = timeline.map((entry) => entry.slot);
|
|
43
|
+
const loop = poseLoopSeconds(timeline), knots = poseKnots(timeline);
|
|
44
|
+
if (n < 2 || !(loop > 0)) {
|
|
45
|
+
const fixed = timeline.map((_, i) => i === 0 ? 1 : 0);
|
|
46
|
+
return { slots, loop: Math.max(loop, 0), weightsAt: () => [...fixed] };
|
|
47
|
+
}
|
|
48
|
+
return { slots, loop, weightsAt: (time) => splineWeights(knots, loop, n, time) };
|
|
49
|
+
}
|
|
50
|
+
function splineWeights(knots, loop, n, time) {
|
|
51
|
+
const cursor = (time % loop + loop) % loop, weights = new Array(n).fill(0);
|
|
52
|
+
let k = n - 1;
|
|
53
|
+
while (k > 0 && cursor < knots[k]) k--;
|
|
54
|
+
const start = knots[k], end = k + 1 < n ? knots[k + 1] : loop;
|
|
55
|
+
const h = end - start, t = h > 0 ? (cursor - start) / h : 0, next = (k + 1) % n;
|
|
56
|
+
if (n < 3 || !(h > 0)) {
|
|
57
|
+
weights[k] = 1 - smoothStep(t);
|
|
58
|
+
weights[next] += smoothStep(t);
|
|
59
|
+
return weights;
|
|
60
|
+
}
|
|
61
|
+
const coordinate = (i) => i < 0 ? knots[i + n] - loop : i >= n ? knots[i - n] + loop : knots[i];
|
|
62
|
+
const unit = (i) => {
|
|
63
|
+
const result = new Array(n).fill(0);
|
|
64
|
+
result[(i + n) % n] = 1;
|
|
65
|
+
return result;
|
|
66
|
+
};
|
|
67
|
+
const subtract = (a2, b2, scale) => a2.map((v, j) => (v - b2[j]) / scale);
|
|
68
|
+
const derivatives = (i) => {
|
|
69
|
+
const before = coordinate(i) - coordinate(i - 1), after = coordinate(i + 1) - coordinate(i);
|
|
70
|
+
const previous = subtract(unit(i), unit(i - 1), Math.max(before, 1e-8));
|
|
71
|
+
const following = subtract(unit(i + 1), unit(i), Math.max(after, 1e-8));
|
|
72
|
+
return {
|
|
73
|
+
velocity: previous.map((v, j) => (v * after + following[j] * before) / (before + after)),
|
|
74
|
+
acceleration: previous.map((v, j) => 2 * (following[j] - v) / (before + after))
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
const a = derivatives(k), b = derivatives(k + 1), p = unit(k), q = unit(k + 1);
|
|
78
|
+
for (let j = 0; j < n; j++) {
|
|
79
|
+
const v0 = h * a.velocity[j], v1 = h * b.velocity[j], a0 = h * h * a.acceleration[j], a1 = h * h * b.acceleration[j];
|
|
80
|
+
const d = q[j] - p[j] - v0 - a0 / 2, v = v1 - v0 - a0, acc = a1 - a0;
|
|
81
|
+
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)))));
|
|
82
|
+
}
|
|
83
|
+
return weights;
|
|
84
|
+
}
|
|
85
|
+
var conjugate = (q) => [-q[0], -q[1], -q[2], q[3]];
|
|
86
|
+
var multiply = (a, b) => [
|
|
87
|
+
a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],
|
|
88
|
+
a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],
|
|
89
|
+
a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],
|
|
90
|
+
a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2]
|
|
91
|
+
];
|
|
92
|
+
function rotate(q, v) {
|
|
93
|
+
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]);
|
|
94
|
+
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)];
|
|
95
|
+
}
|
|
96
|
+
var safeScale = (v) => Math.abs(v) > 1e-8 ? v : 1e-8;
|
|
97
|
+
function localPose(pose, parent) {
|
|
98
|
+
if (!parent) return pose;
|
|
99
|
+
const inverse = conjugate(parent.rotation);
|
|
100
|
+
const offset = rotate(inverse, [pose.position[0] - parent.position[0], pose.position[1] - parent.position[1], pose.position[2] - parent.position[2]]);
|
|
101
|
+
return {
|
|
102
|
+
position: [offset[0] / safeScale(parent.scale[0]), offset[1] / safeScale(parent.scale[1]), offset[2] / safeScale(parent.scale[2])],
|
|
103
|
+
rotation: multiply(inverse, pose.rotation),
|
|
104
|
+
scale: [pose.scale[0] / safeScale(parent.scale[0]), pose.scale[1] / safeScale(parent.scale[1]), pose.scale[2] / safeScale(parent.scale[2])]
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
function worldPose(local, parent) {
|
|
108
|
+
if (!parent) return local;
|
|
109
|
+
const scaled = [local.position[0] * parent.scale[0], local.position[1] * parent.scale[1], local.position[2] * parent.scale[2]];
|
|
110
|
+
const offset = rotate(parent.rotation, scaled);
|
|
111
|
+
return {
|
|
112
|
+
position: [parent.position[0] + offset[0], parent.position[1] + offset[1], parent.position[2] + offset[2]],
|
|
113
|
+
rotation: multiply(parent.rotation, local.rotation),
|
|
114
|
+
scale: [local.scale[0] * parent.scale[0], local.scale[1] * parent.scale[1], local.scale[2] * parent.scale[2]]
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function hierarchyOrder(pins, parents) {
|
|
118
|
+
const index = new Map(pins.map((pin, i) => [pin.id, i]));
|
|
119
|
+
const parentOf = pins.map((pin) => {
|
|
120
|
+
const p = index.get(parents.get(pin.id) ?? "");
|
|
121
|
+
return p === index.get(pin.id) ? void 0 : p;
|
|
122
|
+
});
|
|
123
|
+
const order = [], state = new Uint8Array(pins.length);
|
|
124
|
+
const visit = (i) => {
|
|
125
|
+
if (state[i]) {
|
|
126
|
+
if (state[i] === 1) parentOf[i] = void 0;
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
state[i] = 1;
|
|
130
|
+
const parent = parentOf[i];
|
|
131
|
+
if (parent !== void 0) visit(parent);
|
|
132
|
+
state[i] = 2;
|
|
133
|
+
order.push(i);
|
|
134
|
+
};
|
|
135
|
+
for (let i = 0; i < pins.length; i++) visit(i);
|
|
136
|
+
return { order, parentOf };
|
|
137
|
+
}
|
|
138
|
+
function blendRotations(rotations, weights) {
|
|
139
|
+
let [x, y, z, w] = [0, 0, 0, 0];
|
|
140
|
+
const reference = rotations[weights.findIndex((weight) => weight > 1e-12)] ?? rotations[0];
|
|
141
|
+
let dominant = reference, best = -Infinity;
|
|
142
|
+
for (let i = 0; i < rotations.length; i++) {
|
|
143
|
+
const q = rotations[i];
|
|
144
|
+
if (weights[i] === 0) continue;
|
|
145
|
+
const aligned = q[0] * reference[0] + q[1] * reference[1] + q[2] * reference[2] + q[3] * reference[3] < 0 ? [-q[0], -q[1], -q[2], -q[3]] : q;
|
|
146
|
+
if (weights[i] > best) {
|
|
147
|
+
best = weights[i];
|
|
148
|
+
dominant = aligned;
|
|
149
|
+
}
|
|
150
|
+
x += aligned[0] * weights[i];
|
|
151
|
+
y += aligned[1] * weights[i];
|
|
152
|
+
z += aligned[2] * weights[i];
|
|
153
|
+
w += aligned[3] * weights[i];
|
|
154
|
+
}
|
|
155
|
+
const length = Math.hypot(x, y, z, w);
|
|
156
|
+
return length > 1e-6 ? [x / length, y / length, z / length, w / length] : dominant;
|
|
157
|
+
}
|
|
158
|
+
function blendPins(from, to, t, parents = /* @__PURE__ */ new Map()) {
|
|
159
|
+
if (t <= 0 && from.length === to.length && to.every((pin, i) => from[i]?.id === pin.id)) return from;
|
|
160
|
+
const aligned = to.map((pin) => from.find((other) => other.id === pin.id) ?? pin);
|
|
161
|
+
return blendPoses(to, [aligned, to], [1 - t, t], parents);
|
|
162
|
+
}
|
|
163
|
+
function blendPoses(base, poses, weights, parents = /* @__PURE__ */ new Map()) {
|
|
164
|
+
if (!poses.length || poses.some((pose) => pose.length !== base.length)) return base;
|
|
165
|
+
const { order, parentOf } = hierarchyOrder(base, parents);
|
|
166
|
+
const world = new Array(base.length), blended = new Array(base.length);
|
|
167
|
+
for (const i of order) {
|
|
168
|
+
const parent = parentOf[i], parentWorld = parent === void 0 ? void 0 : world[parent];
|
|
169
|
+
const locals = poses.map((pose, k) => localPose(pose[i].pose, parent === void 0 ? void 0 : poses[k][parent].pose));
|
|
170
|
+
world[i] = worldPose(weightedPose(locals, weights), parentWorld);
|
|
171
|
+
const pin = { ...base[i], pose: world[i] };
|
|
172
|
+
if (!poses.every((pose) => pose[i].ikTarget)) {
|
|
173
|
+
blended[i] = pin;
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
const targets = poses.map((pose) => pose[i].ikTarget);
|
|
177
|
+
blended[i] = { ...pin, ikTarget: {
|
|
178
|
+
position: [0, 1, 2].map((axis) => targets.reduce((sum, target, k) => sum + target.position[axis] * weights[k], 0)),
|
|
179
|
+
rotation: blendRotations(targets.map((target) => target.rotation), weights)
|
|
180
|
+
} };
|
|
181
|
+
}
|
|
182
|
+
return blended;
|
|
183
|
+
}
|
|
184
|
+
function weightedPose(poses, weights) {
|
|
185
|
+
const position = [0, 0, 0], scale = [0, 0, 0];
|
|
186
|
+
for (let k = 0; k < poses.length; k++) for (let axis = 0; axis < 3; axis++) {
|
|
187
|
+
position[axis] += poses[k].position[axis] * weights[k];
|
|
188
|
+
scale[axis] += poses[k].scale[axis] * weights[k];
|
|
189
|
+
}
|
|
190
|
+
return { position, rotation: blendRotations(poses.map((pose) => pose.rotation), weights), scale };
|
|
191
|
+
}
|
|
192
|
+
export {
|
|
193
|
+
DEFAULT_POSE_SECONDS,
|
|
194
|
+
MAX_POSE_SECONDS,
|
|
195
|
+
MIN_POSE_SECONDS,
|
|
196
|
+
POSE_TIME_HEADROOM,
|
|
197
|
+
blendPins,
|
|
198
|
+
blendPoses,
|
|
199
|
+
blendRotations,
|
|
200
|
+
poseKnots,
|
|
201
|
+
poseLoopSeconds,
|
|
202
|
+
posePassSeconds,
|
|
203
|
+
poseSecondsAt,
|
|
204
|
+
poseTimeOf,
|
|
205
|
+
poseTimeOffset,
|
|
206
|
+
poseTimeScale,
|
|
207
|
+
preparePoseSpline,
|
|
208
|
+
smoothStep
|
|
209
|
+
};
|
|
210
|
+
//# sourceMappingURL=pose-timeline.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/deformation/pose-timeline.ts"],
|
|
4
|
+
"sourcesContent": ["import type { PinPose, PinRecord, Point, Rotation } from './pin-types.js';\r\nimport type { PinParents } from './pin-types.js';\r\n\r\n/** A pose slot's time controls its share of the loop around its own moment.\r\n * The transition settles at each authored pose without holding a flat frame. */\r\nexport const DEFAULT_POSE_SECONDS = 0.7;\r\nexport const MIN_POSE_SECONDS = 0.05;\r\nexport const MAX_POSE_SECONDS = 60;\r\n/** Travel kept below the longest pose so a slider dragged to the bottom can\r\n * always be dragged further on the next pass, and shrinks back when shortened. */\r\nexport const POSE_TIME_HEADROOM = 0.5;\r\n\r\nexport type PoseTiming = { readonly slot: number; readonly seconds: number };\r\nexport type PoseTimeline = readonly PoseTiming[];\r\n\r\nexport function poseTimeScale(timeline: PoseTimeline): number {\r\n return Math.max(DEFAULT_POSE_SECONDS, ...timeline.map(entry => entry.seconds)) + POSE_TIME_HEADROOM;\r\n}\r\n\r\n/** The strip reads downwards: zero at the top, the scale at the bottom, which\r\n * is what makes \"drag down\" mean \"stay longer\". */\r\nexport function poseSecondsAt(offset: number, height: number, scale: number): number {\r\n if (!(height > 0)) return MIN_POSE_SECONDS;\r\n return Math.min(1, Math.max(0, offset / height)) * scale;\r\n}\r\n\r\n/** How far down the strip a time sits, as a percentage for the fill and handle. */\r\nexport function poseTimeOffset(seconds: number, scale: number): number {\r\n if (!(scale > 0)) return 0;\r\n return Math.min(100, Math.max(0, (seconds / scale) * 100));\r\n}\r\n\r\nexport function poseLoopSeconds(timeline: PoseTimeline): number {\r\n return timeline.reduce((total, entry) => total + Math.max(0, entry.seconds), 0);\r\n}\r\n\r\n/** The moment each pose is reached. Neighbours split the gap between them in\r\n * proportion to their own times, which is what makes a time an ownership share\r\n * rather than the length of one arc. */\r\nexport function poseKnots(timeline: PoseTimeline): number[] {\r\n const knots = [0];\r\n for (let i = 1; i < timeline.length; i++) {\r\n knots.push(knots[i - 1] + (Math.max(0, timeline[i - 1].seconds) + Math.max(0, timeline[i].seconds)) / 2);\r\n }\r\n return knots;\r\n}\r\n\r\n/** How long one pass takes: the first pose's moment to the last one's.\r\n * Looping playback adds the closing transition up to poseLoopSeconds. */\r\nexport function posePassSeconds(timeline: PoseTimeline): number {\r\n const knots = poseKnots(timeline);\r\n return knots.length ? knots[knots.length - 1] : 0;\r\n}\r\n\r\nexport function poseTimeOf(timeline: PoseTimeline, slot: number): number {\r\n const index = timeline.findIndex(entry => entry.slot === slot);\r\n return index < 0 ? 0 : poseKnots(timeline)[index];\r\n}\r\n\r\n/** Septic: zero first, second AND third derivative at both ends, so a one-shot\r\n * move away from rest and back to rest is G3 at the moment it starts and the\r\n * moment it settles. A cubic smoothstep leaves a jerk step at both. */\r\nexport function smoothStep(t: number): number {\r\n const x = Math.min(1, Math.max(0, t));\r\n return x ** 4 * (35 + x * (-84 + x * (70 - 20 * x)));\r\n}\r\n\r\nexport interface PoseSpline {\r\n readonly slots: readonly number[];\r\n readonly loop: number;\r\n /** How much each pose owns of the frame at this moment; sums to one, and is\r\n * one on a pose exactly at its own moment. */\r\n weightsAt(time: number): number[];\r\n}\r\n\r\n/** A periodic C2 interpolant of the authored poses. Its weights are shared by\r\n * rig playback, GLB clip mixing and trajectory sampling, so the visible path\r\n * is the path the animation actually follows. */\r\nexport function preparePoseSpline(timeline: PoseTimeline): PoseSpline {\r\n const n = timeline.length, slots = timeline.map(entry => entry.slot);\r\n const loop = poseLoopSeconds(timeline), knots = poseKnots(timeline);\r\n if (n < 2 || !(loop > 0)) {\r\n const fixed = timeline.map((_, i) => (i === 0 ? 1 : 0));\r\n return { slots, loop: Math.max(loop, 0), weightsAt: () => [...fixed] };\r\n }\r\n return { slots, loop, weightsAt: time => splineWeights(knots,loop,n,time) };\r\n}\r\n\r\nfunction splineWeights(knots: readonly number[], loop: number, n: number, time: number): number[] {\r\n const cursor = ((time % loop) + loop) % loop, weights = new Array<number>(n).fill(0);\r\n let k = n - 1; while (k > 0 && cursor < knots[k]) k--;\r\n const start = knots[k], end = k + 1 < n ? knots[k + 1] : loop;\r\n const h=end-start,t=h>0?(cursor-start)/h:0,next=(k+1)%n;\r\n if(n<3||!(h>0)){weights[k]=1-smoothStep(t);weights[next]+=smoothStep(t);return weights;}\r\n const coordinate=(i:number)=>i<0?knots[i+n]-loop:i>=n?knots[i-n]+loop:knots[i];\r\n const unit=(i:number)=>{const result=new Array<number>(n).fill(0);result[(i+n)%n]=1;return result;};\r\n const subtract=(a:readonly number[],b:readonly number[],scale:number)=>a.map((v,j)=>(v-b[j])/scale);\r\n const derivatives=(i:number)=>{\r\n const before=coordinate(i)-coordinate(i-1),after=coordinate(i+1)-coordinate(i);\r\n const previous=subtract(unit(i),unit(i-1),Math.max(before,1e-8));\r\n const following=subtract(unit(i+1),unit(i),Math.max(after,1e-8));\r\n // Full centered tangents round a three-pose corner visibly. Reducing them\r\n // to a quarter left a mathematically C2 but visibly triangular path.\r\n return {velocity:previous.map((v,j)=>(v*after+following[j]*before)/(before+after)),\r\n acceleration:previous.map((v,j)=>2*(following[j]-v)/(before+after))};\r\n };\r\n const a=derivatives(k),b=derivatives(k+1),p=unit(k),q=unit(k+1);\r\n for(let j=0;j<n;j++){\r\n const v0=h*a.velocity[j],v1=h*b.velocity[j],a0=h*h*a.acceleration[j],a1=h*h*b.acceleration[j];\r\n const d=q[j]-p[j]-v0-a0/2,v=v1-v0-a0,acc=a1-a0;\r\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)))));\r\n }\r\n return weights;\r\n}\r\n\r\nconst conjugate = (q: Rotation): Rotation => [-q[0], -q[1], -q[2], q[3]];\r\nconst multiply = (a: Rotation, b: Rotation): Rotation => [\r\n a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],\r\n a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],\r\n a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],\r\n a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2],\r\n];\r\nfunction rotate(q: Rotation, v: Point): Point {\r\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]);\r\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)];\r\n}\r\nconst safeScale = (v: number) => (Math.abs(v) > 1e-8 ? v : 1e-8);\r\n\r\n/** A pose in its parent's frame. */\r\nfunction localPose(pose: PinPose, parent: PinPose | undefined): PinPose {\r\n if (!parent) return pose;\r\n const inverse = conjugate(parent.rotation);\r\n const offset = rotate(inverse, [pose.position[0] - parent.position[0], pose.position[1] - parent.position[1], pose.position[2] - parent.position[2]]);\r\n return {\r\n position: [offset[0] / safeScale(parent.scale[0]), offset[1] / safeScale(parent.scale[1]), offset[2] / safeScale(parent.scale[2])],\r\n rotation: multiply(inverse, pose.rotation),\r\n scale: [pose.scale[0] / safeScale(parent.scale[0]), pose.scale[1] / safeScale(parent.scale[1]), pose.scale[2] / safeScale(parent.scale[2])],\r\n };\r\n}\r\n\r\n/** The inverse of localPose: a local transform read back out into the world. */\r\nfunction worldPose(local: PinPose, parent: PinPose | undefined): PinPose {\r\n if (!parent) return local;\r\n const scaled: Point = [local.position[0] * parent.scale[0], local.position[1] * parent.scale[1], local.position[2] * parent.scale[2]];\r\n const offset = rotate(parent.rotation, scaled);\r\n return {\r\n position: [parent.position[0] + offset[0], parent.position[1] + offset[1], parent.position[2] + offset[2]],\r\n rotation: multiply(parent.rotation, local.rotation),\r\n scale: [local.scale[0] * parent.scale[0], local.scale[1] * parent.scale[1], local.scale[2] * parent.scale[2]],\r\n };\r\n}\r\n\r\n/** Parents before children, with any cycle in a derived hierarchy broken by\r\n * treating the pin that closes it as a root. */\r\nfunction hierarchyOrder(pins: readonly PinRecord[], parents: PinParents): { order: number[]; parentOf: (number | undefined)[] } {\r\n const index = new Map(pins.map((pin, i) => [pin.id, i]));\r\n const parentOf = pins.map(pin => { const p = index.get(parents.get(pin.id) ?? ''); return p === index.get(pin.id) ? undefined : p; });\r\n const order: number[] = [], state = new Uint8Array(pins.length);\r\n const visit = (i: number) => {\r\n if (state[i]) { if (state[i] === 1) parentOf[i] = undefined; return; }\r\n state[i] = 1;\r\n const parent = parentOf[i];\r\n if (parent !== undefined) visit(parent);\r\n state[i] = 2; order.push(i);\r\n };\r\n for (let i = 0; i < pins.length; i++) visit(i);\r\n return { order, parentOf };\r\n}\r\n\r\n\r\n/** The active pair shares one hemisphere, including the last-to-first seam. */\r\nexport function blendRotations(rotations: readonly Rotation[], weights: readonly number[]): Rotation {\r\n let [x, y, z, w] = [0, 0, 0, 0];\r\n const reference=rotations[weights.findIndex(weight=>weight>1e-12)]??rotations[0];\r\n let dominant = reference, best = -Infinity;\r\n for (let i = 0; i < rotations.length; i++) {\r\n const q = rotations[i];\r\n if(weights[i]===0)continue;\r\n const aligned: Rotation = q[0] * reference[0] + q[1] * reference[1] + q[2] * reference[2] + q[3] * reference[3] < 0\r\n ? [-q[0], -q[1], -q[2], -q[3]] : q;\r\n if (weights[i] > best) { best = weights[i]; dominant = aligned; }\r\n x += aligned[0] * weights[i]; y += aligned[1] * weights[i];\r\n z += aligned[2] * weights[i]; w += aligned[3] * weights[i];\r\n }\r\n const length = Math.hypot(x, y, z, w);\r\n // Opposed rotations at equal weight cancel and name no orientation at all.\r\n return length > 1e-6 ? [x / length, y / length, z / length, w / length] : dominant;\r\n}\r\n\r\n/** Blends by id, so a pin missing from either side simply keeps its own pose \u2014\r\n * it appears on both sides of the blend and cannot move. Everything but the\r\n * transform comes from the destination: ids, rest positions and flags are\r\n * shared between slots and are not animated. */\r\nexport function blendPins(from: readonly PinRecord[], to: readonly PinRecord[], t: number, parents: PinParents = new Map()): readonly PinRecord[] {\r\n if (t <= 0 && from.length === to.length && to.every((pin, i) => from[i]?.id === pin.id)) return from;\r\n const aligned = to.map(pin => from.find(other => other.id === pin.id) ?? pin);\r\n return blendPoses(to, [aligned, to], [1 - t, t], parents);\r\n}\r\n\r\n/** Every pose at once, by weight. `poses` are the same pins in the same order\r\n * as `base` \u2014 they all come from resolving one document \u2014 so this walks them by\r\n * index rather than searching per pin per frame.\r\n *\r\n * The blend happens in each pin's PARENT frame, never in world space. A chain\r\n * posed two ways differs mostly in its joints' rotations, and averaging world\r\n * positions cuts the chord between them: the limb shortens in the middle of\r\n * every transition and lengthens again at each pose. In the parent's frame only\r\n * the joint's own rotation and offset move, so the chain keeps its shape, and a\r\n * pin's transform stays relative to whatever IK did to its parent \u2014 which is\r\n * what makes moving an IK target interpolate as one arc rather than dragging\r\n * every pin along a straight line of its own. */\r\nexport function blendPoses(base: readonly PinRecord[], poses: readonly (readonly PinRecord[])[], weights: readonly number[], parents: PinParents = new Map()): readonly PinRecord[] {\r\n if (!poses.length || poses.some(pose => pose.length !== base.length)) return base;\r\n const { order, parentOf } = hierarchyOrder(base, parents);\r\n const world = new Array<PinPose>(base.length), blended = new Array<PinRecord>(base.length);\r\n for (const i of order) {\r\n const parent = parentOf[i], parentWorld = parent === undefined ? undefined : world[parent];\r\n const locals = poses.map((pose, k) => localPose(pose[i].pose, parent === undefined ? undefined : poses[k][parent].pose));\r\n world[i] = worldPose(weightedPose(locals, weights), parentWorld);\r\n const pin: PinRecord = { ...base[i], pose: world[i] };\r\n // A goal is an anchor in the world, not a point on its parent. A planted\r\n // foot has the same goal in every pose, and must come out of the blend as\r\n // that goal exactly however the body above it moves.\r\n if (!poses.every(pose => pose[i].ikTarget)) { blended[i] = pin; continue; }\r\n const targets = poses.map(pose => pose[i].ikTarget!);\r\n blended[i] = { ...pin, ikTarget: {\r\n position: [0, 1, 2].map(axis => targets.reduce((sum, target, k) => sum + target.position[axis] * weights[k], 0)) as unknown as Point,\r\n rotation: blendRotations(targets.map(target => target.rotation), weights),\r\n } };\r\n }\r\n return blended;\r\n}\r\n\r\n/** One pose out of many, by weight. */\r\nfunction weightedPose(poses: readonly PinPose[], weights: readonly number[]): PinPose {\r\n const position: [number, number, number] = [0, 0, 0], scale: [number, number, number] = [0, 0, 0];\r\n for (let k = 0; k < poses.length; k++) for (let axis = 0; axis < 3; axis++) {\r\n position[axis] += poses[k].position[axis] * weights[k];\r\n scale[axis] += poses[k].scale[axis] * weights[k];\r\n }\r\n return { position, rotation: blendRotations(poses.map(pose => pose.rotation), weights), scale };\r\n}\r\n"],
|
|
5
|
+
"mappings": ";;;AAKO,IAAM,uBAAuB;AAC7B,IAAM,mBAAmB;AACzB,IAAM,mBAAmB;AAGzB,IAAM,qBAAqB;AAK3B,SAAS,cAAc,UAAgC;AAC5D,SAAO,KAAK,IAAI,sBAAsB,GAAG,SAAS,IAAI,WAAS,MAAM,OAAO,CAAC,IAAI;AACnF;AAIO,SAAS,cAAc,QAAgB,QAAgB,OAAuB;AACnF,MAAI,EAAE,SAAS,GAAI,QAAO;AAC1B,SAAO,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,SAAS,MAAM,CAAC,IAAI;AACrD;AAGO,SAAS,eAAe,SAAiB,OAAuB;AACrE,MAAI,EAAE,QAAQ,GAAI,QAAO;AACzB,SAAO,KAAK,IAAI,KAAK,KAAK,IAAI,GAAI,UAAU,QAAS,GAAG,CAAC;AAC3D;AAEO,SAAS,gBAAgB,UAAgC;AAC9D,SAAO,SAAS,OAAO,CAAC,OAAO,UAAU,QAAQ,KAAK,IAAI,GAAG,MAAM,OAAO,GAAG,CAAC;AAChF;AAKO,SAAS,UAAU,UAAkC;AAC1D,QAAM,QAAQ,CAAC,CAAC;AAChB,WAAS,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;AACxC,UAAM,KAAK,MAAM,IAAI,CAAC,KAAK,KAA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
|
|
1
|
+
// @ts-nocheck
|
|
2
|
+
|
|
3
|
+
// src/deformation/rig-drivers.ts
|
|
4
|
+
import { Matrix4, Quaternion, Vector3 } from "three";
|
|
5
|
+
var matrix = (pose) => new Matrix4().compose(new Vector3().fromArray(pose.position), new Quaternion().fromArray(pose.rotation), new Vector3().fromArray(pose.scale));
|
|
6
|
+
function driverDelta(driver, pins, reference) {
|
|
7
|
+
const affine = new Matrix4();
|
|
8
|
+
affine.elements.fill(0);
|
|
9
|
+
const rotation = new Quaternion(0, 0, 0, 0), scale = new Vector3();
|
|
10
|
+
let hemisphere;
|
|
11
|
+
for (const influence of driver.influences) {
|
|
12
|
+
const current = pins.find((p) => p.id === influence.id).pose, rest = reference.find((p) => p.id === influence.id).pose, w = influence.weight;
|
|
13
|
+
const delta = matrix(current).multiply(matrix(rest).invert()), q = new Quaternion().fromArray(current.rotation).multiply(new Quaternion().fromArray(rest.rotation).invert());
|
|
14
|
+
hemisphere ??= q;
|
|
15
|
+
const sign = hemisphere.dot(q) < 0 ? -w : w;
|
|
16
|
+
delta.elements.forEach((value, i) => affine.elements[i] += value * w);
|
|
17
|
+
rotation.set(rotation.x + q.x * sign, rotation.y + q.y * sign, rotation.z + q.z * sign, rotation.w + q.w * sign);
|
|
18
|
+
scale.addScaledVector(new Vector3().fromArray(current.scale).divide(new Vector3().fromArray(rest.scale)), w);
|
|
19
|
+
}
|
|
20
|
+
if (!driver.influences.length) {
|
|
21
|
+
affine.identity();
|
|
22
|
+
rotation.identity();
|
|
23
|
+
scale.setScalar(1);
|
|
24
|
+
}
|
|
25
|
+
return { affine, rotation: rotation.normalize(), scale };
|
|
26
|
+
}
|
|
27
|
+
function drivenPose(pose, driver, pins, reference) {
|
|
28
|
+
const delta = driverDelta(driver, pins, reference);
|
|
29
|
+
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() };
|
|
30
|
+
}
|
|
31
|
+
function referencePose(pose, driver, pins, reference) {
|
|
32
|
+
const delta = driverDelta(driver, pins, reference);
|
|
33
|
+
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.");
|
|
34
|
+
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() };
|
|
35
|
+
}
|
|
36
|
+
function driveRig(pins, reference, drivers) {
|
|
37
|
+
return pins.map((pin) => {
|
|
38
|
+
const driver = drivers.find((d) => d.id === pin.id);
|
|
39
|
+
return driver ? { ...pin, pose: drivenPose(pin.pose, driver, pins, reference) } : pin;
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
export {
|
|
43
|
+
driveRig,
|
|
44
|
+
drivenPose,
|
|
45
|
+
driverDelta,
|
|
46
|
+
referencePose
|
|
47
|
+
};
|
|
48
|
+
//# sourceMappingURL=rig-drivers.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/deformation/rig-drivers.ts"],
|
|
4
|
+
"sourcesContent": ["import { Matrix4, Quaternion, Vector3 } from 'three';\r\nimport type { PinPose, PinRecord } from './pin-types.js';\r\nexport interface BoneDriver { id:string; influences:readonly {id:string;weight:number}[] }\r\nconst matrix=(pose:PinPose)=>new Matrix4().compose(new Vector3().fromArray(pose.position),new Quaternion().fromArray(pose.rotation),new Vector3().fromArray(pose.scale));\r\n/** Drivers reference actual fitted bones, never hidden authoring nodes. The\r\n * driven bone's reference frame remains independently FK editable. */\r\nexport function driverDelta(driver:BoneDriver,pins:readonly PinRecord[],reference:readonly PinRecord[]){\r\n const affine=new Matrix4();affine.elements.fill(0);\r\n const rotation=new Quaternion(0,0,0,0),scale=new Vector3();let hemisphere:Quaternion|undefined;\r\n for(const influence of driver.influences){\r\n const current=pins.find(p=>p.id===influence.id)!.pose,rest=reference.find(p=>p.id===influence.id)!.pose,w=influence.weight;\r\n const delta=matrix(current).multiply(matrix(rest).invert()),q=new Quaternion().fromArray(current.rotation).multiply(new Quaternion().fromArray(rest.rotation).invert());\r\n hemisphere??=q;const sign=hemisphere.dot(q)<0?-w:w;\r\n delta.elements.forEach((value,i)=>affine.elements[i]+=value*w);\r\n rotation.set(rotation.x+q.x*sign,rotation.y+q.y*sign,rotation.z+q.z*sign,rotation.w+q.w*sign);\r\n scale.addScaledVector(new Vector3().fromArray(current.scale).divide(new Vector3().fromArray(rest.scale)),w);\r\n }\r\n if(!driver.influences.length){affine.identity();rotation.identity();scale.setScalar(1);}\r\n return {affine,rotation:rotation.normalize(),scale};\r\n}\r\nexport function drivenPose(pose:PinPose,driver:BoneDriver,pins:readonly PinRecord[],reference:readonly PinRecord[]):PinPose{\r\n const delta=driverDelta(driver,pins,reference);\r\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()};\r\n}\r\nexport function referencePose(pose:PinPose,driver:BoneDriver,pins:readonly PinRecord[],reference:readonly PinRecord[]):PinPose{\r\n const delta=driverDelta(driver,pins,reference);\r\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.');\r\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()};\r\n}\r\nexport function driveRig(pins:readonly PinRecord[],reference:readonly PinRecord[],drivers:readonly BoneDriver[]){\r\n return pins.map(pin=>{const driver=drivers.find(d=>d.id===pin.id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