flutter3d
Showcase Changelog 62 packages API reference

Pausing and stepping a running game: the source

since 0.7.0 Widgets and the rest

Regions the guide quotes: timeline (line 21), play (line 120), pause (line 131), rewind (line 135).

1/// Pausing, stepping and rewinding a running game from outside it, built on
2/// a live rewind buffer.
3///
4/// **`flutter3d_game`'s real `RunTimeline` is not a dependency of this
5/// app.** Its mechanism is made of types this app already depends on
6/// through `flutter3d_sim` — `RewindBuffer`, `InputState`,
7/// `InputTapePlayback`, `Snapshot` — so this page carries the mechanism over
8/// with a step and a restore of the toy's own. The real class steps and
9/// restores through an `EngineLoop` and its snapshots instead
10/// (`RunTimeline(rewind:, loop:)`), so a rewind covers every part of the
11/// state.
12///
13/// Quoted by `run_timeline.md` and shown whole in the Source tab.
14library;
16import 'package:flutter/widgets.dart';
17import 'package:flutter3d/flutter3d.dart';
18import 'package:flutter3d_showcase/src/demo/demo.dart';
19import 'package:flutter3d_sim/flutter3d_sim.dart';
21/// Pause, step and rewind, over a live [RewindBuffer] — carried over from
22/// `flutter3d_game`'s real class, whose whole body is `flutter3d_sim` types.
23final class _RunTimeline {
24 _RunTimeline({
25 required this.rewind,
26 required this.input,
27 required this.stepSim,
28 required this.restore,
29 this.stepSeconds = 1.0 / 60.0,
30 });
32 final RewindBuffer rewind;
33 final InputState input;
34 final void Function(double dt) stepSim;
35 final void Function(Snapshot snapshot) restore;
36 final double stepSeconds;
38 bool _paused = false;
39 bool get isPaused => _paused;
41 void pause() => _paused = true;
42 void resume() => _paused = false;
44 void stepOnce() {
45 if (!_paused) {
46 throw StateError('stepOnce is only valid while the timeline is paused');
47 }
48 stepSim(stepSeconds);
49 }
51 RewindPoint? preview(double secondsAgo) => rewind.rewindBy(secondsAgo);
53 void releaseAt(RewindPoint point) {
54 restore(point.snapshot);
55 final toPoint = InputTapePlayback.tape(point.tapeToPoint);
56 while (!toPoint.isFinished) {
57 toPoint.applyTo(input);
58 stepSim(stepSeconds);
59 }
60 rewind.cut(point);
61 _paused = false;
62 }
65/// The `run-timeline` page: a runner paused, stepped and rewound from
66/// outside. Its check is that twenty steps reach 20, a manual step while
67/// paused advances it, and a rewind lands ten recorded steps back.
68final class RunTimelineDemo extends ShowcaseDemo {
69 late final String _report;
70 late final double _beforePause;
71 late final double _afterOneStep;
72 late final double _afterRelease;
73 late final bool _timelinePausedAfterRelease;
75 @override
76 Scene build(DemoContext context) {
77 final (
78 String report,
79 double beforePause,
80 double afterOneStep,
81 double afterRelease,
82 bool timelinePausedAfterRelease,
83 ) = _run();
84 _report = report;
85 _beforePause = beforePause;
86 _afterOneStep = afterOneStep;
87 _afterRelease = afterRelease;
88 _timelinePausedAfterRelease = timelinePausedAfterRelease;
89 final material = RenderMaterial(
90 name: 'runner',
91 baseColor: LinearColor.fromSrgb(0.6, 0.8, 0.5, 1.0),
92 );
93 final node = MeshNode(
94 DeviceMesh.upload(context.device, SphereShape(segments: 16).build()),
95 material,
96 );
97 return Scene()
98 ..add(node)
99 ..add(
100 LightNode(name: 'sun', intensity: 3.0 * LightNode.legacyUnit)
101 ..setLocalForward(Vector3(-0.4, -1.0, -0.3)),
102 );
103 }
105 static (String, double, double, double, bool) _run() {
106 var x = 0.0;
107 final buffer = RewindBuffer(
108 stepsPerSecond: 10,
109 keyframeEvery: 5,
110 history: 5,
111 );
112 final timeline = _RunTimeline(
113 rewind: buffer,
114 input: InputState(),
115 stepSim: (double dt) => x += 1.0,
116 restore: (Snapshot s) => x = (s.data['x']! as num).toDouble(),
117 stepSeconds: 1 / 10,
118 );
120 // Twenty steps of ordinary play, recorded the way a game loop already
121 // records every step for the rewind buffer.
122 for (var i = 0; i < 20; i++) {
123 buffer.recorder.tape.frames.add(InputFrame(stickX: 1.0));
124 if (buffer.isKeyframeDue) {
125 buffer.keyframe(Snapshot(<String, Object?>{'x': x}));
126 }
127 timeline.stepSim(1 / 10);
128 }
129 final beforePause = x;
131 timeline.pause();
132 timeline.stepOnce();
133 final afterOneStep = x;
135 final point = timeline.preview(1.0)!;
136 timeline.releaseAt(point);
137 final afterRelease = x;
139 final report =
140 'after twenty steps: x=$beforePause\n'
141 'paused, then stepped once by hand: x=$afterOneStep\n'
142 'rewound one second and released: x=$afterRelease, timeline paused: '
143 '${timeline.isPaused}';
144 return (report, beforePause, afterOneStep, afterRelease, timeline.isPaused);
145 }
147 @override
148 Widget? customBody(BuildContext buildContext, DemoContext context) =>
149 Container(
150 color: const Color(0xFF14161A),
151 padding: const EdgeInsets.all(24),
152 alignment: Alignment.topLeft,
153 child: DefaultTextStyle(
154 style: const TextStyle(color: Color(0xFFE8E8EC), fontSize: 16),
155 child: Text(_report),
156 ),
157 );
159 @override
160 void verify(Scene scene, FrameResult frame) {
161 if (frame.drawCalls < 1) {
162 throw StateError('the runner marker was not drawn');
163 }
164 // Compared as numbers, not read back out of `_report`: each of these is
165 // a whole-number double, and a web backend prints one of those without
166 // its trailing `.0` — a compiled `20` failing a substring match against
167 // `'x=20.0'` would be this check catching its own string, not the
168 // timeline.
169 if (_beforePause != 20.0) {
170 throw StateError('twenty recorded steps of one each should reach 20');
171 }
172 if (_afterOneStep != 21.0) {
173 throw StateError('a manual step while paused should still advance x');
174 }
175 if (_afterRelease != 10.0) {
176 throw StateError(
177 'rewinding one second on a ten-steps-a-second buffer should land '
178 'on the recorded state ten steps back, discarding the manual step '
179 'that was never recorded',
180 );
181 }
182 if (_timelinePausedAfterRelease) {
183 throw StateError(
184 'releasing a rewind point should leave the timeline '
185 'running, not paused',
186 );
187 }
188 }