@margoengine/kinematics-constraints 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,203 @@
1
+ import type { ConvexHullVolume } from './hull.js';
2
+ import type { ConstraintVolume, Vec3View } from './types.js';
3
+ /** Why a solve ended: clear, swivel-rate limited, clamped by a singularity band, or blocked by an obstacle. */
4
+ export declare enum SolveStatus {
5
+ /** The evaluated discrete pose and its checked link capsules have static clearance. */
6
+ Success = 0,
7
+ /** A sampled clear pose requires exceeding the permitted swivel movement. */
8
+ SwivelRateLimitExceeded = 1,
9
+ /** The target was clamped out of a near-singular fold or reach exclusion band. */
10
+ SingularDeadZone = 2,
11
+ /** No clear pose was found within the search budget; this is not a nonexistence proof. */
12
+ ObstacleOccluded = 3
13
+ }
14
+ /** Per-solve options: swivel speed limit, reach and fold margins and the angular search budget. */
15
+ export interface SolveOptions {
16
+ /** Optional pure legal-pose test, before obstacle acceptance. Default none. Rejection continues the swivel search. */
17
+ acceptPose?: PosePredicate;
18
+ /** Maximum swivel speed, radians/second. Defaults to 2 PI. */
19
+ swivelSpeedLimit?: number;
20
+ /** Distance excluded at full extension. Defaults to 1e-5 scene units. */
21
+ reachMargin?: number;
22
+ /** Distance excluded at full compression. Defaults to 1e-5 scene units. */
23
+ foldMargin?: number;
24
+ /** Additional angular candidates per search pass, 0..256. Defaults to 32. */
25
+ searchBudget?: number;
26
+ }
27
+ /**
28
+ * A chain link checked as its own convex hull instead of a capsule. The hull's points are in the link's local space,
29
+ * such as its bone's. The solver moves the hull to each candidate pose: `axis` along the link, `hinge` on the normal
30
+ * of the plane through root, elbow and hand, in the direction of `(elbow - root) x (hand - elbow)`.
31
+ */
32
+ export interface LinkHullOptions {
33
+ /** The hull to move. The solver owns its transform; do not list it in the colliders. */
34
+ hull: ConvexHullVolume;
35
+ /** Local position of the link's start joint. Defaults to the local origin. */
36
+ origin?: Vec3View;
37
+ /** Local direction from the link's start joint toward its end joint. Defaults to +Y, as in a glTF bone. */
38
+ axis?: Vec3View;
39
+ /** Local direction of the elbow's hinge axis; need not be square to `axis`. Defaults to +X. */
40
+ hinge?: Vec3View;
41
+ }
42
+ /** Options of AvoidanceSolver: the colliders, clearances, damping, iteration limit and tolerance. */
43
+ export interface AvoidanceSolverOptions {
44
+ colliders?: readonly ConstraintVolume[];
45
+ minClearance?: number;
46
+ complianceMargin?: number;
47
+ targetRadius?: number;
48
+ /** Exponential smoothing time constant in seconds; zero disables smoothing. */
49
+ damping?: number;
50
+ maxIterations?: number;
51
+ /** Numerical acceptance tolerance in scene units. Defaults to 1e-6. */
52
+ tolerance?: number;
53
+ /** null explicitly excludes the upper link (for an attachment within a torso). */
54
+ upperArmRadius?: number | null;
55
+ /** Length excluded from the root end of the checked upper link. Defaults to zero. */
56
+ rootExclusion?: number;
57
+ /**
58
+ * Upper link and forearm hulls, in that order; leave either out for its capsule. An upper link hull takes the place
59
+ * of `upperArmRadius` and `rootExclusion`, so setting those as well throws.
60
+ */
61
+ links?: readonly [(LinkHullOptions | null)?, (LinkHullOptions | null)?];
62
+ }
63
+ /**
64
+ * Outcome of resolving a target: whether it resolved, the clearance, the deepest penetration and the iterations used.
65
+ */
66
+ export interface TargetResult {
67
+ resolved: boolean;
68
+ clearance: number;
69
+ maxPenetration: number;
70
+ iterations: number;
71
+ }
72
+ /** Outcome of a solve: status, the resolved target and elbow positions and the pole angle. */
73
+ export interface SolveResult extends TargetResult {
74
+ status: SolveStatus;
75
+ targetResolved: boolean;
76
+ target: Float32Array;
77
+ elbow: Float32Array;
78
+ poleAngle: number;
79
+ /** Alias of poleAngle for adapters using the earlier draft terminology. */
80
+ poleAngleOffset: number;
81
+ }
82
+ /**
83
+ * Outcome of searching the pole angle for clearance: the elbow and pole positions, their offset, the clearance and the iterations used.
84
+ */
85
+ export interface PoleClearanceResult {
86
+ resolved: boolean;
87
+ elbow: Float32Array;
88
+ pole: Float32Array;
89
+ poleAngleOffset: number;
90
+ clearance: number;
91
+ iterations: number;
92
+ }
93
+ /** Writes the elbow position for a root, a target and a pole angle into `outElbow`. */
94
+ export type ElbowEvaluator = (root: Vec3View, target: Vec3View, poleAngle: number, outElbow: Float32Array) => void;
95
+ /** Pure test of one candidate pose. Inputs are borrowed scratch copies; return false to reject its joint limits. */
96
+ export type PosePredicate = (root: Vec3View, elbow: Vec3View, target: Vec3View, poleAngle: number) => boolean;
97
+ /**
98
+ * One stateful solver per chain. Volumes and all coordinates share one coordinate frame.
99
+ * Results and their buffers are reused; copy them if retaining a previous result.
100
+ *
101
+ * Success certifies static proxy clearance at the evaluated instant, within tolerance.
102
+ * It does not certify swept-volume clearance between frames, arbitrary joint limits,
103
+ * physical robot safety, or clearance of geometry outside the supplied proxies.
104
+ */
105
+ export declare class AvoidanceSolver {
106
+ private readonly volumes;
107
+ readonly minClearance: number;
108
+ readonly complianceMargin: number;
109
+ readonly targetRadius: number;
110
+ readonly damping: number;
111
+ readonly maxIterations: number;
112
+ readonly tolerance: number;
113
+ readonly rootExclusion: number;
114
+ private readonly upperArmRadius;
115
+ private readonly upperHull;
116
+ private readonly forearmHull;
117
+ private readonly linkMatrix;
118
+ private readonly linkFrame;
119
+ private readonly measured;
120
+ private readonly surface;
121
+ private readonly normal;
122
+ private readonly distance;
123
+ private readonly poseDistance;
124
+ private readonly solveInputs;
125
+ private readonly poleArguments;
126
+ private readonly segmentResult;
127
+ private readonly point;
128
+ private readonly previousTarget;
129
+ private readonly candidate;
130
+ private readonly filterElbow;
131
+ private poseFilter?;
132
+ private readonly callbackRoot;
133
+ private readonly callbackTarget;
134
+ private readonly bestElbow;
135
+ private readonly boundedElbow;
136
+ private readonly trim;
137
+ private readonly root;
138
+ private readonly hand;
139
+ private readonly raw;
140
+ private readonly target;
141
+ private readonly outputTarget;
142
+ private hasTarget;
143
+ private hasPole;
144
+ private previousPole;
145
+ private busy;
146
+ private targetClearance;
147
+ private targetIterations;
148
+ private singular;
149
+ private bestAngle;
150
+ private bestClearance;
151
+ private searchIterations;
152
+ private rotationX;
153
+ private rotationY;
154
+ private rotationZ;
155
+ private radialX;
156
+ private radialY;
157
+ private radialZ;
158
+ private crossX;
159
+ private crossY;
160
+ private crossZ;
161
+ private readonly poleResult;
162
+ readonly targetResult: TargetResult;
163
+ private readonly result;
164
+ constructor(volumes?: readonly ConstraintVolume[], options?: AvoidanceSolverOptions);
165
+ constructor(options?: AvoidanceSolverOptions);
166
+ private checkVolume;
167
+ addVolume(volume: ConstraintVolume): void;
168
+ /** Clear both target and swivel history after a teleport or change of pole convention. */
169
+ reset(): void;
170
+ private enter;
171
+ private copyInput;
172
+ private evaluateInto;
173
+ /** The point's clearance from every volume, into `targetClearance`. */
174
+ private updateTargetClearance;
175
+ /** The distance from `from` (root or elbow) to `to`, into `measured`. */
176
+ private measure;
177
+ private clampReach;
178
+ private project;
179
+ /** Target-only projection; it does not check reach, links, or motion between frames. */
180
+ resolveTarget(rawTarget: Vec3View, dt: number): Float32Array;
181
+ private segmentInto;
182
+ /**
183
+ * The bend-plane normal for this pose goes to `linkFrame`. A straight chain has none, and the search never accepts
184
+ * one (the reach margin keeps it out), so any axis across the chain serves; this one is repeatable.
185
+ */
186
+ private bendNormal;
187
+ /** Moves a link hull onto segment start-end and writes the worst gap to the colliders into `distance`. */
188
+ private linkGapInto;
189
+ private poseClearanceInto;
190
+ private testPoseInto;
191
+ private search;
192
+ /**
193
+ * dt is caller supplied in seconds and must be positive. The callback must use a
194
+ * stable pole-angle convention across calls and write a valid two-bone elbow.
195
+ * No callback should commit transforms; commit only a successful returned pose.
196
+ *
197
+ * Success describes this discrete endpoint pose, not a continuous trajectory.
198
+ */
199
+ solve(rootPos: Vec3View, currentHandPos: Vec3View, rawTarget: Vec3View, upperArmLen: number, forearmLen: number, elbowRadius: number, forearmRadius: number, dt: number, evaluateElbowIK: ElbowEvaluator, options?: SolveOptions): SolveResult;
200
+ private readonly rotateElbow;
201
+ /** Geometric swivel of an already solved pose; this helper does not apply temporal limits. */
202
+ calculatePoleClearance(root: Vec3View, elbow: Vec3View, end: Vec3View, radius: number): PoleClearanceResult;
203
+ }
@@ -0,0 +1,48 @@
1
+ import type { ConstraintVolume, Vec3View } from './types.js';
2
+ /** A joint position in the common world frame. */
3
+ export type ChainPoint = [number, number, number];
4
+ /** Bounded, static obstacle-aware IK settings. */
5
+ export interface ChainOptions {
6
+ /** Position solver. Default 'fabrik'. */
7
+ algorithm?: 'ccd' | 'fabrik';
8
+ /** Capsule radius, shared or one per link. Default 0. */
9
+ radius?: number | readonly number[];
10
+ /** Required gap beyond the capsule radii. Default 0. */
11
+ minClearance?: number;
12
+ /** Target and link-length tolerance in world units. Default 1e-5. */
13
+ tolerance?: number;
14
+ /** Maximum sweeps per candidate, 1..1024. Default 64. */
15
+ iterations?: number;
16
+ /** Maximum deterministic bend seeds and swivel candidates, 1..256. Default 32. */
17
+ candidates?: number;
18
+ /** Optional legal-pose test, called before accepting any candidate. Default none. */
19
+ acceptPose?: (joints: readonly ChainPoint[]) => boolean;
20
+ }
21
+ /** Owned output; failed solves return the unchanged input pose and never claim clearance. */
22
+ export interface ChainResult {
23
+ /** A reachable, length-preserving pose passed every obstacle and pose test. */
24
+ resolved: boolean;
25
+ /** Joint positions; safe to retain across calls. */
26
+ joints: ChainPoint[];
27
+ /** End-to-target distance of the returned pose. */
28
+ distance: number;
29
+ /** Smallest checked static gap, or -Infinity on failure. */
30
+ clearance: number;
31
+ /** Candidates examined. A failure is not a proof of infeasibility. */
32
+ candidates: number;
33
+ }
34
+ /**
35
+ * N-link CCD or FABRIK with bounded deterministic redundancy search and complete capsule clearance checks.
36
+ * Queries the existing capsule, hull, mesh and SDF volume protocol; no physics or renderer is loaded.
37
+ * Candidate rotations preserve every length. Nonlinear searches may fail despite an existing solution.
38
+ */
39
+ export declare class ChainAvoidanceSolver {
40
+ private readonly volumes;
41
+ private readonly options;
42
+ /** Copies the collider list and settings; moving volumes themselves remain live. */
43
+ constructor(volumes?: readonly ConstraintVolume[], options?: ChainOptions);
44
+ /** Returns an owned accepted pose, or the input unchanged. Never mutates caller joints or targets. */
45
+ solve(initial: readonly Vec3View[], target: Vec3View): ChainResult;
46
+ }
47
+ /** Adapter for Animator FullBodyLimb.avoidance; a rejected search returns null for atomic body rollback. */
48
+ export declare function createLimbAvoidance(solver: ChainAvoidanceSolver): (joints: readonly ChainPoint[]) => ChainPoint | null;
package/dist/chain.js ADDED
@@ -0,0 +1,159 @@
1
+ import { n as e } from "./errors-D5_2oB8I.js";
2
+ import { t } from "./validate-vector-7JTvvTtJ.js";
3
+ //#region src/chain.ts
4
+ var n = (e) => e.map((e) => [
5
+ e[0],
6
+ e[1],
7
+ e[2]
8
+ ]), r = (e, t) => [
9
+ e[0] - t[0],
10
+ e[1] - t[1],
11
+ e[2] - t[2]
12
+ ], i = (e, t) => e[0] * t[0] + e[1] * t[1] + e[2] * t[2], a = (e, t) => [
13
+ e[1] * t[2] - e[2] * t[1],
14
+ e[2] * t[0] - e[0] * t[2],
15
+ e[0] * t[1] - e[1] * t[0]
16
+ ], o = (e) => Math.hypot(e[0], e[1], e[2]), s = (e, t) => o(r(e, t)), c = (e) => {
17
+ let t = o(e);
18
+ return t > 1e-14 ? [
19
+ e[0] / t,
20
+ e[1] / t,
21
+ e[2] / t
22
+ ] : [
23
+ 1,
24
+ 0,
25
+ 0
26
+ ];
27
+ };
28
+ function l(e, t, n) {
29
+ let r = Math.cos(n), o = Math.sin(n), s = i(e, t) * (1 - r), c = a(t, e);
30
+ return [
31
+ e[0] * r + c[0] * o + t[0] * s,
32
+ e[1] * r + c[1] * o + t[1] * s,
33
+ e[2] * r + c[2] * o + t[2] * s
34
+ ];
35
+ }
36
+ function u(e, t, n) {
37
+ let s = a(t, n), c = 0, l = 0, u = 0, d = 0, f = 0, p = 0;
38
+ for (let t = 1; t < e.length - 1; t++) {
39
+ let a = r(e[t], e[0]), m = i(a, n), h = i(a, s), g = Math.hypot(m, h);
40
+ c += m, l += h, p = Math.max(p, o(a)), g > u && (u = g, d = m, f = h);
41
+ }
42
+ let m = 1e-9 * p;
43
+ return Math.hypot(c, l) > m ? Math.atan2(l, c) : u > m ? Math.atan2(f, d) : NaN;
44
+ }
45
+ function d(e, t, n, i, a) {
46
+ let s = r(e[t], e[n]), l = o(s) > 1e-14 ? c(s) : c([
47
+ a[0],
48
+ a[1],
49
+ a[2]
50
+ ]);
51
+ for (let r = 0; r < 3; r++) e[t][r] = e[n][r] + l[r] * i;
52
+ }
53
+ function f(e, t, n, u, f, p) {
54
+ let m = [...e[0]], h = e.length - 1;
55
+ for (let g = 0; g < f && s(e[h], t) > p; g++) if (u === "fabrik") {
56
+ e[h] = [
57
+ t[0],
58
+ t[1],
59
+ t[2]
60
+ ];
61
+ for (let t = h - 1; t >= 0; t--) d(e, t, t + 1, n[t], [
62
+ -1,
63
+ 0,
64
+ 0
65
+ ]);
66
+ e[0] = [...m];
67
+ for (let t = 1; t <= h; t++) d(e, t, t - 1, n[t - 1], [
68
+ 1,
69
+ 0,
70
+ 0
71
+ ]);
72
+ } else for (let n = h - 1; n >= 0; n--) {
73
+ let s = c(r(e[h], e[n])), u = c(r(t, e[n])), d = a(s, u);
74
+ o(d) < 1e-12 && (d = a(s, Math.abs(s[0]) < .8 ? [
75
+ 1,
76
+ 0,
77
+ 0
78
+ ] : [
79
+ 0,
80
+ 1,
81
+ 0
82
+ ])), d = c(d);
83
+ let f = Math.acos(Math.max(-1, Math.min(1, i(s, u))));
84
+ for (let t = n + 1; t <= h; t++) {
85
+ let i = l(r(e[t], e[n]), d, f);
86
+ for (let r = 0; r < 3; r++) e[t][r] = e[n][r] + i[r];
87
+ }
88
+ }
89
+ }
90
+ var p = class {
91
+ constructor(t = [], n = {}) {
92
+ this.volumes = [...t], this.options = {
93
+ ...n,
94
+ radius: Array.isArray(n.radius) ? [...n.radius] : n.radius
95
+ };
96
+ let { algorithm: r = "fabrik", minClearance: i = 0, tolerance: a = 1e-5, iterations: o = 64, candidates: s = 32 } = n;
97
+ if (!["ccd", "fabrik"].includes(r) || !(i >= 0 && Number.isFinite(i)) || !(a > 0 && Number.isFinite(a)) || !Number.isInteger(o) || o < 1 || o > 1024 || !Number.isInteger(s) || s < 1 || s > 256 || n.acceptPose !== void 0 && typeof n.acceptPose != "function") throw e("Invalid chain settings; choose CCD or FABRIK, finite gaps and bounded iteration counts", "kinematics");
98
+ }
99
+ solve(i, o) {
100
+ if (i.length < 2 || i.length > 257) throw e("Supply 2..257 chain joints", "kinematics");
101
+ i.forEach((e) => t(e, "chain joint")), t(o, "chain target");
102
+ let { algorithm: p = "fabrik", minClearance: m = 0, tolerance: h = 1e-5, iterations: g = 64, candidates: _ = 32, acceptPose: v } = this.options, y = i.slice(1).map((e, t) => s(e, i[t]));
103
+ if (y.some((e) => !(e > 1e-12 && e < 1e50))) throw e("Supply nonzero chain lengths below 1e50", "kinematics");
104
+ let b = this.options.radius ?? 0, x = typeof b == "number" ? y.map(() => b) : [...b];
105
+ if (x.length !== y.length || x.some((e) => !(e >= 0 && Number.isFinite(e)))) throw e("Supply a finite nonnegative radius for every link", "kinematics");
106
+ let S = (e) => ({
107
+ resolved: !1,
108
+ joints: n(i),
109
+ distance: s(i.at(-1), o),
110
+ clearance: -Infinity,
111
+ candidates: e
112
+ });
113
+ if (s(i[0], o) > y.reduce((e, t) => e + t, 0) + h) return S(0);
114
+ let C = c(r(o, i[0])), w = c(a(C, Math.abs(C[0]) < .8 ? [
115
+ 1,
116
+ 0,
117
+ 0
118
+ ] : [
119
+ 0,
120
+ 1,
121
+ 0
122
+ ])), T = 0;
123
+ for (let e = 0; e < _; e++) {
124
+ let t = n(i), a = 2 * Math.PI * e / _;
125
+ if (e > 0) for (let e = 1; e < t.length - 1; e++) {
126
+ let n = l(w, C, a), r = y.reduce((e, t) => e + t, 0) * .15 * Math.sin(Math.PI * e / (t.length - 1));
127
+ for (let i = 0; i < 3; i++) t[e][i] += n[i] * r;
128
+ }
129
+ if (e > 0) for (let e = 1; e < t.length; e++) d(t, e, e - 1, y[e - 1], r(i[e], i[e - 1]));
130
+ if (f(t, o, y, p, g, h), s(t.at(-1), o) > h) continue;
131
+ let c = u(t, C, w);
132
+ if (e === 0) T = Number.isNaN(c) ? 0 : c;
133
+ else if (!Number.isNaN(c)) for (let e = 1; e < t.length - 1; e++) {
134
+ let n = l(r(t[e], t[0]), C, T + a - c);
135
+ for (let r = 0; r < 3; r++) t[e][r] = t[0][r] + n[r];
136
+ }
137
+ if (y.some((e, n) => Math.abs(s(t[n], t[n + 1]) - e) > h)) continue;
138
+ let b = Infinity, S = /* @__PURE__ */ new Float64Array(1);
139
+ for (let e = 0; e < y.length; e++) for (let n of this.volumes) n.segmentClearanceInto ? n.segmentClearanceInto(t[e], t[e + 1], x[e], S) : S[0] = n.segmentClearance(t[e], t[e + 1], x[e]), b = Math.min(b, Number.isFinite(S[0]) ? S[0] : -Infinity);
140
+ if (!(b < m || v && !v(n(t)))) return {
141
+ resolved: !0,
142
+ joints: t,
143
+ distance: s(t.at(-1), o),
144
+ clearance: b,
145
+ candidates: e + 1
146
+ };
147
+ }
148
+ return S(_);
149
+ }
150
+ };
151
+ function m(t) {
152
+ return (n) => {
153
+ if (n.length !== 3) throw e("Full-body limb avoidance needs exactly three joints", "kinematics");
154
+ let r = t.solve(n, n[2]);
155
+ return r.resolved ? r.joints[1] : null;
156
+ };
157
+ }
158
+ //#endregion
159
+ export { p as ChainAvoidanceSolver, m as createLimbAvoidance };
@@ -0,0 +1,7 @@
1
+ //#region ../shared/errors.js
2
+ var e = (e, t) => Object.assign(Error(t), {
3
+ name: "MargoError",
4
+ code: e
5
+ }), t = (e, t) => `${e}; see https://margoengine.com/errors#${t}`, n = (e, n) => TypeError(t(e, n)), r = (e, n) => RangeError(t(e, n));
6
+ //#endregion
7
+ export { r as n, n as r, e as t };