flutter3d
Showcase Changelog 62 packages API reference

A car on four springs: the source

since 1.0.0-rc.1 Physics and particles

Regions the guide quotes: road (line 82), wheels (line 108), drive (line 140), draw (line 290), check (line 416).

1/// A car on four springs, driven round a loop by a simple driver on the
2/// physics core: a box chassis, four wheels that are rays cast down from
3/// it, a plank across the road to bump over, and a road that can be
4/// tarmac or ice.
5///
6/// Quoted by `vehicle.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/// The `vehicle` page: a raycast car driving a loop over a plank on tarmac
17/// or ice, on the physics core. Its check rests the car and drives it
18/// straight.
19final class VehicleDemo extends ShowcaseDemo {
20 NativeWorld? _world;
21 NativeBody? _chassis;
22 NativeVehicle? _car;
24 /// Why there is no car, or null when there is one.
25 String? fallback;
27 /// What the driver asks for: the steering angle along the car's middle,
28 /// radians to the left, and the speed to hold, m/s.
29 double steer = 0.25;
31 /// The speed the driver holds, in m/s, -4 to 12 on the "Speed" slider; the
32 /// engine pushes in proportion to how far the chassis is below it.
33 double speed = 6.0;
35 /// Whether all four wheels brake; the engine stops pushing while they do.
36 bool braking = false;
38 /// Tarmac or ice: the tyres' grip.
39 bool icy = false;
41 late MeshNode _body;
42 late MeshNode _cabin;
43 final List<MeshNode> _tireSet = <MeshNode>[];
44 final List<MeshNode> _spokes = <MeshNode>[];
45 final List<RenderMaterial> _tyrePaint = <RenderMaterial>[];
47 static const double _step = 1 / 60;
48 static const double _mass = 1200.0;
49 static const double _stiffness = 30000.0;
51 /// Front to back between the axles, and side to side between the wheels.
52 static const double _wheelbase = 2.6;
53 static const double _track = 1.6;
55 /// Where the plank lies across the loop: the far side of the circle the
56 /// default steering drives.
57 static Vector3 get _plank => Vector3(20.4, 0.04, 0.0);
59 @override
60 void configureView(DemoContext context) {
61 context.orbit
62 ..distance = 16.0
63 ..pitch = 0.45
64 ..yaw = 0.6;
65 context.orbit.target.setValues(0.0, 0.8, 0.0);
66 }
68 NativeWorld? _open() {
69 fallback = null;
70 if (!physicsCoreLoaded) {
71 fallback = 'the core is not loaded in this browser yet';
72 return null;
73 }
74 try {
75 return NativeWorld();
76 } on Object catch (e) {
77 fallback = '$e';
78 return null;
79 }
80 }
82 /// A floor, a plank across the loop, and a chassis of 1200 kg at the
83 /// start, facing +z.
84 void _restart() {
85 _world?.dispose();
86 final NativeWorld? world = _world = _open();
87 if (world == null) return;
88 final NativeBody floor = world.addBody(
89 position: Vector3(0.0, -0.5, 0.0),
90 type: NativeBodyType.fixed,
91 mass: 0.0,
92 );
93 world.setShape(floor, NativeShape.box(Vector3(60.0, 0.5, 60.0)));
94 final NativeBody plank = world.addBody(
95 position: _plank,
96 type: NativeBodyType.fixed,
97 mass: 0.0,
98 );
99 world.setShape(plank, NativeShape.box(Vector3(2.0, 0.04, 0.3)));
100 final NativeBody chassis = _chassis = world.addBody(
101 position: Vector3(0.0, 1.0, 0.0),
102 mass: _mass,
103 );
104 world.setShape(chassis, NativeShape.box(Vector3(0.9, 0.3, 2.0)));
105 _fit();
106 }
108 /// Puts the car's four wheels under its chassis, for the road's grip.
109 /// Up is the chassis's +y and forward its +z; wheels 0 and 1 are the
110 /// front pair, right then left, and 2 and 3 the rear.
111 void _fit() {
112 final NativeWorld world = _world!;
113 final NativeBody chassis = _chassis!;
114 if (_car case final NativeVehicle old) world.removeVehicle(old);
115 final NativeVehicle car = _car = world.createVehicle(
116 chassis,
117 up: Vector3(0.0, 1.0, 0.0),
118 forward: Vector3(0.0, 0.0, 1.0),
119 );
120 for (final (double x, double z) in const <(double, double)>[
121 (-0.8, 1.3),
122 (0.8, 1.3),
123 (-0.8, -1.3),
124 (0.8, -1.3),
125 ]) {
126 world.addWheel(
127 car,
128 NativeWheelSettings(
129 attach: Vector3(x, -0.2, z),
130 rest: 0.4,
131 radius: 0.35,
132 stiffness: _stiffness,
133 damping: 3000.0,
134 grip: icy ? 0.1 : 1.0,
135 ),
136 );
137 }
138 }
140 /// One step of the driver, then one of the world. The front wheels steer
141 /// about the same point on the line of the rear axle, the inner one more;
142 /// the rear wheels push to hold [speed]; the brake holds all four.
143 void _drive() {
144 final NativeWorld world = _world!;
145 final NativeVehicle car = _car!;
146 final NativeBody chassis = _chassis!;
147 var right = 0.0;
148 var left = 0.0;
149 if (steer != 0.0) {
150 final double radius = _wheelbase / math.tan(steer);
151 right = math.atan(_wheelbase / (radius + _track / 2));
152 left = math.atan(_wheelbase / (radius - _track / 2));
153 }
154 final Vector3 forward = world
155 .orientationOf(chassis)
156 .asRotationMatrix()
157 .transformed(Vector3(0.0, 0.0, 1.0));
158 final double going = world.velocityOf(chassis).dot(forward);
159 final double push = braking
160 ? 0.0
161 : (800.0 * (speed - going)).clamp(-2400.0, 2400.0);
162 final double brake = braking ? 4000.0 : 0.0;
163 world
164 ..setWheel(car, 0, steer: right, brake: brake)
165 ..setWheel(car, 1, steer: left, brake: brake)
166 ..setWheel(car, 2, drive: push, brake: brake)
167 ..setWheel(car, 3, drive: push, brake: brake)
168 ..step(_step);
169 }
171 @override
172 void dispose() => _world?.dispose();
174 @override
175 Scene build(DemoContext context) {
176 _restart();
177 final Scene scene = Scene()
178 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
179 ..ambientIntensity = 0.3 * LightNode.legacyUnit
180 ..add(
181 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
182 ..setLocalForward(Vector3(-0.3, -0.7, -0.4)),
183 )
184 ..add(
185 MeshNode(
186 DeviceMesh.upload(
187 context.device,
188 CuboidShape(size: Vector3(120.0, 1.0, 120.0)).build(),
189 ),
190 RenderMaterial(
191 name: 'road',
192 baseColor: LinearColor.fromSrgb(0.36, 0.38, 0.4, 1.0),
193 ),
194 name: 'road',
195 )..setPosition(0.0, -0.5, 0.0),
196 )
197 ..add(
198 MeshNode(
199 DeviceMesh.upload(
200 context.device,
201 CuboidShape(size: Vector3(4.0, 0.08, 0.6)).build(),
202 ),
203 RenderMaterial(
204 name: 'plank',
205 baseColor: LinearColor.fromSrgb(0.62, 0.45, 0.28, 1.0),
206 ),
207 name: 'plank',
208 )..setPositionFrom(_plank),
209 );
210 // Posts inside and outside the loop, so the car's motion reads against
211 // something. They are only drawn: the car never reaches them.
212 final DeviceMesh post = DeviceMesh.upload(
213 context.device,
214 CuboidShape(size: Vector3(0.25, 0.8, 0.25)).build(),
215 );
216 final postPaint = RenderMaterial(
217 name: 'post',
218 baseColor: LinearColor.fromSrgb(0.9, 0.85, 0.75, 1.0),
219 );
220 for (var i = 0; i < 24; i++) {
221 final double a = i * math.pi / 12;
222 for (final double r in <double>[6.0, 15.0]) {
223 scene.add(
224 MeshNode(post, postPaint, name: 'post $r $i')
225 ..setPosition(10.2 + r * math.cos(a), 0.4, r * math.sin(a)),
226 );
227 }
228 }
229 final paint = RenderMaterial(
230 name: 'chassis',
231 baseColor: LinearColor.fromSrgb(0.75, 0.2, 0.15, 1.0),
232 roughness: 0.4,
233 );
234 _body = MeshNode(
235 DeviceMesh.upload(
236 context.device,
237 CuboidShape(size: Vector3(1.8, 0.6, 4.0)).build(),
238 ),
239 paint,
240 name: 'chassis',
241 );
242 _cabin = MeshNode(
243 DeviceMesh.upload(
244 context.device,
245 CuboidShape(size: Vector3(1.5, 0.45, 1.9)).build(),
246 ),
247 RenderMaterial(
248 name: 'cabin',
249 baseColor: LinearColor.fromSrgb(0.2, 0.25, 0.3, 1.0),
250 ),
251 name: 'cabin',
252 );
253 scene
254 ..add(_body)
255 ..add(_cabin);
256 final DeviceMesh tyre = DeviceMesh.upload(
257 context.device,
258 const CylinderShape(
259 radiusTop: 0.35,
260 radiusBottom: 0.35,
261 height: 0.25,
262 segments: 24,
263 ).build(),
264 );
265 final DeviceMesh spoke = DeviceMesh.upload(
266 context.device,
267 CuboidShape(size: Vector3(0.27, 0.6, 0.1)).build(),
268 );
269 final spokePaint = RenderMaterial(
270 name: 'spoke',
271 baseColor: LinearColor.fromSrgb(0.85, 0.85, 0.8, 1.0),
272 );
273 for (var i = 0; i < 4; i++) {
274 final tyrePaint = RenderMaterial(
275 name: 'tyre $i',
276 baseColor: LinearColor.fromSrgb(0.08, 0.08, 0.08, 1.0),
277 roughness: 0.9,
278 );
279 _tyrePaint.add(tyrePaint);
280 _tireSet.add(MeshNode(tyre, tyrePaint, name: 'tyre $i'));
281 _spokes.add(MeshNode(spoke, spokePaint, name: 'spoke $i'));
282 scene
283 ..add(_tireSet[i])
284 ..add(_spokes[i]);
285 }
286 _place(context);
287 return scene;
288 }
290 /// The chassis where the core has it, and each wheel at its centre,
291 /// turned by its steering about the chassis's up and by its rotation
292 /// about its axle. A tyre past its grip turns red.
293 void _place(DemoContext context) {
294 final NativeWorld? world = _world;
295 if (world == null) return;
296 final Vector3 at = world.localPositionOf(_chassis!);
297 final Quaternion turn = world.orientationOf(_chassis!);
298 final Matrix3 frame = turn.asRotationMatrix();
299 final Vector3 roof = at + frame.transformed(Vector3(0.0, 0.5, -0.3));
300 _body
301 ..setPositionFrom(at)
302 ..setRotation(turn);
303 _cabin
304 ..setPositionFrom(roof)
305 ..setRotation(turn);
306 final List<NativeWheelState> wheels = world.wheelsOf(_car!);
307 for (var i = 0; i < wheels.length; i++) {
308 final NativeWheelState w = wheels[i];
309 final Quaternion rolled =
310 turn *
311 Quaternion.axisAngle(Vector3(0.0, 1.0, 0.0), w.steer) *
312 Quaternion.axisAngle(Vector3(1.0, 0.0, 0.0), w.rotation);
313 _spokes[i]
314 ..setPositionFrom(w.center)
315 ..setRotation(rolled);
316 _tireSet[i]
317 ..setPositionFrom(w.center)
318 // The cylinder stands along its y; its axle is the wheel's x.
319 ..setRotation(
320 rolled * Quaternion.axisAngle(Vector3(0.0, 0.0, 1.0), math.pi / 2),
321 );
322 final double slide = math.min(w.skid, 1.0);
323 _tyrePaint[i].baseColor = LinearColor.fromSrgb(
324 0.08 + 0.8 * slide,
325 0.08,
326 0.08,
327 1.0,
328 );
329 }
330 context.orbit.target.setValues(at.x, 0.8, at.z);
331 context.orbit.apply();
332 }
334 @override
335 void update(DemoContext context, double dt) {
336 final NativeWorld? world = _world;
337 if (world == null) return;
338 _drive();
339 // Off the road, or on its roof: start again.
340 final Vector3 at = world.localPositionOf(_chassis!);
341 final double up = world
342 .orientationOf(_chassis!)
343 .asRotationMatrix()
344 .transformed(Vector3(0.0, 1.0, 0.0))
345 .y;
346 if (at.y < -2.0 || at.x.abs() > 55.0 || at.z.abs() > 55.0 || up < 0.2) {
347 _restart();
348 }
349 _place(context);
350 }
352 @override
353 List<DemoControl> controls(DemoContext context) => <DemoControl>[
354 ChoiceControl(
355 'Road',
356 options: const <String>['Tarmac', 'Ice'],
357 index: () => icy ? 1 : 0,
358 onChanged: (int i) {
359 icy = i == 1;
360 // The same car, its wheels fitted again for the new grip.
361 if (_world != null) _fit();
362 },
363 ),
364 SliderControl(
365 'Steering',
366 min: -0.4,
367 max: 0.4,
368 value: () => steer,
369 onChanged: (double v) => steer = v,
370 format: (double v) => v == 0.0
371 ? 'straight'
372 : '${v.abs().toStringAsFixed(2)} rad ${v > 0 ? 'left' : 'right'}',
373 ),
374 SliderControl(
375 'Speed',
376 min: -4.0,
377 max: 12.0,
378 value: () => speed,
379 onChanged: (double v) => speed = v,
380 format: (double v) => '${v.toStringAsFixed(1)} m/s',
381 ),
382 ToggleControl('Brake', value: () => braking, onChanged: (v) => braking = v),
383 ToggleControl(
384 fallback == null ? 'Start again' : 'Unavailable: $fallback',
385 value: () => false,
386 onChanged: (bool v) {
387 if (v) _restart();
388 },
389 ),
390 ];
392 /// Where the chassis is and which way it faces, for the check.
393 ({Vector3 at, Vector3 forward}) get _pose {
394 final NativeWorld world = _world!;
395 return (
396 at: world.localPositionOf(_chassis!),
397 forward: world
398 .orientationOf(_chassis!)
399 .asRotationMatrix()
400 .transformed(Vector3(0.0, 0.0, 1.0)),
401 );
402 }
404 /// Runs [steps] of the driver as it is set.
405 @visibleForTesting
406 void drive(int steps) {
407 for (var i = 0; i < steps; i++) {
408 _drive();
409 }
410 }
412 @override
413 void verify(Scene scene, FrameResult frame) {
414 if (frame.drawCalls < 1) throw StateError('nothing reached the frame');
415 if (_world == null) throw StateError('no physics core: $fallback');
416 // On tarmac, standing still for three seconds: each spring holds a
417 // quarter of the weight, squeezed m g / 4k from its rest length, which
418 // puts the chassis 0.2 + 0.35 + 0.4 m, less that, over the road.
419 icy = false;
420 braking = false;
421 steer = 0.0;
422 speed = 0.0;
423 _restart();
424 drive(180);
425 final double squeeze = _mass * _world!.gravityMagnitude / 4 / _stiffness;
426 final double height = _pose.at.y;
427 if ((height - (0.95 - squeeze)).abs() > 3e-3) {
428 throw StateError('the chassis rests at $height, not ${0.95 - squeeze}');
429 }
430 if (!_world!.wheelsOf(_car!).every((w) => w.touching)) {
431 throw StateError('a wheel at rest is off the road');
432 }
433 // Two seconds asking for 5 m/s, straight: forward along +z, and not
434 // sideways. The core gets 5.9 m.
435 speed = 5.0;
436 drive(120);
437 final Vector3 straight = _pose.at;
438 if (straight.z < 4.0 || straight.x.abs() > 0.05) {
439 throw StateError('driving straight ended at $straight');
440 }
441 // A second and a half steered 0.2 rad to the left: left of a car facing
442 // +z with +y up is +x, and it has turned that way, about +y. The core
443 // ends 2.3 m to the left, facing 0.51 of the way round to +x.
444 steer = 0.2;
445 drive(90);
446 final turned = _pose;
447 final double yaw = _world!.angularVelocityOf(_chassis!).y;
448 if (turned.at.x < 1.0 || turned.forward.x < 0.3 || yaw < 0.2) {
449 throw StateError(
450 'steering left ended at ${turned.at}, facing ${turned.forward}, '
451 'turning at $yaw rad/s',
452 );
453 }
454 }