Liquids on the core
Open the live demo · Read the source · View on GitHub
flutter3d_physics keeps liquids as a FluidWorld: vessels with a surface
that sloshes, pipes between them, the stream that runs over a lip, the drops
it breaks into, and rigid bodies floating in it. What is where, and how much,
is kept in Dart either way. The parts stepped through time (the surface's
waves, a stream's parcels in the air, spilt particles, the column in a pipe
and the push on a floating body) go to a FluidSolver. On the physics core
that is NativeLiquid, the same arithmetic in C. The chemistry bench uses
exactly these pieces for its glassware.
This page shows three of them on one bench: a U-tube that levels out, a floating block, and a pour from one test tube into another.
Step 1: The core's solver, or the reference's #
A game calls startPhysics() once, and every FluidWorld made after that
without a solver takes the run's, usePhysics().fluid. This page passes one
itself so the switch beside the viewport can turn the core off: NativeLiquid
where a core world can be made, DartFluid where it cannot, with the reason
kept to show.
/// The core's fluid solver where the core starts, the reference where it
/// does not, and the reason kept to say so. A game that called
/// `startPhysics()` would leave this out: a `FluidWorld` made without a
/// solver takes the run's, `usePhysics().fluid`.
FluidSolver _solver() {
fallback = null;
if (!onCore) return const DartFluid();
if (!physicsCoreLoaded) {
fallback = 'the core is not loaded in this browser yet';
return const DartFluid();
}
try {
NativeWorld().dispose();
return const NativeLiquid();
} on Object catch (e) {
fallback = '$e';
return const DartFluid();
}
}
Step 2: Two tubes and a pipe #
Two tubes four centimetres across, one filled to twelve centimetres and one to six, joined at their floors by a pipe three centimetres long with a bore of eight millimetres. The water in the pipe has mass, so the difference in pressure accelerates it rather than moving it at once, and friction in the pipe and at its ends slows it down. The levels overshoot by a couple of millimetres, swing back and are level in about two seconds.
// Two tubes four centimetres across, one filled to twelve centimetres and
// one to six, joined at their floors by a pipe of eight millimetres bore
// and three centimetres long.
_vessels = FluidWorld(
world: WorldProperties(gravity: _gravity),
dt: 1 / 120,
solver: solver,
);
LiquidBody water(RevolvedVessel shape, double radius, double level) =>
LiquidBody(
shape: shape,
medium: FluidMedium.water,
volume: math.pi * radius * radius * level,
modes: 2,
);
final LiquidBody left = water(_tube(0.02, 0.2), 0.02, 0.12);
final LiquidBody right = water(_tube(0.02, 0.2), 0.02, 0.06);
_pipe = Pipe(
from: left,
at: Vector3(0.0, 0.002, 0.0),
to: right,
toAt: Vector3(0.0, 0.002, 0.0),
radius: 0.004,
length: 0.03,
);
_vessels.bodies.addAll(<LiquidBody>[left, right]);
_vessels.pipes.add(_pipe);
Step 3: A block that floats #
A basin twenty centimetres across with six of water, and a block of pine let
go a centimetre above it. The block is an ordinary RigidBody stepped by a
Dynamics; float hands it to the fluid world, which each step lifts it by
the weight of the water it displaces, drags it as it moves through the water,
and raises the basin's level by the volume it takes up.
// A basin twenty centimetres across, six deep, and a block of pine let go
// a centimetre over it. The block is an ordinary rigid body; the world
// lifts it by the water it displaces and drags it as it moves.
final LiquidBody basin = water(_tube(0.1, 0.12), 0.1, 0.06);
_vessels.bodies.add(basin);
_dynamics = Dynamics(world: CollisionWorld(), gravity: _gravity);
_block = RigidBody(
world: _dynamics.world,
shape: CollisionBox(_half),
position: Vector3(0.0, 0.06 + _half.y + 0.01, 0.0),
mass: _density * 8.0 * _half.x * _half.y * _half.z,
);
_dynamics.add(_block);
_vessels.float(_block);
Step 4: A pour #
A narrow tube seven tenths full is tipped over a wider empty one. What runs over its lip becomes a stream the world flies, parcel by parcel. What the wide tube catches is added to its liquid, and what misses lands on the bench as particles. The stream needs a finer step than the vessels, so the pour has a world of its own at a two hundred and fortieth of a second.
// A narrow test tube seven tenths full, tipped over a wider empty one.
// What runs over its lip is a stream the world flies, and what the wide
// tube catches is added to it; what misses lands on the bench as
// particles.
_pouring = FluidWorld(
world: WorldProperties(gravity: _gravity),
floor: <JetObstacle>[
PlaneObstacle(normal: Vector3(0.0, 1.0, 0.0), offset: 0.0),
],
solver: solver,
);
final source = LiquidBody(
shape: _tube(0.008, 0.1),
medium: FluidMedium.water,
volume: math.pi * 0.008 * 0.008 * 0.07,
modes: 6,
wallThickness: 0.0008,
);
final target = LiquidBody(
shape: _tube(0.012, 0.1),
medium: FluidMedium.water,
volume: 0.0,
modes: 6,
wallThickness: 0.0008,
);
_pouring.bodies.addAll(<LiquidBody>[source, target]);
_pourTotal = _pouring.volume;
Step 5: Step them #
Each world runs on by whole steps of its own. Every vessel is placed before
each step with the time it is there at, because a vessel's acceleration is
read from its path. The block's Dynamics steps with the vessels' world, so
it falls once for every push it gets.
/// One frame: each world run on by its own whole steps, every vessel put
/// where it stands before each, and the block stepped with the vessels'
/// world so it is pushed once for every step it falls.
void _run(double seconds) {
_runVessels(seconds);
_runPour(seconds);
}
void _runVessels(double seconds) {
for (var i = 0; i < (seconds / _vessels.dt).round(); i++) {
for (final _Glass g in <_Glass>[_left, _right, _basin]) {
g.body.place(g.turn, g.at, timeSeconds: _vessels.timeSeconds);
}
_vessels.update(_vessels.dt);
_dynamics.step(_vessels.dt);
}
}
void _runPour(double seconds) {
for (var i = 0; i < (seconds / _pouring.dt).round(); i++) {
// Tipped over half a second, to seventy-five degrees.
_source.tilt = math.min(1.3, 2.6 * _pouring.timeSeconds);
for (final _Glass g in <_Glass>[_source, _target]) {
g.body.place(g.turn, g.at, timeSeconds: _pouring.timeSeconds);
}
_pouring.update(_pouring.dt);
}
}
Step 6: What has to happen #
After two and a half seconds the two tubes have to be level within three millimetres; on macOS they are within one. The block is still bobbing then, so what is checked is the share of it under water, averaged over the last second and a quarter. At rest the water it displaces weighs what it does, so that share is its density over water's, 0.6. It has to come within 0.05, and comes to 0.61. The pour has to have reached the wide tube, with every drop accounted for: the two tubes, the air and the bench together hold what the narrow tube held to start with.
// Two and a half seconds. The block bobs for longer than that, so what
// is held is the share of it under water on average over the last one
// and a quarter: the weight of the water it displaces is its own, so
// that share is its density over water's.
final double volume = 8.0 * _half.x * _half.y * _half.z;
var under = 0.0;
var samples = 0;
for (var i = 0; i < 150; i++) {
_runVessels(_frame);
// The pour is the dear part: a second and a quarter of it is enough
// for the stream to reach the wide tube.
if (i < 75) _runPour(_frame);
if (i >= 75) {
under += _vessels.floating.single.submergedIn(_basin.body) / volume;
samples++;
}
}
// The U-tube has swung from six centimetres apart to level.
final double apart = (_left.body.height - _right.body.height).abs();
if (apart > 0.003) {
throw StateError('the U-tube is ${apart * 1000} mm out of level');
}
final double share = under / samples;
if ((share - _density / FluidMedium.water.density).abs() > 0.05) {
throw StateError('the block floats ${share.toStringAsFixed(3)} under');
}
// The pour has reached the other tube, and not a drop is lost: what is
// in the two tubes, in the air and on the bench is what there was.
if (_target.body.volume <= 0.0) throw StateError('nothing was poured');
if ((_pouring.volume - _pourTotal).abs() > _pourTotal * 1e-9) {
throw StateError('the pour lost ${_pourTotal - _pouring.volume} m³');
}
Note. The core is not the reference to the bit. It works in single precision and sums in another order, so a U-tube on it swings within a fiftieth of a millimetre of the reference's and a floating body stays within a tenth of one, but a splash goes its own way. Only the stepping moves to the core: the floating block here is still stepped by the Dart
Dynamics, and a wall the core has no record for, a caller's own obstacle, sends that step back to the reference. The liquid in the tipped tube is drawn as a column along its axis, which shows it emptying but is not where the water lies.