Convex shapes and mesh floors: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: ground (line 51), rock (line 69), mesh (line 99), cylinder (line 108), cone (line 129), hull (line 137), rounded (line 152), draw (line 235), check (line 331).
1/// The core's shapes past boxes, balls and capsules, on a floor that is a
2/// triangle mesh: a cylinder rolling down its ramp, a cone and a hull of
3/// six points dropped on it, and a rounded box thrown tumbling.
4///
5/// Quoted by `convex_shapes.md` and shown whole in the Source tab.
6library;
8import 'dart:math' as math;
10import 'package:flutter3d/flutter3d.dart';
11import 'package:flutter3d_physics_native/flutter3d_physics_native.dart';
12import 'package:flutter3d_showcase/src/demo/demo.dart';
14/// The bodies, in the order the scene draws them, and the hull's offset.
15typedef _Bodies = ({
16 NativeWorld world,
17 NativeBody cylinder,
18 NativeBody cone,
19 NativeBody rock,
20 NativeBody box,
21 Vector3 rockOffset,
22});
24/// The `convex-shapes` page: a cylinder, a cone, a six-point hull and a
25/// rounded box on a triangle-mesh floor. Its check is where each comes to
26/// rest: the cylinder off its ramp and on its side, the cone upright.
27final class ConvexShapesDemo extends ShowcaseDemo {
28 _Bodies? _bodies;
30 /// Why nothing moves: the core would not start. Null when it did.
31 String? unavailable;
33 final List<SceneNode> _nodes = <SceneNode>[];
34 double _age = 0.0;
36 static const double _step = 1 / 60;
38 static const double _cylinderRadius = 0.3, _cylinderHalf = 0.4;
39 static const double _coneRadius = 0.35, _coneHeight = 0.6;
40 static const double _boxHalf = 0.25, _rounding = 0.08;
43 void configureView(DemoContext context) {
44 context.orbit
45 ..distance = 11.0
46 ..pitch = 0.4
47 ..yaw = 0.25;
48 context.orbit.target.setValues(-0.5, 0.4, 0.0);
49 }
51 /// The ground as one triangle mesh: a ramp from x = −6, 1.5 m up, down
52 /// to x = −3, and the floor from there to x = 6, four metres wide. Four
53 /// triangles, wound counter-clockwise seen from above, the side bodies
54 /// touch. The ramp and the floor share the vertices at its foot, so that
55 /// edge is internal and a body rolls over it without a bump.
56 static final List<Vector3> _groundPoints = <Vector3>[
57 Vector3(-6.0, 1.5, -2.0),
58 Vector3(-6.0, 1.5, 2.0),
59 Vector3(-3.0, 0.0, -2.0),
60 Vector3(-3.0, 0.0, 2.0),
61 Vector3(6.0, 0.0, -2.0),
62 Vector3(6.0, 0.0, 2.0),
63 ];
64 static const List<int> _groundTriangles = <int>[
65 0, 1, 2, 2, 1, 3, //
66 2, 3, 4, 4, 3, 5,
67 ];
69 /// A rock of six points: four round its middle in a level plane, one
70 /// above it and one below, not quite over each other. Its faces are the
71 /// eight triangles from the top and the bottom to each edge of the
72 /// middle; the core finds the same hull from the points alone.
73 static final List<Vector3> _rockPoints = <Vector3>[
74 Vector3(0.08, 0.4, 0.05),
75 Vector3(-0.05, -0.3, 0.02),
76 Vector3(0.5, 0.0, 0.05),
77 Vector3(0.05, 0.0, 0.4),
78 Vector3(-0.45, 0.0, 0.0),
79 Vector3(0.0, 0.0, -0.35),
80 ];
81 static const List<int> _rockTriangles = <int>[
82 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 5, 2, //
83 1, 3, 2, 1, 4, 3, 1, 5, 4, 1, 2, 5,
84 ];
86 _Bodies? _build() {
87 unavailable = null;
88 if (!physicsCoreLoaded) {
89 unavailable = 'the core is not loaded in this browser yet';
90 return null;
91 }
92 final NativeWorld w;
93 try {
94 w = NativeWorld();
95 } on Object catch (e) {
96 unavailable = '$e';
97 return null;
98 }
99 // The world keeps the mesh; a fixed body is shaped as it.
100 final NativeMesh mesh = w.createMesh(_groundPoints, _groundTriangles);
101 final NativeBody ground = w.addBody(
102 position: Vector3.zero(),
103 type: NativeBodyType.fixed,
104 mass: 0.0,
105 );
106 w.setMesh(ground, mesh);
108 // A cylinder stands along its body's y. Turned a quarter about x, it
109 // lies across the ramp, set a little above the slope near the top.
110 final double slope = math.atan2(1.5, 3.0);
111 final Vector3 up = Vector3(math.sin(slope), math.cos(slope), 0.0);
112 final NativeBody cylinder = w.addBody(
113 position: Vector3(-5.5, 1.25, -1.2) + up * (_cylinderRadius + 0.02),
114 mass: 3.0,
115 );
116 w
117 ..setShape(
118 cylinder,
119 const NativeShape.cylinder(_cylinderRadius, _cylinderHalf),
120 )
121 ..setOrientation(
122 cylinder,
123 Quaternion.axisAngle(Vector3(1.0, 0.0, 0.0), math.pi / 2),
124 )
125 // Nothing here resists rolling, so a cylinder on a level floor would
126 // roll on to its end. Damping its spin stands in for that.
127 ..setDamping(cylinder, angular: 1.5);
129 // A cone's origin is its centre of mass, a quarter of its height above
130 // its base.
131 final NativeBody cone = w.addBody(
132 position: Vector3(0.0, 0.6, 0.8),
133 mass: 2.0,
134 );
135 w.setShape(cone, const NativeShape.cone(_coneRadius, _coneHeight));
137 // The hull is built from the points and moved so its centre of mass is
138 // the body's origin; hullOffset says by how much, and the mesh drawn
139 // for it has to be moved by the same.
140 final NativeHull hull = w.createHull(_rockPoints);
141 final NativeBody rock = w.addBody(
142 position: Vector3(2.0, 1.0, 0.5),
143 mass: 3.0,
144 );
145 w
146 ..setHull(rock, hull)
147 ..setOrientation(
148 rock,
149 Quaternion.axisAngle(Vector3(1.0, 0.0, 1.0).normalized(), 0.7),
150 );
152 // A box rounded by eight centimetres: the box grown by a ball, so its
153 // edges and corners are round and it stands 0.33 m from its centre to
154 // each face. Thrown spinning, it tumbles before it settles.
155 final NativeBody box = w.addBody(
156 position: Vector3(4.0, 1.2, -0.5),
157 mass: 2.0,
158 );
159 w
160 ..setShape(box, NativeShape.box(Vector3.all(_boxHalf)))
161 ..setRounding(box, _rounding)
162 ..setAngularVelocity(box, Vector3(3.0, 1.0, 5.0))
163 ..setVelocity(box, Vector3(-1.0, 0.0, 0.0));
165 return (
166 world: w,
167 cylinder: cylinder,
168 cone: cone,
169 rock: rock,
170 box: box,
171 rockOffset: w.hullOffset(hull),
172 );
173 }
175 void _restart() {
176 _bodies?.world.dispose();
177 _bodies = _build();
178 _age = 0.0;
179 }
182 void dispose() => _bodies?.world.dispose();
184 /// Triangles with a normal of their own each, so the faces are drawn
185 /// flat; each wound to face away from [inside].
186 static MeshData _faceted(
187 List<Vector3> points,
188 List<int> triangles, {
189 Vector3? inside,
190 }) {
191 final MeshBuilder builder = MeshBuilder(VertexLayout.standard);
192 for (var t = 0; t < triangles.length; t += 3) {
193 final Vector3 a = points[triangles[t]];
194 Vector3 b = points[triangles[t + 1]];
195 Vector3 c = points[triangles[t + 2]];
196 Vector3 normal = (b - a).cross(c - a)..normalize();
197 if (inside != null && normal.dot(a - inside) < 0) {
198 (b, c) = (c, b);
199 normal = -normal;
200 }
201 builder.addTriangle(
202 builder.addVertex(position: a, normal: normal),
203 builder.addVertex(position: b, normal: normal),
204 builder.addVertex(position: c, normal: normal),
205 );
206 }
207 return builder.build();
208 }
211 Scene build(DemoContext context) {
212 _bodies = _build();
213 final Scene scene = Scene()
214 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
215 ..ambientIntensity = 0.3 * LightNode.legacyUnit
216 ..add(
217 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
218 ..setLocalForward(Vector3(-0.3, -0.7, -0.4)),
219 );
220 DeviceMesh upload(MeshData data) => DeviceMesh.upload(context.device, data);
221 RenderMaterial paint(String name, double r, double g, double b) =>
222 RenderMaterial(
223 name: name,
224 baseColor: LinearColor.fromSrgb(r, g, b, 1.0),
225 roughness: 0.6,
226 );
228 scene.add(
229 MeshNode(
230 upload(_faceted(_groundPoints, _groundTriangles)),
231 paint('ground', 0.45, 0.47, 0.5),
232 name: 'ground',
233 ),
234 );
235 // The cone's mesh has its middle at its origin, half its height above
236 // the base; the body's origin is a quarter above it. A node at the body
237 // holds the mesh a quarter of the height up.
238 final cone = SceneNode(name: 'cone')
239 ..add(
240 MeshNode(
241 upload(
242 const ConeShape(radius: _coneRadius, height: _coneHeight).build(),
243 ),
244 paint('cone', 0.8, 0.6, 0.3),
245 name: 'cone mesh',
246 )..setPosition(0.0, _coneHeight / 4, 0.0),
247 );
248 // The rock's mesh is its points less the offset the hull was moved by.
249 final Vector3 offset = _bodies?.rockOffset ?? Vector3.zero();
250 final List<Vector3> moved = <Vector3>[
251 for (final Vector3 p in _rockPoints) p - offset,
252 ];
253 final Vector3 middle =
254 moved.fold(Vector3.zero(), (Vector3 sum, Vector3 p) => sum + p) /
255 moved.length.toDouble();
256 _nodes.addAll(<SceneNode>[
257 MeshNode(
258 upload(
259 const CylinderShape(
260 radiusTop: _cylinderRadius,
261 radiusBottom: _cylinderRadius,
262 height: 2 * _cylinderHalf,
263 ).build(),
264 ),
265 paint('cylinder', 0.35, 0.55, 0.8),
266 name: 'cylinder',
267 ),
268 cone,
269 MeshNode(
270 upload(_faceted(moved, _rockTriangles, inside: middle)),
271 paint('rock', 0.55, 0.5, 0.45),
272 name: 'rock',
273 ),
274 // Drawn as a plain cube of the rounded box's outer size.
275 MeshNode(
276 upload(
277 CuboidShape(size: Vector3.all(2 * (_boxHalf + _rounding))).build(),
278 ),
279 paint('rounded box', 0.75, 0.4, 0.45),
280 name: 'rounded box',
281 ),
282 ]);
283 _nodes.forEach(scene.add);
284 _place();
285 return scene;
286 }
288 void _place() {
289 final _Bodies? b = _bodies;
290 if (b == null) return;
291 final List<NativeBody> bodies = <NativeBody>[
292 b.cylinder,
293 b.cone,
294 b.rock,
295 b.box,
296 ];
297 for (var i = 0; i < bodies.length; i++) {
298 _nodes[i]
299 ..setPositionFrom(b.world.localPositionOf(bodies[i]))
300 ..setRotation(b.world.orientationOf(bodies[i]));
301 }
302 }
305 void update(DemoContext context, double dt) {
306 final _Bodies? b = _bodies;
307 if (b == null) return;
308 b.world.step(_step);
309 _age += dt;
310 if (_age > 10.0) _restart();
311 _place();
312 }
315 List<DemoControl> controls(DemoContext context) => <DemoControl>[
316 ToggleControl(
317 unavailable == null
318 ? 'Drop again'
319 : 'Drop again (the core is unavailable: $unavailable)',
320 value: () => false,
321 onChanged: (bool v) {
322 if (v) _restart();
323 },
324 ),
325 ];
328 void verify(Scene scene, FrameResult frame) {
329 if (frame.drawCalls < 1) throw StateError('nothing reached the frame');
330 if (unavailable != null) return;
331 // Ten seconds from the drop.
332 _restart();
333 final _Bodies b = _bodies!;
334 final NativeWorld w = b.world;
335 for (var i = 0; i < 600; i++) {
336 w.step(_step);
337 }
338 Vector3 axisOf(NativeBody body) =>
339 w.orientationOf(body).asRotationMatrix().transformed(Vector3(0, 1, 0));
340 void rests(String what, double height, double at) {
341 if ((height - at).abs() > 0.01) {
342 throw StateError('$what rests at $height m, not $at');
343 }
344 }
346 // The cylinder rolled off the ramp, at least a metre past its foot,
347 // and lies on its side, its axis level and its centre a radius up.
348 final Vector3 cylinder = w.localPositionOf(b.cylinder);
349 if (cylinder.x < -2.0) throw StateError('the cylinder stayed on the ramp');
350 if (axisOf(b.cylinder).y.abs() > 0.02) {
351 throw StateError('the cylinder is not on its side');
352 }
353 rests('the cylinder', cylinder.y, _cylinderRadius);
354 // The cone stands on its base, its centre of mass a quarter of its
355 // height up.
356 if (axisOf(b.cone).y < 0.999) throw StateError('the cone fell over');
357 rests('the cone', w.localPositionOf(b.cone).y, _coneHeight / 4);
358 // The rock rests on a face: its lowest corner on the floor.
359 final Matrix3 turn = w.orientationOf(b.rock).asRotationMatrix();
360 final Vector3 at = w.localPositionOf(b.rock);
361 final double lowest = _rockPoints
362 .map((Vector3 p) => (at + turn.transformed(p - b.rockOffset)).y)
363 .reduce(math.min);
364 rests('the rock\'s lowest corner', lowest, 0.0);
365 // The rounded box lies on a face, its half size plus the rounding up.
366 rests('the rounded box', w.localPositionOf(b.box).y, _boxHalf + _rounding);
367 for (final NativeBody body in <NativeBody>[b.cone, b.rock, b.box]) {
368 if (!w.isAsleep(body)) throw StateError('a shape never came to rest');
369 }
370 }
371}