Bridging a falling rigid body and its collision: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: live (line 135), world (line 218), body (line 234), bridge (line 243), fall (line 273).
1/// `FlameRigidBody` and `CollisionBridge` carrying a falling
2/// `RigidBody`'s own physics, and its landing, onto Flame.
3///
4/// Quoted by `flame_physics_bridge.md` and shown whole in the Source tab.
5library;
7import 'package:flame/components.dart';
8import 'package:flame_flutter3d/flame_flutter3d.dart';
9import 'package:flutter/widgets.dart';
10import 'package:flutter3d/flutter3d.dart';
11import 'package:flutter3d_physics/flutter3d_physics.dart';
12import 'package:flutter3d_physics_native/flutter3d_physics_native.dart';
13import 'package:flutter3d_showcase/src/demo/demo.dart';
14import 'package:flutter3d_showcase/src/demo/flame_layer.dart';
16/// Hears about the crate's landing the way any Flame component would, and
17/// tells whoever is watching.
18final class _TrackingRigidBodyComponent extends FlameRigidBody {
19 _TrackingRigidBodyComponent({
20 required super.body,
21 required super.node,
22 required super.scene,
23 required super.plane,
24 this.onTouch,
25 });
27 bool collided = false;
28 PositionComponent? other;
30 /// Called with `true` when the crate starts touching the landing pad and
31 /// `false` when it stops.
32 final void Function(bool touching)? onTouch;
35 void onCollisionStart(
36 Set<Vector2> intersectionPoints,
37 PositionComponent other,
38 ) {
39 super.onCollisionStart(intersectionPoints, other);
40 collided = true;
41 this.other = other;
42 onTouch?.call(true);
43 }
46 void onCollisionEnd(PositionComponent other) {
47 super.onCollisionEnd(other);
48 onTouch?.call(false);
49 }
50}
52/// The `flame-physics-bridge` page: a crate dropped onto the ground by the
53/// physics and followed by a Flame component. Its check is that the crate
54/// settles at y = 0.3 and that `CollisionBridge` relays the landing.
55final class FlamePhysicsBridgeDemo extends ShowcaseDemo {
56 late final String _report;
57 late final double _crateHeight;
58 late final bool _collided;
60 /// Where the crate starts above the ground, in metres, 0.5 to 4.0 on the
61 /// "Drop height" slider; read again each time it is dropped.
62 double dropHeight = 2.5;
64 late final DemoContext _context;
65 late final Scene _scene;
67 /// The live fall's core, let go with the page.
68 NativeDynamics? _native;
71 void dispose() => _native?.dispose();
72 late final MeshNode _pad;
73 late final TransparentFlameGame _game;
74 late final Widget _body = flameOrbit(
75 _context,
76 Flutter3dFlameWidget(
77 game: _game,
78 camera: _context.camera,
79 existing: BorrowedRenderer(
80 device: _context.device,
81 renderer: _context.renderer,
82 ),
83 buildScene: (GraphicsDevice device) => _scene,
84 ),
85 );
87 static const Color _idle = Color(0xFFE6B333);
88 static const Color _touching = Color(0xFF4DD966);
89 static Vector4 get _padIdle => Vector4(0.45, 0.36, 0.14, 1.0);
90 static Vector4 get _padTouching => Vector4(0.2, 0.6, 0.28, 1.0);
93 void configureView(DemoContext context) {
94 context.orbit
95 ..distance = 6.5
96 ..pitch = 0.3
97 ..yaw = 0.7;
98 context.orbit.target.setValues(0.0, 0.8, 0.0);
99 }
102 Scene build(DemoContext context) {
103 _context = context;
104 final (String report, double height, bool collided) = _run(context.device);
105 _report = report;
106 _crateHeight = height;
107 _collided = collided;
109 MeshNode cuboid(String name, Vector3 size, Vector4 color) => MeshNode(
110 DeviceMesh.upload(context.device, CuboidShape(size: size).build()),
111 RenderMaterial(name: name, baseColor: _fromSrgb(color)),
112 name: name,
113 );
114 _pad = cuboid('landing pad', Vector3(6.0, 0.1, 6.0), _padIdle)
115 ..setPosition(0.0, 0.02, 0.0);
116 final MeshNode crate = cuboid(
117 'crate',
118 Vector3(0.6, 0.6, 0.6),
119 Vector4(0.7, 0.5, 0.3, 1.0),
120 );
121 _scene = Scene()
122 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
123 ..ambientIntensity = 0.3 * LightNode.legacyUnit
124 ..add(
125 cuboid('floor', Vector3(6.0, 1.0, 6.0), Vector4(0.36, 0.4, 0.38, 1.0))
126 ..setPosition(0.0, -0.5, 0.0),
127 )
128 ..add(_pad)
129 ..add(crate)
130 ..add(
131 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
132 ..setLocalForward(Vector3(-0.3, -0.6, -0.4)),
133 );
135 // The same world, body and bridge as above, running: a component steps the
136 // solver and dispatches the overlaps, and the crate's own component copies
137 // where the body went. The map is a side view, Flame's y being height.
138 final CollisionWorld world = CollisionWorld()
139 ..addBox(Vector3(0.0, -0.5, 0.0), Vector3(6.0, 1.0, 6.0));
140 final Collider sensor = world.add(
141 Collider(
142 shape: CollisionBox(Vector3(3.0, 0.05, 3.0)),
143 position: Vector3(0.0, 0.02, 0.0),
144 kind: ColliderKind.trigger,
145 ),
146 );
147 final RigidDynamics dynamics = usePhysics().dynamics(
148 DynamicsRequest(world),
149 );
150 if (dynamics case final NativeDynamics core) _native = core;
151 final RigidBody body = dynamics.add(
152 RigidBody(
153 world: world,
154 shape: CollisionBox(Vector3(0.3, 0.3, 0.3)),
155 position: Vector3(0.0, dropHeight, 0.0),
156 mass: 1.0,
157 ),
158 );
159 final Map<String, Object?> start = body.save();
161 final RectangleComponent landing = RectangleComponent(
162 position: Vector2(-3.0, -0.03),
163 size: Vector2(6.0, 0.1),
164 paint: Paint()..color = _idle,
165 );
166 final _TrackingRigidBodyComponent crateComponent =
167 _TrackingRigidBodyComponent(
168 body: body,
169 node: crate,
170 scene: _scene,
171 plane: BridgePlane.backdrop(),
172 // The Flame side reacts to the collision it was handed.
173 onTouch: (bool touching) {
174 landing.paint.color = touching ? _touching : _idle;
175 _pad.material.baseColor = _fromSrgb(
176 touching ? _padTouching : _padIdle,
177 );
178 },
179 )..add(
180 RectangleComponent(
181 size: Vector2.all(0.6),
182 anchor: Anchor.center,
183 paint: Paint()..color = const Color(0xFFB2804D),
184 ),
185 );
186 CollisionBridge(
187 collider: body.collider,
188 component: crateComponent,
189 resolveOther: (Collider other) => other == sensor ? landing : null,
190 );
192 final FlameMinimap map = FlameMinimap();
193 map.world.position = Vector2(120.0, 190.0);
194 map.world.addAll(<Component>[
195 RectangleComponent(
196 position: Vector2(-4.0, 0.0),
197 size: Vector2(8.0, 0.6),
198 paint: Paint()..color = const Color(0xFF5C6660),
199 ),
200 landing,
201 crateComponent,
202 ]);
203 _game = TransparentFlameGame()
204 ..add(_Fall(world, dynamics, body, start, () => dropHeight))
205 ..add(map)
206 ..add(flameCaption('the map: a side view of the same fall'))
207 ..add(
208 flameCaption(
209 'the pad turns green when Flame hears the landing',
210 at: Vector2(16.0, 40.0),
211 ),
212 )
213 ..add(flameCaption(_report, at: Vector2(16.0, 64.0)));
214 return _scene;
215 }
217 static (String, double, bool) _run(GraphicsDevice device) {
218 final world = CollisionWorld();
219 world.addBox(Vector3(0.0, -0.5, 0.0), Vector3(6.0, 1.0, 6.0));
220 // A thin trigger embedded just above the floor, so the crate's fall
221 // overlaps something there is an overlap to relay for — the floor is not
222 // one: its contacts are the solver's, not the world's overlaps. Triggers
223 // stand nowhere in the core, so this sensor never affects how or where
224 // the crate actually lands.
225 final landingSensor = world.add(
226 Collider(
227 shape: CollisionBox(Vector3(3.0, 0.05, 3.0)),
228 position: Vector3(0.0, 0.02, 0.0),
229 kind: ColliderKind.trigger,
230 ),
231 );
232 final dynamics = usePhysics().dynamics(DynamicsRequest(world));
234 final body = dynamics.add(
235 RigidBody(
236 world: world,
237 shape: CollisionBox(Vector3(0.3, 0.3, 0.3)),
238 position: Vector3(0.0, 2.0, 0.0),
239 mass: 1.0,
240 ),
241 );
243 final scene = Scene();
244 final node = MeshNode(
245 DeviceMesh.upload(
246 device,
247 CuboidShape(size: Vector3(0.6, 0.6, 0.6)).build(),
248 ),
249 RenderMaterial(
250 name: 'bridged-crate',
251 baseColor: LinearColor.fromSrgb(0.7, 0.5, 0.3, 1.0),
252 ),
253 );
254 scene.add(node);
255 final component = _TrackingRigidBodyComponent(
256 body: body,
257 node: node,
258 scene: scene,
259 plane: BridgePlane.ground(),
260 );
261 // A Flame component standing in for the landing sensor, so the bridge
262 // below has somewhere real to hand back — a collider with no Flame side
263 // of its own would make `resolveOther` answer null, and the bridge
264 // calls nothing when it does.
265 final landingMarker = PositionComponent();
266 CollisionBridge(
267 collider: body.collider,
268 component: component,
269 resolveOther: (Collider other) =>
270 other == landingSensor ? landingMarker : null,
271 );
273 // Falls, lands, and the world dispatches the overlap each step — the
274 // same two calls `physics_particles/collision_layers.dart` already makes
275 // by hand, now feeding a Flame collision callback instead of a listener
276 // this page owns directly.
277 const double step = 1 / 60;
278 for (var i = 0; i < 180; i++) {
279 dynamics.step(step);
280 world.update();
281 }
282 component.update(step);
284 final settled = body.position.y;
285 usePhysics().release(world);
286 return (
287 'settled at y=${settled.toStringAsFixed(2)}; the bridge heard '
288 'the landing: ${component.collided}',
289 settled,
290 component.collided,
291 );
292 }
294 /// The Flame game the page runs, for a test that steps it without a window.
296 TransparentFlameGame get game => _game;
299 Widget? customBody(BuildContext buildContext, DemoContext context) => _body;
302 void update(DemoContext context, double dt) {
303 context.orbit.syncProjectionDepth(context.camera);
304 }
307 List<DemoControl> controls(DemoContext context) => <DemoControl>[
308 SliderControl(
309 'Drop height',
310 min: 0.5,
311 max: 4.0,
312 value: () => dropHeight,
313 onChanged: (double v) => dropHeight = v,
314 format: (double v) => '${v.toStringAsFixed(1)} m',
315 ),
316 ];
319 void verify(Scene scene, FrameResult frame) {
320 if (frame.drawCalls < 1) {
321 throw StateError('the crate marker was not drawn');
322 }
323 // Compared as numbers and booleans, not read back out of `_report`: see
324 // `sim_audio_xr/actors.dart` for why.
325 if ((_crateHeight - 0.3).abs() > 0.05) {
326 throw StateError(
327 'the crate should have settled at y = 0.3, got $_crateHeight',
328 );
329 }
330 if (!_collided) {
331 throw StateError(
332 'CollisionBridge should have relayed the landing to the Flame '
333 'component',
334 );
335 }
336 }
337}
339/// Steps the solver and the collision world once a Flame frame, and lets the
340/// crate go again a moment after it lands. Added before the crate's own
341/// component, so the body has moved by the time the component copies it.
342final class _Fall extends Component {
343 _Fall(this._world, this._dynamics, this._body, this._start, this._height);
345 final CollisionWorld _world;
346 final RigidDynamics _dynamics;
347 final RigidBody _body;
348 final Map<String, Object?> _start;
349 final double Function() _height;
350 double _rest = 0.0;
353 void update(double dt) {
354 super.update(dt);
355 _dynamics.step(1 / 60);
356 _world.update();
357 _rest = _body.isAsleep ? _rest + dt : 0.0;
358 if (_rest > 1.2) {
359 _body.restore(_start);
360 _body.collider.position.y = _height();
361 _rest = 0.0;
362 }
363 }
364}
366/// A `Vector4` holding a colour sRGB-encoded, as the linear colour it names.
367LinearColor _fromSrgb(Vector4 c) => LinearColor.fromSrgb(c.x, c.y, c.z, c.w);