flutter3d
Showcase Changelog 62 packages API reference

The virtual pendulum lab: the source

since 0.7.0 Simulation, audio and XR

Regions the guide quotes: pendulum (line 27), live (line 178), assignment (line 244), student (line 251), compare (line 260).

1/// A worked example small enough that changing one number visibly changes
2/// how a run unfolds, and the digest that tells an instructor exactly where
3/// a student's run first parted from the assignment.
4///
5/// **`flutter3d_education/lab.dart` is not a dependency of this app.** Its real
6/// `PendulumSimulation` is a few lines of semi-implicit Euler over
7/// `Portable.sin`, with its damping of 0.02 1/s and its length that keeps
8/// the swing's angular momentum when it changes; this page reimplements
9/// exactly that by hand,
10/// against the same `Portable` this app already depends on through
11/// `flutter3d_sim`, and uses the real `DigestTrace` to compare two runs —
12/// the verification mechanism is genuine, only the tiny pendulum formula is
13/// not imported.
14///
15/// Quoted by `pendulum_lab.md` and shown whole in the Source tab.
16library;
18import 'dart:math' as math;
20import 'package:flutter3d/flutter3d.dart';
21import 'package:flutter3d_foundation/flutter3d_foundation.dart';
22import 'package:flutter3d_matter/flutter3d_matter.dart';
23import 'package:flutter3d_showcase/src/demo/demo.dart';
24import 'package:flutter3d_showcase/src/demo/scene_kit.dart';
25import 'package:flutter3d_sim/flutter3d_sim.dart';
27/// The lab's own worked example: semi-implicit Euler over a gravity
28/// pendulum, the same order of integrator the rest of the engine steps
29/// with.
30final class _Pendulum {
31 _Pendulum({required double length, double startAngle = 0.6})
32 : // A private field behind a public parameter name, which an
33 // initializing formal cannot be.
34 // ignore: prefer_initializing_formals
35 _length = length,
36 theta = startAngle,
37 omega = 0.0;
39 /// A pendulum on its own, in no world: the Earth's.
40 static const double _gravity = standardGravity;
42 /// Linear drag on the swing, 1/s: θ'' = −(g/L)·sin θ − c·θ'.
43 static const double _damping = 0.02;
45 double _length;
46 double theta;
47 double omega;
49 double get length => _length;
51 /// A string drawn in or let out through the pivot keeps the bob's angular
52 /// momentum, m·L²·ω: the swing turns (L / L′)² as fast.
53 set length(double value) {
54 if (value == _length) return;
55 final ratio = _length / value;
56 omega *= ratio * ratio;
57 _length = value;
58 }
60 void step(double dt) {
61 final alpha =
62 -(_gravity / _length) * Portable.sin(theta) - _damping * omega;
63 omega += alpha * dt;
64 theta += omega * dt;
65 }
67 Map<String, Object?> get state => <String, Object?>{
68 'theta': theta,
69 'omega': omega,
70 };
73/// The `pendulum-lab` page: a student's pendulum run beside the assignment,
74/// digested at checkpoints. Its check is that a length changed at step 30 is
75/// caught at the checkpoint covering it.
76final class PendulumLabDemo extends ShowcaseDemo {
77 late final String _report;
79 /// The step at which the student's run changes its length, 40 to 200.
80 double changeAt = 100.0;
82 /// The length it changes to, in metres, 0.6 to 2.
83 double newLength = 1.5;
85 static const int _steps = 240;
86 static const int _every = 40;
88 late final List<MeshNode> _rods;
89 late final List<MeshNode> _bobs;
90 late final List<MeshNode> _lamps;
91 bool _restart = true;
92 int _step = 0;
93 double _owed = 0.0;
94 double _pause = 0.0;
95 _Pendulum _assignmentLive = _Pendulum(length: 1.0);
96 _Pendulum _studentLive = _Pendulum(length: 1.0);
97 DigestTrace _assignmentTrace = DigestTrace(every: _every);
98 DigestTrace _studentTrace = DigestTrace(every: _every);
100 static const double _pivotY = 3.4;
101 static const List<double> _pivotX = <double>[-2.0, 2.0];
103 @override
104 void configureView(DemoContext context) {
105 context.orbit
106 ..distance = 10.0
107 ..pitch = 0.1
108 ..yaw = 0.0;
109 context.orbit.target.setValues(0.0, 1.6, 0.0);
110 }
112 @override
113 Scene build(DemoContext context) {
114 _report = _run();
115 final List<Vector4> inks = <Vector4>[
116 Vector4(0.45, 0.8, 0.5, 1.0),
117 Vector4(0.9, 0.6, 0.3, 1.0),
118 ];
119 _rods = <MeshNode>[
120 for (var i = 0; i < 2; i++)
121 blockNode(context, 'rod $i', Vector3(0.06, 1.0, 0.06), inks[i]),
122 ];
123 _bobs = <MeshNode>[
124 for (var i = 0; i < 2; i++) ballNode(context, 'bob $i', 0.28, inks[i]),
125 ];
126 _lamps = <MeshNode>[
127 for (var i = 0; i < _steps ~/ _every; i++)
128 ballNode(
129 context,
130 'lamp $i',
131 0.16,
132 Vector4(0.3, 0.3, 0.33, 1.0),
133 at: Vector3(-1.5 + i * 0.6, 0.2, 1.0),
134 ),
135 ];
136 return sceneOf(<SceneNode>[
137 floorNode(context, width: 9.0, depth: 4.0),
138 for (final double x in _pivotX)
139 blockNode(
140 context,
141 'pivot',
142 Vector3(0.3, 0.12, 0.3),
143 Vector4(0.2, 0.2, 0.24, 1.0),
144 at: Vector3(x, _pivotY + 0.05, 0.0),
145 ),
146 ..._rods,
147 ..._bobs,
148 ..._lamps,
149 ]);
150 }
152 void _begin() {
153 _restart = false;
154 _step = 0;
155 _owed = 0.0;
156 _pause = 0.0;
157 _assignmentLive = _Pendulum(length: 1.0);
158 _studentLive = _Pendulum(length: 1.0);
159 _assignmentTrace = DigestTrace(every: _every);
160 _studentTrace = DigestTrace(every: _every);
161 for (final MeshNode lamp in _lamps) {
162 lamp.material.baseColor = LinearColor.fromSrgb(0.3, 0.3, 0.33, 1.0);
163 }
164 }
166 @override
167 void update(DemoContext context, double dt) {
168 if (_restart) _begin();
169 if (_step >= _steps) {
170 _pause += dt;
171 if (_pause > 2.0) _restart = true;
172 } else {
173 // Two thirds of real time, so a swing is slow enough to follow.
174 _owed += dt * 60.0 * 0.66;
175 while (_owed >= 1.0 && _step < _steps) {
176 _owed -= 1.0;
177 _step++;
178 // The same two runs as above, a step at a time: one checkpoint every
179 // `_every` steps, and the student's length changes when the slider
180 // says.
181 _assignmentLive.step(1 / 60);
182 _assignmentTrace.observe(_step, _assignmentLive.state);
183 if (_step == changeAt.round()) _studentLive.length = newLength;
184 _studentLive.step(1 / 60);
185 _studentTrace.observe(_step, _studentLive.state);
186 if (_step % _every == 0) {
187 final int where = _step ~/ _every - 1;
188 final Divergence? parted = _studentTrace.divergenceFrom(
189 _assignmentTrace.digests,
190 );
191 final bool bad = parted != null && _step >= parted.step;
192 _lamps[where].material.baseColor = LinearColor.fromSrgb(
193 bad ? 0.9 : 0.35,
194 bad ? 0.3 : 0.85,
195 bad ? 0.3 : 0.4,
196 1.0,
197 );
198 }
199 }
200 }
201 _place(0, _assignmentLive);
202 _place(1, _studentLive);
203 }
205 void _place(int i, _Pendulum p) {
206 final double x = _pivotX[i];
207 final double length = p.length * 2.0;
208 final double dx = length * math.sin(p.theta);
209 final double dy = -length * math.cos(p.theta);
210 _bobs[i].setPosition(x + dx, _pivotY + dy, 0.0);
211 _rods[i]
212 ..setScale(1.0, length, 1.0)
213 ..setRotation(Quaternion.axisAngle(Vector3(0.0, 0.0, 1.0), p.theta))
214 ..setPosition(x + dx / 2, _pivotY + dy / 2, 0.0);
215 }
217 @override
218 List<DemoControl> controls(DemoContext context) => <DemoControl>[
219 SliderControl(
220 'Length changes at step',
221 min: 40,
222 max: 200,
223 value: () => changeAt,
224 onChanged: (double v) {
225 changeAt = v.roundToDouble();
226 _restart = true;
227 },
228 format: (double v) => v.round().toString(),
229 ),
230 SliderControl(
231 'New length',
232 min: 0.6,
233 max: 2.0,
234 value: () => newLength,
235 onChanged: (double v) {
236 newLength = v;
237 _restart = true;
238 },
239 format: (double v) => '${v.toStringAsFixed(2)} m',
240 ),
241 ];
243 static String _run() {
244 final assignment = DigestTrace(every: 10);
245 final assignmentPendulum = _Pendulum(length: 1.0);
246 for (var step = 1; step <= 60; step++) {
247 assignmentPendulum.step(1 / 60);
248 assignment.observe(step, assignmentPendulum.state);
249 }
251 // A student who changed the length partway through the run.
252 final studentPendulum = _Pendulum(length: 1.0);
253 final student = DigestTrace(every: 10);
254 for (var step = 1; step <= 60; step++) {
255 if (step == 30) studentPendulum.length = 1.3;
256 studentPendulum.step(1 / 60);
257 student.observe(step, studentPendulum.state);
258 }
260 final where = student.divergenceFrom(assignment.digests);
262 return 'the assignment and an unchanged replay agree at every '
263 'checkpoint\n'
264 'a student who changed the length at step 30 diverges at $where';
265 }
267 @override
268 void verify(Scene scene, FrameResult frame) {
269 if (frame.drawCalls < 1) {
270 throw StateError('the pendulum bob was not drawn');
271 }
272 if (!_report.contains('diverges at step 30')) {
273 throw StateError(
274 'changing the length at step 30 should be caught at '
275 'the checkpoint covering it',
276 );
277 }
278 }