flutter3d
Showcase Changelog 62 packages API reference

A ragdoll

since 1.0.0-rc.1 Physics and particles

A ragdoll is a body made of capsules, one for each bone, joined where each bone meets its parent. Each joint lets its bone turn only as far as the joint it stands for: a knee bends one way, a shoulder swings in a wide cone. NativeRagdoll builds one in the physics core from a list of bones given in world space. It knows nothing about scenes or skinned models, so a page can make one from a dozen numbers.

This page stands a figure of eleven bones at the top of four steps, shoves it in the chest and lets it fall. Ragdolls exist only on the core. Where the core will not start, the page shows the stairs and says why beside the viewport.

Step 1: The bones #

A RagdollBone has a name, the index of its parent (−1 for the root, and always an earlier bone), a head where it meets the parent, a tail where its capsule ends, a radius and a mass. Its joint says how it is held to its parent. RagdollBall is a ball joint with a cone for the swing and limits on the twist, for the spine, neck, shoulders and hips. RagdollHinge is a hinge about an axis in the bone's own frame, from a lower to an upper angle, for elbows and knees.

/// A figure standing with its feet at [o]: hips, chest, head, two arms
/// and two legs, each bone from its head (where it meets its parent) to
/// its tail, with a radius and a mass — the reference man's 73 kg shared
/// as de Leva measured (`SegmentMassShares`), a forearm with its hand and a
/// shin with its foot. Its spine and neck are ball joints
/// in a narrow cone, the shoulders and hips wide ones, the elbows and
/// knees hinges that bend one way.
static List<RagdollBone> _figure(Vector3 o) {
  const spine = RagdollBall(cone: 0.5, twistLower: -0.4, twistUpper: 0.4);
  const shoulder = RagdollBall(cone: 1.5, twistLower: -1.0, twistUpper: 1.0);
  const hip = RagdollBall(cone: 1.2, twistLower: -0.5, twistUpper: 0.5);
  final elbow = RagdollHinge(axis: Vector3(1, 0, 0), lower: 0, upper: 2.4);
  final knee = RagdollHinge(axis: Vector3(1, 0, 0), lower: -2.4, upper: 0);
  double kg(double share) => referenceBodyMass * share;
  RagdollBone bone(
    String name,
    int parent,
    (double, double, double) head,
    (double, double, double) tail,
    double radius,
    double mass, [
    RagdollJoint? joint,
  ]) => RagdollBone(
    name: name,
    parent: parent,
    head: o + Vector3(head.$1, head.$2, head.$3),
    tail: o + Vector3(tail.$1, tail.$2, tail.$3),
    orientation: Quaternion.identity(),
    radius: radius,
    mass: mass,
    joint: joint,
  );
  return <RagdollBone>[
    bone(
      'hips',
      -1,
      (0, 0.92, 0),
      (0, 1.1, 0),
      0.13,
      kg(SegmentMassShares.lowerTrunk),
    ),
    bone(
      'chest',
      0,
      (0, 1.1, 0),
      (0, 1.55, 0),
      0.15,
      kg(SegmentMassShares.upperTrunk + SegmentMassShares.middleTrunk),
      spine,
    ),
    bone(
      'head',
      1,
      (0, 1.58, 0),
      (0, 1.82, 0),
      0.11,
      kg(SegmentMassShares.head),
      spine,
    ),
    bone(
      'arm.L',
      1,
      (-0.25, 1.5, 0),
      (-0.25, 1.2, 0),
      0.05,
      kg(SegmentMassShares.upperArm),
      shoulder,
    ),
    bone(
      'arm.R',
      1,
      (0.25, 1.5, 0),
      (0.25, 1.2, 0),
      0.05,
      kg(SegmentMassShares.upperArm),
      shoulder,
    ),
    bone(
      'forearm.L',
      3,
      (-0.25, 1.2, 0),
      (-0.25, 0.92, 0),
      0.045,
      kg(SegmentMassShares.forearm + SegmentMassShares.hand),
      elbow,
    ),
    bone(
      'forearm.R',
      4,
      (0.25, 1.2, 0),
      (0.25, 0.92, 0),
      0.045,
      kg(SegmentMassShares.forearm + SegmentMassShares.hand),
      elbow,
    ),
    bone(
      'thigh.L',
      0,
      (-0.1, 0.92, 0),
      (-0.1, 0.5, 0),
      0.07,
      kg(SegmentMassShares.thigh),
      hip,
    ),
    bone(
      'thigh.R',
      0,
      (0.1, 0.92, 0),
      (0.1, 0.5, 0),
      0.07,
      kg(SegmentMassShares.thigh),
      hip,
    ),
    bone(
      'shin.L',
      7,
      (-0.1, 0.5, 0),
      (-0.1, 0.06, 0),
      0.055,
      kg(SegmentMassShares.shank + SegmentMassShares.foot),
      knee,
    ),
    bone(
      'shin.R',
      8,
      (0.1, 0.5, 0),
      (0.1, 0.06, 0),
      0.055,
      kg(SegmentMassShares.shank + SegmentMassShares.foot),
      knee,
    ),
  ];
}

Step 2: The world, and the ragdoll in it #

The floor and the steps are fixed boxes. The ragdoll is made in the world with NativeRagdoll(world, bones): one capsule for each bone and one joint where each bone meets its parent. The joints' limits are taken from the pose the bones are given in, so a ragdoll is built standing and only then moved into another pose with place. This one is not moved at all.

Every joint is made of JointTissue.human by default: it damps the joint's turning, a newton metre for each radian a second, and gives a little past the end of its range. Without that damping a ragdoll lying on the floor never stops moving, because nothing slows a head rolling or a leg turning about its own length. The world takes eight substeps a step instead of four. With four, an arm hitting the edge of a step can swing past its cone for a step.

/// A world with the floor and the stairs as fixed boxes, and the figure
/// standing on the landing. Eight substeps a step, not four: at four, a
/// limb struck on a stair's edge can swing past its cone for a step.
void _build() {
  unavailable = null;
  _world = null;
  _doll = null;
  if (!physicsCoreLoaded) {
    unavailable = 'the core is not loaded in this browser yet';
    return;
  }
  final NativeWorld world;
  try {
    world = NativeWorld()..substeps = 8;
  } on Object catch (e) {
    unavailable = '$e';
    return;
  }
  for (final (Vector3 center, Vector3 half) in _blocks) {
    final NativeBody block = world.addBody(
      position: center,
      type: NativeBodyType.fixed,
      mass: 0.0,
    );
    world.setShape(block, NativeShape.box(half));
  }
  _world = world;
  // Every joint's tissue damps its turning, the default; without it a
  // ragdoll on the floor never comes to rest.
  _doll = NativeRagdoll(world, _figure(_feet));
}

Step 3: The push #

bodyOf gives the core's body for a bone, and an impulse on the chest pushes the whole figure. Push it again wakes it and pushes it once more from wherever it lies.

/// A shove to the chest, forward and a little to the side: ninety-five
/// newton seconds on its 23.6 kilograms, four metres a second.
void _push() {
  final NativeRagdoll? doll = _doll;
  if (doll == null) return;
  _world!.applyImpulse(doll.bodyOf(1), Vector3(95.0, 0.0, 12.5));
}

Step 4: Draw each bone as its capsule #

A ragdoll's capsule lies along its body's own y axis, and its straight part is the bone's length less a radius at each end. So each bone is drawn as a CapsuleShape of that size, placed each frame at its body's position and orientation. poseOf would give the bone's own frame instead, for a skinned model whose rig chose its own axes.

// Each bone drawn as the capsule its body is: along the body's own y,
// its straight part as long as the bone less its two rounded ends.
final cloth = RenderMaterial(
  name: 'ragdoll',
  baseColor: LinearColor.fromSrgb(0.8, 0.55, 0.35, 1.0),
  roughness: 0.6,
);
for (final RagdollBone bone in _figure(_feet)) {
  final double length = bone.head.distanceTo(bone.tail);
  final double straight = math.max(0.02, length - 2 * bone.radius);
  final node = MeshNode(
    DeviceMesh.upload(
      context.device,
      CapsuleShape(radius: bone.radius, height: straight).build(),
    ),
    cloth,
    name: bone.name,
  );
  _bones.add(node);
  scene.add(node);
}

Step 5: What it has to do #

The check pushes the figure again and steps until every bone is asleep, giving up after fifteen seconds. After every step it measures each bone's head against its parent's and compares the distance with the one the bones were built with. No joint may open by more than three centimetres on the way down. The hips have to end at least half a metre lower than they started, and no bone may end inside the floor. On macOS the figure sleeps after about four and a half seconds, and no joint opens by more than six millimetres.

// From the push until it sleeps, each bone's head read against its
// parent's after every step: how far apart they are against how far
// apart they were built.
_restart();
final NativeRagdoll doll = _doll!;
final List<RagdollBone> bones = doll.bones;
final double hipsFrom = doll.poseOf(0).position.y;
var stretched = 0.0;
var steps = 0;
while (!doll.isAsleep && steps < 900) {
  _world!.step(_step);
  steps++;
  for (var i = 1; i < bones.length; i++) {
    final RagdollBone b = bones[i];
    final double built = b.head.distanceTo(bones[b.parent].head);
    final double now = doll
        .poseOf(i)
        .position
        .distanceTo(doll.poseOf(b.parent).position);
    stretched = math.max(stretched, (now - built).abs());
  }
}
if (!doll.isAsleep) throw StateError('it never came to rest');
// No joint opens by more than 3 cm on the way down.
if (stretched > 0.03) {
  throw StateError('a joint opened by ${stretched.toStringAsFixed(3)} m');
}
// It came down the stairs, and nothing ended inside the floor: a
// capsule lying on it has its centre a radius up.
if (doll.poseOf(0).position.y > hipsFrom - 0.5) {
  throw StateError('it never went down the stairs');
}
for (var i = 0; i < bones.length; i++) {
  final double y = _world!.localPositionOf(doll.bodyOf(i)).y;
  if (y < bones[i].radius - 0.01) {
    throw StateError('${bones[i].name} ended in the floor at $y');
  }
}

Note. The joints are soft. A joint can open by a few centimetres for a step when a limb hits hard, and a limb can go a few degrees past its limit, before the solver pulls it back. At rest the error is a fraction of a millimetre. The figure here is made of plain capsules with no hands or feet, so it slides on the steps more than a body would. For a skinned model, SkeletonRagdoll builds the bones from the model's skeleton and writes the bodies back into its joints.