@margoengine/ragdoll 0.1.0 → 1.0.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,200 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { Mesh } from '@margoengine/core/extension';
3
+ // @ts-ignore optional peer: its types apply when it is installed
4
+ import type { Animator } from '@margoengine/animator';
5
+ import type { CharacterController, CharacterDebugOptions, CharacterMoveFilter, CharacterMoveResult, DebugLines, DynamicCharacter, PhysicsBody } from '@margoengine/physics';
6
+ import { type GetUp, type GetUpOptions, type GetUpSide } from './getup.js';
7
+ import { type RagdollMotorOptions, type RagdollMotors } from './powered.js';
8
+ import type { Ragdoll, RagdollDebugOptions, RagdollLimb, RagdollPart } from './ragdoll.js';
9
+ /** Lifecycle state of a {@link CharacterRagdoll}. */
10
+ export type CharacterRagdollState = 'walking' | 'ragdoll' | 'recovering';
11
+ /** Options of {@link addCharacterRagdoll}. */
12
+ export interface CharacterRagdollOptions {
13
+ /** Kinematic `CharacterController` or dynamic `DynamicCharacter` driving locomotion. */
14
+ controller: CharacterController | DynamicCharacter;
15
+ /** Ragdoll attached to the same `Physics` world and skeleton. */
16
+ ragdoll: Ragdoll;
17
+ /** Optional animator controlling the character's clips (required if `getUp` is passed as options). */
18
+ animator?: Animator;
19
+ /** Optional pre-created `RagdollMotors`, or options to create one automatically. */
20
+ motors?: RagdollMotors | RagdollMotorOptions;
21
+ /** Optional pre-created `GetUp`, or options to create one automatically (requires `animator`). */
22
+ getUp?: GetUp | GetUpOptions;
23
+ /**
24
+ * Top-level visual mesh moved with the character controller while walking. Defaults to `animator.animation.model.root`
25
+ * when an animator is provided, or `controller.body.mesh` if set.
26
+ */
27
+ root?: Mesh;
28
+ /**
29
+ * Offset from `controller.body.position` to `root` world position while walking (e.g. `[0, -0.9, 0]` when a capsule's
30
+ * center is 0.9 m above the feet). Defaults to the initial `root.position - controller.body.position` at construction.
31
+ */
32
+ rootOffset?: readonly [number, number, number];
33
+ /**
34
+ * Collision group index (0..15) assigned to the character controller's capsule so it never collides with its own
35
+ * ragdoll hitboxes while still colliding with the world. Default 14 (group 15 is the ragdoll's default).
36
+ */
37
+ characterGroup?: number;
38
+ /** World up unit vector. Default `[0, 1, 0]`. */
39
+ up?: readonly [number, number, number];
40
+ }
41
+ /** Options of {@link CharacterRagdoll.knockdown}. */
42
+ export interface CharacterKnockdownOptions {
43
+ /** World point where the impact impulse lands. Default the struck bone's centre of mass. */
44
+ point?: readonly [number, number, number];
45
+ /**
46
+ * When given, activates only that limb (partial ragdoll) and keeps the character walking instead of disabling the
47
+ * controller. Omit for a full-body knockdown.
48
+ */
49
+ limb?: RagdollLimb;
50
+ /** Motor strength while knocked down (when `motors` is present). Default 0 (full limp). */
51
+ motorStrength?: number;
52
+ /** Share of motor strength weakened on a partial-ragdoll hit. Default 0.8. */
53
+ weaken?: number;
54
+ /** Seconds for a partial-ragdoll hit to recover motor strength. Default 0.6. */
55
+ recover?: number;
56
+ }
57
+ /** Options of {@link CharacterRagdoll.recover}. */
58
+ export interface CharacterRecoverOptions {
59
+ /** Force `'faceUp'` or `'faceDown'` get-up clip instead of picking automatically. */
60
+ side?: GetUpSide;
61
+ /** Blend duration in seconds when recovering without a `GetUp` clip. Default 0.4. */
62
+ blend?: number;
63
+ /** Motor strength to restore once recovery finishes (when `motors` is present). Default the strength before knockdown. */
64
+ motorStrength?: number;
65
+ /** Cancels waiting on recovery; rejects the promise with `signal.reason`. */
66
+ signal?: AbortSignal;
67
+ }
68
+ /** Result returned when {@link CharacterRagdoll.recover} finishes. */
69
+ export interface CharacterRecoverResult {
70
+ /** The get-up clip chosen, or `null` when recovered via direct ragdoll blend without `GetUp`. */
71
+ side: GetUpSide | null;
72
+ /** Root orientation mismatch in radians reported by `GetUp`, or 0 without `GetUp`. */
73
+ mismatch: number;
74
+ /** World position the controller capsule settled onto. */
75
+ capsulePosition: [number, number, number];
76
+ }
77
+ /** Combined debug render options for {@link CharacterRagdoll.debugRender}. */
78
+ export interface CharacterRagdollDebugOptions {
79
+ /** Controller debug options, or `false` to hide the controller overlay. */
80
+ controller?: boolean | CharacterDebugOptions;
81
+ /** Ragdoll debug options, or `false` to hide the ragdoll overlay. */
82
+ ragdoll?: boolean | RagdollDebugOptions;
83
+ }
84
+ /**
85
+ * First-class bridge between a physics character controller (`CharacterController` or `DynamicCharacter`) and a
86
+ * {@link Ragdoll} (plus optional {@link Animator}, {@link RagdollMotors}, and {@link GetUp}).
87
+ *
88
+ * - Automatically isolates collision groups so the character capsule never self-collides with its own ragdoll hitboxes
89
+ * while still interacting with floors, slopes, stairs, moving platforms, and pushable crates.
90
+ * - `knockdown()` carries walking momentum into a full ragdoll (disabling controller sweep while limp) or triggers a
91
+ * partial-limb hit while walking continues.
92
+ * - `recover()` relocates the controller capsule onto the ground beneath `ragdoll.rootPosition`, blends smoothly out of
93
+ * ragdoll (through `GetUp` when available), and re-enables locomotion with zero pop.
94
+ */
95
+ export declare class CharacterRagdoll {
96
+ /** The linked kinematic or dynamic character controller. */
97
+ readonly controller: CharacterController | DynamicCharacter;
98
+ /** The linked ragdoll. */
99
+ readonly ragdoll: Ragdoll;
100
+ /** The optional animator. */
101
+ readonly animator: Animator | null;
102
+ /** The optional ragdoll motors (passed in or created automatically). */
103
+ readonly motors: RagdollMotors | null;
104
+ /** The optional get-up helper (passed in or created automatically). */
105
+ readonly getUp: GetUp | null;
106
+ /** Visual root mesh synced with the controller while walking, if any. */
107
+ readonly root: Mesh | null;
108
+ /** Packed collision groups assigned to the character controller's colliders. */
109
+ readonly characterGroups: number;
110
+ private currentState;
111
+ private readonly up;
112
+ private readonly rootOffset;
113
+ private readonly ownsMotors;
114
+ private readonly ownsGetUp;
115
+ private readonly ragdollBodies;
116
+ private readonly savedGroups;
117
+ private readonly offAfterStep;
118
+ private savedMotorStrength;
119
+ private pendingRecovery?;
120
+ private disposed;
121
+ /** @internal use {@link addCharacterRagdoll}. */
122
+ constructor(options: CharacterRagdollOptions);
123
+ /** Current lifecycle state: `'walking'`, `'ragdoll'`, or `'recovering'`. */
124
+ get state(): CharacterRagdollState;
125
+ /** Whether the character is currently standing on ground (false while knocked down or recovering). */
126
+ get grounded(): boolean;
127
+ /** The body the character is standing on, or null while airborne, knocked down, or recovering. */
128
+ get platform(): PhysicsBody | null;
129
+ /**
130
+ * Moves a kinematic `CharacterController` for one fixed step while `'walking'`, automatically excluding this
131
+ * character's own ragdoll hitboxes from the sweep. No-op returning zero movement while `'ragdoll'` or `'recovering'`.
132
+ * @throws TypeError if constructed with a `DynamicCharacter` instead of a `CharacterController`.
133
+ */
134
+ move(desired: readonly [number, number, number], filter?: CharacterMoveFilter): CharacterMoveResult;
135
+ /**
136
+ * Sets target velocity on a `DynamicCharacter` while `'walking'` (ignored while `'ragdoll'` or `'recovering'`).
137
+ * @throws TypeError if constructed with a kinematic `CharacterController`.
138
+ */
139
+ setTargetVelocity(velocity: readonly [number, number, number]): this;
140
+ /**
141
+ * Requests a jump on a `DynamicCharacter` while `'walking'`. Returns false while knocked down or recovering.
142
+ * @throws TypeError if constructed with a kinematic `CharacterController`.
143
+ */
144
+ jump(speed: number): boolean;
145
+ /**
146
+ * Steps a `DynamicCharacter` controller before the physics step while `'walking'` (no-op while `'ragdoll'` or `'recovering'`).
147
+ * @throws TypeError if constructed with a kinematic `CharacterController`.
148
+ */
149
+ update(): void;
150
+ /**
151
+ * Transitions to full ragdoll (default) or triggers a partial-limb ragdoll hit (`options.limb`).
152
+ *
153
+ * - Full knockdown: disables the controller body so its standing capsule never obstructs the fall, activates the ragdoll
154
+ * (each limp bone keeps the velocity the walk gave its hit box, so the fall carries the walking momentum), and applies
155
+ * `impulse` to `bone` (defaults to the root bone).
156
+ * - Partial knockdown (`options.limb` set): activates only the specified limb and applies `impulse` while the
157
+ * character continues walking under controller locomotion.
158
+ */
159
+ knockdown(bone?: Mesh | RagdollPart, impulse?: readonly [number, number, number], options?: CharacterKnockdownOptions): this;
160
+ /**
161
+ * True when knocked down and every limp bone has slowed below `linearSpeed` (default 0.15 m/s) and `angularSpeed`
162
+ * (default 0.3 rad/s), ready for {@link CharacterRagdoll.recover}.
163
+ */
164
+ isSettled(linearSpeed?: number, angularSpeed?: number): boolean;
165
+ /**
166
+ * Recovers from a full knockdown: finds the ground under `ragdoll.rootPosition`, relocates the controller capsule
167
+ * there, blends back into animation (through `GetUp` if provided, or `ragdoll.deactivate(blend)`), and re-enables the
168
+ * controller with zero pop once standing.
169
+ * @throws MargoError with code `state` if the character is not currently in `'ragdoll'` state.
170
+ */
171
+ recover(options?: CharacterRecoverOptions): Promise<CharacterRecoverResult>;
172
+ /**
173
+ * Combined debug lines for the character controller (while walking) and the ragdoll (always, tinted by mode).
174
+ */
175
+ debugRender(options?: CharacterRagdollDebugOptions): DebugLines;
176
+ private resolveBone;
177
+ private groundBeneath;
178
+ private placeController;
179
+ private setControllerEnabled;
180
+ private onAfterStep;
181
+ private waitForBlend;
182
+ private cancelPendingRecovery;
183
+ private live;
184
+ /**
185
+ * Detaches the bridge, restores original collision groups on live colliders, re-enables the controller body, and
186
+ * disposes any `motors` or `getUp` instances it created internally. Safe to call twice.
187
+ */
188
+ dispose(): void;
189
+ [Symbol.dispose]: () => void;
190
+ }
191
+ /**
192
+ * Links a character controller (`CharacterController` or `DynamicCharacter`) with a {@link Ragdoll} (and optional
193
+ * {@link Animator}, {@link RagdollMotors}, and {@link GetUp}): isolates collision groups, disables controller sweep
194
+ * while limp, and recovers smoothly from the settled hips position back into walking with zero pop.
195
+ * @example
196
+ * const bridge = addCharacterRagdoll({ controller, ragdoll, animator, getUp: { faceUp: 'back', faceDown: 'front' } });
197
+ * bridge.knockdown(head, [0, 2, -40]);
198
+ * await bridge.recover();
199
+ */
200
+ export declare function addCharacterRagdoll(options: CharacterRagdollOptions): CharacterRagdoll;
@@ -0,0 +1,325 @@
1
+ import { t as e } from "./errors-CDwcEs-j.js";
2
+ import { addRagdollMotors as t } from "./powered.js";
3
+ import { addGetUp as n } from "./getup.js";
4
+ import { MargoError as r } from "@margoengine/math/errors";
5
+ //#region src/character.ts
6
+ function i(e) {
7
+ return typeof e.move == "function";
8
+ }
9
+ function a(e) {
10
+ return typeof e.hit == "function" && typeof e.fade == "function";
11
+ }
12
+ function o(e) {
13
+ return typeof e.start == "function" && typeof e.pick == "function";
14
+ }
15
+ function s(e, t) {
16
+ return ((e & 65535) << 16 | t & 65535) >>> 0;
17
+ }
18
+ function c(e, t) {
19
+ if (!e.vertices.length) return t;
20
+ if (!t.vertices.length) return e;
21
+ let n = new Float32Array(e.vertices.length + t.vertices.length), r = new Float32Array(e.colors.length + t.colors.length);
22
+ return n.set(e.vertices, 0), n.set(t.vertices, e.vertices.length), r.set(e.colors, 0), r.set(t.colors, e.colors.length), {
23
+ vertices: n,
24
+ colors: r
25
+ };
26
+ }
27
+ var l = class {
28
+ constructor(r) {
29
+ if (this.currentState = "walking", this.savedGroups = /* @__PURE__ */ new Map(), this.savedMotorStrength = 1, this.disposed = !1, !r?.controller?.body || !r.ragdoll?.bones) throw e("addCharacterRagdoll needs { controller, ragdoll }; pass a CharacterController or DynamicCharacter and a Ragdoll.");
30
+ this.controller = r.controller, this.ragdoll = r.ragdoll, this.animator = r.animator ?? null;
31
+ let c = r.up ?? [
32
+ 0,
33
+ 1,
34
+ 0
35
+ ], l = Math.hypot(c[0], c[1], c[2]);
36
+ if (!(l > 0) || !Number.isFinite(l)) throw e("CharacterRagdoll up must be a nonzero finite [x, y, z]; pass e.g. [0, 1, 0].");
37
+ if (this.up = [
38
+ c[0] / l,
39
+ c[1] / l,
40
+ c[2] / l
41
+ ], this.root = r.root ?? this.animator?.animation.model.root ?? this.controller.body.mesh ?? null, r.rootOffset) {
42
+ if (r.rootOffset.length !== 3 || !r.rootOffset.every(Number.isFinite)) throw e("CharacterRagdoll rootOffset must be three finite numbers [x, y, z].");
43
+ this.rootOffset = [
44
+ r.rootOffset[0],
45
+ r.rootOffset[1],
46
+ r.rootOffset[2]
47
+ ];
48
+ } else if (this.root) {
49
+ this.root.engine.store.tick(!1);
50
+ let e = this.root.matrix, t = this.controller.body.position;
51
+ this.rootOffset = [
52
+ e[12] - t[0],
53
+ e[13] - t[1],
54
+ e[14] - t[2]
55
+ ];
56
+ } else this.rootOffset = [
57
+ 0,
58
+ 0,
59
+ 0
60
+ ];
61
+ if (r.motors ? (a(r.motors) ? (this.motors = r.motors, this.ownsMotors = !1) : (this.motors = t(this.ragdoll, r.motors), this.ownsMotors = !0), this.savedMotorStrength = this.motors.strength) : (this.motors = null, this.ownsMotors = !1), r.getUp) {
62
+ if (o(r.getUp)) this.getUp = r.getUp, this.ownsGetUp = !1;
63
+ else {
64
+ if (!this.animator) throw e("CharacterRagdoll getUp options need an animator; pass { animator, getUp: { faceUp, faceDown } }.");
65
+ this.getUp = n(this.ragdoll, this.animator, {
66
+ root: this.root ?? void 0,
67
+ up: this.up,
68
+ ...r.getUp
69
+ }), this.ownsGetUp = !0;
70
+ }
71
+ } else this.getUp = null, this.ownsGetUp = !1;
72
+ let u = this.ragdoll.settings.collisionGroups >>> 16 & 65535, d = r.characterGroup ?? 14;
73
+ if (!Number.isInteger(d) || d < 0 || d > 15) throw e(`CharacterRagdoll characterGroup must be an integer from 0 to 15 (got ${d}).`);
74
+ if (u & 1 << d) {
75
+ let t = -1;
76
+ for (let e = 15; e >= 0; e--) if (!(u & 1 << e)) {
77
+ t = e;
78
+ break;
79
+ }
80
+ if (t < 0) throw e("Ragdoll occupies all 16 collision groups, leaving none for the character capsule; give the ragdoll a single group bit.");
81
+ d = t;
82
+ }
83
+ let f = 1 << d, p = [this.controller.body];
84
+ i(this.controller) && this.controller.innerBody && p.push(this.controller.innerBody);
85
+ let m = s(f, 65535 & ~u & ~f);
86
+ for (let e of p) for (let t of e.colliders) {
87
+ let e = t.collisionGroups();
88
+ this.savedGroups.set(t, e), m = s(f, e & 65535 & ~u & ~f), t.setCollisionGroups(m);
89
+ }
90
+ this.characterGroups = m;
91
+ let h = /* @__PURE__ */ new Set();
92
+ for (let e of this.ragdoll.bones) {
93
+ h.add(e.body);
94
+ for (let t of e.body.colliders) {
95
+ let e = t.collisionGroups();
96
+ this.savedGroups.set(t, e);
97
+ let n = e >>> 16 & 65535, r = e & 65535 & ~f;
98
+ t.setCollisionGroups(s(n, r));
99
+ }
100
+ }
101
+ this.ragdollBodies = h, this.offAfterStep = this.ragdoll.physics.on("afterstep", () => this.onAfterStep());
102
+ }
103
+ get state() {
104
+ return this.currentState;
105
+ }
106
+ get grounded() {
107
+ return this.currentState === "walking" && this.controller.grounded;
108
+ }
109
+ get platform() {
110
+ return this.currentState === "walking" ? this.controller.platform : null;
111
+ }
112
+ move(t, n) {
113
+ if (this.live(), !i(this.controller)) throw e("move() is for a kinematic CharacterController; use setTargetVelocity() and update() with a DynamicCharacter.");
114
+ if (this.currentState !== "walking") return {
115
+ movement: [
116
+ 0,
117
+ 0,
118
+ 0
119
+ ],
120
+ grounded: !1,
121
+ collisions: 0,
122
+ slidingDownSlope: !1
123
+ };
124
+ let r = n?.predicate, a = {
125
+ ...n,
126
+ groups: n?.groups ?? this.characterGroups,
127
+ predicate: (e) => !this.ragdollBodies.has(e.body) && (!r || r(e))
128
+ };
129
+ return this.controller.move(t, a);
130
+ }
131
+ setTargetVelocity(t) {
132
+ if (this.live(), i(this.controller)) throw e("setTargetVelocity() is for a DynamicCharacter; call move(desired) for a kinematic CharacterController.");
133
+ return this.currentState === "walking" && this.controller.setTargetVelocity(t), this;
134
+ }
135
+ jump(t) {
136
+ if (this.live(), i(this.controller)) throw e("jump() is for a DynamicCharacter; add vertical velocity to move() for CharacterController.");
137
+ return this.currentState === "walking" && this.controller.jump(t);
138
+ }
139
+ update() {
140
+ if (this.live(), i(this.controller)) throw e("update() is for a DynamicCharacter; call move(desired) for a kinematic CharacterController.");
141
+ this.currentState === "walking" && this.controller.update();
142
+ }
143
+ knockdown(e, t, n = {}) {
144
+ this.live();
145
+ let r = this.resolveBone(e);
146
+ return n.limb === void 0 ? (this.cancelPendingRecovery(), this.currentState = "ragdoll", this.setControllerEnabled(!1), this.ragdoll.activate(), this.motors && (this.savedMotorStrength = this.motors.strength, this.motors.strength = n.motorStrength ?? 0), t && r.body.applyImpulse(t, n.point), this) : (this.ragdoll.activate(n.limb), t && (this.motors ? this.motors.hit(r, t, {
147
+ point: n.point,
148
+ weaken: n.weaken,
149
+ recover: n.recover
150
+ }) : r.body.applyImpulse(t, n.point)), this);
151
+ }
152
+ isSettled(e = .15, t = .3) {
153
+ if (this.disposed || this.currentState !== "ragdoll") return !1;
154
+ let n = e * e, r = t * t;
155
+ for (let e of this.ragdoll.bones) {
156
+ if (!e.limp || !e.body.valid) continue;
157
+ let t = e.body.linearVelocity, i = e.body.angularVelocity;
158
+ if (t[0] * t[0] + t[1] * t[1] + t[2] * t[2] > n || i[0] * i[0] + i[1] * i[1] + i[2] * i[2] > r) return !1;
159
+ }
160
+ return !0;
161
+ }
162
+ async recover(e = {}) {
163
+ if (this.live(), this.currentState !== "ragdoll") throw new r("state", "Character is not knocked down; call knockdown() before recover().");
164
+ e.signal?.throwIfAborted(), this.currentState = "recovering";
165
+ let t = this.ragdoll.rootPosition, n = this.groundBeneath(t), i = [
166
+ n[0] - this.rootOffset[0],
167
+ n[1] - this.rootOffset[1],
168
+ n[2] - this.rootOffset[2]
169
+ ];
170
+ this.placeController(i);
171
+ let a = null, o = 0;
172
+ try {
173
+ if (this.getUp) {
174
+ let t = await this.getUp.start({
175
+ side: e.side,
176
+ signal: e.signal
177
+ });
178
+ a = t.side, o = t.mismatch;
179
+ } else {
180
+ let t = e.blend ?? .4;
181
+ this.root && (this.root.setPosition(n), this.root.engine.store.tick(!1)), this.ragdoll.deactivate(t), t > 0 && await this.waitForBlend(e.signal);
182
+ }
183
+ } catch (e) {
184
+ throw this.disposed || (this.currentState = this.ragdoll.active ? "ragdoll" : "walking"), e;
185
+ }
186
+ if (this.disposed) return {
187
+ side: a,
188
+ mismatch: o,
189
+ capsulePosition: i
190
+ };
191
+ let s = i;
192
+ if (this.root) {
193
+ this.root.engine.store.tick(!1);
194
+ let e = this.root.matrix;
195
+ s = [
196
+ e[12] - this.rootOffset[0],
197
+ e[13] - this.rootOffset[1],
198
+ e[14] - this.rootOffset[2]
199
+ ];
200
+ }
201
+ return this.placeController(s), this.setControllerEnabled(!0), this.motors && (this.motors.strength = e.motorStrength ?? this.savedMotorStrength), this.currentState = "walking", {
202
+ side: a,
203
+ mismatch: o,
204
+ capsulePosition: s
205
+ };
206
+ }
207
+ debugRender(e = {}) {
208
+ this.live();
209
+ let t = {
210
+ vertices: /* @__PURE__ */ new Float32Array(),
211
+ colors: /* @__PURE__ */ new Float32Array()
212
+ };
213
+ return c(e.controller !== !1 && this.currentState === "walking" ? this.controller.debugRender(typeof e.controller == "object" ? e.controller : void 0) : t, e.ragdoll === !1 ? t : this.ragdoll.debugRender(typeof e.ragdoll == "object" ? e.ragdoll : void 0));
214
+ }
215
+ resolveBone(t) {
216
+ if (!t) return this.ragdoll.bones[0];
217
+ if ("body" in t) {
218
+ if (!this.ragdoll.bones.includes(t)) throw e("That part does not belong to this ragdoll; pass one of ragdoll.bones.");
219
+ return t;
220
+ }
221
+ let n = this.ragdoll.part(t);
222
+ if (!n) throw e("That node is not a bone of this ragdoll; pass a node from ragdoll.bones.");
223
+ return n;
224
+ }
225
+ groundBeneath(e) {
226
+ let t = [
227
+ -this.up[0],
228
+ -this.up[1],
229
+ -this.up[2]
230
+ ], n = this.ragdoll.physics.raycast(e, t, {
231
+ maxDistance: 100,
232
+ excludeDynamic: !0,
233
+ excludeKinematic: !0,
234
+ predicate: (e) => !this.ragdollBodies.has(e) && e !== this.controller.body
235
+ });
236
+ if (n) return [
237
+ n.point[0],
238
+ n.point[1],
239
+ n.point[2]
240
+ ];
241
+ if (this.root) {
242
+ this.root.engine.store.tick(!1);
243
+ let t = this.root.matrix, n = (e) => e[0] * this.up[0] + e[1] * this.up[1] + e[2] * this.up[2], r = n([
244
+ t[12],
245
+ t[13],
246
+ t[14]
247
+ ]) - n(e);
248
+ return [
249
+ e[0] + this.up[0] * r,
250
+ e[1] + this.up[1] * r,
251
+ e[2] + this.up[2] * r
252
+ ];
253
+ }
254
+ return [
255
+ e[0],
256
+ e[1],
257
+ e[2]
258
+ ];
259
+ }
260
+ placeController(e) {
261
+ let t = this.controller.body;
262
+ t.valid && (t.setPosition(e, !1), t.type === "kinematicPosition" ? t.setNextPosition(e) : t.type === "dynamic" && (t.setLinearVelocity([
263
+ 0,
264
+ 0,
265
+ 0
266
+ ], !1), t.setAngularVelocity([
267
+ 0,
268
+ 0,
269
+ 0
270
+ ], !1)), i(this.controller) && this.controller.innerBody?.valid && (this.controller.innerBody.setPosition(e, !1), this.controller.innerBody.setNextPosition(e)));
271
+ }
272
+ setControllerEnabled(e) {
273
+ let t = this.controller.body;
274
+ if (t.valid) {
275
+ t.enabled = e;
276
+ for (let n of t.colliders) n.setEnabled(e);
277
+ }
278
+ if (i(this.controller) && this.controller.innerBody?.valid) {
279
+ this.controller.innerBody.enabled = e;
280
+ for (let t of this.controller.innerBody.colliders) t.setEnabled(e);
281
+ }
282
+ }
283
+ onAfterStep() {
284
+ if (this.disposed || this.currentState !== "walking" || !this.root || this.controller.body.mesh === this.root || !this.controller.body.valid) return;
285
+ let e = this.controller.body.position;
286
+ this.root.setPosition([
287
+ e[0] + this.rootOffset[0],
288
+ e[1] + this.rootOffset[1],
289
+ e[2] + this.rootOffset[2]
290
+ ]);
291
+ }
292
+ waitForBlend(e) {
293
+ return this.ragdoll.weight <= 0 ? Promise.resolve() : new Promise((t, n) => {
294
+ let r = () => {
295
+ a(), this.pendingRecovery = void 0, e?.removeEventListener("abort", i);
296
+ }, i = () => {
297
+ r(), n(e.reason);
298
+ }, a = this.ragdoll.physics.on("afterstep", () => {
299
+ (this.disposed || this.ragdoll.weight <= 0) && (r(), t());
300
+ });
301
+ this.pendingRecovery = r, e?.addEventListener("abort", i, { once: !0 });
302
+ });
303
+ }
304
+ cancelPendingRecovery() {
305
+ this.pendingRecovery?.(), this.pendingRecovery = void 0;
306
+ }
307
+ live() {
308
+ if (this.disposed) throw new r("disposed", "CharacterRagdoll is disposed; create a new one with addCharacterRagdoll.");
309
+ }
310
+ dispose() {
311
+ if (!this.disposed) {
312
+ this.disposed = !0, this.cancelPendingRecovery(), this.offAfterStep();
313
+ for (let [e, t] of this.savedGroups) e.valid && e.setCollisionGroups(t);
314
+ this.savedGroups.clear(), this.setControllerEnabled(!0), this.ownsMotors && this.motors?.dispose(), this.ownsGetUp && this.getUp?.dispose();
315
+ }
316
+ }
317
+ [Symbol.dispose ?? Symbol()]() {
318
+ this.dispose();
319
+ }
320
+ };
321
+ function u(e) {
322
+ return new l(e);
323
+ }
324
+ //#endregion
325
+ export { l as CharacterRagdoll, u as addCharacterRagdoll };
@@ -0,0 +1,5 @@
1
+ import { MargoError as e } from "@margoengine/math/errors";
2
+ //#region src/errors.ts
3
+ var t = (t) => new e("unsupported", `${t} See https://margoengine.com/errors#ragdolls`);
4
+ //#endregion
5
+ export { t };
@@ -0,0 +1,3 @@
1
+ import { MargoError } from '@margoengine/math/errors';
2
+ /** A coded error for bad input to a ragdoll, its debug lines or its character bridge, linked to its help entry. */
3
+ export declare const ragdollError: (message: string) => MargoError;