Fast bodies and thin walls: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: worlds (line 63), lanes (line 82), fire (line 158), step (line 238), check (line 281).
1/// Three balls fired at a wall a centimetre thick, each faster than the wall
2/// is thin by a long way: one stopped by the core's soft speculative
3/// contacts, one by the hard sweep a bullet gets, and one with neither,
4/// which goes through.
5///
6/// Quoted by `continuous_collision.md` and shown whole in the Source tab.
7library;
9import 'package:flutter/foundation.dart' show visibleForTesting;
10import 'package:flutter3d/flutter3d.dart';
11import 'package:flutter3d_physics_native/flutter3d_physics_native.dart';
12import 'package:flutter3d_showcase/src/demo/demo.dart';
14/// One ball: the world it flies in, its body, the lane it flies along and
15/// what it is drawn as.
16final class _Lane {
17 _Lane(this.world, this.ball, this.z, this.mesh, this.trail);
19 final NativeWorld world;
20 final NativeBody ball;
21 final double z;
22 final MeshNode mesh;
23 final MeshNode trail;
24}
26/// The `continuous-collision` page: three fast balls fired at a thin wall
27/// on the physics core. Its check is that the speculative ball and the
28/// bullet stop and the unprotected one goes through.
29final class ContinuousCollisionDemo extends ShowcaseDemo {
30 /// Speculative contacts on: the world a new `NativeWorld` is.
31 NativeWorld? _soft;
33 /// Speculative contacts off, for the bullet and the unprotected ball.
34 NativeWorld? _hard;
36 final List<_Lane> _lanes = <_Lane>[];
38 /// Why there is nothing to fire, or null when the core started.
39 String? fallback;
41 /// Metres a second the balls leave at.
42 double speed = 300.0;
44 double _sinceShot = 0.0;
46 static const double _step = 1 / 60;
47 static const double _radius = 0.05;
48 static const double _launchX = -3.0;
49 static const double _height = 0.6;
51 /// Half the wall's thickness: a centimetre in all.
52 static const double _wallHalf = 0.005;
55 void configureView(DemoContext context) {
56 context.orbit
57 ..distance = 6.5
58 ..pitch = 0.45
59 ..yaw = -0.5;
60 context.orbit.target.setValues(-0.6, 0.4, 0.0);
61 }
63 /// Two worlds of the core. Speculative contacts are a setting of the
64 /// world, on for a new one, so the lane that shows them on lives in a
65 /// world of its own, and the two that show them off share the other.
66 void _makeWorlds() {
67 try {
68 _soft = NativeWorld()..gravity = Vector3.zero();
69 _hard = NativeWorld()
70 ..gravity = Vector3.zero()
71 ..speculative = false;
72 } on Object catch (e) {
73 _soft?.dispose();
74 _soft = null;
75 _hard = null;
76 fallback = physicsCoreLoaded
77 ? '$e'
78 : 'the core is not loaded in this browser yet';
79 }
80 }
82 /// A fixed wall a centimetre thick across [world], and a small ball in
83 /// front of it at [z], made a bullet when [bullet] is set.
84 static NativeBody _wallAndBall(
85 NativeWorld world,
86 double z, {
87 required bool bullet,
88 }) {
89 final NativeBody wall = world.addBody(
90 position: Vector3(0.0, _height, 0.0),
91 type: NativeBodyType.fixed,
92 mass: 0.0,
93 );
94 world.setShape(wall, NativeShape.box(Vector3(_wallHalf, 0.6, 1.2)));
95 final NativeBody ball = world.addBody(
96 position: Vector3(_launchX, _height, z),
97 mass: 0.03,
98 );
99 world.setShape(ball, const NativeShape.sphere(_radius));
100 // Hard continuous collision: swept from where the step began to where it
101 // ended, and put back at the first thing it met.
102 if (bullet) world.setBullet(ball);
103 return ball;
104 }
106 /// The wall in the soft world is added once, with its ball; the hard
107 /// world's wall stands for both of its balls.
108 void _buildLanes(DemoContext context, Scene scene) {
109 final NativeWorld soft = _soft!;
110 final NativeWorld hard = _hard!;
111 final NativeBody softBall = _wallAndBall(soft, -0.7, bullet: false);
112 final NativeBody bulletBall = _wallAndBall(hard, 0.0, bullet: true);
113 final NativeBody plainBall = hard.addBody(
114 position: Vector3(_launchX, _height, 0.7),
115 mass: 0.03,
116 );
117 hard.setShape(plainBall, const NativeShape.sphere(_radius));
119 final DeviceMesh sphere = DeviceMesh.upload(
120 context.device,
121 const SphereShape(radius: _radius, segments: 16, rings: 8).build(),
122 );
123 final DeviceMesh unit = DeviceMesh.upload(
124 context.device,
125 CuboidShape(size: Vector3.all(1.0)).build(),
126 );
127 for (final (NativeWorld world, NativeBody ball, double z, Vector3 color)
128 in <(NativeWorld, NativeBody, double, Vector3)>[
129 (soft, softBall, -0.7, Vector3(0.35, 0.85, 0.45)),
130 (hard, bulletBall, 0.0, Vector3(0.95, 0.7, 0.25)),
131 (hard, plainBall, 0.7, Vector3(0.95, 0.3, 0.3)),
132 ]) {
133 final mesh = MeshNode(
134 sphere,
135 RenderMaterial(
136 name: 'ball $z',
137 baseColor: LinearColor.fromSrgb(color.x, color.y, color.z, 1.0),
138 emissive: (color * 0.4).toLinearColor(),
139 ),
140 name: 'ball $z',
141 );
142 final trail = MeshNode(
143 unit,
144 RenderMaterial(
145 name: 'trail $z',
146 baseColor: LinearColor.fromSrgb(color.x, color.y, color.z, 1.0),
147 emissive: (color * 0.8).toLinearColor(),
148 ),
149 name: 'trail $z',
150 );
151 scene
152 ..add(mesh)
153 ..add(trail);
154 _lanes.add(_Lane(world, ball, z, mesh, trail));
155 }
156 }
158 /// Every ball back at the line and off again at [speed].
159 void _fire() {
160 for (final _Lane lane in _lanes) {
161 lane.world
162 ..setPosition(lane.ball, Vector3(_launchX, _height, lane.z))
163 ..setAngularVelocity(lane.ball, Vector3.zero())
164 ..setVelocity(lane.ball, Vector3(speed, 0.0, 0.0))
165 ..wake(lane.ball);
166 }
167 _sinceShot = 0.0;
168 }
171 void dispose() {
172 _soft?.dispose();
173 _hard?.dispose();
174 }
177 Scene build(DemoContext context) {
178 _makeWorlds();
179 final Scene scene = Scene()
180 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
181 ..ambientIntensity = 0.3 * LightNode.legacyUnit
182 ..add(
183 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
184 ..setLocalForward(Vector3(-0.3, -0.7, -0.4)),
185 )
186 ..add(
187 MeshNode(
188 DeviceMesh.upload(
189 context.device,
190 CuboidShape(size: Vector3(8.0, 0.1, 2.6)).build(),
191 ),
192 RenderMaterial(
193 name: 'ground',
194 baseColor: LinearColor.fromSrgb(0.3, 0.32, 0.35, 1.0),
195 ),
196 name: 'ground',
197 )..setPosition(-0.5, -0.05, 0.0),
198 )
199 ..add(
200 MeshNode(
201 DeviceMesh.upload(
202 context.device,
203 CuboidShape(size: Vector3(2 * _wallHalf, 1.2, 2.4)).build(),
204 ),
205 RenderMaterial(
206 name: 'wall',
207 baseColor: LinearColor.fromSrgb(0.75, 0.78, 0.82, 1.0),
208 ),
209 name: 'wall',
210 )..setPosition(0.0, _height, 0.0),
211 );
212 if (_soft != null) {
213 _buildLanes(context, scene);
214 _fire();
215 _place();
216 }
217 return scene;
218 }
220 /// Each ball where its world has it, and a streak from the line to it so
221 /// a ball too fast to see in a frame leaves its path behind.
222 void _place() {
223 for (final _Lane lane in _lanes) {
224 final Vector3 p = lane.world.localPositionOf(lane.ball);
225 lane.mesh.setPosition(p.x, p.y, p.z);
226 final double end = p.x.clamp(_launchX, 3.0);
227 final double length = end - _launchX;
228 lane.trail
229 ..isVisible = length > 0.01
230 ..setPosition(_launchX + 0.5 * length, p.y, lane.z)
231 ..setScale(length, 0.012, 0.012);
232 }
233 }
236 void update(DemoContext context, double dt) {
237 if (_soft == null) return;
238 _soft!.step(_step);
239 _hard!.step(_step);
240 _sinceShot += dt;
241 if (_sinceShot > 1.5) _fire();
242 _place();
243 }
246 List<DemoControl> controls(DemoContext context) => <DemoControl>[
247 SliderControl(
248 'Speed',
249 min: 50.0,
250 max: 600.0,
251 value: () => speed,
252 onChanged: (double v) => speed = v,
253 format: (double v) => '${v.round()} m/s',
254 ),
255 ToggleControl(
256 fallback == null ? 'Fire again' : 'Fire again (unavailable: $fallback)',
257 value: () => false,
258 onChanged: (bool v) {
259 if (v && _soft != null) _fire();
260 },
261 ),
262 ];
264 /// Where each ball is along x after [steps] steps from a fresh shot: the
265 /// soft one, the bullet, the unprotected one.
267 List<double> shoot({int steps = 30}) {
268 _fire();
269 for (var i = 0; i < steps; i++) {
270 _soft!.step(_step);
271 _hard!.step(_step);
272 }
273 return <double>[
274 for (final _Lane lane in _lanes) lane.world.localPositionOf(lane.ball).x,
275 ];
276 }
279 void verify(Scene scene, FrameResult frame) {
280 if (_soft == null) throw StateError('the core did not start: $fallback');
281 // At three hundred metres a second a ball goes five metres a step, five
282 // hundred times the wall's thickness. The soft ball and the bullet have
283 // to end on the near side of it, the ball with neither on the far side.
284 speed = 300.0;
285 final [double soft, double bullet, double plain] = shoot();
286 if (soft >= 0.0) {
287 throw StateError('the soft ball went through, to x = $soft');
288 }
289 if (bullet >= 0.0) {
290 throw StateError('the bullet went through, to x = $bullet');
291 }
292 if (plain <= 0.0) {
293 throw StateError('the unprotected ball stopped at x = $plain');
294 }
295 if (frame.drawCalls < 1) throw StateError('nothing reached the frame');
296 }
297}