Systems and events: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: live (line 88), systems (line 168), run (line 190), remove (line 197).
1/// Work a game adds to the loop's fixed step without owning the step itself,
2/// and the events a step reports so a frame can react without polling.
3///
4/// Quoted by `step_systems.md` and shown whole in the Source tab.
5library;
7import 'package:flutter3d/flutter3d.dart';
8import 'package:flutter3d_showcase/src/demo/demo.dart';
9import 'package:flutter3d_showcase/src/demo/scene_kit.dart';
10import 'package:flutter3d_sim/flutter3d_sim.dart';
12final class _ScoreChanged extends GameEvent {
13 const _ScoreChanged(this.total);
14 final int total;
17 String get name => 'ScoreChanged($total)';
18}
20/// The `step-systems` page: a coin collected by systems added to the fixed
21/// step. Its check is that a lower order runs first whatever the
22/// registration order, and that a removed system does not run.
23final class StepSystemsDemo extends ShowcaseDemo {
24 late final String _report;
26 /// Whether scoring runs before input rather than after it.
27 bool scoringFirst = false;
29 /// Whether the logging system is registered.
30 bool loggingOn = true;
32 bool _dirty = true;
33 late EngineLoop _loop;
34 final List<String> _ran = <String>[];
35 late final List<MeshNode> _slots;
36 late final BarGauge _tower;
37 int _score = 0;
38 double _sinceStep = 0.0;
40 static const Map<String, List<double>> _colors = <String, List<double>>{
41 'input': <double>[0.45, 0.65, 0.95],
42 'scoring': <double>[0.95, 0.8, 0.3],
43 'logging': <double>[0.75, 0.45, 0.85],
44 };
47 void configureView(DemoContext context) {
48 context.orbit
49 ..distance = 10.0
50 ..pitch = 0.75
51 ..yaw = 0.0;
52 context.orbit.target.setValues(1.0, 0.5, 0.0);
53 }
56 Scene build(DemoContext context) {
57 _report = _run();
58 _slots = <MeshNode>[
59 for (var i = 0; i < 3; i++)
60 blockNode(
61 context,
62 'slot $i',
63 Vector3(1.4, 0.5, 1.4),
64 Vector4(0.25, 0.26, 0.3, 1.0),
65 at: Vector3(-1.5 + i * 2.0, 0.25, 1.5),
66 ),
67 ];
68 _tower = BarGauge(
69 context,
70 'score',
71 Vector4(0.95, 0.8, 0.3, 1.0),
72 Vector3(-5.0, 0.0, 0.0),
73 height: 4.0,
74 width: 1.0,
75 vertical: true,
76 );
77 return sceneOf(<SceneNode>[
78 floorNode(context, width: 14.0, depth: 8.0),
79 ..._slots,
80 ..._tower.nodes,
81 ]);
82 }
84 /// The three systems of the page, registered in one order and asked to run
85 /// in another: `scoring` is registered before `input` and, unless the
86 /// toggle says otherwise, named to run after it.
87 void _register() {
88 final loop = EngineLoop(input: InputState());
89 loop.addSystem(
90 'scoring',
91 LoopPhase.rules,
92 (LoopContext step) {
93 _ran.add('scoring');
94 _score += 5;
95 },
96 settings: SystemSettings(
97 after: scoringFirst ? const <String>[] : const <String>['input'],
98 ),
99 );
100 loop.addSystem(
101 'input',
102 LoopPhase.rules,
103 (LoopContext step) => _ran.add('input'),
104 );
105 if (loggingOn) {
106 loop.addSystem(
107 'logging',
108 LoopPhase.rules,
109 (LoopContext step) => _ran.add('logging'),
110 settings: const SystemSettings(after: <String>['scoring', 'input']),
111 );
112 }
113 _loop = loop;
114 }
117 void update(DemoContext context, double dt) {
118 if (_dirty) {
119 _dirty = false;
120 _register();
121 }
122 _sinceStep += dt;
123 if (_sinceStep >= 0.6) {
124 _sinceStep = 0.0;
125 _ran.clear();
126 _loop.runSteps(1);
127 if (_score >= 100) _score = 0;
128 }
129 // Slot i shows whichever system ran i-th this step, dimming as the next
130 // step approaches.
131 final double glow = 1.0 - _sinceStep / 0.6;
132 for (var i = 0; i < _slots.length; i++) {
133 final List<double> c = i < _ran.length
134 ? _colors[_ran[i]]!
135 : const <double>[0.25, 0.26, 0.3];
136 final double k = i < _ran.length ? 0.35 + 0.65 * glow : 1.0;
137 _slots[i].material.baseColor = LinearColor.fromSrgb(
138 c[0] * k,
139 c[1] * k,
140 c[2] * k,
141 1.0,
142 );
143 }
144 _tower.set(_score / 100.0);
145 }
148 List<DemoControl> controls(DemoContext context) => <DemoControl>[
149 ToggleControl(
150 'Scoring before input',
151 value: () => scoringFirst,
152 onChanged: (bool v) {
153 scoringFirst = v;
154 _dirty = true;
155 },
156 ),
157 ToggleControl(
158 'Logging registered',
159 value: () => loggingOn,
160 onChanged: (bool v) {
161 loggingOn = v;
162 _dirty = true;
163 },
164 ),
165 ];
167 static String _run() {
168 final loop = EngineLoop(input: InputState());
169 // The bus the step publishes onto. A game's is its `EngineLoop`'s, whose
170 // step channel is heard at the end of the step; this page wants each
171 // event as it is published, so a `DirectBus`.
172 final events = DirectBus();
173 final heard = <GameEvent>[];
174 events.onStep<GameEvent>('step_systems.heard', (d) => heard.add(d.event));
175 var score = 0;
176 final order = <String>[];
178 final logging = loop.addSystem(
179 'logging',
180 LoopPhase.rules,
181 (LoopContext step) => order.add('logging'),
182 settings: const SystemSettings(after: <String>['scoring']),
183 );
184 loop.addSystem('scoring', LoopPhase.rules, (LoopContext step) {
185 order.add('scoring');
186 score += 5;
187 events.publish(_ScoreChanged(score));
188 });
190 // Registered "logging" first but named to run after "scoring": the
191 // constraint wins, and only what nothing names falls back on
192 // registration.
193 loop.runSteps(1);
194 final published = List<GameEvent>.of(heard);
195 final firstOrder = List<String>.of(order);
197 // The handle `addSystem` returned removes the system again; a step run
198 // after that no longer calls it.
199 logging.cancel();
200 order.clear();
201 loop.runSteps(1);
202 final afterRemoval = List<String>.of(order);
204 return 'ran in order: ${firstOrder.join(', ')}; '
205 'score is now $score; '
206 'events this step: ${published.map((GameEvent e) => e.name).join(', ')}; '
207 'after removing logging: $afterRemoval';
208 }
211 void verify(Scene scene, FrameResult frame) {
212 if (frame.drawCalls < 1) {
213 throw StateError('the coin was not drawn');
214 }
215 if (!_report.contains('ran in order: scoring, logging')) {
216 throw StateError(
217 'a lower order number should run first, whatever order '
218 'the systems were registered in',
219 );
220 }
221 if (!_report.contains('after removing logging: [scoring]')) {
222 throw StateError('a removed system should not run on the next step');
223 }
224 }
225}