flutter3d
Showcase Changelog 62 packages API reference

Liquids on the core: the source

since 1.0.0-rc.1 Physics and particles

Regions the guide quotes: solver (line 93), utube (line 116), float (line 144), pour (line 159), step (line 252), check (line 411).

1/// Glassware on the physics core: two tubes joined at the bottom by a short
2/// pipe, filled to different heights, which swing and settle level; a
3/// wooden block floating in a basin; and a test tube tipped over another,
4/// pouring a stream that the other catches.
5///
6/// Quoted by `liquids.md` and shown whole in the Source tab.
7library;
8
9import 'dart:math' as math;
11import 'package:flutter/foundation.dart' show visibleForTesting;
12import 'package:flutter3d/flutter3d.dart';
13import 'package:flutter3d_matter/flutter3d_matter.dart';
14import 'package:flutter3d_physics/flutter3d_physics.dart';
15import 'package:flutter3d_physics_native/flutter3d_physics_native.dart';
16import 'package:flutter3d_showcase/src/demo/demo.dart';
18/// A straight tube [radius] wide and [height] tall with a flat floor, its
19/// floor at the origin of its own frame.
20RevolvedVessel _tube(double radius, double height) => RevolvedVessel(<Vector2>[
21 Vector2(0.0, 0.0),
22 Vector2(radius, 0.0),
23 Vector2(radius, height),
24]);
26/// One vessel as it is drawn: its glass, the liquid in it, and where it
27/// stands.
28final class _Glass {
29 _Glass(this.body, this.radius, this.height, this.at, this.glass, this.fill);
31 final LiquidBody body;
32 final double radius;
33 final double height;
34 final Vector3 at;
35 final MeshNode glass;
36 final MeshNode fill;
38 /// Turned this far about x, radians: the pouring tube tips.
39 double tilt = 0.0;
41 Matrix3 get turn => Matrix3.rotationX(tilt);
44/// The `liquids` page: a U-tube, a floating block and a pour between test
45/// tubes on the physics core. Its check is that the U-tube levels, the
46/// block floats at its share, and the pour loses no volume.
47final class LiquidsDemo extends ShowcaseDemo {
48 /// The U-tube and the basin, at a hundred and twentieth of a second.
49 late FluidWorld _vessels;
51 /// The pour, at the finer step a stream in the air needs.
52 late FluidWorld _pouring;
54 late Dynamics _dynamics;
55 late RigidBody _block;
56 late _Glass _left, _right, _basin, _source, _target;
57 late Pipe _pipe;
58 late double _pourTotal;
60 final List<MeshNode> _drops = <MeshNode>[];
61 late MeshNode _blockNode;
62 late MeshNode _pipeNode;
64 /// Why the liquids are on the reference, or null when they are on the
65 /// core.
66 String? fallback;
68 /// Whether to ask for the core. Off, both worlds are the reference.
69 bool onCore = true;
71 double _age = 0.0;
73 static const double _frame = 1 / 60;
75 /// The one gravity both worlds on this page are made with.
76 static Vector3 get _gravity => standardGravityVector;
78 /// Half the block: six by four centimetres and two and a half thick.
79 static Vector3 get _half => Vector3(0.03, 0.012, 0.02);
81 /// Pine, at six hundred kilograms a cubic metre.
82 static const double _density = 600.0;
84 @override
85 void configureView(DemoContext context) {
86 context.orbit
87 ..distance = 0.75
88 ..pitch = 0.4
89 ..yaw = 0.25;
90 context.orbit.target.setValues(0.0, 0.07, 0.0);
91 }
93 /// The core's fluid solver where the core starts, the reference where it
94 /// does not, and the reason kept to say so. A game that called
95 /// `startPhysics()` would leave this out: a `FluidWorld` made without a
96 /// solver takes the run's, `usePhysics().fluid`.
97 FluidSolver _solver() {
98 fallback = null;
99 if (!onCore) return const DartFluid();
100 if (!physicsCoreLoaded) {
101 fallback = 'the core is not loaded in this browser yet';
102 return const DartFluid();
103 }
104 try {
105 NativeWorld().dispose();
106 return const NativeLiquid();
107 } on Object catch (e) {
108 fallback = '$e';
109 return const DartFluid();
110 }
111 }
113 /// The liquids and the glass that draws them, built afresh.
114 void _fill(DemoContext context, Scene scene) {
115 final FluidSolver solver = _solver();
116 // Two tubes four centimetres across, one filled to twelve centimetres and
117 // one to six, joined at their floors by a pipe of eight millimetres bore
118 // and three centimetres long.
119 _vessels = FluidWorld(
120 world: WorldProperties(gravity: _gravity),
121 dt: 1 / 120,
122 solver: solver,
123 );
124 LiquidBody water(RevolvedVessel shape, double radius, double level) =>
125 LiquidBody(
126 shape: shape,
127 medium: FluidMedium.water,
128 volume: math.pi * radius * radius * level,
129 modes: 2,
130 );
131 final LiquidBody left = water(_tube(0.02, 0.2), 0.02, 0.12);
132 final LiquidBody right = water(_tube(0.02, 0.2), 0.02, 0.06);
133 _pipe = Pipe(
134 from: left,
135 at: Vector3(0.0, 0.002, 0.0),
136 to: right,
137 toAt: Vector3(0.0, 0.002, 0.0),
138 radius: 0.004,
139 length: 0.03,
140 );
141 _vessels.bodies.addAll(<LiquidBody>[left, right]);
142 _vessels.pipes.add(_pipe);
144 // A basin twenty centimetres across, six deep, and a block of pine let go
145 // a centimetre over it. The block is an ordinary rigid body; the world
146 // lifts it by the water it displaces and drags it as it moves.
147 final LiquidBody basin = water(_tube(0.1, 0.12), 0.1, 0.06);
148 _vessels.bodies.add(basin);
149 _dynamics = Dynamics(world: CollisionWorld(), gravity: _gravity);
150 _block = RigidBody(
151 world: _dynamics.world,
152 shape: CollisionBox(_half),
153 position: Vector3(0.0, 0.06 + _half.y + 0.01, 0.0),
154 mass: _density * 8.0 * _half.x * _half.y * _half.z,
155 );
156 _dynamics.add(_block);
157 _vessels.float(_block);
159 // A narrow test tube seven tenths full, tipped over a wider empty one.
160 // What runs over its lip is a stream the world flies, and what the wide
161 // tube catches is added to it; what misses lands on the bench as
162 // particles.
163 _pouring = FluidWorld(
164 world: WorldProperties(gravity: _gravity),
165 floor: <JetObstacle>[
166 PlaneObstacle(normal: Vector3(0.0, 1.0, 0.0), offset: 0.0),
167 ],
168 solver: solver,
169 );
170 final source = LiquidBody(
171 shape: _tube(0.008, 0.1),
172 medium: FluidMedium.water,
173 volume: math.pi * 0.008 * 0.008 * 0.07,
174 modes: 6,
175 wallThickness: 0.0008,
176 );
177 final target = LiquidBody(
178 shape: _tube(0.012, 0.1),
179 medium: FluidMedium.water,
180 volume: 0.0,
181 modes: 6,
182 wallThickness: 0.0008,
183 );
184 _pouring.bodies.addAll(<LiquidBody>[source, target]);
185 _pourTotal = _pouring.volume;
187 final RenderMaterial glassLook = RenderMaterial(
188 name: 'glass',
189 baseColor: LinearColor.fromSrgb(0.85, 0.92, 1.0, 0.18),
190 roughness: 0.1,
191 alphaMode: MaterialAlphaMode.blend,
192 doubleSided: true,
193 );
194 final RenderMaterial waterLook = RenderMaterial(
195 name: 'water',
196 baseColor: LinearColor.fromSrgb(0.2, 0.45, 0.85, 1.0),
197 roughness: 0.2,
198 );
199 final DeviceMesh cylinder = DeviceMesh.upload(
200 context.device,
201 const CylinderShape(radiusTop: 1.0, radiusBottom: 1.0).build(),
202 );
203 _Glass glass(LiquidBody body, double radius, double height, Vector3 at) {
204 final g = _Glass(
205 body,
206 radius,
207 height,
208 at,
209 MeshNode(cylinder, glassLook, name: 'glass'),
210 MeshNode(cylinder, waterLook, name: 'water'),
211 );
212 // The water first, so the glass round it blends over it.
213 scene
214 ..add(g.fill)
215 ..add(g.glass);
216 return g;
217 }
219 _left = glass(left, 0.02, 0.2, Vector3(-0.235, 0.0, 0.0));
220 _right = glass(right, 0.02, 0.2, Vector3(-0.165, 0.0, 0.0));
221 _basin = glass(basin, 0.1, 0.12, Vector3(0.0, 0.0, 0.0));
222 _source = glass(source, 0.008, 0.1, Vector3(0.2, 0.1, -0.1045));
223 _target = glass(target, 0.012, 0.1, Vector3(0.2, 0.0, 0.0));
224 _pipeNode = MeshNode(cylinder, waterLook, name: 'pipe')
225 ..setRotation(Quaternion.axisAngle(Vector3(0.0, 0.0, 1.0), math.pi / 2))
226 ..setPosition(-0.2, 0.004, 0.0)
227 ..setScale(0.004, 0.07, 0.004);
228 _blockNode = MeshNode(
229 DeviceMesh.upload(context.device, CuboidShape(size: _half * 2.0).build()),
230 RenderMaterial(
231 name: 'pine',
232 baseColor: LinearColor.fromSrgb(0.8, 0.62, 0.38, 1.0),
233 ),
234 name: 'block',
235 );
236 scene
237 ..add(_pipeNode)
238 ..add(_blockNode);
239 final DeviceMesh drop = DeviceMesh.upload(
240 context.device,
241 const SphereShape(radius: 0.0015, segments: 8, rings: 4).build(),
242 );
243 for (var i = 0; i < 160; i++) {
244 final node = MeshNode(drop, waterLook, name: 'drop $i')
245 ..isVisible = false;
246 _drops.add(node);
247 scene.add(node);
248 }
249 _age = 0.0;
250 }
252 /// One frame: each world run on by its own whole steps, every vessel put
253 /// where it stands before each, and the block stepped with the vessels'
254 /// world so it is pushed once for every step it falls.
255 void _run(double seconds) {
256 _runVessels(seconds);
257 _runPour(seconds);
258 }
260 void _runVessels(double seconds) {
261 for (var i = 0; i < (seconds / _vessels.dt).round(); i++) {
262 for (final _Glass g in <_Glass>[_left, _right, _basin]) {
263 g.body.place(g.turn, g.at, timeSeconds: _vessels.timeSeconds);
264 }
265 _vessels.update(_vessels.dt);
266 _dynamics.step(_vessels.dt);
267 }
268 }
270 void _runPour(double seconds) {
271 for (var i = 0; i < (seconds / _pouring.dt).round(); i++) {
272 // Tipped over half a second, to seventy-five degrees.
273 _source.tilt = math.min(1.3, 2.6 * _pouring.timeSeconds);
274 for (final _Glass g in <_Glass>[_source, _target]) {
275 g.body.place(g.turn, g.at, timeSeconds: _pouring.timeSeconds);
276 }
277 _pouring.update(_pouring.dt);
278 }
279 }
281 @override
282 Scene build(DemoContext context) {
283 final Scene scene = Scene()
284 ..ambientColor = LinearColor(0.55, 0.6, 0.7)
285 ..ambientIntensity = 0.35 * LightNode.legacyUnit
286 ..add(
287 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
288 ..setLocalForward(Vector3(-0.3, -0.7, -0.5)),
289 )
290 ..add(
291 MeshNode(
292 DeviceMesh.upload(
293 context.device,
294 CuboidShape(size: Vector3(0.7, 0.02, 0.35)).build(),
295 ),
296 RenderMaterial(
297 name: 'bench',
298 baseColor: LinearColor.fromSrgb(0.3, 0.3, 0.32, 1.0),
299 ),
300 name: 'bench',
301 )..setPosition(0.0, -0.011, 0.0),
302 );
303 _fill(context, scene);
304 _context = context;
305 _scene = scene;
306 _place();
307 return scene;
308 }
310 late DemoContext _context;
311 late Scene _scene;
313 /// Every glass and its liquid where the worlds have them, and the drops in
314 /// the air and on the bench.
315 void _place() {
316 for (final _Glass g in <_Glass>[_left, _right, _basin, _source, _target]) {
317 final Quaternion q = Quaternion.axisAngle(Vector3(1.0, 0.0, 0.0), g.tilt);
318 final Vector3 axis = g.turn.transformed(Vector3(0.0, 1.0, 0.0));
319 g.glass
320 ..setRotation(q)
321 ..setPositionFrom(g.at + axis * (0.5 * g.height))
322 ..setScale(g.radius, g.height, g.radius);
323 // Upright, the liquid is a column to the surface the world keeps. The
324 // tipped tube's is drawn as the same volume along its axis, which is
325 // where it is not, but near enough to see it empty.
326 final double depth = g.tilt == 0.0
327 ? g.body.height
328 : g.body.volume / (math.pi * g.radius * g.radius);
329 final double shown = depth.clamp(0.0, g.height);
330 g.fill
331 ..isVisible = shown > 1e-4
332 ..setRotation(q)
333 ..setPositionFrom(g.at + axis * (0.5 * shown))
334 ..setScale(0.97 * g.radius, shown, 0.97 * g.radius);
335 }
336 _blockNode
337 ..setPositionFrom(_block.position)
338 ..setRotation(_block.orientation);
339 final List<Vector3> airborne = <Vector3>[
340 for (final Jet jet in _pouring.jets.values)
341 for (final List<JetSample> run in jet.runs)
342 for (final JetSample s in run) s.position,
343 for (final ParticleFluid fluid in _pouring.particles.values)
344 ...fluid.positions,
345 ];
346 for (var i = 0; i < _drops.length; i++) {
347 final bool shown = i < airborne.length;
348 _drops[i].isVisible = shown;
349 if (shown) _drops[i].setPositionFrom(airborne[i]);
350 }
351 }
353 @override
354 void update(DemoContext context, double dt) {
355 _run(_frame);
356 _age += _frame;
357 if (_age > 8.0) _restart();
358 _place();
359 }
361 void _restart() {
362 for (final MeshNode n in <MeshNode>[
363 for (final _Glass g in <_Glass>[
364 _left,
365 _right,
366 _basin,
367 _source,
368 _target,
369 ]) ...<MeshNode>[g.glass, g.fill],
370 _pipeNode,
371 _blockNode,
372 ..._drops,
373 ]) {
374 _scene.remove(n);
375 }
376 _drops.clear();
377 _fill(_context, _scene);
378 _place();
379 }
381 @override
382 List<DemoControl> controls(DemoContext context) => <DemoControl>[
383 ToggleControl(
384 fallback == null
385 ? 'Liquids on the core'
386 : 'Liquids on the core (unavailable: $fallback)',
387 value: () => onCore && fallback == null,
388 onChanged: (bool v) {
389 onCore = v;
390 _restart();
391 },
392 ),
393 ToggleControl(
394 'Fill again',
395 value: () => false,
396 onChanged: (bool v) {
397 if (v) _restart();
398 },
399 ),
400 ];
402 /// The solver both worlds are stepped by, for a test that checks it.
403 @visibleForTesting
404 FluidSolver get solver => _vessels.solver;
406 @override
407 void verify(Scene scene, FrameResult frame) {
408 if (fallback == null && _vessels.solver is! NativeLiquid) {
409 throw StateError('the liquids are not on the core');
410 }
411 // Two and a half seconds. The block bobs for longer than that, so what
412 // is held is the share of it under water on average over the last one
413 // and a quarter: the weight of the water it displaces is its own, so
414 // that share is its density over water's.
415 final double volume = 8.0 * _half.x * _half.y * _half.z;
416 var under = 0.0;
417 var samples = 0;
418 for (var i = 0; i < 150; i++) {
419 _runVessels(_frame);
420 // The pour is the dear part: a second and a quarter of it is enough
421 // for the stream to reach the wide tube.
422 if (i < 75) _runPour(_frame);
423 if (i >= 75) {
424 under += _vessels.floating.single.submergedIn(_basin.body) / volume;
425 samples++;
426 }
427 }
428 // The U-tube has swung from six centimetres apart to level.
429 final double apart = (_left.body.height - _right.body.height).abs();
430 if (apart > 0.003) {
431 throw StateError('the U-tube is ${apart * 1000} mm out of level');
432 }
433 final double share = under / samples;
434 if ((share - _density / FluidMedium.water.density).abs() > 0.05) {
435 throw StateError('the block floats ${share.toStringAsFixed(3)} under');
436 }
437 // The pour has reached the other tube, and not a drop is lost: what is
438 // in the two tubes, in the air and on the bench is what there was.
439 if (_target.body.volume <= 0.0) throw StateError('nothing was poured');
440 if ((_pouring.volume - _pourTotal).abs() > _pourTotal * 1e-9) {
441 throw StateError('the pour lost ${_pourTotal - _pouring.volume} m³');
442 }
443 if (frame.drawCalls < 1) throw StateError('nothing reached the frame');
444 }