@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.
package/README.md CHANGED
@@ -1,381 +1,431 @@
1
- # @margoengine/ragdoll
2
-
3
- Import `margoengine/ragdoll` from the `margoengine` package, or `@margoengine/ragdoll` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
-
5
- Ragdolls for animated characters, on `@margoengine/physics`. Give it the hips of a skeleton and it builds one
6
- capsule body per bone, joined at the bone origins with swing and twist limits. While the character is animated the
7
- bodies follow the bones as kinematic hit boxes that push the world; `activate()` makes it limp, keeping the momentum the
8
- animation gave each bone; `deactivate(seconds)` blends the bones back to the animation. Core and physics stay the same
9
- size: an app that does not import this package ships none of it.
10
-
11
- ```ts
12
- import { EngineKernel } from 'margoengine/core';
13
- import { loadGLTF } from 'margoengine/gltf/pbr';
14
- import { Animation } from 'margoengine/animation';
15
- import { Animator } from 'margoengine/animator';
16
- import { Physics } from 'margoengine/physics';
17
- import { Ragdoll } from 'margoengine/ragdoll';
18
-
19
- await Physics.load();
20
- const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!);
21
- const physics = new Physics(engine);
22
- physics.addBody(null, { type: 'fixed', colliders: { shape: 'box', halfExtents: [20, 0.1, 20] } });
23
- const model = await loadGLTF(engine, '/Rig_Medium_MovementBasic.glb'); // KayKit's skinned mannequin (CC0), with a Running_A clip
24
- Animator.attach(Animation.attach(model), { initial: 'run', states: { run: 'Running_A' } });
25
-
26
- // After the Animator, so it runs after the animation each frame.
27
- const hips = model.nodes.find((node) => node.name === 'hips')!;
28
- const ragdoll = Ragdoll.attach(physics, { root: hips });
29
-
30
- // A hit: go limp and push the bone that was struck.
31
- const head = ragdoll.bones.find((part) => part.node.name === 'head');
32
- ragdoll.activate();
33
- head?.body.applyImpulse([0, 2, -30]);
34
-
35
- // Two seconds later, get up: hand the bones back to the animation over half a second.
36
- setTimeout(() => ragdoll.deactivate(0.5), 2000);
37
- engine.start();
38
- ```
39
-
40
- ## What it builds
41
-
42
- `Ragdoll.attach(physics, {root})` walks every node under `root`. A node with children becomes a bone; its capsule runs
43
- from the node's origin toward its children's centre (the farthest child when that centre is at the origin). End nodes
44
- and bones whose farthest child is nearer than `minLength` (fingers, toes) are left out with their children and keep their animation. The
45
- radius is `thickness` times the length, or half the distance the children sit off the bone's line when that is more,
46
- so a pelvis between the legs and a chest between the arms come out round. Mass is the capsule volume times `density`.
47
- The pose at construction is the rest pose the joint limits measure from: build it in a T or A pose, or the first frame
48
- of a clip.
49
-
50
- Each body's frame is its bone's world frame, so a body's origin is its joint with the parent bone, and the bone's world
51
- pose is the body's pose. `ragdoll.bones` lists the parts, parents first; `bones[0]` is the root. Each part has its
52
- `node`, `body` (a `PhysicsBody`; apply impulses to it), `joint` (null on the root), `parent` index, `length` and
53
- `radius`. Every body's `userData` is `{ragdoll, node}`, so a raycast hit tells you which bone was struck.
54
-
55
- For full control, list the bones yourself instead of `root`: each is a node or `{node, joint, length, radius, mass}`.
56
- One bone is the root, and every other bone's parent node must be in the list.
57
-
58
- ```ts
59
- // A second mannequin on the same rig: a skeleton has one ragdoll.
60
- const other = await loadGLTF(engine, '/Rig_Medium_General.glb');
61
- const node = (name: string) => other.nodes.find((n) => n.name === name)!;
62
- const custom = Ragdoll.attach(physics, {
63
- bones: [
64
- node('hips'),
65
- { node: node('spine'), joint: { type: 'cone', swing: 0.4, twist: [-0.3, 0.3] } },
66
- node('chest'),
67
- { node: node('head'), length: 0.25, radius: 0.1 },
68
- node('upperleg.l'),
69
- { node: node('lowerleg.l'), joint: { type: 'hinge', axis: [1, 0, 0], limits: [0, 2.4] } },
70
- ],
71
- });
72
- ```
73
-
74
- ## Joints
75
-
76
- | Joint | Meaning |
77
- | --- | --- |
78
- | `{type: 'cone', swing, twist}` | A ball joint. The bone stays inside a cone of half angle `swing` radians around its rest direction and twists about its own axis between `twist[0]` and `twist[1]` radians. Shoulders, hips, spine, neck. Defaults `swing` π/4, `twist` [-π/6, π/6]. |
79
- | `{type: 'hinge', axis, limits}` | One axis of rotation, `axis` in the bone's local frame, turning between `limits` radians from the rest pose. Knees, elbows. Default `limits` [-3π/4, 0]. Built as a revolute joint with both frames lined up at rest. |
80
- | `{type: 'free'}` | A ball joint with no limits. |
81
-
82
- Cone limits are measured by splitting the joint's rotation from rest into a swing of the bone axis and a twist about
83
- it. Where one passes its limit, an impulse stops the two bodies' relative spin that drives it further out, and the
84
- child turns back about the joint by `limitStiffness` (default 0.2) of the error each step. The stop is inelastic, so a
85
- limit does not bounce, and turning about the joint never pulls the joint apart.
86
-
87
- ## Modes and blending
88
-
89
- | Member | Meaning |
90
- | --- | --- |
91
- | `activate(limb?)` | Goes limp: each body becomes dynamic with the velocity its bone had in the last physics step, and physics drives the bones. With a bone or a list, only those limbs. |
92
- | `deactivate(duration = 0.3, limb?)` | The bodies follow the animation again (they jump to it, without sweeping through the world), and the drawn pose blends from the ragdoll's last pose to the animation over `duration` seconds, eased (the cubic Hermite step `3u^2 - 2u^3`) so it starts and lands with no jump in speed. With a bone or a list, only those limbs. |
93
- | `active` | True while physics drives any bone. |
94
- | `weight` | How much of the drawn pose is the ragdoll's, 0 to 1 (the largest of any bone's). Set it while active for a partial blend of the limp bones. |
95
- | `rootPosition` | World position of the root bone's body: where to move a character before it gets up. |
96
- | `part(node)` | The part of a node, or undefined. |
97
- | `dispose()` | Removes the bodies and joints and the plugin; the bones keep their last pose. `using` works. |
98
-
99
- A bone that is not limp aims its body (a kinematic hit box) at the pose drawn this frame, read after the ragdoll writes it, and the physics step of that frame reaches it (`tests/ragdoll.test.js`, "with Physics added first, a kinematic bone's body is on the pose drawn"). Frame order: `Physics` is a late plugin (core's `late`): the engine updates it after every plugin that is not, whichever was added first, so each frame it steps after the frame's animation and after a ragdoll or follower has set its targets from the pose drawn. A body whose pose comes from an animation (a ragdoll's hit boxes, a body following an animated mesh) is therefore on the pose drawn, on the frame it is drawn (KB-PHYS-FRAMEORDER1, fixed). The shot tool drives the page's own frame loop on the shot's clock, so a film has the same order.
100
-
101
- The ragdoll is an engine plugin that runs each frame after the plugins attached before it: create it after the
102
- Animator. It reads the bones' animated pose, sets the kinematic targets, and writes the blended pose. A bone's pose
103
- blends in its parent's frame (rotations for every bone, position for the root bone only), so limbs keep their lengths.
104
- Without an animation, blending back returns to the pose the bones had before the ragdoll moved them.
105
-
106
- ## Partial ragdolls
107
-
108
- `activate(limb)` makes one limb physical while the rest keeps animating: pass a bone (a node or a part), or a list. That bone and every bone under it go limp and hang from the bones that keep animating, so a hit swings one arm while the character walks on. `deactivate(seconds, limb)` blends that limb back alone. The spine takes the whole upper body, with the legs still walking.
109
-
110
- ```ts
111
- const arm = model.nodes.find((node) => node.name === 'upperarm.l')!;
112
- ragdoll.activate(arm);
113
- ragdoll.part(arm)?.body.applyImpulse([0, 2, -20]);
114
- setTimeout(() => ragdoll.deactivate(0.4, arm), 800);
115
-
116
- const rightArm = model.nodes.find((node) => node.name === 'upperarm.r')!;
117
- const spine = model.nodes.find((node) => node.name === 'spine')!;
118
- ragdoll.activate([arm, rightArm]); // a list: both arms
119
- ragdoll.activate(spine); // the upper body; `activate()` with no bone is all of them
120
- ```
121
-
122
- Each part has its own `limp` and `weight`, so a second limb can go limp while the first is still blending back. `ragdoll.active` is true while any bone is limp, and `ragdoll.weight` reads the largest weight. Bones that are not limp and have no weight are not written at all, so their animation reaches the screen unchanged. A limb stays attached to the drawn body to within a physics step: the bones above it are kinematic, and a kinematic body reaches a frame's pose at that frame's step.
123
-
124
- ## Options
125
-
126
- | Option | Default | Meaning |
127
- | --- | --- | --- |
128
- | `root` | none | The skeleton's root bone, usually the hips. Pass `root` or `bones`. |
129
- | `bones` | none | An explicit list of nodes or `{node, joint, length, radius, mass}`. |
130
- | `joint` | cone, π/4, [-π/6, π/6] | Joint of every bone that does not set its own. |
131
- | `minLength` | `0.05` | With `root`, bones whose farthest child is nearer than this (metres) are left out with their children. |
132
- | `thickness` | `0.2` | Capsule radius as a fraction of the bone length. |
133
- | `density` | `1000` | Kilograms per cubic metre, about a human body's. |
134
- | `active` | `false` | Start limp. |
135
- | `collisionGroups` | group 15, colliding with 0 to 14 | Packed groups for every capsule (`collisionGroups()` from physics). The default keeps a ragdoll's parts from colliding with each other; give a character controller's own queries a filter without group 15 so it ignores its hit boxes. |
136
- | `friction` | `0.6` | Capsule friction. |
137
- | `linearDamping` | `0.05` | Per body, so a limp ragdoll settles. |
138
- | `angularDamping` | `0.8` | Per body. |
139
- | `limitStiffness` | `0.2` | Share of a cone limit's error removed per physics step, 0 to 1. |
140
-
141
- Bones take any positive scale, even or uneven; zero and mirrored bones are refused. Lengths and shapes are read in world units, so a stretched bone gets a longer body. Under an uneven scale a child's world rotation is not its parent's times its own, so each part keeps `bind`, the difference, measured when the bone goes limp: the pose does not jump. Errors follow the package conventions: a `TypeError` or `RangeError` naming
142
- the fix for bad options, and a `MargoError` with code `disposed` after `dispose()`, `attached` for a second ragdoll on
143
- one skeleton or the wrong engine, and `unsupported` for a hinge on a solver without joint frames.
144
-
145
- ## Powered ragdolls (`margoengine/ragdoll/powered`)
146
-
147
- `addRagdollMotors(ragdoll, options)` gives every joint a motor that pulls its bone toward the pose the animation gives it, while the bone is physical. The character keeps moving, a hit bends it, and the motors take the pose back, instead of it only going limp.
148
-
149
- ```ts
150
- import { EngineKernel } from 'margoengine/core';
151
- import { loadGLTF } from 'margoengine/gltf/pbr';
152
- import { Physics } from 'margoengine/physics';
153
- import { Ragdoll } from 'margoengine/ragdoll';
154
- import { addRagdollMotors } from 'margoengine/ragdoll/powered';
155
-
156
- await Physics.load();
157
- const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!);
158
- const physics = new Physics(engine);
159
- physics.addBody(null, { type: 'fixed', colliders: { shape: 'box', halfExtents: [20, 0.1, 20] } });
160
- const model = await loadGLTF(engine, '/Rig_Medium_MovementBasic.glb'); // KayKit's skinned mannequin (CC0)
161
- const bone = (name: string) => model.nodes.find((node) => node.name === name)!;
162
- const hips = bone('hips');
163
- const ragdoll = Ragdoll.attach(physics, { root: hips });
164
- const motors = addRagdollMotors(ragdoll, { root: 1 });
165
- ragdoll.activate(); // physical, and still walking its clip
166
-
167
- // A hit: the impulse lands on the chest, the limb weakens at once and gets its strength back over 0.6 seconds.
168
- motors.hit(ragdoll.bones[4], [0, 0, -150], { weaken: 0.8, recover: 0.6 });
169
-
170
- motors.setStrength(bone('hand.l'), 0); // that limb hangs while the rest stays powered
171
- motors.fade(0, 1.5); // weaken over a second and a half: a slow collapse
172
- ```
173
-
174
- | Option | Default | Meaning |
175
- | --- | --- | --- |
176
- | `frequency` | `6` | How fast a motor closes on its target, as a natural frequency in hertz. |
177
- | `damping` | `1` | Damping ratio: 1 settles without overshoot, less rings. |
178
- | `strength` | `1` | Share of the pull, 0 (limp) to 1. |
179
- | `maxAcceleration` | `400` | Largest angular acceleration a motor may give the limb it carries, rad/s². Each joint's torque cap is this times the limb's inertia about the joint, read from where the limb's mass lies. Less gives floppier limbs; 400 is what the hands and feet of a real walk clip need. |
180
- | `root` | `0` | Share of a spring from the world to the root bone, toward where the animation puts it. |
181
-
182
- | Member | Meaning |
183
- | --- | --- |
184
- | `strength` | Read or set the share of the pull. |
185
- | `root` | Read or set the root spring's share. |
186
- | `fade(to, seconds)` | Moves `strength` to `to` over `seconds`. |
187
- | `setStrength(bone, share)` | The share of a bone and every bone under it. |
188
- | `hit(bone, impulse, {point, weaken, recover})` | Applies the impulse and weakens the bone, the bones under it and the bones above it up to the root. |
189
- | `error` | Largest angle, radians, between a powered bone and its target at the last step. |
190
- | `dispose()` | Takes the motors and the added mass off. `using` works. |
191
-
192
- Joint motors are equal and opposite torques on two bodies, so they keep a pose but cannot hold a character up. With `root: 0` a powered character falls over stiff. `root` above 0 keeps it up, and that spring is an outside force, not a muscle: it acts on every bone by its motor's share, so a limp limb still hangs. To stand on its feet and step, use `margoengine/ragdoll/balance`.
193
-
194
- A motor's target stops at the joint's limits, so it never pulls against a limit it would have to pass. The default cone of π/4 is tighter than most clips: give a ragdoll that follows a clip wider limits, or `{type: 'free'}`, or the clip is clipped. The target's own spin is fed to the motor, so a moving pose is tracked without the lag a spring alone has.
195
-
196
- Skeletons put small bodies between big limbs, and a solver cannot hold a strong motor against a body hundreds of times lighter. `addRagdollMotors` adds mass up to an eighth of each body's heaviest neighbour and inertia up to a tenth of the heaviest limb it carries, reckoning each body as a rod along its bone because that is what suits the solver, and `dispose()` takes it off. The motors themselves work from where the mass really lies, so a heavy head on a short neck holds with nothing added: Knight's head moves 0.003 rad in its first second where a rod per body let it fall 0.83 rad to its cone limit.
197
-
198
- ## Getting up (`margoengine/ragdoll/getup`)
199
-
200
- `addGetUp(ragdoll, animator, options)` gets a character up from a ragdoll. `start()` compares how the body lies with the first frame of each clip, picks the one that fits, turns and moves the character so that frame lies on the body, on the ground under it, and blends the bones from the ragdoll's pose into the clip. When the clip ends the animator goes on to `then`.
201
-
202
- ```ts
203
- import { Ragdoll } from 'margoengine/ragdoll';
204
- import { addGetUp } from 'margoengine/ragdoll/getup';
205
- import { Animation } from 'margoengine/animation';
206
- import { EngineKernel } from 'margoengine/core';
207
- import { loadGLTF } from 'margoengine/gltf/pbr';
208
- import { Physics } from 'margoengine/physics';
209
- import { Animator } from 'margoengine/animator';
210
-
211
- await Physics.load();
212
- const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!);
213
- const physics = new Physics(engine);
214
- physics.addBody(null, { type: 'fixed', colliders: { shape: 'box', halfExtents: [20, 0.1, 20] } });
215
- const model = await loadGLTF(engine, '/hero.glb');
216
- const bone = (name: string) => model.nodes.find((node) => node.name === name)!;
217
- const hips = bone('Hips');
218
- const animator = Animator.attach(Animation.attach(model), {
219
- initial: 'idle',
220
- states: { idle: 'Idle', back: 'GetUpFromBack', front: 'GetUpFromFront' },
221
- });
222
- const ragdoll = Ragdoll.attach(physics, { root: hips });
223
- const getUp = addGetUp(ragdoll, animator, { faceUp: 'back', faceDown: 'front', then: 'idle' });
224
-
225
- ragdoll.activate();
226
- ragdoll.part(bone('Head'))?.body.applyImpulse([0, 2, -30]);
227
- setTimeout(async () => {
228
- const { side, mismatch } = await getUp.start();
229
- console.log(`got up ${side}, ${mismatch} radians from the clip at the root`);
230
- }, 2000);
231
- ```
232
-
233
- | Option | Default | Meaning |
234
- | --- | --- | --- |
235
- | `faceUp` | none | Animator state of the clip that gets up from lying on the back. |
236
- | `faceDown` | none | Animator state of the clip that gets up from lying on the front. |
237
- | `then` | the animator's state now | State to go to when the clip ends. |
238
- | `blend` | `0.4` | Seconds from the ragdoll's pose into the clip. |
239
- | `fade` | `0.2` | Seconds from the end of the clip into `then`. |
240
- | `root` | the model's root | The top node of the character, moved and turned to the body. |
241
- | `up` | `[0, 1, 0]` | World up. |
242
-
243
- `pick()` says which clip fits now, and `mismatch(side)` by how many radians. `start({side, signal})` forces a clip, and an aborted signal rejects the promise while the clip plays on. It throws a `MargoError` with code `state` when no bone is limp or a get-up is running. The promise gives `{side, mismatch}`, where `mismatch` is the radians between the body and the clip's first frame at the root bone.
244
-
245
- No facing convention is needed: only the turn about the up axis is free, and what is left over tells the clips apart. `addGetUp` reads each clip's first frame through the animator once, and puts it back as it was; a `statechange` listener sees that visit. The ground is found with a ray down from the hips that ignores moving bodies; with no ground the character keeps its height. The clip should loop off, or be a state with a later transition: the end of its first cycle is what ends the get-up.
246
-
247
- ## Body shapes from the skin (`margoengine/ragdoll/hulls`)
248
-
249
- `fitRagdollShapes(ragdoll, model, options)` swaps each bone's capsule for a convex hull of the vertices it carries, or for the smallest box around them that lies along the bone. A vertex belongs to the bone that dominates its skin weights, and skin joints with no body (fingers, toes) count toward the bone above them. Hits land on what the player sees.
250
-
251
- ```ts
252
- import { Ragdoll } from 'margoengine/ragdoll';
253
- import { EngineKernel } from 'margoengine/core';
254
- import { loadGLTF } from 'margoengine/gltf/pbr';
255
- import { Physics } from 'margoengine/physics';
256
- import { fitRagdollShapes } from 'margoengine/ragdoll/hulls';
257
-
258
- await Physics.load();
259
- const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!);
260
- const physics = new Physics(engine);
261
- physics.addBody(null, { type: 'fixed', colliders: { shape: 'box', halfExtents: [20, 0.1, 20] } });
262
- const model = await loadGLTF(engine, '/Rig_Medium_MovementBasic.glb'); // KayKit's skinned mannequin (CC0)
263
- const bone = (name: string) => model.nodes.find((node) => node.name === name)!;
264
- const hips = bone('hips');
265
- const ragdoll = Ragdoll.attach(physics, { root: hips });
266
- const fitted = fitRagdollShapes(ragdoll, model);
267
- console.log(`${fitted.length} of ${ragdoll.bones.length} bones fit the mesh`);
268
-
269
- fitRagdollShapes(ragdoll, model, { shape: 'box', minWeight: 0.3 }); // boxes, with blended vertices counted
270
- ```
271
-
272
- | Option | Default | Meaning |
273
- | --- | --- | --- |
274
- | `shape` | `'hull'` | `'hull'`, or `'box'`: cheaper, and looser. |
275
- | `minWeight` | `0.5` | A vertex counts toward a bone when the bone carries this share of it. |
276
- | `maxPoints` | `64` | Most corners a hull keeps, 8 to 1,024. |
277
-
278
- The source is the glTF model the skeleton belongs to, or a `RagdollSkin` of your own (`positions`, `joints`, `weights`, `nodes`, `inverseBindMatrices`). The result lists the bones that got a shape; a bone with no vertices that span a volume keeps its capsule. Mass, friction, groups and joints stay as they were, and each bone's inertia follows its new shape. Call it before `addRagdollMotors`, and give a leaf bone you want a hull for, such as a head with no child, a `length` so it is a bone.
279
-
280
- The same data goes in by hand: `ragdoll.setShape(bone, shape)`, or `shape` on an entry of `bones`, takes `{type: 'capsule'}`, `{type: 'hull', points}` or `{type: 'box', center, halfExtents, rotation}`, in the bone's own frame. `part.shape` reads it back and `part.mass` the mass as built.
281
-
282
- ## Saved profiles (`margoengine/ragdoll/profile`)
283
-
284
- A profile is a ragdoll as plain JSON: bones by name, joints and limits, sizes, masses, shapes and the shared body settings. Tune a ragdoll once, save it, and every copy of the character builds the same one. `humanoidProfile` is a place to start.
285
-
286
- ```ts
287
- import { Ragdoll } from 'margoengine/ragdoll';
288
- import { EngineKernel } from 'margoengine/core';
289
- import { loadGLTF } from 'margoengine/gltf/pbr';
290
- import { Physics } from 'margoengine/physics';
291
- import { humanoidProfile, ragdollOptions, saveRagdollProfile } from 'margoengine/ragdoll/profile';
292
-
293
- await Physics.load();
294
- const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!);
295
- const physics = new Physics(engine);
296
- physics.addBody(null, { type: 'fixed', colliders: { shape: 'box', halfExtents: [20, 0.1, 20] } });
297
- // Two KayKit mannequins (CC0) on one rig: one engine has one Physics, which both ragdolls share.
298
- const model = await loadGLTF(engine, '/Rig_Medium_MovementBasic.glb');
299
- const otherModel = await loadGLTF(engine, '/Rig_Medium_General.glb');
300
- const bone = (name: string) => model.nodes.find((node) => node.name === name)!;
301
- // KayKit names its bones its own way, so name the humanoid ones.
302
- const bones = {
303
- hips: bone('hips'), spine: bone('spine'), chest: bone('chest'), head: bone('head'),
304
- leftUpperArm: bone('upperarm.l'), leftLowerArm: bone('lowerarm.l'), leftHand: bone('wrist.l'),
305
- rightUpperArm: bone('upperarm.r'), rightLowerArm: bone('lowerarm.r'), rightHand: bone('wrist.r'),
306
- leftUpperLeg: bone('upperleg.l'), leftLowerLeg: bone('lowerleg.l'), leftFoot: bone('foot.l'),
307
- rightUpperLeg: bone('upperleg.r'), rightLowerLeg: bone('lowerleg.r'), rightFoot: bone('foot.r'),
308
- };
309
-
310
- // Anatomical ranges, hinged knees and elbows, published mass shares.
311
- const ragdoll = Ragdoll.attach(physics, ragdollOptions(humanoidProfile(model.nodes, { mass: 82, bones }), model.nodes));
312
-
313
- const saved = JSON.stringify(saveRagdollProfile(ragdoll));
314
- const again = Ragdoll.attach(physics, ragdollOptions(JSON.parse(saved), otherModel.nodes));
315
- ```
316
-
317
- | Function | Gives |
318
- | --- | --- |
319
- | `saveRagdollProfile(ragdoll)` | The profile, every value as built. Bones need unique names. |
320
- | `ragdollOptions(profile, nodes)` | The options for `new Ragdoll` or `Ragdoll.attach`; add your own beside them. It throws a `RangeError` naming a bone the skeleton lacks, and for a profile of a newer version. |
321
- | `humanoidProfile(nodes, {mass, bones})` | A profile for a humanoid in a T or A pose. `mass` defaults to 70 kg. |
322
-
323
- `humanoidProfile` finds bones by the names `detectSkeleton` knows (Mixamo, Godot, Roblox, humanoid). For other names, pass `bones: {hips: node, leftUpperLeg: node, ...}`; it needs hips, a head, and upper and lower arms and legs. Every node between two named bones joins the lower one's mass, with a small cone. `ragdoll.settings` reads the shared settings a profile saves.
324
-
325
- ## Balance (`margoengine/ragdoll/balance`)
326
-
327
- `addRagdollBalance(ragdoll, motors, {feet})` keeps a powered character on its feet, on its own legs. It watches the capture point of the centre of mass, the spot a step must reach to stop the fall, and swings a foot there; two-bone maths sets each leg from where the hips should be to where its foot is. The weight goes down the stance legs as torque pairs at knee and ankle, held to what the sole can answer, so no outside force holds it up.
328
-
329
- ```ts
330
- import { Ragdoll } from 'margoengine/ragdoll';
331
- import { addRagdollBalance } from 'margoengine/ragdoll/balance';
332
- import { addRagdollMotors } from 'margoengine/ragdoll/powered';
333
- import { EngineKernel } from 'margoengine/core';
334
- import { loadGLTF } from 'margoengine/gltf/pbr';
335
- import { Physics } from 'margoengine/physics';
336
- import { humanoidProfile, ragdollOptions } from 'margoengine/ragdoll/profile';
337
-
338
- await Physics.load();
339
- const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!);
340
- const physics = new Physics(engine);
341
- physics.addBody(null, { type: 'fixed', colliders: { shape: 'box', halfExtents: [20, 0.1, 20] } });
342
- const model = await loadGLTF(engine, '/Rig_Medium_MovementBasic.glb'); // KayKit's skinned mannequin (CC0)
343
- const bone = (name: string) => model.nodes.find((node) => node.name === name)!;
344
- // KayKit names its bones its own way, so name the humanoid ones.
345
- const bones = {
346
- hips: bone('hips'), spine: bone('spine'), chest: bone('chest'), head: bone('head'),
347
- leftUpperArm: bone('upperarm.l'), leftLowerArm: bone('lowerarm.l'), leftHand: bone('wrist.l'),
348
- rightUpperArm: bone('upperarm.r'), rightLowerArm: bone('lowerarm.r'), rightHand: bone('wrist.r'),
349
- leftUpperLeg: bone('upperleg.l'), leftLowerLeg: bone('lowerleg.l'), leftFoot: bone('foot.l'),
350
- rightUpperLeg: bone('upperleg.r'), rightLowerLeg: bone('lowerleg.r'), rightFoot: bone('foot.r'),
351
- };
352
- const ragdoll = Ragdoll.attach(physics, ragdollOptions(humanoidProfile(model.nodes, { bones }), model.nodes));
353
- const motors = addRagdollMotors(ragdoll, { frequency: 8 });
354
- const balance = addRagdollBalance(ragdoll, motors, { feet: [bone('foot.l'), bone('foot.r')] });
355
- ragdoll.activate();
356
-
357
- motors.hit(bone('spine'), [0, 0, -40]); // it stumbles, steps and catches itself
358
- if (balance.state === 'fallen') motors.fade(0, 0.5);
359
- ```
360
-
361
- | Option | Default | Meaning |
362
- | --- | --- | --- |
363
- | `feet` | none | The two foot bones. Each needs a knee hinge above it, as `humanoidProfile` builds. |
364
- | `stepTime` | `0.28` | Seconds a step takes at most; a harder push shortens it (below). |
365
- | `stepHeight` | `0.15` | How high a foot lifts, as a share of the leg's length. |
366
- | `stepTrigger` | `0.2` | How far the capture point may leave the feet before a step, as a share of the leg's length. |
367
- | `stance` | `0.97` | Hip height held, as a share of the height when added. |
368
- | `carry` | `0` | Share of the upper body's weight an outside force carries, 0 to 1. Off: it stands on its own legs. |
369
- | `upright` | `10` | Frequency in rad/s of the turn that holds the hips upright, answered through the legs by the ground. |
370
- | `maxUpright` | `40` | Largest turn that gives, in rad/s². A harder blow knocks the character over. |
371
- | `fallTilt` | `0.8` | Radians of lean past which it has fallen and balancing stops. |
372
- | `gravity` | `9.81` | World gravity along up, in m/s². |
373
-
374
- A step lands where the capture point will be when the foot comes down, and a hard push makes the capture point run away from the stance foot as e^(omega t), so a step that took its full `stepTime` would land short and the stance foot would be dragged off the ground. Each step takes no longer than the capture point needs to reach the edge of the leg's reach, ln(reach / d) / omega for a capture point d from the stance foot, and no less than 0.4 / omega (0.094 s for a figure 0.26 m tall at the hips): step timing adaptation (Khadiv, Herzog, Moosavian and Righetti, IEEE T-RO 2020) on the capture point of Pratt et al. (2006) and Englsberger et al. (2011). A planted foot's target stays on the ground, so a stance foot a push lifts is pressed back down, and a foot that is off the ground anyway steps next. Both feet are held level, the swing foot heading where the hips head as SIMBICON keeps it (Yin, Loken and van de Panne 2007), and every target stays inside the ankle's cone. The ankle's limits hold under the weight, which they did not on Rapier: `docs/limits.md`, Ragdoll balance. Knight recovers a 1.5 m/s push of its upper body in each of four directions at every solver setting from 2 to 6 iterations, 4, 8 and 16 substeps and warm start on and off, which `node packages/ragdoll/scripts/balance-ab.mjs --sweep` checks.
375
-
376
- Every torque is a pair inside the body, so a hard enough blow knocks it over. Set `carry` to lend an outside force, capped at 1.5 times the share asked for; `balance.carried` reads the share of the body's weight it gave at the last step, and is 0 without it. While it balances it adds inertia to the feet and shins, brings the character's island, not the world, to at least 8 solver passes, and stands a foot fitted with a hull on a flat sole of four corners; `dispose` takes all three away. A stance knee takes its torque from the balance, with a spring of its own beside it, so `motors.setStrength` reaches only the swinging leg's knee. Its torques are forces, so more solver passes only steady it, and a force of your own on a bone stays yours. `steps` counts steps, `capture` is the capture point, `tilt` the lean, and `state` is `standing`, `stepping` or `fallen`. Add it with the character standing still, before `activate`. After a fall, get up with `margoengine/ragdoll/getup` and call `reset()`. `motors.setTarget(bone, rotation)` is what it drives the legs with, and is open to any controller: a rotation relative to the parent bone, or `null` for the animation's pose.
377
-
378
- ## Clean room
379
-
380
- Written from public descriptions only, cited in [docs/clean-room.md](../../docs/clean-room.md); no engine's ragdoll code
381
- was read.
1
+ # @margoengine/ragdoll
2
+
3
+ Import `margoengine/ragdoll` from the `margoengine` package, or `@margoengine/ragdoll` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ Ragdolls for animated characters, on `@margoengine/physics`. Give it the hips of a skeleton and it builds one
6
+ capsule body per bone, joined at the bone origins with swing and twist limits. While the character is animated the
7
+ bodies follow the bones as kinematic hit boxes that push the world; `activate()` makes it limp, keeping the momentum the
8
+ animation gave each bone; `deactivate(seconds)` blends the bones back to the animation. Core and physics stay the same
9
+ size: an app that does not import this package ships none of it.
10
+
11
+ ## Quick start
12
+
13
+ ```ts
14
+ import { EngineKernel } from 'margoengine/core';
15
+ import { loadGLTF } from 'margoengine/gltf/pbr';
16
+ import { Physics } from 'margoengine/physics';
17
+ import { Ragdoll } from 'margoengine/ragdoll';
18
+ await Physics.load();
19
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!);
20
+ const physics = new Physics(engine);
21
+ const model = await loadGLTF(engine, '/Rig_Medium_MovementBasic.glb');
22
+ Ragdoll.attach(physics, { root: model.nodes.find((n) => n.name === 'hips')! }).activate();
23
+ ```
24
+
25
+ ## Full animated ragdoll example
26
+
27
+ ```ts
28
+ import { EngineKernel } from 'margoengine/core';
29
+ import { loadGLTF } from 'margoengine/gltf/pbr';
30
+ import { Animation } from 'margoengine/animation';
31
+ import { Animator } from 'margoengine/animator';
32
+ import { Physics } from 'margoengine/physics';
33
+ import { Ragdoll } from 'margoengine/ragdoll';
34
+
35
+ await Physics.load();
36
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!);
37
+ const physics = new Physics(engine);
38
+ physics.addBody(null, { type: 'fixed', colliders: { shape: 'box', halfExtents: [20, 0.1, 20] } });
39
+ const model = await loadGLTF(engine, '/Rig_Medium_MovementBasic.glb'); // KayKit's skinned mannequin (CC0), with a Running_A clip
40
+ Animator.attach(Animation.attach(model), { initial: 'run', states: { run: 'Running_A' } });
41
+
42
+ // After the Animator, so it runs after the animation each frame.
43
+ const hips = model.nodes.find((node) => node.name === 'hips')!;
44
+ const ragdoll = Ragdoll.attach(physics, { root: hips });
45
+
46
+ // A hit: go limp and push the bone that was struck.
47
+ const head = ragdoll.bones.find((part) => part.node.name === 'head');
48
+ ragdoll.activate();
49
+ head?.body.applyImpulse([0, 2, -30]);
50
+
51
+ // Two seconds later, get up: hand the bones back to the animation over half a second.
52
+ setTimeout(() => ragdoll.deactivate(0.5), 2000);
53
+ engine.start();
54
+ ```
55
+
56
+ ## What it builds
57
+
58
+ `Ragdoll.attach(physics, {root})` walks every node under `root`. A node with children becomes a bone; its capsule runs
59
+ from the node's origin toward its children's centre (the farthest child when that centre is at the origin). End nodes
60
+ and bones whose farthest child is nearer than `minLength` (fingers, toes) are left out with their children and keep their animation. The
61
+ radius is `thickness` times the length, or half the distance the children sit off the bone's line when that is more,
62
+ so a pelvis between the legs and a chest between the arms come out round. Mass is the capsule volume times `density`.
63
+ The pose at construction is the rest pose the joint limits measure from: build it in a T or A pose, or the first frame
64
+ of a clip.
65
+
66
+ Each body's frame is its bone's world frame, so a body's origin is its joint with the parent bone, and the bone's world
67
+ pose is the body's pose. `ragdoll.bones` lists the parts, parents first; `bones[0]` is the root. Each part has its
68
+ `node`, `body` (a `PhysicsBody`; apply impulses to it), `joint` (null on the root), `parent` index, `length` and
69
+ `radius`. Every body's `userData` is `{ragdoll, node}`, so a raycast hit tells you which bone was struck.
70
+
71
+ For full control, list the bones yourself instead of `root`: each is a node or `{node, joint, length, radius, mass}`.
72
+ One bone is the root, and every other bone's parent node must be in the list.
73
+
74
+ ```ts
75
+ // A second mannequin on the same rig: a skeleton has one ragdoll.
76
+ const other = await loadGLTF(engine, '/Rig_Medium_General.glb');
77
+ const node = (name: string) => other.nodes.find((n) => n.name === name)!;
78
+ const custom = Ragdoll.attach(physics, {
79
+ bones: [
80
+ node('hips'),
81
+ { node: node('spine'), joint: { type: 'cone', swing: 0.4, twist: [-0.3, 0.3] } },
82
+ node('chest'),
83
+ { node: node('head'), length: 0.25, radius: 0.1 },
84
+ node('upperleg.l'),
85
+ { node: node('lowerleg.l'), joint: { type: 'hinge', axis: [1, 0, 0], limits: [0, 2.4] } },
86
+ ],
87
+ });
88
+ ```
89
+
90
+ ## Joints
91
+
92
+ | Joint | Meaning |
93
+ | --- | --- |
94
+ | `{type: 'cone', swing, twist}` | A ball joint. The bone stays inside a cone of half angle `swing` radians around its rest direction and twists about its own axis between `twist[0]` and `twist[1]` radians. Shoulders, hips, spine, neck. Defaults `swing` π/4, `twist` [-π/6, π/6]. |
95
+ | `{type: 'hinge', axis, limits}` | One axis of rotation, `axis` in the bone's local frame, turning between `limits` radians from the rest pose. Knees, elbows. Default `limits` [-3π/4, 0]. Built as a revolute joint with both frames lined up at rest. |
96
+ | `{type: 'free'}` | A ball joint with no limits. |
97
+
98
+ Cone limits are measured by splitting the joint's rotation from rest into a swing of the bone axis and a twist about
99
+ it. Where one passes its limit, an impulse stops the two bodies' relative spin that drives it further out, and the
100
+ child turns back about the joint by `limitStiffness` (default 0.2) of the error each step. The stop is inelastic, so a
101
+ limit does not bounce, and turning about the joint never pulls the joint apart.
102
+
103
+ ## Modes and blending
104
+
105
+ | Member | Meaning |
106
+ | --- | --- |
107
+ | `activate(limb?)` | Goes limp: each body becomes dynamic with the velocity its bone had in the last physics step, and physics drives the bones. With a bone or a list, only those limbs. |
108
+ | `deactivate(duration = 0.3, limb?)` | The bodies follow the animation again (they jump to it, without sweeping through the world), and the drawn pose blends from the ragdoll's last pose to the animation over `duration` seconds, eased (the cubic Hermite step `3u^2 - 2u^3`) so it starts and lands with no jump in speed. With a bone or a list, only those limbs. |
109
+ | `active` | True while physics drives any bone. |
110
+ | `weight` | How much of the drawn pose is the ragdoll's, 0 to 1 (the largest of any bone's). Set it while active for a partial blend of the limp bones. |
111
+ | `rootPosition` | World position of the root bone's body: where to move a character before it gets up. |
112
+ | `part(node)` | The part of a node, or undefined. |
113
+ | `debugRender({capsules, limits, bones, limitScale})` | Returns `{vertices, colors}` debug line segments showing bone colliders tinted by mode (kinematic blue, limp green, blending cyan), swing cones, hinge limit arcs, and bone links. |
114
+ | `dispose()` | Removes the bodies and joints and the plugin; the bones keep their last pose. `using` works. |
115
+
116
+ A bone that is not limp aims its body (a kinematic hit box) at the pose drawn this frame, read after the ragdoll writes it, and the physics step of that frame reaches it (`tests/ragdoll.test.js`, "with Physics added first, a kinematic bone's body is on the pose drawn"). Frame order: `Physics` is a late plugin (core's `late`): the engine updates it after every plugin that is not, whichever was added first, so each frame it steps after the frame's animation and after a ragdoll or follower has set its targets from the pose drawn. A body whose pose comes from an animation (a ragdoll's hit boxes, a body following an animated mesh) is therefore on the pose drawn, on the frame it is drawn (KB-PHYS-FRAMEORDER1, fixed). The shot tool drives the page's own frame loop on the shot's clock, so a film has the same order.
117
+
118
+ The ragdoll is an engine plugin that runs each frame after the plugins attached before it: create it after the
119
+ Animator. It reads the bones' animated pose, sets the kinematic targets, and writes the blended pose. A bone's pose
120
+ blends in its parent's frame (rotations for every bone, position for the root bone only), so limbs keep their lengths.
121
+ Without an animation, blending back returns to the pose the bones had before the ragdoll moved them.
122
+
123
+ ## Partial ragdolls
124
+
125
+ `activate(limb)` makes one limb physical while the rest keeps animating: pass a bone (a node or a part), or a list. That bone and every bone under it go limp and hang from the bones that keep animating, so a hit swings one arm while the character walks on. `deactivate(seconds, limb)` blends that limb back alone. The spine takes the whole upper body, with the legs still walking.
126
+
127
+ ```ts
128
+ const arm = model.nodes.find((node) => node.name === 'upperarm.l')!;
129
+ ragdoll.activate(arm);
130
+ ragdoll.part(arm)?.body.applyImpulse([0, 2, -20]);
131
+ setTimeout(() => ragdoll.deactivate(0.4, arm), 800);
132
+
133
+ const rightArm = model.nodes.find((node) => node.name === 'upperarm.r')!;
134
+ const spine = model.nodes.find((node) => node.name === 'spine')!;
135
+ ragdoll.activate([arm, rightArm]); // a list: both arms
136
+ ragdoll.activate(spine); // the upper body; `activate()` with no bone is all of them
137
+ ```
138
+
139
+ Each part has its own `limp` and `weight`, so a second limb can go limp while the first is still blending back. `ragdoll.active` is true while any bone is limp, and `ragdoll.weight` reads the largest weight. Bones that are not limp and have no weight are not written at all, so their animation reaches the screen unchanged. A limb stays attached to the drawn body to within a physics step: the bones above it are kinematic, and a kinematic body reaches a frame's pose at that frame's step.
140
+
141
+ ## Options
142
+
143
+ | Option | Default | Meaning |
144
+ | --- | --- | --- |
145
+ | `root` | none | The skeleton's root bone, usually the hips. Pass `root` or `bones`. |
146
+ | `bones` | none | An explicit list of nodes or `{node, joint, length, radius, mass}`. |
147
+ | `joint` | cone, π/4, [-π/6, π/6] | Joint of every bone that does not set its own. |
148
+ | `minLength` | `0.05` | With `root`, bones whose farthest child is nearer than this (metres) are left out with their children. |
149
+ | `thickness` | `0.2` | Capsule radius as a fraction of the bone length. |
150
+ | `density` | `1000` | Kilograms per cubic metre, about a human body's. |
151
+ | `active` | `false` | Start limp. |
152
+ | `collisionGroups` | group 15, colliding with 0 to 14 | Packed groups for every capsule (`collisionGroups()` from physics). The default keeps a ragdoll's parts from colliding with each other; give a character controller's own queries a filter without group 15 so it ignores its hit boxes. |
153
+ | `friction` | `0.6` | Capsule friction. |
154
+ | `linearDamping` | `0.05` | Per body, so a limp ragdoll settles. |
155
+ | `angularDamping` | `0.8` | Per body. |
156
+ | `limitStiffness` | `0.2` | Share of a cone limit's error removed per physics step, 0 to 1. |
157
+
158
+ Bones take any positive scale, even or uneven; zero and mirrored bones are refused. Lengths and shapes are read in world units, so a stretched bone gets a longer body. Under an uneven scale a child's world rotation is not its parent's times its own, so each part keeps `bind`, the difference, measured when the bone goes limp: the pose does not jump. Errors follow the package conventions: a `MargoError` with a help link naming
159
+ the fix for bad options, and a `MargoError` with code `disposed` after `dispose()`, `attached` for a second ragdoll on
160
+ one skeleton or the wrong engine, and `unsupported` for a hinge on a solver without joint frames.
161
+
162
+ ## Powered ragdolls (`margoengine/ragdoll/powered`)
163
+
164
+ `addRagdollMotors(ragdoll, options)` gives every joint a motor that pulls its bone toward the pose the animation gives it, while the bone is physical. The character keeps moving, a hit bends it, and the motors take the pose back, instead of it only going limp.
165
+
166
+ ```ts
167
+ import { EngineKernel } from 'margoengine/core';
168
+ import { loadGLTF } from 'margoengine/gltf/pbr';
169
+ import { Physics } from 'margoengine/physics';
170
+ import { Ragdoll } from 'margoengine/ragdoll';
171
+ import { addRagdollMotors } from 'margoengine/ragdoll/powered';
172
+
173
+ await Physics.load();
174
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!);
175
+ const physics = new Physics(engine);
176
+ physics.addBody(null, { type: 'fixed', colliders: { shape: 'box', halfExtents: [20, 0.1, 20] } });
177
+ const model = await loadGLTF(engine, '/Rig_Medium_MovementBasic.glb'); // KayKit's skinned mannequin (CC0)
178
+ const bone = (name: string) => model.nodes.find((node) => node.name === name)!;
179
+ const hips = bone('hips');
180
+ const ragdoll = Ragdoll.attach(physics, { root: hips });
181
+ const motors = addRagdollMotors(ragdoll, { root: 1 });
182
+ ragdoll.activate(); // physical, and still walking its clip
183
+
184
+ // A hit: the impulse lands on the chest, the limb weakens at once and gets its strength back over 0.6 seconds.
185
+ motors.hit(ragdoll.bones[4], [0, 0, -150], { weaken: 0.8, recover: 0.6 });
186
+
187
+ motors.setStrength(bone('hand.l'), 0); // that limb hangs while the rest stays powered
188
+ motors.fade(0, 1.5); // weaken over a second and a half: a slow collapse
189
+ ```
190
+
191
+ | Option | Default | Meaning |
192
+ | --- | --- | --- |
193
+ | `frequency` | `6` | How fast a motor closes on its target, as a natural frequency in hertz. |
194
+ | `damping` | `1` | Damping ratio: 1 settles without overshoot, less rings. |
195
+ | `strength` | `1` | Share of the pull, 0 (limp) to 1. |
196
+ | `maxAcceleration` | `400` | Largest angular acceleration a motor may give the limb it carries, rad/s². Each joint's torque cap is this times the limb's inertia about the joint, read from where the limb's mass lies. Less gives floppier limbs; 400 is what the hands and feet of a real walk clip need. |
197
+ | `root` | `0` | Share of a spring from the world to the root bone, toward where the animation puts it. |
198
+
199
+ | Member | Meaning |
200
+ | --- | --- |
201
+ | `strength` | Read or set the share of the pull. |
202
+ | `root` | Read or set the root spring's share. |
203
+ | `fade(to, seconds)` | Moves `strength` to `to` over `seconds`. |
204
+ | `setStrength(bone, share)` | The share of a bone and every bone under it. |
205
+ | `hit(bone, impulse, {point, weaken, recover})` | Applies the impulse and weakens the bone, the bones under it and the bones above it up to the root. |
206
+ | `error` | Largest angle, radians, between a powered bone and its target at the last step. |
207
+ | `dispose()` | Takes the motors and the added mass off. `using` works. |
208
+
209
+ Joint motors are equal and opposite torques on two bodies, so they keep a pose but cannot hold a character up. With `root: 0` a powered character falls over stiff. `root` above 0 keeps it up, and that spring is an outside force, not a muscle: it acts on every bone by its motor's share, so a limp limb still hangs. To stand on its feet and step, use `margoengine/ragdoll/balance`.
210
+
211
+ A motor's target stops at the joint's limits, so it never pulls against a limit it would have to pass. The default cone of π/4 is tighter than most clips: give a ragdoll that follows a clip wider limits, or `{type: 'free'}`, or the clip is clipped. The target's own spin is fed to the motor, so a moving pose is tracked without the lag a spring alone has.
212
+
213
+ Skeletons put small bodies between big limbs, and a solver cannot hold a strong motor against a body hundreds of times lighter. `addRagdollMotors` adds mass up to an eighth of each body's heaviest neighbour and inertia up to a tenth of the heaviest limb it carries, reckoning each body as a rod along its bone because that is what suits the solver, and `dispose()` takes it off. The motors themselves work from where the mass really lies, so a heavy head on a short neck holds with nothing added: Knight's head moves 0.003 rad in its first second where a rod per body let it fall 0.83 rad to its cone limit.
214
+
215
+ ## Getting up (`margoengine/ragdoll/getup`)
216
+
217
+ `addGetUp(ragdoll, animator, options)` gets a character up from a ragdoll. `start()` compares how the body lies with the first frame of each clip, picks the one that fits, turns and moves the character so that frame lies on the body, on the ground under it, and blends the bones from the ragdoll's pose into the clip. When the clip ends the animator goes on to `then`.
218
+
219
+ ```ts
220
+ import { Ragdoll } from 'margoengine/ragdoll';
221
+ import { addGetUp } from 'margoengine/ragdoll/getup';
222
+ import { Animation } from 'margoengine/animation';
223
+ import { EngineKernel } from 'margoengine/core';
224
+ import { loadGLTF } from 'margoengine/gltf/pbr';
225
+ import { Physics } from 'margoengine/physics';
226
+ import { Animator } from 'margoengine/animator';
227
+
228
+ await Physics.load();
229
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!);
230
+ const physics = new Physics(engine);
231
+ physics.addBody(null, { type: 'fixed', colliders: { shape: 'box', halfExtents: [20, 0.1, 20] } });
232
+ const model = await loadGLTF(engine, '/hero.glb');
233
+ const bone = (name: string) => model.nodes.find((node) => node.name === name)!;
234
+ const hips = bone('Hips');
235
+ const animator = Animator.attach(Animation.attach(model), {
236
+ initial: 'idle',
237
+ states: { idle: 'Idle', back: 'GetUpFromBack', front: 'GetUpFromFront' },
238
+ });
239
+ const ragdoll = Ragdoll.attach(physics, { root: hips });
240
+ const getUp = addGetUp(ragdoll, animator, { faceUp: 'back', faceDown: 'front', then: 'idle' });
241
+
242
+ ragdoll.activate();
243
+ ragdoll.part(bone('Head'))?.body.applyImpulse([0, 2, -30]);
244
+ setTimeout(async () => {
245
+ const { side, mismatch } = await getUp.start();
246
+ console.log(`got up ${side}, ${mismatch} radians from the clip at the root`);
247
+ }, 2000);
248
+ ```
249
+
250
+ | Option | Default | Meaning |
251
+ | --- | --- | --- |
252
+ | `faceUp` | none | Animator state of the clip that gets up from lying on the back. |
253
+ | `faceDown` | none | Animator state of the clip that gets up from lying on the front. |
254
+ | `then` | the animator's state now | State to go to when the clip ends. |
255
+ | `blend` | `0.4` | Seconds from the ragdoll's pose into the clip. |
256
+ | `fade` | `0.2` | Seconds from the end of the clip into `then`. |
257
+ | `root` | the model's root | The top node of the character, moved and turned to the body. |
258
+ | `up` | `[0, 1, 0]` | World up. |
259
+
260
+ `pick()` says which clip fits now, and `mismatch(side)` by how many radians. `start({side, signal})` forces a clip, and an aborted signal rejects the promise while the clip plays on. It throws a `MargoError` with code `state` when no bone is limp or a get-up is running. The promise gives `{side, mismatch}`, where `mismatch` is the radians between the body and the clip's first frame at the root bone.
261
+
262
+ No facing convention is needed: only the turn about the up axis is free, and what is left over tells the clips apart. `addGetUp` reads each clip's first frame through the animator once, and puts it back as it was; a `statechange` listener sees that visit. The ground is found with a ray down from the hips that ignores moving bodies; with no ground the character keeps its height. The clip should loop off, or be a state with a later transition: the end of its first cycle is what ends the get-up.
263
+
264
+ ## Body shapes from the skin (`margoengine/ragdoll/hulls`)
265
+
266
+ `fitRagdollShapes(ragdoll, model, options)` swaps each bone's capsule for a convex hull of the vertices it carries, or for the smallest box around them that lies along the bone. A vertex belongs to the bone that dominates its skin weights, and skin joints with no body (fingers, toes) count toward the bone above them. Hits land on what the player sees.
267
+
268
+ ```ts
269
+ import { Ragdoll } from 'margoengine/ragdoll';
270
+ import { EngineKernel } from 'margoengine/core';
271
+ import { loadGLTF } from 'margoengine/gltf/pbr';
272
+ import { Physics } from 'margoengine/physics';
273
+ import { fitRagdollShapes } from 'margoengine/ragdoll/hulls';
274
+
275
+ await Physics.load();
276
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!);
277
+ const physics = new Physics(engine);
278
+ physics.addBody(null, { type: 'fixed', colliders: { shape: 'box', halfExtents: [20, 0.1, 20] } });
279
+ const model = await loadGLTF(engine, '/Rig_Medium_MovementBasic.glb'); // KayKit's skinned mannequin (CC0)
280
+ const bone = (name: string) => model.nodes.find((node) => node.name === name)!;
281
+ const hips = bone('hips');
282
+ const ragdoll = Ragdoll.attach(physics, { root: hips });
283
+ const fitted = fitRagdollShapes(ragdoll, model);
284
+ console.log(`${fitted.length} of ${ragdoll.bones.length} bones fit the mesh`);
285
+
286
+ fitRagdollShapes(ragdoll, model, { shape: 'box', minWeight: 0.3 }); // boxes, with blended vertices counted
287
+ ```
288
+
289
+ | Option | Default | Meaning |
290
+ | --- | --- | --- |
291
+ | `shape` | `'hull'` | `'hull'`, or `'box'`: cheaper, and looser. |
292
+ | `minWeight` | `0.5` | A vertex counts toward a bone when the bone carries this share of it. |
293
+ | `maxPoints` | `64` | Most corners a hull keeps, 8 to 1,024. |
294
+
295
+ The source is the glTF model the skeleton belongs to, or a `RagdollSkin` of your own (`positions`, `joints`, `weights`, `nodes`, `inverseBindMatrices`). The result lists the bones that got a shape; a bone with no vertices that span a volume keeps its capsule. Mass, friction, groups and joints stay as they were, and each bone's inertia follows its new shape. Call it before `addRagdollMotors`, and give a leaf bone you want a hull for, such as a head with no child, a `length` so it is a bone.
296
+
297
+ The same data goes in by hand: `ragdoll.setShape(bone, shape)`, or `shape` on an entry of `bones`, takes `{type: 'capsule'}`, `{type: 'hull', points}` or `{type: 'box', center, halfExtents, rotation}`, in the bone's own frame. `part.shape` reads it back and `part.mass` the mass as built.
298
+
299
+ ## Saved profiles (`margoengine/ragdoll/profile`)
300
+
301
+ A profile is a ragdoll as plain JSON: bones by name, joints and limits, sizes, masses, shapes and the shared body settings. Tune a ragdoll once, save it, and every copy of the character builds the same one. `humanoidProfile` is a place to start.
302
+
303
+ ```ts
304
+ import { Ragdoll } from 'margoengine/ragdoll';
305
+ import { EngineKernel } from 'margoengine/core';
306
+ import { loadGLTF } from 'margoengine/gltf/pbr';
307
+ import { Physics } from 'margoengine/physics';
308
+ import { humanoidProfile, ragdollOptions, saveRagdollProfile } from 'margoengine/ragdoll/profile';
309
+
310
+ await Physics.load();
311
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!);
312
+ const physics = new Physics(engine);
313
+ physics.addBody(null, { type: 'fixed', colliders: { shape: 'box', halfExtents: [20, 0.1, 20] } });
314
+ // Two KayKit mannequins (CC0) on one rig: one engine has one Physics, which both ragdolls share.
315
+ const model = await loadGLTF(engine, '/Rig_Medium_MovementBasic.glb');
316
+ const otherModel = await loadGLTF(engine, '/Rig_Medium_General.glb');
317
+ const bone = (name: string) => model.nodes.find((node) => node.name === name)!;
318
+ // KayKit names its bones its own way, so name the humanoid ones.
319
+ const bones = {
320
+ hips: bone('hips'), spine: bone('spine'), chest: bone('chest'), head: bone('head'),
321
+ leftUpperArm: bone('upperarm.l'), leftLowerArm: bone('lowerarm.l'), leftHand: bone('wrist.l'),
322
+ rightUpperArm: bone('upperarm.r'), rightLowerArm: bone('lowerarm.r'), rightHand: bone('wrist.r'),
323
+ leftUpperLeg: bone('upperleg.l'), leftLowerLeg: bone('lowerleg.l'), leftFoot: bone('foot.l'),
324
+ rightUpperLeg: bone('upperleg.r'), rightLowerLeg: bone('lowerleg.r'), rightFoot: bone('foot.r'),
325
+ };
326
+
327
+ // Anatomical ranges, hinged knees and elbows, published mass shares.
328
+ const ragdoll = Ragdoll.attach(physics, ragdollOptions(humanoidProfile(model.nodes, { mass: 82, bones }), model.nodes));
329
+
330
+ const saved = JSON.stringify(saveRagdollProfile(ragdoll));
331
+ const again = Ragdoll.attach(physics, ragdollOptions(JSON.parse(saved), otherModel.nodes));
332
+ ```
333
+
334
+ | Function | Gives |
335
+ | --- | --- |
336
+ | `saveRagdollProfile(ragdoll)` | The profile, every value as built. Bones need unique names. |
337
+ | `ragdollOptions(profile, nodes)` | The options for `new Ragdoll` or `Ragdoll.attach`; add your own beside them. It throws a coded `MargoError` naming a bone the skeleton lacks, and for a profile of a newer version. |
338
+ | `humanoidProfile(nodes, {mass, bones})` | A profile for a humanoid in a T or A pose. `mass` defaults to 70 kg. |
339
+
340
+ `humanoidProfile` finds bones by the names `detectSkeleton` knows (Mixamo, Godot, Roblox, humanoid). For other names, pass `bones: {hips: node, leftUpperLeg: node, ...}`; it needs hips, a head, and upper and lower arms and legs. Every node between two named bones joins the lower one's mass, with a small cone. `ragdoll.settings` reads the shared settings a profile saves.
341
+
342
+ ## Balance (`margoengine/ragdoll/balance`)
343
+
344
+ `addRagdollBalance(ragdoll, motors, {feet})` keeps a powered character on its feet, on its own legs. It watches the capture point of the centre of mass, the spot a step must reach to stop the fall, and swings a foot there; two-bone maths sets each leg from where the hips should be to where its foot is. The weight goes down the stance legs as torque pairs at knee and ankle, held to what the sole can answer as it lies now, through a step too, so no outside force holds it up and a stance foot is not turned onto its heel.
345
+
346
+ ```ts
347
+ import { Ragdoll } from 'margoengine/ragdoll';
348
+ import { addRagdollBalance } from 'margoengine/ragdoll/balance';
349
+ import { addRagdollMotors } from 'margoengine/ragdoll/powered';
350
+ import { EngineKernel } from 'margoengine/core';
351
+ import { loadGLTF } from 'margoengine/gltf/pbr';
352
+ import { Physics } from 'margoengine/physics';
353
+ import { humanoidProfile, ragdollOptions } from 'margoengine/ragdoll/profile';
354
+
355
+ await Physics.load();
356
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!);
357
+ const physics = new Physics(engine);
358
+ physics.addBody(null, { type: 'fixed', colliders: { shape: 'box', halfExtents: [20, 0.1, 20] } });
359
+ const model = await loadGLTF(engine, '/Rig_Medium_MovementBasic.glb'); // KayKit's skinned mannequin (CC0)
360
+ const bone = (name: string) => model.nodes.find((node) => node.name === name)!;
361
+ // KayKit names its bones its own way, so name the humanoid ones.
362
+ const bones = {
363
+ hips: bone('hips'), spine: bone('spine'), chest: bone('chest'), head: bone('head'),
364
+ leftUpperArm: bone('upperarm.l'), leftLowerArm: bone('lowerarm.l'), leftHand: bone('wrist.l'),
365
+ rightUpperArm: bone('upperarm.r'), rightLowerArm: bone('lowerarm.r'), rightHand: bone('wrist.r'),
366
+ leftUpperLeg: bone('upperleg.l'), leftLowerLeg: bone('lowerleg.l'), leftFoot: bone('foot.l'),
367
+ rightUpperLeg: bone('upperleg.r'), rightLowerLeg: bone('lowerleg.r'), rightFoot: bone('foot.r'),
368
+ };
369
+ const ragdoll = Ragdoll.attach(physics, ragdollOptions(humanoidProfile(model.nodes, { bones }), model.nodes));
370
+ const motors = addRagdollMotors(ragdoll, { frequency: 8 });
371
+ const balance = addRagdollBalance(ragdoll, motors, { feet: [bone('foot.l'), bone('foot.r')] });
372
+ ragdoll.activate();
373
+
374
+ motors.hit(bone('spine'), [0, 0, -40]); // it stumbles, steps and catches itself
375
+ if (balance.state === 'fallen') motors.fade(0, 0.5);
376
+ ```
377
+
378
+ | Option | Default | Meaning |
379
+ | --- | --- | --- |
380
+ | `feet` | none | The two foot bones. Each needs a knee hinge above it, as `humanoidProfile` builds. |
381
+ | `stepTime` | `0.28` | Seconds a step takes at most; a harder push shortens it (below). |
382
+ | `stepHeight` | `0.15` | How high a foot lifts, as a share of the leg's length. |
383
+ | `stepTrigger` | `0.2` | How far the capture point may leave the line between the feet before a step, as a share of the leg's length. A step also starts once the capture point leaves both soles. |
384
+ | `stance` | `0.97` | Hip height held, as a share of the height when added. |
385
+ | `carry` | `0` | Share of the upper body's weight an outside force carries, 0 to 1. Off: it stands on its own legs. |
386
+ | `upright` | `10` | Frequency in rad/s of the turn that holds the hips upright, answered through the legs by the ground. |
387
+ | `maxUpright` | `40` | Largest turn that gives, in rad/s². A harder blow knocks the character over. |
388
+ | `fallTilt` | `0.8` | Radians of lean past which it has fallen and balancing stops. |
389
+ | `gravity` | `9.81` | World gravity along up, in m/s². |
390
+
391
+ A step lands where the capture point will be when the foot comes down, and a hard push makes the capture point run away from the stance foot as e^(omega t), so a step that took its full `stepTime` would land short and the stance foot would be dragged off the ground. Each step takes no longer than the capture point needs to reach the edge of the leg's reach, ln(reach / d) / omega for a capture point d from the stance foot, the reach being the longest step people take and recover from, 78.5 percent of stature (Schulz, Ashton-Miller and Alexander 2007), with stature the hip joint's height over the sole over 0.53 (Drillis and Contini), and no less than 0.4 / omega (0.094 s for a figure 0.26 m tall at the hips): step timing adaptation (Khadiv, Herzog, Moosavian and Righetti, IEEE T-RO 2020) on the capture point of Pratt et al. (2006) and Englsberger et al. (2011). Nor does it take longer than the capture point, e outside the stance sole, needs to run past the sole being put down for it, which reaches m beyond its ankle that way: ln(1 + m / e) / omega. A step lands no farther from the stance foot than that, and through the step the hips sink until the swing leg, at its longest from its own hip joint (not the hips' origin), reaches where it lands, so the step the planner counts on is one the leg has. A step starts once the capture point lies `stepTrigger` from the line between the feet, or once it leaves the base of support, the hull of both planted soles, whichever comes first: with both feet down no pressure point under them stops the fall past it (the March 2011 draft of Rebula, Koolen, de Boer and Pratt's capturability analysis, Corollaries 2 and 3, in Koolen's TU Delft MSc thesis; Stephens 2011, eq. 3.15), so Seed-san pushed backward at 0.4 m/s steps on the first frame instead of the 35th (KB-RAGDOLL-SEEDSANLOW1). Once a step has caught the body and the capture point lies inside one sole, that foot alone stops the fall (zero-step capturable, Koolen et al., IJRR 2012), so the other foot, if it stands farther than `stepTrigger` from its place beside it, steps back there and the stance is two feet wide for the next push; the ground's `contactforce` on each foot says which one carries the weight. A body held midway over two feet whose soles do not reach the capture point never meets that, and no step is called for while the point lies near the line between the feet, so with both feet down, apart by more than `stepTrigger`, and the capture point over neither sole, the body is carried over the stood-on point of the foot nearer it, and the other foot is then free to come in. For now this acts only on a foot whose heel is shorter than a quarter of its sole, Seed-san's (0.030 m of 0.228 m): on the other figures the same carry cost extra steps and falls, so it is gated until the follow-through for every figure lifts the gate (KB-RAGDOLL-FOLLOWTHROUGH1 in `docs/known-bugs.md`). A planted foot's target stays on the ground, so a stance foot a push lifts is pressed back down, and a foot that is off the ground anyway steps next. Both feet are held level, the swing foot heading where the hips head as SIMBICON keeps it (Yin, Loken and van de Panne 2007), and every target stays inside the ankle's cone. The ankle's limits hold under the weight, which they did not on the earlier solver: `docs/limits.md`, Ragdoll balance. Knight recovers a 1.5 m/s push of its upper body in each of four directions at every solver setting from 2 to 6 iterations, 4, 8 and 16 substeps and warm start on and off, which `node packages/ragdoll/scripts/balance-ab.mjs --sweep` checks.
392
+
393
+ Every torque is a pair inside the body, so a hard enough blow knocks it over. Set `carry` to lend an outside force, capped at 1.5 times the share asked for; `balance.carried` reads the share of the body's weight it gave at the last step, and is 0 without it. While it balances it adds inertia to the feet and shins, brings the character's island, not the world, to at least 8 solver passes, and stands a foot fitted with a hull on a flat sole of four corners; `dispose` takes all three away, and its `contactforce` listener. A stance knee takes its torque from the balance, with a spring of its own beside it, so `motors.setStrength` reaches only the swinging leg's knee. Its torques are forces, so more solver passes only steady it, and a force of your own on a bone stays yours. `steps` counts steps, `capture` is the capture point, `tilt` the lean, and `state` is `standing`, `stepping` or `fallen`. Add it with the character standing still, before `activate`. After a fall, get up with `margoengine/ragdoll/getup` and call `reset()`. `motors.setTarget(bone, rotation)` is what it drives the legs with, and is open to any controller: a rotation relative to the parent bone, or `null` for the animation's pose.
394
+
395
+ ## Character controller bridge (`margoengine/ragdoll/character`)
396
+
397
+ `addCharacterRagdoll({ controller, ragdoll, animator?, motors?, getUp?, root? })` links a `CharacterController` or `DynamicCharacter` with a `Ragdoll` so a walking character avoids self-colliding with its own ragdoll hitboxes, carries walking momentum into `knockdown(bone, impulse)` (disabling the controller capsule while limp, or triggering a partial-limb ragdoll via `{ limb }`), and recovers via `recover()` by relocating the capsule to `ragdoll.rootPosition`, blending out cleanly (via `GetUp` when provided) and re-enabling locomotion with zero pop.
398
+
399
+ ```ts
400
+ import { EngineKernel } from 'margoengine/core';
401
+ import { loadGLTF } from 'margoengine/gltf/pbr';
402
+ import { Physics } from 'margoengine/physics';
403
+ import { Ragdoll } from 'margoengine/ragdoll';
404
+ import { addCharacterRagdoll } from 'margoengine/ragdoll/character';
405
+ await Physics.load();
406
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!);
407
+ const physics = new Physics(engine);
408
+ physics.addBody(null, { type: 'fixed', position: [0, -0.5, 0], colliders: { shape: 'box', halfExtents: [20, 0.5, 20] } });
409
+ const model = await loadGLTF(engine, '/Rig_Medium_MovementBasic.glb');
410
+ const capsule = physics.addBody(null, { type: 'kinematicPosition', position: [0, 0.9, 0], colliders: { shape: 'capsule', halfHeight: 0.55, radius: 0.35 } });
411
+ const controller = physics.createCharacterController(capsule, { applyImpulsesToDynamicBodies: true, characterMass: 70 });
412
+ const ragdoll = Ragdoll.attach(physics, { root: model.nodes.find((n) => n.name === 'hips')! });
413
+ const bridge = addCharacterRagdoll({ controller, ragdoll, root: model.root });
414
+ bridge.move([0, -0.16, 0.05]);
415
+ ```
416
+
417
+ | Member | Meaning |
418
+ | --- | --- |
419
+ | `state` | `'walking'`, `'ragdoll'`, or `'recovering'`. |
420
+ | `move(desired, filter?)` | Sweeps a kinematic `CharacterController` while `'walking'` (excluding own ragdoll hitboxes); no-op while limp. |
421
+ | `setTargetVelocity(v)` / `jump(speed)` / `update()` | Drives a `DynamicCharacter` while `'walking'`. |
422
+ | `knockdown(bone?, impulse?, options?)` | Full knockdown (disables controller capsule, activates ragdoll, carries velocity) or partial-limb hit (`{ limb }`). |
423
+ | `isSettled(linearSpeed?, angularSpeed?)` | True when knocked down and all limp bones have slowed below the thresholds. |
424
+ | `recover(options?)` | Relocates capsule to ground under `ragdoll.rootPosition`, blends via `GetUp` or `ragdoll.deactivate`, re-enables controller with zero pop. |
425
+ | `debugRender(options?)` | Combined debug lines for the controller and ragdoll. |
426
+ | `dispose()` | Restores original collision groups, re-enables controller, and disposes internally created helpers. `using` works. |
427
+
428
+ ## Clean room
429
+
430
+ Written from public descriptions only, cited in [docs/clean-room.md](../../docs/clean-room.md); no engine's ragdoll code
431
+ was read.