flutter3d
Showcase Changelog 62 packages API reference

A time-travel debugger: the source

since 1.0.0-rc.1 Widgets and the rest

Regions the guide quotes: toy (line 17), record (line 86), scrub (line 187), back-and-forth (line 230), tracks (line 253), branch (line 277), bisect (line 286), named (line 306).

1/// A time-travel debugger over a live run: scrub to any step the rewind
2/// buffer holds and back to the present, read each entity's history as
3/// lanes, branch from a scrubbed moment, and bisect two runs of one tape to
4/// the step and component where they part.
5///
6/// Quoted by `time_travel.md` and shown whole in the Source tab.
7library;
8
9import 'package:flutter/foundation.dart' show visibleForTesting;
10import 'package:flutter3d_game/flutter3d_game.dart';
11import 'package:flutter3d_showcase/src/demo/demo.dart';
12import 'package:flutter3d_showcase/src/demo/scene_kit.dart';
13import 'package:flutter3d_sim/flutter3d_sim.dart';
15const GameAction _fire = GameAction('fire');
17/// Three entities written one row each: a runner that follows the stick, a
18/// door that opens when the runner reaches it, and a target that loses
19/// health by the dice whenever fire is pressed.
20///
21/// [defectAt] is a planted bug: on that step, and only that one, the target
22/// loses a point more. It stands for a code change or another platform, and
23/// it touches one component of one entity so the bisection has something
24/// definite to name.
25final class _Toy {
26 _Toy({this.defectAt});
28 final int? defectAt;
29 final GameRandom dice = GameRandom(11);
30 double x = 0.0;
31 bool open = false;
32 int hp = 200;
33 int steps = 0;
35 void step(InputState input) {
36 x += input.moveAxis.x * 0.05;
37 if (x > 2.0) open = true;
38 if (x < 1.0) open = false;
39 if (input.pressed(_fire)) hp -= 1 + dice.nextInt(6);
40 if (steps == defectAt) hp -= 1;
41 steps++;
42 }
44 Snapshot save() => Snapshot(<String, Object?>{
45 'entities': <String, Object?>{
46 'runner': <String, Object?>{'x': x},
47 'door': <String, Object?>{'open': open},
48 'target': <String, Object?>{'hp': hp},
49 },
50 'random': dice.state,
51 'steps': steps,
52 });
54 void restore(Snapshot snapshot) {
55 final Map<String, Object?> entities = snapshot.data.object('entities')!;
56 x = entities.object('runner')!.number('x');
57 open = entities.object('door')!['open'] == true;
58 hp = entities.object('target')!.integer('hp');
59 dice.state = snapshot.data.integer('random');
60 steps = snapshot.data.integer('steps');
61 }
64/// How the toy's snapshot is read as entities: one row per entity under
65/// `entities`, each row's fields its components.
66final EntityLayout _layout = EntityLayout.rows('entities');
68/// [length] steps of input: the stick swings every second and fire is
69/// pressed now and then.
70InputTape _tape(int length) => InputTape(
71 seed: 11,
72 frames: <InputFrame>[
73 for (var i = 0; i < length; i++)
74 InputFrame(
75 pressed: <String>[if (i % 23 == 5) _fire.name],
76 released: <String>[if (i % 23 == 6) _fire.name],
77 stickX: i % 120 < 60 ? 1.0 : -1.0,
78 ),
79 ],
80);
82/// A run of [steps] steps through an engine loop, with the state before
83/// every step kept to hold a scrub against.
84final class _Run {
85 _Run(int steps) {
86 // The toy is a part of the loop's snapshots and a system in its step;
87 // the buffer is attached, so its keyframes are the loop's captures.
88 loop
89 ..snapshots.add(
90 SnapshotPart.of(
91 id: 'toy',
92 capture: () => toy.save().data,
93 restore: (context) {
94 final data = context.data;
95 if (data is Map) {
96 toy.restore(Snapshot(data.cast<String, Object?>()));
97 }
98 },
99 ),
100 )
101 ..addSystem('toy', LoopPhase.rules, (_) => toy.step(input));
102 rewind.attach(loop);
103 loop.playback = InputTapePlayback.tape(_tape(steps));
104 for (var step = 0; step < steps; step++) {
105 seen[step] = toy.save();
106 loop.runSteps(1);
107 }
108 loop.playback = null;
109 seen[steps] = toy.save();
110 }
112 final _Toy toy = _Toy();
113 final InputState input = InputState();
114 late final EngineLoop loop = EngineLoop(input: input);
115 final RewindBuffer rewind = RewindBuffer(stepsPerSecond: 60, history: 10.0);
116 late final RunTimeline timeline = RunTimeline(rewind: rewind, loop: loop);
117 final Map<int, Snapshot> seen = <int, Snapshot>{};
119 int digestNow() => StateDigest.of(toy.save().data);
120 int digestSeen(int step) => StateDigest.of(seen[step]!.data);
123/// The `time-travel` page: a live run scrubbed, read as lanes, branched and
124/// bisected. Its check is that a scrub lands on the recorded state and that
125/// the lanes hold the door and the hp the run recorded.
126final class TimeTravelDemo extends ShowcaseDemo {
127 static const int _length = 300;
129 /// The run the viewport shows, paused at its present.
130 late final _Run _live;
131 double _scrub = _length.toDouble();
132 bool _dirty = true;
134 late final MeshNode _runner;
135 late final MeshNode _door;
136 late final MeshNode _target;
138 @override
139 void configureView(DemoContext context) {
140 context.orbit
141 ..distance = 7.5
142 ..pitch = 0.4
143 ..yaw = 0.2;
144 context.orbit.target.setValues(1.0, 0.6, 0.0);
145 }
147 @override
148 Scene build(DemoContext context) {
149 _live = _Run(_length);
150 _live.timeline.pause();
151 _runner = ballNode(context, 'runner', 0.3, Vector4(0.45, 0.75, 0.95, 1.0));
152 _door = blockNode(
153 context,
154 'door',
155 Vector3(0.2, 1.4, 1.2),
156 Vector4(0.75, 0.55, 0.35, 1.0),
157 );
158 _target = blockNode(
159 context,
160 'target',
161 Vector3(0.6, 1.0, 0.6),
162 Vector4(0.9, 0.35, 0.3, 1.0),
163 );
164 _place();
165 return sceneOf(<SceneNode>[
166 floorNode(context, width: 6.0, depth: 3.0),
167 _runner,
168 _door,
169 _target,
170 ]);
171 }
173 void _place() {
174 final _Toy toy = _live.toy;
175 _runner.setPosition(toy.x - 0.5, 0.3, 0.0);
176 _door.setPosition(1.5, toy.open ? 2.0 : 0.7, -0.9);
177 final double h = (toy.hp / 200.0).clamp(0.05, 1.0) * 1.6;
178 _target
179 ..setScale(1.0, h, 1.0)
180 ..setPosition(3.2, h / 2.0, 0.0);
181 }
183 @override
184 void update(DemoContext context, double dt) {
185 if (!_dirty) return;
186 _dirty = false;
187 // The slider is the scrubber. Any held step moves the live state there
188 // and keeps the tape and the present; the right end is the present.
189 final int step = _scrub.round();
190 if (step >= _live.rewind.step) {
191 _live.timeline.returnToPresent();
192 } else {
193 _live.timeline.scrubTo(step);
194 }
195 _place();
196 }
198 @override
199 List<DemoControl> controls(DemoContext context) => <DemoControl>[
200 SliderControl(
201 'Scrub to step',
202 min: 0,
203 max: _length.toDouble(),
204 divisions: _length,
205 value: () => _scrub,
206 onChanged: (double v) {
207 _scrub = v.roundToDouble();
208 _dirty = true;
209 },
210 format: (double v) =>
211 v.round() >= _length ? 'the present' : 'before step ${v.round()}',
212 ),
213 ToggleControl(
214 'Back to present',
215 value: () => false,
216 onChanged: (bool v) {
217 if (!v) return;
218 _scrub = _length.toDouble();
219 _dirty = true;
220 },
221 ),
222 ];
224 /// Scrubs a fresh run back and forth and answers the first step whose
225 /// state was not the one recorded before it, or null when every one was.
226 @visibleForTesting
227 static String? scrubMismatch() {
228 final _Run run = _Run(_length);
229 run.timeline.pause();
230 for (final int step in <int>[200, 240, 120, 121, 299, 0, 200]) {
231 final ScrubAnswer answer = run.timeline.scrubTo(step);
232 if (answer is! ScrubMoved) return 'step $step: $answer';
233 if (run.digestNow() != run.digestSeen(step)) return 'step $step';
234 }
235 run.timeline.returnToPresent();
236 if (run.digestNow() != run.digestSeen(_length)) return 'the present';
237 if (run.rewind.step != _length) return 'the tape was cut by a scrub';
238 return null;
239 }
241 @override
242 void verify(Scene scene, FrameResult frame) {
243 if (frame.drawCalls < 1) throw StateError('nothing reached the frame');
245 // Scrubbing back and forth lands on the state recorded before each
246 // step, and the present comes back exactly.
247 final String? mismatch = scrubMismatch();
248 if (mismatch != null) {
249 throw StateError('a scrub missed the recorded state at $mismatch');
250 }
252 final _Run run = _Run(_length)..timeline.pause();
253 final EntityTracks tracks = run.timeline.tracks(
254 layout: _layout,
255 part: 'toy',
256 )!;
257 final List<TrackSample> door = tracks.samples('door', 'open');
258 final TrackSample? hpAt150 = tracks.at('target', 'hp', 150);
259 if (tracks.span != const StepSpan(first: 0, last: _length)) {
260 throw StateError('the lanes cover ${tracks.span}, not 0 to $_length');
261 }
262 if (door.length < 3) {
263 throw StateError('the door opened and closed, but its lane has $door');
264 }
265 final Object? hpSeen = run.seen[150]!.data
266 .object('entities')!
267 .object('target')!['hp'];
268 if (hpAt150?.value != hpSeen) {
269 throw StateError(
270 'the hp lane says ${hpAt150?.value} at 150, not $hpSeen',
271 );
272 }
273 if (run.digestNow() != run.digestSeen(_length)) {
274 throw StateError('reading the lanes moved the live state');
275 }
277 run.timeline.scrubTo(150);
278 final ScrubAnswer branched = run.timeline.branchHere();
279 if (branched is! ScrubMoved ||
280 run.rewind.step != 150 ||
281 !run.timeline.isPaused ||
282 run.digestNow() != run.digestSeen(150)) {
283 throw StateError('branching at 150 did not make 150 the present');
284 }
286 // Two runs of one tape: this build, and one with a defect planted on
287 // step 413. Each side owns its own simulation.
288 ReplaySide side(_Toy toy) {
289 final InputState input = InputState();
290 return ReplaySide(
291 start: toy.save(),
292 tape: _tape(600),
293 input: input,
294 step: () => toy.step(input),
295 restore: toy.restore,
296 capture: toy.save,
297 );
298 }
300 final TapeBisection found = bisectTapes(
301 a: side(_Toy()),
302 b: side(_Toy(defectAt: 413)),
303 layout: _layout,
304 );
305 if (found is! TapesDiverge) throw StateError('the bisection found $found');
306 // `step` counts steps taken, so the tape entry that differed is one less.
307 if (found.step - 1 != 413 ||
308 found.inputsDiffer ||
309 found.component != const EntityComponent('target', 'hp') ||
310 found.components.length != 1 ||
311 found.probes > 12) {
312 throw StateError('the bisection named the wrong place: $found');
313 }
314 }