flutter3d
Showcase Changelog 62 packages API reference

Several shapes on one body: the source

since 1.0.0-rc.1 Physics and particles

Regions the guide quotes: parts (line 58), body (line 178), draw (line 293), follow (line 325), check (line 377).

1/// A table, a dumbbell and a hammer, each one body made of several shapes,
2/// dropped onto a floor by the physics core. They land and rest on their
3/// parts: the table on its four legs, the dumbbell on its two weights, the
4/// hammer on its head and the end of its handle.
5///
6/// Quoted by `compound_shapes.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_physics_native/flutter3d_physics_native.dart';
14import 'package:flutter3d_showcase/src/demo/demo.dart';
16/// One part: the shape as the core takes it, and the mesh that draws it.
17typedef _Piece = ({NativeCompoundPart part, MeshData mesh});
19/// One body made of [pieces], and what the core moved them by so that the
20/// body's origin is their centre of mass.
21final class _Thing {
22 _Thing(this.name, this.body, this.offset, this.pieces);
24 final String name;
25 final NativeBody body;
26 final Vector3 offset;
27 final List<_Piece> pieces;
30/// The `compound-shapes` page: a table, a dumbbell and a hammer, each one
31/// body of several shapes, dropped on the physics core. Its check is that
32/// each comes to rest on the parts it should.
33final class CompoundShapesDemo extends ShowcaseDemo {
34 NativeWorld? _world;
35 List<_Thing> _things = const <_Thing>[];
36 final List<SceneNode> _nodes = <SceneNode>[];
38 /// Why nothing falls, or null when the core is running.
39 String? unavailable;
41 double _age = 0.0;
43 static const double _step = 1 / 60;
45 /// The quarter turn that lays a part made upright along y along x.
46 static Quaternion get _alongX =>
47 Quaternion.axisAngle(Vector3(0.0, 0.0, 1.0), math.pi / 2);
49 @override
50 void configureView(DemoContext context) {
51 context.orbit
52 ..distance = 7.5
53 ..pitch = 0.45
54 ..yaw = 0.35;
55 context.orbit.target.setValues(0.2, 0.3, 0.0);
56 }
58 /// A top and four legs, all boxes. The compound's origin is on the floor
59 /// under the middle of the table, where the legs end.
60 static List<_Piece> _table() => <_Piece>[
61 (
62 part: NativeCompoundPart(
63 NativeShape.box(Vector3(0.6, 0.025, 0.4)),
64 at: Vector3(0.0, 0.725, 0.0),
65 ),
66 mesh: CuboidShape(size: Vector3(1.2, 0.05, 0.8)).build(),
67 ),
68 for (final (double x, double z) in const <(double, double)>[
69 (-0.55, -0.35),
70 (0.55, -0.35),
71 (-0.55, 0.35),
72 (0.55, 0.35),
73 ])
74 (
75 part: NativeCompoundPart(
76 NativeShape.box(Vector3(0.03, 0.35, 0.03)),
77 at: Vector3(x, 0.35, z),
78 ),
79 mesh: CuboidShape(size: Vector3(0.06, 0.7, 0.06)).build(),
80 ),
81 ];
83 /// Two balls and the bar between them. A capsule stands along y, so the
84 /// bar is turned a quarter round z to lie along x.
85 static List<_Piece> _dumbbell() => <_Piece>[
86 for (final double x in const <double>[-0.35, 0.35])
87 (
88 part: NativeCompoundPart(
89 const NativeShape.sphere(0.16),
90 at: Vector3(x, 0.0, 0.0),
91 ),
92 mesh: const SphereShape(radius: 0.16).build(),
93 ),
94 (
95 part: NativeCompoundPart(
96 const NativeShape.capsule(0.035, 0.3),
97 orientation: _alongX,
98 ),
99 mesh: const CapsuleShape(radius: 0.035, height: 0.6).build(),
100 ),
101 ];
103 /// A handle, a cylinder laid along x, and a head that is a hull: a block
104 /// that narrows towards its striking face. The world keeps the hull, and
105 /// moved its points so that its centre of mass is at its origin;
106 /// `hullOffset` says by how much, and the part is placed with it so the
107 /// head sits where its points say.
108 static List<_Piece> _hammer(NativeWorld world) {
109 final NativeHull head = world.createHull(_headPoints);
110 final Vector3 shift = world.hullOffset(head);
111 return <_Piece>[
112 (
113 part: NativeCompoundPart(
114 const NativeShape.cylinder(0.03, 0.3),
115 orientation: _alongX,
116 ),
117 mesh: const CylinderShape(
118 radiusTop: 0.03,
119 radiusBottom: 0.03,
120 height: 0.6,
121 ).build(),
122 ),
123 (
124 part: NativeCompoundPart.hull(
125 head,
126 at: Vector3(0.36, 0.0, 0.0) + shift,
127 ),
128 mesh: _headMesh(shift),
129 ),
130 ];
131 }
133 /// The head's eight corners: 12 cm square at the back, 7 cm at the face,
134 /// 30 cm long along z.
135 static final List<Vector3> _headPoints = <Vector3>[
136 for (final double z in const <double>[-0.15, 0.15])
137 for (final double x in <double>[-1.0, 1.0])
138 for (final double y in <double>[-1.0, 1.0])
139 Vector3(
140 x * (z < 0.0 ? 0.06 : 0.035),
141 y * (z < 0.0 ? 0.06 : 0.035),
142 z,
143 ),
144 ];
146 /// The head drawn from the same corners, less what the hull was moved by,
147 /// one flat face at a time.
148 static MeshData _headMesh(Vector3 shift) {
149 final List<Vector3> p = <Vector3>[
150 for (final Vector3 v in _headPoints) v - shift,
151 ];
152 final Vector3 middle = p.fold(Vector3.zero(), (a, v) => a + v) / 8.0;
153 final MeshBuilder builder = MeshBuilder(VertexLayout.standard);
154 for (final List<int> f in const <List<int>>[
155 <int>[0, 2, 3, 1],
156 <int>[4, 6, 7, 5],
157 <int>[0, 1, 5, 4],
158 <int>[2, 6, 7, 3],
159 <int>[0, 4, 6, 2],
160 <int>[1, 3, 7, 5],
161 ]) {
162 final Vector3 n = (p[f[1]] - p[f[0]]).cross(p[f[2]] - p[f[0]])
163 ..normalize();
164 final Vector3 center =
165 (p[f[0]] + p[f[1]] + p[f[2]] + p[f[3]]) / 4.0 - middle;
166 final bool outward = n.dot(center) > 0.0;
167 final List<int> order = outward ? f : f.reversed.toList();
168 final Vector3 normal = outward ? n : -n;
169 final List<int> at = <int>[
170 for (final int i in order)
171 builder.addVertex(position: p[i], normal: normal),
172 ];
173 builder.addQuad(at[0], at[1], at[2], at[3]);
174 }
175 return builder.build();
176 }
178 /// One body shaped as [pieces], [mass] kilograms, with the compound's own
179 /// origin put at [at] and turned by [turn]. The core moved the parts by
180 /// `compoundOffset` to put their centre of mass on the body's origin, so
181 /// the body goes that much further along.
182 static _Thing _add(
183 NativeWorld world,
184 String name,
185 List<_Piece> pieces, {
186 required Vector3 at,
187 required Quaternion turn,
188 required double mass,
189 }) {
190 final NativeCompound compound = world.createCompound(<NativeCompoundPart>[
191 for (final _Piece p in pieces) p.part,
192 ]);
193 final Vector3 offset = world.compoundOffset(compound);
194 final NativeBody body = world.addBody(
195 position: at + turn.asRotationMatrix().transformed(offset),
196 mass: mass,
197 );
198 world
199 ..setCompound(body, compound)
200 ..setOrientation(body, turn);
201 return _Thing(name, body, offset, pieces);
202 }
204 /// A floor and the three things over it, a little tilted, so each lands
205 /// on one part first and settles onto the rest.
206 static (NativeWorld, List<_Thing>) _drop() {
207 final NativeWorld world = NativeWorld();
208 final NativeBody floor = world.addBody(
209 position: Vector3(0.0, -0.5, 0.0),
210 type: NativeBodyType.fixed,
211 mass: 0.0,
212 );
213 world.setShape(floor, NativeShape.box(Vector3(4.0, 0.5, 3.0)));
214 final List<_Thing> things = <_Thing>[
215 _add(
216 world,
217 'table',
218 _table(),
219 at: Vector3(-1.8, 0.4, 0.0),
220 turn: Quaternion.axisAngle(Vector3(1.0, 0.0, 0.0), 0.12),
221 mass: 20.0,
222 ),
223 _add(
224 world,
225 'dumbbell',
226 _dumbbell(),
227 at: Vector3(0.2, 1.0, 0.0),
228 turn: Quaternion.axisAngle(Vector3(0.0, 0.0, 1.0), 0.25),
229 mass: 8.0,
230 ),
231 _add(
232 world,
233 'hammer',
234 _hammer(world),
235 at: Vector3(1.9, 1.2, 0.0),
236 turn:
237 Quaternion.axisAngle(Vector3(1.0, 0.0, 0.0), 0.5) *
238 Quaternion.axisAngle(Vector3(0.0, 0.0, 1.0), 0.3),
239 mass: 1.5,
240 ),
241 ];
242 return (world, things);
243 }
245 /// Starts the core, or keeps the reason it would not start.
246 void _start() {
247 _world?.dispose();
248 _world = null;
249 _age = 0.0;
250 if (!physicsCoreLoaded) {
251 unavailable = 'the core is not loaded in this browser yet';
252 return;
253 }
254 try {
255 final (NativeWorld world, List<_Thing> things) = _drop();
256 _world = world;
257 _things = things;
258 unavailable = null;
259 } on Object catch (e) {
260 unavailable = '$e';
261 }
262 }
264 @override
265 void dispose() {
266 _world?.dispose();
267 _world = null;
268 }
270 @override
271 Scene build(DemoContext context) {
272 _start();
273 final Scene scene = Scene()
274 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
275 ..ambientIntensity = 0.25 * LightNode.legacyUnit
276 ..add(
277 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
278 ..setLocalForward(Vector3(-0.3, -0.7, -0.4)),
279 )
280 ..add(
281 MeshNode(
282 DeviceMesh.upload(
283 context.device,
284 CuboidShape(size: Vector3(8.0, 1.0, 6.0)).build(),
285 ),
286 RenderMaterial(
287 name: 'floor',
288 baseColor: LinearColor.fromSrgb(0.42, 0.45, 0.48, 1.0),
289 ),
290 name: 'floor',
291 )..setPosition(0.0, -0.5, 0.0),
292 );
293 // A node follows each body; under it, a mesh for every part, where the
294 // part sits once the core has moved it by the offset.
295 for (final (int i, _Thing thing) in _things.indexed) {
296 final material = RenderMaterial(
297 name: thing.name,
298 baseColor: LinearColor.fromSrgb(
299 0.55 + 0.35 * math.sin(i * 1.3 + 0.4),
300 0.45 + 0.3 * math.sin(i * 2.1 + 1.5),
301 0.35 + 0.3 * math.sin(i * 0.7 + 2.6),
302 1.0,
303 ),
304 roughness: 0.6,
305 );
306 final node = SceneNode(name: thing.name);
307 for (final (int j, _Piece piece) in thing.pieces.indexed) {
308 node.add(
309 MeshNode(
310 DeviceMesh.upload(context.device, piece.mesh),
311 material,
312 name: '${thing.name} part $j',
313 )
314 ..setPositionFrom(piece.part.at - thing.offset)
315 ..setRotation(piece.part.orientation),
316 );
317 }
318 _nodes.add(node);
319 scene.add(node);
320 }
321 _follow();
322 return scene;
323 }
325 /// Each node takes its body's place and turn from the core.
326 void _follow() {
327 final NativeWorld? world = _world;
328 if (world == null) return;
329 for (final (int i, _Thing thing) in _things.indexed) {
330 _nodes[i]
331 ..setPositionFrom(world.localPositionOf(thing.body))
332 ..setRotation(world.orientationOf(thing.body));
333 }
334 }
336 @override
337 void update(DemoContext context, double dt) {
338 final NativeWorld? world = _world;
339 if (world == null) return;
340 world.step(_step);
341 _age += dt;
342 if (_age > 6.0) _start();
343 _follow();
344 }
346 @override
347 List<DemoControl> controls(DemoContext context) => <DemoControl>[
348 ToggleControl(
349 unavailable == null
350 ? 'Drop again'
351 : 'Drop again (unavailable: $unavailable)',
352 value: () => false,
353 onChanged: (bool v) {
354 if (v) _start();
355 },
356 ),
357 ];
359 /// Where [local], a point in [thing]'s compound frame, is in the world.
360 @visibleForTesting
361 Vector3 pointOf(String thing, Vector3 local) {
362 final NativeWorld world = _world!;
363 final _Thing t = _things.firstWhere((t) => t.name == thing);
364 return world.localPositionOf(t.body) +
365 world
366 .orientationOf(t.body)
367 .asRotationMatrix()
368 .transformed(local - t.offset);
369 }
371 @override
372 void verify(Scene scene, FrameResult frame) {
373 if (unavailable != null) {
374 throw StateError('the core did not start: $unavailable');
375 }
376 final NativeWorld world = _world!;
377 for (var i = 0; i < 240; i++) {
378 world.step(_step);
379 }
380 for (final _Thing t in _things) {
381 if (!world.isAsleep(t.body)) {
382 throw StateError('the ${t.name} never came to rest');
383 }
384 }
385 // The table: its legs end at the compound's origin, so standing on them
386 // that origin is on the floor, a centimetre at most either way, and the
387 // top is level.
388 final Vector3 feet = pointOf('table', Vector3.zero());
389 final Vector3 top = pointOf('table', Vector3(0.0, 0.75, 0.0));
390 if (feet.y.abs() > 0.01 || (top.y - 0.75).abs() > 0.01) {
391 throw StateError('the table is not on its legs: feet $feet, top $top');
392 }
393 // The dumbbell: both balls on the floor, so the bar lies level at their
394 // radius.
395 for (final double x in const <double>[-0.35, 0.35]) {
396 final Vector3 ball = pointOf('dumbbell', Vector3(x, 0.0, 0.0));
397 if ((ball.y - 0.16).abs() > 0.01) {
398 throw StateError('a dumbbell ball rests at $ball, not on the floor');
399 }
400 }
401 // The hammer: the far end of its handle on the floor at the handle's
402 // radius, and its head low beside it, not propped up on the head alone.
403 final Vector3 end = pointOf('hammer', Vector3(-0.3, 0.0, 0.0));
404 final Vector3 head = pointOf('hammer', Vector3(0.36, 0.0, 0.0));
405 if ((end.y - 0.03).abs() > 0.01 || head.y > 0.07) {
406 throw StateError('the hammer rests at handle $end, head $head');
407 }
408 if (frame.drawCalls < 1) throw StateError('nothing reached the frame');
409 }