@margoengine/ragdoll 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Scott Campbell
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Margo Engine
2
+ Copyright 2026 Scott Campbell
3
+
4
+ This product includes Margo Engine (https://margoengine.com) by Scott Campbell.
package/README.md CHANGED
@@ -1,3 +1,381 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.