@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,650 @@
|
|
|
1
|
+
// @ts-nocheck
|
|
2
|
+
|
|
3
|
+
// src/deformation/pin-ik.ts
|
|
4
|
+
import { Goal, Joint, Link, Solver } from "closed-chain-ik/core";
|
|
5
|
+
import { Euler, Matrix4, Quaternion as Quaternion2, Vector3 as Vector32 } from "three";
|
|
6
|
+
|
|
7
|
+
// src/deformation/motion-settings.ts
|
|
8
|
+
var DEFAULT_MOTION = { reach: 0.5, frequency: 14 / (2 * Math.PI), damping: 0.28, massInfluence: 1, strength: 1 };
|
|
9
|
+
|
|
10
|
+
// src/deformation/ik-constraints.ts
|
|
11
|
+
import { Quaternion, Vector3 } from "three";
|
|
12
|
+
var DEFAULT_IK_CONSTRAINT = { mode: "free", axis: "auto", min: -120, max: 120 };
|
|
13
|
+
function coneFrame(axis, constraint) {
|
|
14
|
+
return new Quaternion().fromArray(constraint.orientation ?? [0, 0, 0, 1]).multiply(new Quaternion().setFromUnitVectors(new Vector3(0, 0, 1), axis.clone().normalize()));
|
|
15
|
+
}
|
|
16
|
+
function coneAngle(constraint, azimuth) {
|
|
17
|
+
const x = (constraint.mode === "cone" ? constraint.max : 90) * Math.PI / 180, y = (constraint.mode === "cone" ? constraint.maxY ?? constraint.max : 90) * Math.PI / 180;
|
|
18
|
+
const c = Math.cos(azimuth), s = Math.sin(azimuth);
|
|
19
|
+
if (x === 0 && Math.abs(c) > 1e-8 || y === 0 && Math.abs(s) > 1e-8) return 0;
|
|
20
|
+
return 1 / Math.sqrt((Math.abs(c) < 1e-8 ? 0 : c / Math.max(x, 1e-12)) ** 2 + (Math.abs(s) < 1e-8 ? 0 : s / Math.max(y, 1e-12)) ** 2);
|
|
21
|
+
}
|
|
22
|
+
function constrainCone(rotation, axis, constraint, movingAxis = axis) {
|
|
23
|
+
const frame = coneFrame(axis, constraint), direction = movingAxis.clone().normalize().applyQuaternion(rotation);
|
|
24
|
+
const local = direction.clone().applyQuaternion(frame.clone().invert()), azimuth = Math.atan2(local.y, local.x);
|
|
25
|
+
const angle = Math.atan2(Math.hypot(local.x, local.y), local.z), limit = coneAngle(constraint, azimuth);
|
|
26
|
+
if (angle <= limit + 1e-8) return rotation.clone();
|
|
27
|
+
const target = new Vector3(Math.sin(limit) * Math.cos(azimuth), Math.sin(limit) * Math.sin(azimuth), Math.cos(limit)).applyQuaternion(frame);
|
|
28
|
+
return new Quaternion().setFromUnitVectors(direction, target).multiply(rotation).normalize();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// src/deformation/pin-ik.ts
|
|
32
|
+
var POSE_CONTINUITY_WEIGHT = 1e-4;
|
|
33
|
+
function articulatedNodes(pins, parents) {
|
|
34
|
+
const nodes = /* @__PURE__ */ new Set();
|
|
35
|
+
for (const pin of pins) if (!pin.guide) {
|
|
36
|
+
let id = pin.id;
|
|
37
|
+
while (id && !nodes.has(id)) {
|
|
38
|
+
nodes.add(id);
|
|
39
|
+
id = parents.get(id);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return nodes;
|
|
43
|
+
}
|
|
44
|
+
function ikChain(pins, parents, id, mass = /* @__PURE__ */ new Map()) {
|
|
45
|
+
const byId = new Map(pins.map((pin2) => [pin2.id, pin2]));
|
|
46
|
+
const element = (pin2) => pin2.rigidGroup ?? pin2.id;
|
|
47
|
+
const articulated = articulatedNodes(pins, parents);
|
|
48
|
+
const children = /* @__PURE__ */ new Map();
|
|
49
|
+
const supportLength = /* @__PURE__ */ new Map();
|
|
50
|
+
for (const pin2 of pins) {
|
|
51
|
+
if (!articulated.has(pin2.id)) continue;
|
|
52
|
+
const parent = byId.get(parents.get(pin2.id) ?? "");
|
|
53
|
+
if (!parent) continue;
|
|
54
|
+
const length = Math.hypot(...pin2.rest.map((x, i) => x - parent.rest[i])) * 0.5;
|
|
55
|
+
supportLength.set(pin2.id, (supportLength.get(pin2.id) ?? 0) + length);
|
|
56
|
+
supportLength.set(parent.id, (supportLength.get(parent.id) ?? 0) + length);
|
|
57
|
+
const set = children.get(element(parent)) ?? /* @__PURE__ */ new Set();
|
|
58
|
+
set.add(element(pin2));
|
|
59
|
+
children.set(element(parent), set);
|
|
60
|
+
}
|
|
61
|
+
const chain = [], seen = /* @__PURE__ */ new Set();
|
|
62
|
+
let pin = byId.get(id);
|
|
63
|
+
const reach = pin?.motion?.reach ?? DEFAULT_MOTION.reach;
|
|
64
|
+
let automatic;
|
|
65
|
+
const density = (p) => mass.has(p.id) ? mass.get(p.id) / Math.max(supportLength.get(p.id) ?? 0, 1e-12) : void 0;
|
|
66
|
+
while (pin && !seen.has(element(pin))) {
|
|
67
|
+
chain.unshift(pin);
|
|
68
|
+
seen.add(element(pin));
|
|
69
|
+
if (pin.independent) break;
|
|
70
|
+
const parent = byId.get(parents.get(pin.id) ?? "");
|
|
71
|
+
if (!parent) break;
|
|
72
|
+
if (!automatic && ((children.get(element(parent))?.size ?? 0) > 1 || !pin.guide && !parent.guide && (density(parent) ?? 0) > 8 * Math.max(density(pin) ?? Infinity, 1e-12))) automatic = parent.id;
|
|
73
|
+
pin = parent;
|
|
74
|
+
}
|
|
75
|
+
if (chain.length < 2) return chain;
|
|
76
|
+
const distance = new Float64Array(chain.length);
|
|
77
|
+
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]));
|
|
78
|
+
const boundary = automatic ? chain.findIndex((p) => p.id === automatic) : -1;
|
|
79
|
+
const automaticDistance = distance[Math.max(0, boundary)];
|
|
80
|
+
const budget = reach <= 0.5 ? automaticDistance * reach * 2 : automaticDistance + (distance[0] - automaticDistance) * (reach - 0.5) * 2;
|
|
81
|
+
const first = reach <= 0.5 && boundary >= 0 ? Math.min(boundary + 1, chain.length - 2) : 0;
|
|
82
|
+
let start = chain.length - 2;
|
|
83
|
+
for (let i = start - 1; i >= first; i--) if (Math.abs(distance[i] - budget) < Math.abs(distance[start] - budget)) start = i;
|
|
84
|
+
if (reach === 1) start = 0;
|
|
85
|
+
return chain.slice(start);
|
|
86
|
+
}
|
|
87
|
+
function solvePinIK(pins, parents, id, target, mass, targetRotation) {
|
|
88
|
+
const pin = pins.find((p) => p.id === id);
|
|
89
|
+
return solvePinIKGoals(pins, parents, [{ id, position: target, rotation: targetRotation ?? pin.ikTarget?.rotation ?? pin.pose.rotation }], mass);
|
|
90
|
+
}
|
|
91
|
+
function solveLocalPinIK(pins, parents, goal, mass, floor = -Infinity) {
|
|
92
|
+
const chain = ikChain(pins, parents, goal.id, mass), key = (p) => p.rigidGroup ?? p.id;
|
|
93
|
+
const keys = new Set(chain.map(key)), byId = new Map(pins.map((p) => [p.id, p]));
|
|
94
|
+
const articulated = articulatedNodes(pins, parents);
|
|
95
|
+
let boundary = -1;
|
|
96
|
+
for (let i = 0; i < chain.length - 1; i++) if (chain[i].independent || pins.some((p) => {
|
|
97
|
+
if (!articulated.has(p.id)) return false;
|
|
98
|
+
const parent = byId.get(parents.get(p.id) ?? "");
|
|
99
|
+
return parent && key(parent) === key(chain[i]) && !keys.has(key(p));
|
|
100
|
+
})) boundary = i;
|
|
101
|
+
const shared = boundary >= 0 && pins.some((p) => {
|
|
102
|
+
if (!articulated.has(p.id)) return false;
|
|
103
|
+
const parent = byId.get(parents.get(p.id) ?? "");
|
|
104
|
+
return parent && key(parent) === key(chain[boundary]) && !keys.has(key(p));
|
|
105
|
+
});
|
|
106
|
+
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)));
|
|
107
|
+
const moving = new Set(chain.slice(boundary + 1).map(key));
|
|
108
|
+
for (let added = true; added; ) {
|
|
109
|
+
added = false;
|
|
110
|
+
for (const p of pins) {
|
|
111
|
+
const parent = byId.get(parents.get(p.id) ?? "");
|
|
112
|
+
if (parent && moving.has(key(parent)) && !moving.has(key(p))) {
|
|
113
|
+
moving.add(key(p));
|
|
114
|
+
added = true;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const retained = new Set(boundary >= 0 ? [key(chain[boundary])] : []);
|
|
119
|
+
return solvePinIKGoals(pins, parents, [goal], mass, fixed, retained, floor).filter((p) => moving.has(key(byId.get(p.id))));
|
|
120
|
+
}
|
|
121
|
+
function solvePlantedPinIKGoals(pins, parents, goals, mass, fixed = /* @__PURE__ */ new Set(), floor = -Infinity) {
|
|
122
|
+
if (!goals.length) return [];
|
|
123
|
+
const edits = /* @__PURE__ */ new Map();
|
|
124
|
+
let independent = true;
|
|
125
|
+
for (const goal of goals) {
|
|
126
|
+
const limb = solveLocalPinIK(pins, parents, goal, mass, floor);
|
|
127
|
+
for (const edit of limb) {
|
|
128
|
+
if (fixed.has(edit.id) || edits.has(edit.id)) {
|
|
129
|
+
independent = false;
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
edits.set(edit.id, edit);
|
|
133
|
+
}
|
|
134
|
+
if (!independent) break;
|
|
135
|
+
}
|
|
136
|
+
return independent ? [...edits.values()] : solvePinIKGoals(pins, parents, goals, mass, fixed, /* @__PURE__ */ new Set(), floor);
|
|
137
|
+
}
|
|
138
|
+
function solveBodyIKGoals(pins, parents, goals, mass, fixed, floor = -Infinity) {
|
|
139
|
+
const poleChains = new Map(goals.map((goal) => [goal.id, ikChain(pins, parents, goal.id, mass)]));
|
|
140
|
+
const full = pins.map((pin) => pin.ik ? { ...pin, motion: { ...DEFAULT_MOTION, ...pin.motion, reach: 1 } } : pin);
|
|
141
|
+
const uses = /* @__PURE__ */ new Map();
|
|
142
|
+
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);
|
|
143
|
+
const anchors = /* @__PURE__ */ new Set([...fixed, ...[...uses].filter(([, count]) => count > 1).map(([id]) => id)]);
|
|
144
|
+
return solvePinIKGoals(full, parents, goals, mass, anchors, /* @__PURE__ */ new Set(), floor, poleChains);
|
|
145
|
+
}
|
|
146
|
+
function solvePinIKGoals(pins, parents, goals, mass, fixed = /* @__PURE__ */ new Set(), retained = /* @__PURE__ */ new Set(), floor = -Infinity, poleChains = /* @__PURE__ */ new Map()) {
|
|
147
|
+
if (!goals.length) return [];
|
|
148
|
+
const byId = new Map(pins.map((p) => [p.id, p])), key = (p) => p.rigidGroup ?? p.id;
|
|
149
|
+
const groups = /* @__PURE__ */ new Map();
|
|
150
|
+
for (const pin of pins) {
|
|
151
|
+
const group = groups.get(key(pin)) ?? [];
|
|
152
|
+
group.push(pin);
|
|
153
|
+
groups.set(key(pin), group);
|
|
154
|
+
}
|
|
155
|
+
const active = /* @__PURE__ */ new Set(), roots = /* @__PURE__ */ new Set();
|
|
156
|
+
const bendSeeds = /* @__PURE__ */ new Map();
|
|
157
|
+
let size = 0;
|
|
158
|
+
for (const goal of goals) {
|
|
159
|
+
const chain = ikChain(pins, parents, goal.id, mass);
|
|
160
|
+
if (chain.length < 2) throw new Error("IK needs a parent chain. Add a parent pin or remove Independent from this endpoint.");
|
|
161
|
+
for (const p of chain) active.add(key(p));
|
|
162
|
+
roots.add(key(chain[0]));
|
|
163
|
+
const start = new Vector32().fromArray(chain[0].pose.position), direction = new Vector32().fromArray(chain.at(-1).pose.position).sub(start);
|
|
164
|
+
const span = direction.length();
|
|
165
|
+
if (span > 1e-8 && new Vector32().fromArray(goal.position).distanceTo(start) < span * (1 - 1e-6)) {
|
|
166
|
+
direction.divideScalar(span);
|
|
167
|
+
const straight = chain.every((p) => new Vector32().fromArray(p.pose.position).sub(start).cross(direction).lengthSq() < span * span * 1e-12);
|
|
168
|
+
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)) : void 0;
|
|
169
|
+
if (candidate) {
|
|
170
|
+
const axis = new Vector32().crossVectors(direction, new Vector32().fromArray(goal.position).sub(start));
|
|
171
|
+
if (axis.lengthSq() < 1e-12) {
|
|
172
|
+
const components = direction.toArray().map(Math.abs);
|
|
173
|
+
axis.setComponent(components.indexOf(Math.min(...components)), 1).addScaledVector(direction, -axis.dot(direction));
|
|
174
|
+
}
|
|
175
|
+
bendSeeds.set(key(candidate), axis.normalize());
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
size = Math.max(size, chain.slice(1).reduce((sum, p, i) => sum + new Vector32().fromArray(p.pose.position).distanceTo(new Vector32().fromArray(chain[i].pose.position)), 0));
|
|
179
|
+
}
|
|
180
|
+
if (size < 1e-8) throw new Error("IK chain has no length. Separate its rest pins first.");
|
|
181
|
+
const parentGroup = /* @__PURE__ */ new Map();
|
|
182
|
+
for (const [id, members] of groups) {
|
|
183
|
+
const parent = members.map((p) => byId.get(parents.get(p.id) ?? "")).find((p) => p && key(p) !== id);
|
|
184
|
+
if (parent) parentGroup.set(id, key(parent));
|
|
185
|
+
}
|
|
186
|
+
const affected = new Set(active);
|
|
187
|
+
for (let changed = true; changed; ) {
|
|
188
|
+
changed = false;
|
|
189
|
+
for (const [id, parent] of parentGroup) if (affected.has(parent) && !affected.has(id)) {
|
|
190
|
+
affected.add(id);
|
|
191
|
+
changed = true;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const unchanged = goals.every((g) => {
|
|
195
|
+
const p = byId.get(g.id);
|
|
196
|
+
return new Vector32().fromArray(g.position).distanceToSquared(new Vector32().fromArray(p.pose.position)) < 1e-20 && new Quaternion2().fromArray(g.rotation).angleTo(new Quaternion2().fromArray(p.pose.rotation)) < 1e-10;
|
|
197
|
+
});
|
|
198
|
+
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 }));
|
|
199
|
+
const origin = new Vector32().fromArray(byId.get(goals[0].id).pose.position);
|
|
200
|
+
const frames = /* @__PURE__ */ new Map(), forest = [], building = /* @__PURE__ */ new Set();
|
|
201
|
+
const coneJoints = /* @__PURE__ */ new Map();
|
|
202
|
+
const freeJoints = /* @__PURE__ */ new Map();
|
|
203
|
+
const branchJoints = /* @__PURE__ */ new Map();
|
|
204
|
+
const build = (id) => {
|
|
205
|
+
const cached = frames.get(id);
|
|
206
|
+
if (cached) return cached;
|
|
207
|
+
if (building.has(id)) throw new Error("Cyclic IK hierarchy.");
|
|
208
|
+
building.add(id);
|
|
209
|
+
const pin = groups.get(id)[0], parentId = parentGroup.get(id), parent = parentId ? groups.get(parentId)[0] : void 0;
|
|
210
|
+
const parentFrame = parentId ? build(parentId) : new Link();
|
|
211
|
+
let attachment = parentFrame;
|
|
212
|
+
if (parentId && active.has(id) && !groups.get(id).some((p) => fixed.has(p.id)) && groups.get(parentId).some((p) => fixed.has(p.id))) {
|
|
213
|
+
const pivot = new Joint();
|
|
214
|
+
pivot.setDoF(3, 4, 5);
|
|
215
|
+
pivot.setDoFValues(0, 0, 0);
|
|
216
|
+
pivot.setRestPoseValues(0, 0, 0);
|
|
217
|
+
parentFrame.addChild(pivot);
|
|
218
|
+
attachment = new Link();
|
|
219
|
+
pivot.addChild(attachment);
|
|
220
|
+
branchJoints.set(id, { joint: pivot, frame: attachment });
|
|
221
|
+
}
|
|
222
|
+
const parentRotation = parent ? new Quaternion2().fromArray(parent.pose.rotation) : new Quaternion2();
|
|
223
|
+
const position = new Vector32().fromArray(pin.pose.position).sub(parent ? new Vector32().fromArray(parent.pose.position) : origin).applyQuaternion(parentRotation.clone().invert()).divideScalar(size);
|
|
224
|
+
const relative = parentRotation.clone().invert().multiply(new Quaternion2().fromArray(pin.pose.rotation)).normalize();
|
|
225
|
+
const joint = new Joint();
|
|
226
|
+
joint.setPosition(position.x, position.y, position.z);
|
|
227
|
+
attachment.addChild(joint);
|
|
228
|
+
const link = new Link(), constraint = pin.ikConstraint ?? DEFAULT_IK_CONSTRAINT;
|
|
229
|
+
const movable = active.has(id) && !groups.get(id).some((p) => fixed.has(p.id));
|
|
230
|
+
if (!movable || constraint.mode === "locked") joint.setQuaternion(...relative.toArray());
|
|
231
|
+
else if (constraint.mode === "hinge") {
|
|
232
|
+
let axis = new Vector32();
|
|
233
|
+
if (constraint.axis !== "auto") axis.setComponent(["x", "y", "z"].indexOf(constraint.axis), 1);
|
|
234
|
+
else {
|
|
235
|
+
const child = pins.find((p) => parents.get(p.id) === pin.id && active.has(key(p)));
|
|
236
|
+
if (parent && child) axis.crossVectors(new Vector32().fromArray(pin.rest).sub(new Vector32().fromArray(parent.rest)), new Vector32().fromArray(child.rest).sub(new Vector32().fromArray(pin.rest)));
|
|
237
|
+
if (axis.lengthSq() < 1e-10) {
|
|
238
|
+
const direction = child ? new Vector32().fromArray(child.rest).sub(new Vector32().fromArray(pin.rest)).normalize() : new Vector32(0, 1, 0);
|
|
239
|
+
axis.crossVectors(direction, Math.abs(direction.z) < 0.9 ? new Vector32(0, 0, 1) : new Vector32(1, 0, 0));
|
|
240
|
+
}
|
|
241
|
+
axis.normalize();
|
|
242
|
+
}
|
|
243
|
+
const basis = new Quaternion2().setFromUnitVectors(new Vector32(0, 0, 1), axis);
|
|
244
|
+
joint.setQuaternion(...basis.toArray());
|
|
245
|
+
link.setQuaternion(...basis.clone().invert().toArray());
|
|
246
|
+
joint.setDoF(5);
|
|
247
|
+
joint.setMinLimits(constraint.min * Math.PI / 180);
|
|
248
|
+
joint.setMaxLimits(constraint.max * Math.PI / 180);
|
|
249
|
+
const twist = 2 * Math.atan2(new Vector32(relative.x, relative.y, relative.z).dot(axis), relative.w);
|
|
250
|
+
joint.setDoFValues(Math.atan2(Math.sin(twist), Math.cos(twist)));
|
|
251
|
+
joint.setRestPoseValues(0);
|
|
252
|
+
} else {
|
|
253
|
+
if (constraint.mode === "cone") coneJoints.set(id, joint);
|
|
254
|
+
else freeJoints.set(id, joint);
|
|
255
|
+
joint.setDoF(3, 4, 5);
|
|
256
|
+
const euler = new Euler().setFromQuaternion(relative, "ZYX");
|
|
257
|
+
joint.setDoFValues(euler.x, euler.y, euler.z);
|
|
258
|
+
joint.setRestPoseValues(euler.x, euler.y, euler.z);
|
|
259
|
+
const seed = bendSeeds.get(id);
|
|
260
|
+
if (seed && !roots.has(id) && !goals.some((g) => key(byId.get(g.id)) === id)) {
|
|
261
|
+
const axis = seed.clone().applyQuaternion(parentRotation.clone().invert());
|
|
262
|
+
const seeded = new Euler().setFromQuaternion(new Quaternion2().setFromAxisAngle(axis, 0.03).multiply(relative), "ZYX");
|
|
263
|
+
joint.setDoFValues(seeded.x, seeded.y, seeded.z);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
joint.addChild(link);
|
|
267
|
+
frames.set(id, link);
|
|
268
|
+
building.delete(id);
|
|
269
|
+
if (!parentId) forest.push(parentFrame);
|
|
270
|
+
return link;
|
|
271
|
+
};
|
|
272
|
+
for (const id of groups.keys()) build(id);
|
|
273
|
+
const limitRotation = (id, rotation, parentRotation) => {
|
|
274
|
+
const pin = groups.get(id)[0];
|
|
275
|
+
if (pin.ikConstraint?.mode !== "cone") return rotation;
|
|
276
|
+
const parentId = parentGroup.get(id), parent = parentId ? groups.get(parentId)[0] : void 0;
|
|
277
|
+
const child = pins.find((p) => parents.get(p.id) === pin.id);
|
|
278
|
+
if (retained.has(id) && child && !active.has(key(child))) return rotation;
|
|
279
|
+
const axis = child ? new Vector32().fromArray(child.rest).sub(new Vector32().fromArray(pin.rest)) : parent ? new Vector32().fromArray(pin.rest).sub(new Vector32().fromArray(parent.rest)) : new Vector32(0, 1, 0);
|
|
280
|
+
if (axis.lengthSq() < 1e-12) axis.set(0, 1, 0);
|
|
281
|
+
const movingAxis = child ? new Vector32().fromArray(child.pose.position).sub(new Vector32().fromArray(pin.pose.position)).applyQuaternion(new Quaternion2().fromArray(pin.pose.rotation).invert()) : axis;
|
|
282
|
+
if (movingAxis.lengthSq() < 1e-12) movingAxis.copy(axis);
|
|
283
|
+
const reference = parentId && retained.has(parentId) ? new Quaternion2().fromArray(parent.pose.rotation) : parentRotation;
|
|
284
|
+
const relative = reference.clone().invert().multiply(parentRotation).multiply(rotation);
|
|
285
|
+
return parentRotation.clone().invert().multiply(reference).multiply(constrainCone(relative, axis, pin.ikConstraint, movingAxis));
|
|
286
|
+
};
|
|
287
|
+
const priorRotations = new Map([...frames.values(), ...[...branchJoints.values()].map((branch) => branch.frame)].map((frame) => {
|
|
288
|
+
frame.updateMatrixWorld();
|
|
289
|
+
return [frame, new Quaternion2().setFromRotationMatrix(new Matrix4().fromArray(frame.matrixWorld))];
|
|
290
|
+
}));
|
|
291
|
+
const closures = [];
|
|
292
|
+
for (const target of goals) {
|
|
293
|
+
const pin = byId.get(target.id), anchor = groups.get(key(pin))[0];
|
|
294
|
+
const offset = new Vector32().fromArray(pin.pose.position).sub(new Vector32().fromArray(anchor.pose.position)).applyQuaternion(new Quaternion2().fromArray(anchor.pose.rotation).invert()).divideScalar(size);
|
|
295
|
+
const attachment = new Joint();
|
|
296
|
+
attachment.setPosition(...offset.toArray());
|
|
297
|
+
frames.get(key(pin)).addChild(attachment);
|
|
298
|
+
const tip = new Link();
|
|
299
|
+
attachment.addChild(tip);
|
|
300
|
+
const goal = new Goal();
|
|
301
|
+
const freeEndpoint = groups.get(key(pin)).length === 1 && (!pin.ikConstraint || pin.ikConstraint.mode === "free");
|
|
302
|
+
if (freeEndpoint) goal.setGoalDoF(0, 1, 2);
|
|
303
|
+
else goal.setGoalDoF(0, 1, 2, 3, 4, 5);
|
|
304
|
+
goal.makeClosure(tip);
|
|
305
|
+
const requested = new Vector32().fromArray(target.position);
|
|
306
|
+
if (goals.length === 1 && freeEndpoint) {
|
|
307
|
+
const chain = ikChain(pins, parents, target.id, mass);
|
|
308
|
+
const first = chain.findIndex((p) => !groups.get(key(p)).some((q) => fixed.has(q.id)) && (p.ikConstraint ?? DEFAULT_IK_CONSTRAINT).mode !== "locked");
|
|
309
|
+
const moving = first < 0 ? [] : chain.slice(branchJoints.has(key(chain[first])) ? Math.max(0, first - 1) : first);
|
|
310
|
+
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")) {
|
|
311
|
+
const pivot = new Vector32().fromArray(moving[0].pose.position);
|
|
312
|
+
const lengths = moving.slice(1).map((p, i) => new Vector32().fromArray(p.pose.position).distanceTo(new Vector32().fromArray(moving[i].pose.position)));
|
|
313
|
+
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();
|
|
314
|
+
if (distance < inner || distance > outer) {
|
|
315
|
+
if (distance < 1e-12) delta.fromArray(moving.at(-1).pose.position).sub(pivot);
|
|
316
|
+
if (delta.lengthSq() > 1e-24) requested.copy(pivot).add(delta.setLength(Math.max(inner, Math.min(outer, distance))));
|
|
317
|
+
}
|
|
318
|
+
if (moving.length === 2) {
|
|
319
|
+
const before = new Vector32().fromArray(moving[1].pose.position).sub(pivot), after = requested.clone().sub(pivot);
|
|
320
|
+
if (before.lengthSq() > 1e-24 && after.lengthSq() > 1e-24) {
|
|
321
|
+
const branch = branchJoints.get(key(moving[1])), parent = branch ? moving[0] : byId.get(parents.get(moving[0].id) ?? "");
|
|
322
|
+
const local = parent ? new Quaternion2().fromArray(parent.pose.rotation).invert() : new Quaternion2();
|
|
323
|
+
local.multiply(new Quaternion2().setFromUnitVectors(before.normalize(), after.normalize())).multiply(new Quaternion2().fromArray(moving[0].pose.rotation));
|
|
324
|
+
const euler = new Euler().setFromQuaternion(local, "ZYX");
|
|
325
|
+
(branch?.joint ?? freeJoints.get(key(moving[0]))).setDoFValues(euler.x, euler.y, euler.z);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
goal.setPosition(...requested.sub(origin).divideScalar(size).toArray());
|
|
331
|
+
goal.setQuaternion(...target.rotation);
|
|
332
|
+
closures.push(goal);
|
|
333
|
+
}
|
|
334
|
+
let analytic = false;
|
|
335
|
+
if (goals.length === 1) {
|
|
336
|
+
const goal = goals[0], chain = ikChain(pins, parents, goal.id, mass);
|
|
337
|
+
const first = chain.findIndex((p, i) => coneJoints.has(key(p)) || freeJoints.has(key(p)) || i + 1 < chain.length && branchJoints.has(key(chain[i + 1])));
|
|
338
|
+
const limb = first < 0 ? [] : chain.slice(first), tipPin = byId.get(goal.id);
|
|
339
|
+
if (limb.length === 3 && limb.every((p) => groups.get(key(p)).length === 1) && limb.slice(0, 2).every((p, i) => coneJoints.has(key(p)) || freeJoints.has(key(p)) || branchJoints.has(key(limb[i + 1]))) && (!tipPin.ikConstraint || tipPin.ikConstraint.mode === "free")) {
|
|
340
|
+
const world = (p) => {
|
|
341
|
+
const frame = frames.get(key(p));
|
|
342
|
+
frame.updateMatrixWorld();
|
|
343
|
+
return new Matrix4().fromArray(frame.matrixWorld);
|
|
344
|
+
};
|
|
345
|
+
const matrices = limb.map(world), points = matrices.map((m) => new Vector32().setFromMatrixPosition(m));
|
|
346
|
+
const [base, knee, tip] = points, a = base.distanceTo(knee), b = knee.distanceTo(tip);
|
|
347
|
+
const direction = new Vector32().fromArray(closures[0].position).sub(base);
|
|
348
|
+
if (a > 1e-10 && b > 1e-10 && direction.lengthSq() > 1e-20) {
|
|
349
|
+
const distance = Math.max(Math.abs(a - b) + 1e-9, Math.min(a + b - 1e-9, direction.length()));
|
|
350
|
+
direction.normalize();
|
|
351
|
+
const oldAxis = tip.clone().sub(base).normalize();
|
|
352
|
+
const bend = knee.clone().sub(base).addScaledVector(oldAxis, -knee.clone().sub(base).dot(oldAxis));
|
|
353
|
+
bend.applyQuaternion(new Quaternion2().setFromUnitVectors(oldAxis, direction));
|
|
354
|
+
if (bend.lengthSq() < 1e-16) {
|
|
355
|
+
bend.fromArray(limb[1].rest).sub(new Vector32().fromArray(limb[0].rest));
|
|
356
|
+
const restAxis = new Vector32().fromArray(limb[2].rest).sub(new Vector32().fromArray(limb[0].rest)).normalize();
|
|
357
|
+
bend.addScaledVector(restAxis, -bend.dot(restAxis)).applyQuaternion(new Quaternion2().setFromRotationMatrix(matrices[0]));
|
|
358
|
+
bend.addScaledVector(direction, -bend.dot(direction));
|
|
359
|
+
}
|
|
360
|
+
if (bend.lengthSq() < 1e-16) {
|
|
361
|
+
bend.set(Math.abs(direction.x) < 0.8 ? 1 : 0, Math.abs(direction.x) < 0.8 ? 0 : 1, 0);
|
|
362
|
+
bend.addScaledVector(direction, -bend.dot(direction));
|
|
363
|
+
}
|
|
364
|
+
const along = (a * a - b * b + distance * distance) / (2 * distance);
|
|
365
|
+
const desiredKnee = base.clone().addScaledVector(direction, along).addScaledVector(bend.normalize(), Math.sqrt(Math.max(0, a * a - along * along)));
|
|
366
|
+
const desiredTip = base.clone().addScaledVector(direction, distance);
|
|
367
|
+
for (const [i, end] of [desiredKnee, desiredTip].entries()) {
|
|
368
|
+
const pin = limb[i], branch = branchJoints.get(key(limb[i + 1])), frame = branch?.frame ?? frames.get(key(pin));
|
|
369
|
+
frame.updateMatrixWorld();
|
|
370
|
+
const matrix = new Matrix4().fromArray(frame.matrixWorld), pivot = new Vector32().setFromMatrixPosition(matrix);
|
|
371
|
+
const before = new Vector32().setFromMatrixPosition(world(limb[i + 1])).sub(pivot), after = end.clone().sub(pivot);
|
|
372
|
+
const parentId = parentGroup.get(key(pin)), parentFrame = branch ? frames.get(key(pin)) : branchJoints.get(key(pin))?.frame ?? (parentId ? frames.get(parentId) : void 0);
|
|
373
|
+
parentFrame?.updateMatrixWorld();
|
|
374
|
+
const parentRotation = parentFrame ? new Quaternion2().setFromRotationMatrix(new Matrix4().fromArray(parentFrame.matrixWorld)) : new Quaternion2();
|
|
375
|
+
const rotation = parentRotation.invert().multiply(new Quaternion2().setFromUnitVectors(before.normalize(), after.normalize())).multiply(new Quaternion2().setFromRotationMatrix(matrix));
|
|
376
|
+
const euler = new Euler().setFromQuaternion(rotation, "ZYX");
|
|
377
|
+
(branch?.joint ?? coneJoints.get(key(pin)) ?? freeJoints.get(key(pin))).setDoFValues(euler.x, euler.y, euler.z);
|
|
378
|
+
}
|
|
379
|
+
analytic = true;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
const positionOnlyGoal = goals.length === 1 && groups.get(key(byId.get(goals[0].id))).length === 1 && (!byId.get(goals[0].id).ikConstraint || byId.get(goals[0].id).ikConstraint.mode === "free");
|
|
384
|
+
const positionOnlyGoals = goals.every((goal) => groups.get(key(byId.get(goal.id))).length === 1 && (!byId.get(goal.id).ikConstraint || byId.get(goal.id).ikConstraint.mode === "free"));
|
|
385
|
+
if (!analytic && !positionOnlyGoal && !positionOnlyGoals) {
|
|
386
|
+
const solver = new Solver([...forest, ...closures]);
|
|
387
|
+
solver.useSVD = true;
|
|
388
|
+
solver.maxIterations = 48;
|
|
389
|
+
solver.restPoseFactor = 1e-3;
|
|
390
|
+
solver.translationConvergeThreshold = 1e-6;
|
|
391
|
+
solver.rotationConvergeThreshold = 1e-6;
|
|
392
|
+
solver.translationErrorClamp = 0.2;
|
|
393
|
+
solver.solve();
|
|
394
|
+
}
|
|
395
|
+
const projectCones = () => {
|
|
396
|
+
for (const [id, joint] of coneJoints) {
|
|
397
|
+
const parentId = parentGroup.get(id), frame = frames.get(id);
|
|
398
|
+
frame.updateMatrixWorld();
|
|
399
|
+
const parentFrame = branchJoints.get(id)?.frame ?? (parentId ? frames.get(parentId) : void 0);
|
|
400
|
+
const parentRotation = parentFrame ? new Quaternion2().setFromRotationMatrix(new Matrix4().fromArray(parentFrame.matrixWorld)) : new Quaternion2();
|
|
401
|
+
const relative = parentRotation.clone().invert().multiply(new Quaternion2().setFromRotationMatrix(new Matrix4().fromArray(frame.matrixWorld)));
|
|
402
|
+
const limited = limitRotation(id, relative, parentRotation), euler = new Euler().setFromQuaternion(limited, "ZYX");
|
|
403
|
+
joint.setDoFValues(euler.x, euler.y, euler.z);
|
|
404
|
+
frame.updateMatrixWorld();
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
if (goals.length === 1 || !positionOnlyGoals) projectCones();
|
|
408
|
+
if (goals.length > 1 && positionOnlyGoals) {
|
|
409
|
+
const world = (frame) => {
|
|
410
|
+
frame.updateMatrixWorld();
|
|
411
|
+
return new Matrix4().fromArray(frame.matrixWorld);
|
|
412
|
+
};
|
|
413
|
+
const tips = goals.map((goal) => ({ goal, frame: frames.get(key(byId.get(goal.id))), desired: new Vector32().fromArray(closures[goals.indexOf(goal)].position), chain: ikChain(pins, parents, goal.id, mass).slice(0, -1).reverse() }));
|
|
414
|
+
const poles = tips.flatMap((tip) => {
|
|
415
|
+
const chain = poleChains.get(tip.goal.id);
|
|
416
|
+
if (!chain || chain.length < 3) return [];
|
|
417
|
+
const base = chain[0], knee = chain[Math.floor((chain.length - 1) / 2)], end = chain.at(-1);
|
|
418
|
+
const restAxis = new Vector32().fromArray(end.rest).sub(new Vector32().fromArray(base.rest));
|
|
419
|
+
const restBend = new Vector32().fromArray(knee.rest).sub(new Vector32().fromArray(base.rest));
|
|
420
|
+
if (restAxis.lengthSq() < 1e-16) return [];
|
|
421
|
+
restBend.addScaledVector(restAxis, -restBend.dot(restAxis) / restAxis.lengthSq());
|
|
422
|
+
if (restBend.length() < restAxis.length() * 0.02) return [];
|
|
423
|
+
const minBend = Math.min(0.03, restBend.length() / size * 0.5);
|
|
424
|
+
return [{ base, knee, chain, tip, minBend, restAxis: restAxis.normalize(), restPole: restBend.normalize() }];
|
|
425
|
+
});
|
|
426
|
+
const poleState = (pole) => {
|
|
427
|
+
const base = new Vector32().setFromMatrixPosition(world(frames.get(key(pole.base))));
|
|
428
|
+
const knee = new Vector32().setFromMatrixPosition(world(frames.get(key(pole.knee))));
|
|
429
|
+
const axis = pole.tip.desired.clone().sub(base).normalize();
|
|
430
|
+
const preferred = pole.restPole.clone().applyQuaternion(new Quaternion2().setFromUnitVectors(pole.restAxis, axis));
|
|
431
|
+
preferred.addScaledVector(axis, -preferred.dot(axis)).normalize();
|
|
432
|
+
const bend = knee.sub(base);
|
|
433
|
+
bend.addScaledVector(axis, -bend.dot(axis));
|
|
434
|
+
return { base, axis, preferred, bend };
|
|
435
|
+
};
|
|
436
|
+
const initial = [...new Set(tips.flatMap((tip) => tip.chain.flatMap((pin) => [frames.get(key(pin)), branchJoints.get(key(pin))?.frame]).filter((frame) => Boolean(frame))))].map((frame) => ({ frame, rotation: new Quaternion2().setFromRotationMatrix(world(frame)) }));
|
|
437
|
+
const cost = () => tips.reduce((sum, tip) => sum + new Vector32().setFromMatrixPosition(world(tip.frame)).distanceToSquared(tip.desired), 0) + POSE_CONTINUITY_WEIGHT * initial.reduce((sum, { frame, rotation }) => sum + new Quaternion2().setFromRotationMatrix(world(frame)).angleTo(rotation) ** 2, 0) + 10 * poles.reduce((sum, pole) => {
|
|
438
|
+
const { preferred, bend } = poleState(pole);
|
|
439
|
+
return sum + Math.max(0, pole.minBend - bend.dot(preferred)) ** 2;
|
|
440
|
+
}, 0);
|
|
441
|
+
for (let sweep = 0; sweep < 96; sweep++) {
|
|
442
|
+
if (cost() < 1e-12) break;
|
|
443
|
+
let largestChange = 0;
|
|
444
|
+
for (const tip of tips) for (const pin of tip.chain) {
|
|
445
|
+
const id = key(pin), joints = [coneJoints.get(id) ?? freeJoints.get(id), branchJoints.get(id)?.joint];
|
|
446
|
+
for (const [index, joint] of joints.entries()) {
|
|
447
|
+
if (!joint) continue;
|
|
448
|
+
const branch = index === 1, frame = branch ? branchJoints.get(id).frame : frames.get(id);
|
|
449
|
+
const matrix = world(frame), pivot = new Vector32().setFromMatrixPosition(matrix), end = new Vector32().setFromMatrixPosition(world(tip.frame));
|
|
450
|
+
const a = end.sub(pivot), b = tip.desired.clone().sub(pivot);
|
|
451
|
+
if (a.lengthSq() < 1e-20 || b.lengthSq() < 1e-20) continue;
|
|
452
|
+
const parentId = parentGroup.get(id), localParent = branch ? parentId ? frames.get(parentId) : void 0 : branchJoints.get(id)?.frame ?? (parentId ? frames.get(parentId) : void 0);
|
|
453
|
+
const parentRotation = localParent ? new Quaternion2().setFromRotationMatrix(world(localParent)) : new Quaternion2();
|
|
454
|
+
const old = parentRotation.clone().invert().multiply(new Quaternion2().setFromRotationMatrix(matrix));
|
|
455
|
+
let rotation = parentRotation.clone().invert().multiply(new Quaternion2().setFromUnitVectors(a.normalize(), b.normalize())).multiply(new Quaternion2().setFromRotationMatrix(matrix));
|
|
456
|
+
if (!branch) rotation = limitRotation(id, rotation, parentRotation);
|
|
457
|
+
const before = cost(), set = (q) => {
|
|
458
|
+
const e = new Euler().setFromQuaternion(q, "ZYX");
|
|
459
|
+
joint.setDoFValues(e.x, e.y, e.z);
|
|
460
|
+
frame.updateMatrixWorld();
|
|
461
|
+
};
|
|
462
|
+
for (let fraction = 1; fraction >= 1 / 32; fraction /= 2) {
|
|
463
|
+
const attempt = old.clone().slerp(rotation, fraction);
|
|
464
|
+
set(attempt);
|
|
465
|
+
if (cost() < before - 1e-14) {
|
|
466
|
+
largestChange = Math.max(largestChange, old.angleTo(attempt));
|
|
467
|
+
break;
|
|
468
|
+
}
|
|
469
|
+
set(old);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
for (const pole of poles) {
|
|
474
|
+
const { base, preferred, bend } = poleState(pole), along = bend.dot(preferred);
|
|
475
|
+
if (along >= pole.minBend) continue;
|
|
476
|
+
const baseId = key(pole.base), nextId = key(pole.chain[1]);
|
|
477
|
+
const branch = branchJoints.get(nextId), joint = branch?.joint ?? coneJoints.get(baseId) ?? freeJoints.get(baseId);
|
|
478
|
+
const frame = branch?.frame ?? frames.get(baseId);
|
|
479
|
+
if (!joint || !frame) continue;
|
|
480
|
+
const knee = new Vector32().setFromMatrixPosition(world(frames.get(key(pole.knee))));
|
|
481
|
+
const arm = knee.sub(base), aim = arm.clone().addScaledVector(preferred, Math.min(0.01, pole.minBend - along));
|
|
482
|
+
if (arm.lengthSq() < 1e-20 || aim.lengthSq() < 1e-20) continue;
|
|
483
|
+
const parentId = branch ? baseId : parentGroup.get(baseId), parentFrame = parentId ? frames.get(parentId) : void 0;
|
|
484
|
+
const parentRotation = parentFrame ? new Quaternion2().setFromRotationMatrix(world(parentFrame)) : new Quaternion2();
|
|
485
|
+
const matrix = world(frame), old = parentRotation.clone().invert().multiply(new Quaternion2().setFromRotationMatrix(matrix));
|
|
486
|
+
let proposal = parentRotation.clone().invert().multiply(new Quaternion2().setFromUnitVectors(arm.normalize(), aim.normalize())).multiply(new Quaternion2().setFromRotationMatrix(matrix));
|
|
487
|
+
if (!branch) proposal = limitRotation(baseId, proposal, parentRotation);
|
|
488
|
+
const before = cost(), set = (q) => {
|
|
489
|
+
const e = new Euler().setFromQuaternion(q, "ZYX");
|
|
490
|
+
joint.setDoFValues(e.x, e.y, e.z);
|
|
491
|
+
frame.updateMatrixWorld();
|
|
492
|
+
};
|
|
493
|
+
for (let fraction = 1; fraction >= 1 / 32; fraction /= 2) {
|
|
494
|
+
const attempt = old.clone().slerp(proposal, fraction);
|
|
495
|
+
set(attempt);
|
|
496
|
+
if (cost() < before - 1e-14) {
|
|
497
|
+
largestChange = Math.max(largestChange, old.angleTo(attempt));
|
|
498
|
+
break;
|
|
499
|
+
}
|
|
500
|
+
set(old);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
if (largestChange < 1e-5) break;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
if (goals.length === 1) {
|
|
507
|
+
const target = goals[0], tipPin = byId.get(target.id);
|
|
508
|
+
if (groups.get(key(tipPin)).length === 1 && (!tipPin.ikConstraint || tipPin.ikConstraint.mode === "free")) {
|
|
509
|
+
const tip = frames.get(key(tipPin)), desired = new Vector32().fromArray(closures[0].position);
|
|
510
|
+
const ordered = ikChain(pins, parents, target.id, mass), chain = ordered.slice(0, -1).reverse();
|
|
511
|
+
const world = (frame) => {
|
|
512
|
+
frame.updateMatrixWorld();
|
|
513
|
+
return new Matrix4().fromArray(frame.matrixWorld);
|
|
514
|
+
};
|
|
515
|
+
const ground = tipPin.chainRole?.kind === "leg" && Number.isFinite(floor) ? (floor - origin.y) / size : -Infinity;
|
|
516
|
+
const point = (pin) => new Vector32().setFromMatrixPosition(world(frames.get(key(pin))));
|
|
517
|
+
const initial = [...new Set(chain.flatMap((pin) => [frames.get(key(pin)), branchJoints.get(key(pin))?.frame].filter((frame) => Boolean(frame))))].map((frame) => ({ frame, rotation: priorRotations.get(frame) }));
|
|
518
|
+
const poles = ordered.slice(1, -1).flatMap((knee, i) => {
|
|
519
|
+
const base = ordered[i], end = ordered[i + 2];
|
|
520
|
+
const chord = new Vector32().fromArray(end.pose.position).sub(new Vector32().fromArray(base.pose.position)), span = chord.length(), axis = chord.normalize();
|
|
521
|
+
const bend = new Vector32().fromArray(knee.pose.position).sub(new Vector32().fromArray(base.pose.position));
|
|
522
|
+
bend.addScaledVector(axis, -bend.dot(axis));
|
|
523
|
+
if (bend.length() < span * 0.02) {
|
|
524
|
+
const restAxis = new Vector32().fromArray(end.rest).sub(new Vector32().fromArray(base.rest)).normalize();
|
|
525
|
+
bend.fromArray(knee.rest).sub(new Vector32().fromArray(base.rest));
|
|
526
|
+
bend.addScaledVector(restAxis, -bend.dot(restAxis));
|
|
527
|
+
const rotation = new Quaternion2().fromArray(base.pose.rotation);
|
|
528
|
+
bend.applyQuaternion(rotation);
|
|
529
|
+
restAxis.applyQuaternion(rotation);
|
|
530
|
+
bend.applyQuaternion(new Quaternion2().setFromUnitVectors(restAxis, axis));
|
|
531
|
+
}
|
|
532
|
+
return bend.length() < span * 0.02 ? [] : [{ base, knee, end, axis, pole: bend.normalize() }];
|
|
533
|
+
});
|
|
534
|
+
const poleCost = () => poles.reduce((sum, pole) => {
|
|
535
|
+
const base = point(pole.base), axis = point(pole.end).sub(base).normalize();
|
|
536
|
+
const preferred = pole.pole.clone().applyQuaternion(new Quaternion2().setFromUnitVectors(pole.axis, axis));
|
|
537
|
+
const bend = point(pole.knee).sub(base);
|
|
538
|
+
bend.addScaledVector(axis, -bend.dot(axis));
|
|
539
|
+
return sum + Math.max(0, -bend.dot(preferred)) ** 2;
|
|
540
|
+
}, 0);
|
|
541
|
+
const cost = () => {
|
|
542
|
+
const error = new Vector32().setFromMatrixPosition(world(tip)).distanceToSquared(desired);
|
|
543
|
+
let penetration = 0;
|
|
544
|
+
if (Number.isFinite(ground)) for (const pin of ordered.slice(1, -1)) penetration += Math.max(0, ground - point(pin).y) ** 2;
|
|
545
|
+
const drift = initial.reduce((sum, { frame, rotation }) => sum + new Quaternion2().setFromRotationMatrix(world(frame)).angleTo(rotation) ** 2, 0);
|
|
546
|
+
return error + 16 * penetration + 100 * poleCost() + POSE_CONTINUITY_WEIGHT * drift;
|
|
547
|
+
};
|
|
548
|
+
for (let sweep = 0; sweep < 128; sweep++) {
|
|
549
|
+
if (cost() < 1e-12) break;
|
|
550
|
+
let largestChange = 0;
|
|
551
|
+
for (const pin of chain) {
|
|
552
|
+
const id = key(pin);
|
|
553
|
+
const joints = [coneJoints.get(id) ?? freeJoints.get(id), branchJoints.get(id)?.joint];
|
|
554
|
+
for (const [jointIndex, joint] of joints.entries()) {
|
|
555
|
+
if (!joint) continue;
|
|
556
|
+
const branch = jointIndex === 1, frame = branch ? branchJoints.get(id).frame : frames.get(id);
|
|
557
|
+
const matrix = world(frame), pivot = new Vector32().setFromMatrixPosition(matrix);
|
|
558
|
+
const end = new Vector32().setFromMatrixPosition(world(tip)), before = cost();
|
|
559
|
+
const a = end.clone().sub(pivot), b = desired.clone().sub(pivot);
|
|
560
|
+
if (a.lengthSq() < 1e-20 || b.lengthSq() < 1e-20) continue;
|
|
561
|
+
const parentId = parentGroup.get(id), localParent = branch ? parentId ? frames.get(parentId) : void 0 : branchJoints.get(id)?.frame ?? (parentId ? frames.get(parentId) : void 0);
|
|
562
|
+
const parentRotation = localParent ? new Quaternion2().setFromRotationMatrix(world(localParent)) : new Quaternion2();
|
|
563
|
+
const old = parentRotation.clone().invert().multiply(new Quaternion2().setFromRotationMatrix(matrix));
|
|
564
|
+
let rotation = parentRotation.clone().invert().multiply(new Quaternion2().setFromUnitVectors(a.normalize(), b.normalize())).multiply(new Quaternion2().setFromRotationMatrix(matrix));
|
|
565
|
+
if (!branch) rotation = limitRotation(id, rotation, parentRotation);
|
|
566
|
+
const set = (q) => {
|
|
567
|
+
const e = new Euler().setFromQuaternion(q, "ZYX");
|
|
568
|
+
joint.setDoFValues(e.x, e.y, e.z);
|
|
569
|
+
frame.updateMatrixWorld();
|
|
570
|
+
};
|
|
571
|
+
let accepted = false;
|
|
572
|
+
for (let fraction = 1; fraction >= 1 / 32; fraction /= 2) {
|
|
573
|
+
let attempt = old.clone().slerp(rotation, fraction);
|
|
574
|
+
if (!branch) attempt = limitRotation(id, attempt, parentRotation);
|
|
575
|
+
set(attempt);
|
|
576
|
+
if (cost() <= before + 1e-14) {
|
|
577
|
+
largestChange = Math.max(largestChange, old.angleTo(attempt));
|
|
578
|
+
accepted = true;
|
|
579
|
+
break;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
if (!accepted) set(old);
|
|
583
|
+
if (Number.isFinite(ground)) for (const descendant of ordered.slice(ordered.indexOf(pin) + 1, -1)) {
|
|
584
|
+
const lower = point(descendant);
|
|
585
|
+
if (lower.y >= ground) continue;
|
|
586
|
+
const current = point(pin), arm = lower.clone().sub(current), raised = lower.clone();
|
|
587
|
+
raised.y = ground;
|
|
588
|
+
const aim = raised.sub(current);
|
|
589
|
+
if (arm.lengthSq() < 1e-20 || aim.lengthSq() < 1e-20) continue;
|
|
590
|
+
const parentNow = localParent ? new Quaternion2().setFromRotationMatrix(world(localParent)) : new Quaternion2();
|
|
591
|
+
const previous = parentNow.clone().invert().multiply(new Quaternion2().setFromRotationMatrix(world(frame)));
|
|
592
|
+
let proposal = parentNow.clone().invert().multiply(new Quaternion2().setFromUnitVectors(arm.normalize(), aim.normalize())).multiply(new Quaternion2().setFromRotationMatrix(world(frame)));
|
|
593
|
+
if (!branch) proposal = limitRotation(id, proposal, parentNow);
|
|
594
|
+
const start = cost();
|
|
595
|
+
for (let fraction = 1; fraction >= 1 / 16; fraction /= 2) {
|
|
596
|
+
const attempt = previous.clone().slerp(proposal, fraction);
|
|
597
|
+
set(attempt);
|
|
598
|
+
if (cost() < start - 1e-14) {
|
|
599
|
+
largestChange = Math.max(largestChange, previous.angleTo(attempt));
|
|
600
|
+
break;
|
|
601
|
+
}
|
|
602
|
+
set(previous);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
if (largestChange < 1e-5) break;
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
if (goals.length === 1 || !positionOnlyGoals) projectCones();
|
|
612
|
+
for (const goal of goals) {
|
|
613
|
+
const id = key(byId.get(goal.id)), joint = freeJoints.get(id);
|
|
614
|
+
if (!joint || groups.get(id).length !== 1) continue;
|
|
615
|
+
const parentId = parentGroup.get(id), parent = parentId ? frames.get(parentId) : void 0;
|
|
616
|
+
parent?.updateMatrixWorld();
|
|
617
|
+
const rotation = parent ? new Quaternion2().setFromRotationMatrix(new Matrix4().fromArray(parent.matrixWorld)).invert() : new Quaternion2();
|
|
618
|
+
rotation.multiply(new Quaternion2().fromArray(goal.rotation));
|
|
619
|
+
const e = new Euler().setFromQuaternion(rotation, "ZYX");
|
|
620
|
+
joint.setDoFValues(e.x, e.y, e.z);
|
|
621
|
+
frames.get(id).updateMatrixWorld();
|
|
622
|
+
}
|
|
623
|
+
const result = pins.filter((p) => affected.has(key(p))).map((pin) => {
|
|
624
|
+
if (fixed.has(pin.id)) return { id: pin.id, pose: pin.pose };
|
|
625
|
+
const anchor = groups.get(key(pin))[0], frame = frames.get(key(pin));
|
|
626
|
+
frame.updateMatrixWorld();
|
|
627
|
+
const matrix = new Matrix4().fromArray(frame.matrixWorld), rotation = new Quaternion2().setFromRotationMatrix(matrix).normalize();
|
|
628
|
+
const position = new Vector32().setFromMatrixPosition(matrix).multiplyScalar(size).add(origin);
|
|
629
|
+
const delta = rotation.clone().multiply(new Quaternion2().fromArray(anchor.pose.rotation).invert());
|
|
630
|
+
const goal = goals.find((g) => key(byId.get(g.id)) === key(pin));
|
|
631
|
+
const terminal = ![...parentGroup.values()].includes(key(pin));
|
|
632
|
+
if (goal && terminal && (!pin.ikConstraint || pin.ikConstraint.mode === "free")) rotation.fromArray(goal.rotation);
|
|
633
|
+
const offset = new Vector32().fromArray(pin.pose.position).sub(new Vector32().fromArray(anchor.pose.position));
|
|
634
|
+
if (goal && terminal && (!pin.ikConstraint || pin.ikConstraint.mode === "free")) delta.copy(rotation).multiply(new Quaternion2().fromArray(anchor.pose.rotation).invert());
|
|
635
|
+
position.add(offset.applyQuaternion(delta));
|
|
636
|
+
if (!parentGroup.has(key(pin)) && pin.id === anchor.id) position.fromArray(pin.pose.position);
|
|
637
|
+
if (![...position.toArray(), ...rotation.toArray()].every(Number.isFinite)) throw new Error("IK produced an invalid pose.");
|
|
638
|
+
return { id: pin.id, pose: { position: position.toArray(), rotation: rotation.toArray(), scale: pin.pose.scale } };
|
|
639
|
+
});
|
|
640
|
+
return result;
|
|
641
|
+
}
|
|
642
|
+
export {
|
|
643
|
+
ikChain,
|
|
644
|
+
solveBodyIKGoals,
|
|
645
|
+
solveLocalPinIK,
|
|
646
|
+
solvePinIK,
|
|
647
|
+
solvePinIKGoals,
|
|
648
|
+
solvePlantedPinIKGoals
|
|
649
|
+
};
|
|
650
|
+
//# sourceMappingURL=pin-ik.js.map
|