flutter3d
Showcase Changelog 62 packages API reference

Rigid bodies: the source

since 0.2.0 Physics and particles

Regions the guide quotes: world (line 55), body (line 83), snapshot (line 124), live (line 134), shove (line 153), restore (line 162), check (line 188).

1/// Crates dropped one after another onto a floor: they land, stack, settle and
2/// fall asleep, and a snapshot taken before any of it winds the pile back to
3/// where it began. The physics runs live, a step to a frame.
4///
5/// Quoted by `rigid_bodies.md` and shown whole in the Source tab.
6library;
7
8import 'dart:math' as math;
9
10import 'package:flutter/foundation.dart' show visibleForTesting;
11import 'package:flutter3d/flutter3d.dart';
12import 'package:flutter3d_physics/flutter3d_physics.dart';
13import 'package:flutter3d_physics_native/flutter3d_physics_native.dart';
14import 'package:flutter3d_showcase/src/demo/demo.dart';
16/// The `rigid-bodies` page: crates dropped onto a floor, stepped live. Its
17/// check is that the pile lands, rests and sleeps, and that restoring the
18/// snapshot puts every crate back.
19final class RigidBodiesDemo extends ShowcaseDemo {
20 late final CollisionWorld _world;
21 late final RigidDynamics _dynamics;
23 /// The core's world, let go with the page; null until the page is built.
24 NativeDynamics? _native;
26 /// [_native], for a test that leaves the page.
27 @visibleForTesting
28 NativeDynamics? get core => _native;
29 final List<RigidBody> _crates = <RigidBody>[];
30 final List<double> _halves = <double>[];
31 final List<MeshNode> _meshes = <MeshNode>[];
32 final List<Map<String, Object?>> _start = <Map<String, Object?>>[];
34 bool _shoveAsked = false;
35 double _atRest = 0.0;
36 double _age = 0.0;
38 static const int _count = 8;
39 static const double _step = 1 / 60;
41 @override
42 void configureView(DemoContext context) {
43 context.orbit
44 ..distance = 8.0
45 ..pitch = 0.35
46 ..yaw = 0.6;
47 context.orbit.target.setValues(0.0, 1.0, 0.0);
48 }
50 @override
51 void dispose() => _native?.dispose();
53 @override
54 Scene build(DemoContext context) {
55 _world = CollisionWorld();
56 _world.addBox(Vector3(0.0, -0.5, 0.0), Vector3(6.0, 1.0, 6.0));
57 // The run's backend: the core, or the Dart reference where it will
58 // not start.
59 _dynamics = usePhysics().dynamics(DynamicsRequest(_world));
60 if (_dynamics case final NativeDynamics core) _native = core;
62 final Scene scene = Scene()
63 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
64 ..ambientIntensity = 0.25 * LightNode.legacyUnit
65 ..add(
66 MeshNode(
67 DeviceMesh.upload(
68 context.device,
69 CuboidShape(size: Vector3(6.0, 1.0, 6.0)).build(),
70 ),
71 RenderMaterial(
72 name: 'floor',
73 baseColor: LinearColor.fromSrgb(0.42, 0.46, 0.43, 1.0),
74 ),
75 name: 'floor',
76 )..setPosition(0.0, -0.5, 0.0),
77 )
78 ..add(
79 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
80 ..setLocalForward(Vector3(-0.3, -0.6, -0.4)),
81 );
83 // Eight crates, each higher up and a little off to one side of the last,
84 // so they arrive one at a time and land on one another as often as on
85 // the floor.
86 for (var i = 0; i < _count; i++) {
87 final double half = 0.3 + 0.08 * (i % 3);
88 final RigidBody crate = _dynamics.add(
89 RigidBody(
90 world: _world,
91 shape: CollisionBox(Vector3(half, half, half)),
92 position: Vector3(
93 0.5 * math.sin(i * 2.4),
94 1.2 + i * 1.1,
95 0.5 * math.cos(i * 1.9),
96 ),
97 mass: 2.0,
98 friction: 0.7,
99 ),
100 );
101 _crates.add(crate);
102 _halves.add(half);
103 final MeshNode mesh = MeshNode(
104 DeviceMesh.upload(
105 context.device,
106 CuboidShape(size: Vector3.all(half * 2)).build(),
107 ),
108 RenderMaterial(
109 name: 'crate $i',
110 baseColor: LinearColor.fromSrgb(
111 0.55 + 0.4 * math.sin(i * 0.9),
112 0.5 + 0.3 * math.sin(i * 1.7 + 1.0),
113 0.35 + 0.3 * math.sin(i * 2.3 + 2.0),
114 1.0,
115 ),
116 roughness: 0.7,
117 ),
118 name: 'crate $i',
119 )..setPositionFrom(crate.position);
120 _meshes.add(mesh);
121 scene.add(mesh);
122 }
124 // Taken before a single step: everything a body needs to be put back
125 // exactly here — position, velocity, whether it is asleep.
126 for (final RigidBody crate in _crates) {
127 _start.add(crate.save());
128 }
129 return scene;
130 }
132 @override
133 void update(DemoContext context, double dt) {
134 _age += dt;
135 // A step of a sixtieth of a second, however long the frame took: the
136 // same drop lands the same way on every machine.
137 _dynamics.step(_step);
139 if (_shoveAsked) {
140 _shoveAsked = false;
141 _shove();
142 }
144 _atRest = _crates.every((RigidBody c) => c.isAsleep) ? _atRest + dt : 0.0;
145 // Watched for a moment at rest, then wound back and dropped again.
146 if (_atRest > 1.5 || _age > 12.0) _rewind();
148 for (var i = 0; i < _count; i++) {
149 _meshes[i].setPositionFrom(_crates[i].position);
150 }
151 }
153 void _shove() {
154 for (var i = 0; i < _count; i++) {
155 _crates[i].applyImpulse(
156 Vector3(math.sin(i * 2.1) * 3.0, 4.0, math.cos(i * 1.7) * 3.0),
157 );
158 }
159 _atRest = 0.0;
160 }
162 void _rewind() {
163 for (var i = 0; i < _count; i++) {
164 _crates[i].restore(_start[i]);
165 }
166 _atRest = 0.0;
167 _age = 0.0;
168 }
170 @override
171 List<DemoControl> controls(DemoContext context) => <DemoControl>[
172 ToggleControl(
173 'Shove them',
174 value: () => _shoveAsked,
175 onChanged: (bool v) => _shoveAsked = v,
176 ),
177 ToggleControl(
178 'Rewind to the start',
179 value: () => false,
180 onChanged: (bool v) {
181 if (v) _rewind();
182 },
183 ),
184 ];
186 @override
187 void verify(Scene scene, FrameResult frame) {
188 // Let the pile come to rest. Every crate has to end up on the floor or
189 // on another crate: none fallen through, none left hanging in the air.
190 for (var i = 0; i < 600; i++) {
191 _dynamics.step(_step);
192 }
193 for (var i = 0; i < _count; i++) {
194 final double y = _crates[i].position.y;
195 if (y < _halves[i] - 0.05) {
196 throw StateError('crate $i fell through the floor: y = $y');
197 }
198 if (y > 8.0) {
199 throw StateError('crate $i is still in the air: y = $y');
200 }
201 }
202 if (!_crates.every((RigidBody c) => c.isAsleep)) {
203 throw StateError('the pile should have come to rest and gone to sleep');
204 }
206 // Winding back has to undo all of it, exactly.
207 _rewind();
208 for (var i = 0; i < _count; i++) {
209 final Vector3 back = _crates[i].position;
210 final Vector3 saved = Vector3(
211 0.5 * math.sin(i * 2.4),
212 1.2 + i * 1.1,
213 0.5 * math.cos(i * 1.9),
214 );
215 if ((back - saved).length > 1e-6) {
216 throw StateError('restore should have put crate $i back where it was');
217 }
218 }
219 if (frame.drawCalls < 1) {
220 throw StateError('the crates did not reach the frame');
221 }
222 }