flutter3d
Showcase Changelog 62 packages API reference

The physics core

since 1.0.0-rc.1 Physics and particles

Rigid bodies, cloth and liquids can be stepped by two backends. The Dart reference is flutter3d_physics itself: plain Dart, on every platform, from the first line. The core is flutter3d_physics_native, the same physics written in C, built by the package's hook for each target and loaded as WebAssembly in the browser. A game asks once, at the start of the run, and every world after that is made on the answer. The core is the default; the reference is what a run falls back to when the core will not start.

This page drops the same six crates twice. The left pile is on the reference and the right pile on the core, so you can watch the two agree.

Step 1: Ask for the core, and keep the reason when there is none #

A game calls startPhysics() in its main and usePhysics() everywhere after, which makes one choice for the whole run. This page needs both backends at once, so it builds them itself and leaves the run's choice alone.

NativePhysics is the core as a PhysicsBackend, and DartPhysics is the reference. Starting the core is tested, not assumed: a world is made and freed straight away, which is the first call that would find a missing library or bindings for another ABI. If that throws, the right pile goes to the reference too, and the switch beside the viewport says why. In the browser the core has to be fetched first, so a page opened before anything loaded it says that instead.

/// The backend the right pile is stepped by: the core where it starts,
/// the reference where it does not, and the reason kept to say so.
PhysicsBackend _rightBackend() {
  fallback = null;
  if (!onCore) return const DartPhysics();
  if (!physicsCoreLoaded) {
    fallback = 'the core is not loaded in this browser yet';
    return const DartPhysics();
  }
  try {
    // Made and freed at once: the first call that would find a missing
    // library or bindings for another ABI.
    NativeWorld().dispose();
    return NativePhysics();
  } on Object catch (e) {
    fallback = '$e';
    return const DartPhysics();
  }
}

Step 2: One drop, built the same way twice #

Both piles are built by one function from the same numbers: a floor, and six crates nearly in a column, each a little higher than the last. The backend is the only argument. dynamics(DynamicsRequest(world)) is where it matters, and it answers a RigidDynamics, the interface that Dynamics and the core's NativeDynamics both implement. The crates are the same RigidBody objects on either side, with their colliders in an ordinary CollisionWorld, so the rest of a game never needs to know which backend stepped them.

/// A floor and six crates over it, nearly in a column, on [backend]. Both
/// piles are built by this, with the same numbers, so any difference
/// between them is the backend's.
static _Pile _drop(PhysicsBackend backend) {
  final world = CollisionWorld()
    ..addBox(Vector3(0.0, -0.5, 0.0), Vector3(2.4, 1.0, 2.4));
  final RigidDynamics dynamics = backend.dynamics(DynamicsRequest(world));
  final crates = <RigidBody>[
    for (var i = 0; i < _count; i++)
      dynamics.add(
        RigidBody(
          world: world,
          shape: CollisionBox(Vector3.all(0.3)),
          position: Vector3(
            0.12 * math.sin(i * 2.4),
            1.0 + i * 0.9,
            0.12 * math.cos(i * 1.9),
          ),
          mass: 2.0,
          friction: 0.7,
        ),
      ),
  ];
  return _Pile(world, dynamics, crates);
}

Step 3: Step both #

One step of each a frame, at a sixtieth of a second. The left pile is on the left floor and the right pile on the green one. Every six seconds both are dropped again. Switch Right pile on the core off and both sides are the reference, moving as one.

// One step of each, the same sixtieth of a second.
_left.dynamics.step(_step);
_right.dynamics.step(_step);

Step 4: What the two should agree on #

Left for four hundred steps, every crate on both sides has to end on the floor or on another crate, and asleep. The right pile has to really be on the core wherever the core started. The two towers have to end within three centimetres of each other, crate by crate. On macOS they come within one and a half.

// On a machine where the core starts, the right pile has to be on it.
if (fallback == null && _right.dynamics is! NativeDynamics) {
  throw StateError('the right pile is not on the core');
}
final double gap = settledGap();
for (final _Pile pile in <_Pile>[_left, _right]) {
  for (final RigidBody c in pile.crates) {
    if (c.position.y < 0.25) {
      throw StateError('a crate fell through the floor: ${c.position}');
    }
    if (!c.isAsleep) throw StateError('a crate never came to rest');
  }
}
// The core is not the reference to the bit, but this tower ends where
// the reference's does to within three centimetres (one and a half,
// measured, on macOS).
if (gap > 0.03) {
  throw StateError('the two piles part by ${gap.toStringAsFixed(3)} m');
}

Note. The core is not the reference to the bit. It steps in single precision with its own contact solver, so a run's digests differ between the two, though the core gives the same bits on every platform. A tower like this one settles to almost the same place either way. A crate that lands on the edge of another can fall off on one side and stay on the other: dropped further apart, these same six crates end up more than a metre apart. A replay therefore records which backend it ran on, and plays back on that one.