A chain that does not stretch: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: lay (line 73), both (line 108), gap (line 140), draw (line 241), check (line 317).
1/// The same chain twice, side by side on the physics core: twelve light
2/// links and a heavy weight on the end, laid out level and let go. The
3/// left chain is held by ordinary hinge joints, the right one is a
4/// multibody. Each link reddens as the joint above it opens.
5///
6/// Quoted by `multibody_chain.md` and shown whole in the Source tab.
7library;
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 `multibody-chain` page: one chain on hinge joints and the same chain
17/// as a multibody, let go side by side on the physics core. Its check is
18/// that the multibody's joints stay closed where the hinges open.
19final class MultibodyChainDemo extends ShowcaseDemo {
20 NativeWorld? _world;
22 /// Each chain's bodies: its post, then its links, the weight last.
23 List<NativeBody> _joints = const <NativeBody>[];
24 List<NativeBody> _multibody = const <NativeBody>[];
26 /// Why there are no chains, or null when there are.
27 String? fallback;
29 /// The weight on the end of each chain, kg. Every link is 0.1 kg.
30 double weight = 10.0;
32 double _age = 0.0;
34 final List<MeshNode> _jointMeshes = <MeshNode>[];
35 final List<MeshNode> _multibodyMeshes = <MeshNode>[];
36 final List<RenderMaterial> _jointPaint = <RenderMaterial>[];
37 final List<RenderMaterial> _multibodyPaint = <RenderMaterial>[];
39 static const int _count = 12;
40 static const double _half = 0.15;
41 static const double _radius = 0.15;
42 static const double _height = 5.0;
44 /// Where each chain's post stands along x. Both are laid out to +x from
45 /// their post, and this far apart they never swing into each other.
46 static const double _left = -4.0;
47 static const double _right = 4.0;
48 static const double _step = 1 / 60;
51 void configureView(DemoContext context) {
52 context.orbit
53 ..distance = 15.0
54 ..pitch = 0.1
55 ..yaw = 0.0;
56 context.orbit.target.setValues(0.0, 3.0, 0.0);
57 }
59 NativeWorld? _open() {
60 fallback = null;
61 if (!physicsCoreLoaded) {
62 fallback = 'the core is not loaded in this browser yet';
63 return null;
64 }
65 try {
66 return NativeWorld()..setSleep(speed: 0.0, timeSeconds: 0.0);
67 } on Object catch (e) {
68 fallback = '$e';
69 return null;
70 }
71 }
73 /// A post at [x] and a chain laid out level from it to +x: twelve links
74 /// 0.3 m long and 0.1 kg each, then a ball of [weight] kg. [join] holds
75 /// each body to the one before it, link [parent] of [bodies], at
76 /// [anchor].
77 List<NativeBody> _lay(
78 NativeWorld world,
79 double x,
80 void Function(List<NativeBody> bodies, int parent, Vector3 anchor) join,
81 ) {
82 final NativeBody post = world.addBody(
83 position: Vector3(x, _height, 0.0),
84 type: NativeBodyType.fixed,
85 mass: 0.0,
86 );
87 world.setShape(post, NativeShape.box(Vector3.all(0.05)));
88 final bodies = <NativeBody>[post];
89 for (var k = 0; k <= _count; k++) {
90 final bool last = k == _count;
91 final double near = x + k * 2 * _half;
92 final NativeBody body = world.addBody(
93 position: Vector3(near + (last ? _radius : _half), _height, 0.0),
94 mass: last ? weight : 0.1,
95 );
96 world.setShape(
97 body,
98 last
99 ? const NativeShape.sphere(_radius)
100 : NativeShape.box(Vector3(_half, 0.03, 0.03)),
101 );
102 bodies.add(body);
103 join(bodies, k, Vector3(near, _height, 0.0));
104 }
105 return bodies;
106 }
108 /// The left chain on ordinary hinges about z, each a constraint the
109 /// solver pulls closed; the right one a multibody, rooted at its post,
110 /// each link placed from its parent by one angle about z.
111 void _restart() {
112 _world?.dispose();
113 final NativeWorld? world = _world = _open();
114 _age = 0.0;
115 if (world == null) return;
116 final Vector3 z = Vector3(0.0, 0.0, 1.0);
117 _joints = _lay(world, _left, (bodies, parent, at) {
118 world.createJoint(
119 NativeJointType.revolute,
120 bodies[parent],
121 bodies.last,
122 anchor: at,
123 axis: z,
124 );
125 });
126 NativeMultibody? chain;
127 _multibody = _lay(world, _right, (bodies, parent, at) {
128 chain ??= world.createMultibody(bodies.first);
129 world.addLink(
130 chain!,
131 bodies.last,
132 parent: parent,
133 type: NativeJointType.revolute,
134 anchor: at,
135 axis: z,
136 );
137 });
138 }
140 /// How far apart the two sides of the joint above link [k] of [bodies]
141 /// are, m: the parent's far end against the link's near end, each where
142 /// its own body has it now. Nought for a joint that holds.
143 double _gap(List<NativeBody> bodies, int k) {
144 final NativeWorld world = _world!;
145 Vector3 end(NativeBody body, double along) =>
146 world.localPositionOf(body) +
147 world
148 .orientationOf(body)
149 .asRotationMatrix()
150 .transformed(Vector3(along, 0.0, 0.0));
151 final NativeBody parent = bodies[k - 1];
152 final NativeBody link = bodies[k];
153 return (end(parent, k == 1 ? 0.0 : _half) -
154 end(link, k == bodies.length - 1 ? -_radius : -_half))
155 .length;
156 }
158 /// The widest joint of [bodies] now.
159 double _widest(List<NativeBody> bodies) => <double>[
160 for (var k = 1; k < bodies.length; k++) _gap(bodies, k),
161 ].reduce(math.max);
164 void dispose() => _world?.dispose();
167 Scene build(DemoContext context) {
168 _restart();
169 final Scene scene = Scene()
170 ..ambientColor = LinearColor(0.5, 0.55, 0.65)
171 ..ambientIntensity = 0.3 * LightNode.legacyUnit
172 ..add(
173 LightNode(name: 'sun', intensity: 2.5 * LightNode.legacyUnit)
174 ..setLocalForward(Vector3(-0.3, -0.6, -0.5)),
175 )
176 ..add(
177 MeshNode(
178 DeviceMesh.upload(
179 context.device,
180 CuboidShape(size: Vector3(20.0, 0.2, 6.0)).build(),
181 ),
182 RenderMaterial(
183 name: 'floor',
184 baseColor: LinearColor.fromSrgb(0.4, 0.42, 0.45, 1.0),
185 ),
186 name: 'floor',
187 )..setPosition(0.0, -0.1, 0.0),
188 );
189 final DeviceMesh post = DeviceMesh.upload(
190 context.device,
191 CuboidShape(size: Vector3(0.12, 5.2, 0.12)).build(),
192 );
193 final DeviceMesh link = DeviceMesh.upload(
194 context.device,
195 CuboidShape(size: Vector3(2 * _half, 0.06, 0.06)).build(),
196 );
197 final DeviceMesh ball = DeviceMesh.upload(
198 context.device,
199 const SphereShape(radius: _radius, segments: 24, rings: 12).build(),
200 );
201 for (final (
202 double x,
203 String side,
204 List<MeshNode> meshes,
205 List<RenderMaterial> paint,
206 )
207 in <(double, String, List<MeshNode>, List<RenderMaterial>)>[
208 (_left, 'joints', _jointMeshes, _jointPaint),
209 (_right, 'multibody', _multibodyMeshes, _multibodyPaint),
210 ]) {
211 scene.add(
212 MeshNode(
213 post,
214 RenderMaterial(
215 name: 'post',
216 baseColor: LinearColor.fromSrgb(0.3, 0.3, 0.32, 1.0),
217 ),
218 name: 'post $side',
219 )..setPosition(x, _height / 2, -0.1),
220 );
221 for (var k = 0; k <= _count; k++) {
222 final material = RenderMaterial(
223 name: '$side link $k',
224 baseColor: LinearColor.fromSrgb(0.8, 0.8, 0.78, 1.0),
225 roughness: 0.5,
226 );
227 final mesh = MeshNode(
228 k == _count ? ball : link,
229 material,
230 name: '$side link $k',
231 );
232 paint.add(material);
233 meshes.add(mesh);
234 scene.add(mesh);
235 }
236 }
237 _place();
238 return scene;
239 }
241 /// Every link where the core has it, reddening as the joint above it
242 /// opens: fully red at three centimetres.
243 void _place() {
244 if (_world == null) return;
245 for (final (List<NativeBody> bodies, List<MeshNode> meshes, paint)
246 in <(List<NativeBody>, List<MeshNode>, List<RenderMaterial>)>[
247 (_joints, _jointMeshes, _jointPaint),
248 (_multibody, _multibodyMeshes, _multibodyPaint),
249 ]) {
250 for (var k = 1; k < bodies.length; k++) {
251 meshes[k - 1]
252 ..setPositionFrom(_world!.localPositionOf(bodies[k]))
253 ..setRotation(_world!.orientationOf(bodies[k]));
254 final double open = math.min(_gap(bodies, k) / 0.03, 1.0);
255 paint[k - 1].baseColor = LinearColor.fromSrgb(
256 0.8 + 0.15 * open,
257 0.8 - 0.65 * open,
258 0.78 - 0.65 * open,
259 1.0,
260 );
261 }
262 }
263 }
266 void update(DemoContext context, double dt) {
267 final NativeWorld? world = _world;
268 if (world == null) return;
269 world.step(_step);
270 _age += _step;
271 if (_age > 10.0) _restart();
272 _place();
273 }
276 List<DemoControl> controls(DemoContext context) => <DemoControl>[
277 SliderControl(
278 'Weight on the end',
279 min: 1.0,
280 max: 20.0,
281 divisions: 19,
282 value: () => weight,
283 onChanged: (double v) {
284 weight = v;
285 _restart();
286 },
287 format: (double v) => '${v.toStringAsFixed(0)} kg',
288 ),
289 ToggleControl(
290 fallback == null ? 'Let go again' : 'Unavailable: $fallback',
291 value: () => false,
292 onChanged: (bool v) {
293 if (v) _restart();
294 },
295 ),
296 ];
298 /// The widest any joint of each chain opens over [steps] from a fresh
299 /// start, m.
301 ({double joints, double multibody}) widestOver(int steps) {
302 _restart();
303 var joints = 0.0;
304 var multibody = 0.0;
305 for (var i = 0; i < steps; i++) {
306 _world!.step(_step);
307 joints = math.max(joints, _widest(_joints));
308 multibody = math.max(multibody, _widest(_multibody));
309 }
310 return (joints: joints, multibody: multibody);
311 }
314 void verify(Scene scene, FrameResult frame) {
315 if (frame.drawCalls < 1) throw StateError('nothing reached the frame');
316 if (_world == null) throw StateError('no physics core: $fallback');
317 // Two seconds from level with ten kilograms on the end. The core holds
318 // every multibody joint to a thousandth of a millimetre, and lets an
319 // ordinary one open by four centimetres.
320 weight = 10.0;
321 final (:double joints, :double multibody) = widestOver(120);
322 if (multibody > 1e-3) {
323 throw StateError('a multibody joint opened by $multibody m');
324 }
325 if (joints < 1e-2) {
326 throw StateError('the ordinary chain held to $joints m');
327 }
328 // And the multibody has swung: its weight is well below its post.
329 final double low = _world!.localPositionOf(_multibody.last).y;
330 if (low > _height - 2.0) {
331 throw StateError('the multibody weight is still at $low');
332 }
333 }
334}