The ECS world: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: live (line 126), world (line 184), remap (line 202), read (line 227).
1/// The entity store every simulation in the engine is built on, and the tool
2/// that carries a save across a level that has since been edited.
3///
4/// Quoted by `ecs_world.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 _Position {
13 const _Position(this.x);
14 final double x;
15}
17/// The `ecs-world` page: entities saved and carried into a level that was
18/// edited since. Its check is that the remap carries each position to its own
19/// name.
20final class EcsWorldDemo extends ShowcaseDemo {
21 late final double? _goblinX;
22 late final double? _trollX;
24 /// Which edited level the save is reloaded into, an index into the four the
25 /// choice names.
26 int reload = 0;
27 int _shown = -1;
29 late final Map<String, Object?> _saved;
30 late final List<MeshNode> _balls;
31 late final List<BarGauge> _bars;
32 late final List<MeshNode> _pedestals;
34 /// The names the reloaded level offers, in slot order, for each choice.
35 static const List<List<String?>> _levels = <List<String?>>[
36 <String?>['goblin', 'ogre', 'troll'],
37 <String?>['troll', 'goblin'],
38 <String?>['goblin'],
39 <String?>['ogre', 'goblin', 'ogre', 'troll'],
40 ];
43 void configureView(DemoContext context) {
44 context.orbit
45 ..distance = 12.0
46 ..pitch = 0.55
47 ..yaw = 0.2;
48 context.orbit.target.setValues(0.0, 0.8, 0.0);
49 }
52 Scene build(DemoContext context) {
53 final (String _, double? goblinX, double? trollX) = _run();
54 _goblinX = goblinX;
55 _trollX = trollX;
57 // The saved world, the same two entities `_run` saves.
58 final EcsWorld world = _newWorld();
59 final Entity goblin = world.spawn();
60 final Entity troll = world.spawn();
61 world
62 ..set(goblin, const _Position(3.0))
63 ..set(troll, const _Position(9.0));
64 _saved = world.save();
66 // Four slots is the most any choice below has: a pedestal, a ball that
67 // sits on it and a bar that stands for the number stored there.
68 const int slots = 4;
69 _pedestals = <MeshNode>[];
70 _balls = <MeshNode>[];
71 _bars = <BarGauge>[];
72 final List<SceneNode> nodes = <SceneNode>[
73 floorNode(context, width: 16.0, depth: 8.0),
74 ];
75 for (var i = 0; i < slots; i++) {
76 final double x = (i - (slots - 1) / 2) * 2.6;
77 final MeshNode pedestal = blockNode(
78 context,
79 'slot $i',
80 Vector3(1.8, 0.3, 1.8),
81 Vector4(0.5, 0.42, 0.34, 1.0),
82 at: Vector3(x, 0.15, 0.0),
83 );
84 final MeshNode ball = ballNode(
85 context,
86 'entity $i',
87 0.5,
88 Vector4(0.9, 0.9, 0.9, 1.0),
89 at: Vector3(x, 0.8, 0.0),
90 );
91 final BarGauge bar = BarGauge(
92 context,
93 'value $i',
94 Vector4(0.9, 0.75, 0.3, 1.0),
95 Vector3(x, 0.3, 1.8),
96 height: 2.5,
97 width: 0.4,
98 vertical: true,
99 );
100 _pedestals.add(pedestal);
101 _balls.add(ball);
102 _bars.add(bar);
103 nodes
104 ..add(pedestal)
105 ..add(ball)
106 ..addAll(bar.nodes);
107 }
108 return sceneOf(nodes);
109 }
111 EcsWorld _newWorld() => EcsWorld()
112 ..components.add<_Position>(
113 ComponentCodec<_Position>.of(
114 id: 'position',
115 encode: (_Position p) => p.x,
116 decode: (context) {
117 final data = context.data;
118 return _Position((data! as num).toDouble());
119 },
120 ),
121 );
123 /// The position stored in each slot of a level laid out as [names], or null
124 /// for a slot nothing was saved into.
125 List<double?> _reloadInto(List<String?> names) {
126 // The same remap as above, for whichever level is chosen: each saved
127 // entity finds its own name in the new layout, wherever that now is.
128 final remap = remapEntitySave(
129 _saved,
130 oldNames: <String?>['goblin', 'troll'],
131 newNames: names,
132 newGenerations: List<int>.filled(names.length, 0),
133 newFree: <int>[],
134 );
135 final EcsWorld reloaded = _newWorld();
136 final List<Entity> ids = <Entity>[
137 for (var i = 0; i < names.length; i++) reloaded.spawn(),
138 ];
139 reloaded.restore(remap.save);
140 return <double?>[
141 for (final Entity id in ids) reloaded.get<_Position>(id)?.x,
142 ];
143 }
146 void update(DemoContext context, double dt) {
147 if (reload == _shown) return;
148 _shown = reload;
149 final List<String?> names = _levels[reload];
150 final List<double?> found = _reloadInto(names);
151 for (var i = 0; i < _balls.length; i++) {
152 final bool has = i < names.length;
153 final double? x = has ? found[i] : null;
154 _pedestals[i].isVisible = has;
155 _balls[i].isVisible = x != null;
156 for (final SceneNode n in _bars[i].nodes) {
157 n.isVisible = x != null;
158 }
159 if (x == null) continue;
160 // Whoever held 3 is the goblin and whoever held 9 the troll.
161 _balls[i].material.baseColor = x < 5.0
162 ? LinearColor.fromSrgb(0.5, 0.8, 0.35, 1.0)
163 : LinearColor.fromSrgb(0.85, 0.35, 0.3, 1.0);
164 _bars[i].set(x / 9.0);
165 }
166 }
169 List<DemoControl> controls(DemoContext context) => <DemoControl>[
170 ChoiceControl(
171 'The level reloads as',
172 options: const <String>[
173 'goblin, ogre, troll',
174 'troll, goblin',
175 'goblin only',
176 'ogre, goblin, ogre, troll',
177 ],
178 index: () => reload,
179 onChanged: (int i) => reload = i,
180 ),
181 ];
183 static (String, double?, double?) _run() {
184 final world = EcsWorld()
185 ..components.add<_Position>(
186 ComponentCodec<_Position>.of(
187 id: 'position',
188 encode: (_Position p) => p.x,
189 decode: (context) {
190 final data = context.data;
191 return _Position((data! as num).toDouble());
192 },
193 ),
194 );
195 final goblin = world.spawn();
196 final troll = world.spawn();
197 world
198 ..set(goblin, const _Position(3.0))
199 ..set(troll, const _Position(9.0));
200 final saved = world.save();
202 // The level is reloaded with the goblin's old slot now empty and a third
203 // monster ahead of the troll, so the indices EcsWorld would otherwise
204 // reuse no longer mean what they meant.
205 final remap = remapEntitySave(
206 saved,
207 oldNames: <String?>['goblin', 'troll'],
208 newNames: <String?>['goblin', 'ogre', 'troll'],
209 newGenerations: <int>[0, 0, 0],
210 newFree: <int>[],
211 );
212 final reloaded = EcsWorld()
213 ..components.add<_Position>(
214 ComponentCodec<_Position>.of(
215 id: 'position',
216 encode: (_Position p) => p.x,
217 decode: (context) {
218 final data = context.data;
219 return _Position((data! as num).toDouble());
220 },
221 ),
222 );
223 // Three spawns to give the world the same three slots `newNames` describes.
224 final ids = <Entity>[for (var i = 0; i < 3; i++) reloaded.spawn()];
225 reloaded.restore(remap.save);
227 final goblinX = reloaded.get<_Position>(ids[0])?.x;
228 final trollX = reloaded.get<_Position>(ids[2])?.x;
229 return (
230 'goblin at x=$goblinX, troll at x=$trollX, dropped: ${remap.dropped}',
231 goblinX,
232 trollX,
233 );
234 }
237 void verify(Scene scene, FrameResult frame) {
238 if (frame.drawCalls < 1) {
239 throw StateError('the entity marker was not drawn');
240 }
241 // Compared as numbers, not read back out of `_report`: a double that
242 // survives a JSON-shaped map on the way here is not guaranteed the type
243 // inference a web backend needs to print it with its trailing `.0`, and
244 // a compiled `3` failing a substring match against `'x=3.0'` would be
245 // this check catching its own string, not the remap.
246 if (_goblinX != 3.0 || _trollX != 9.0) {
247 throw StateError('the remap should carry each position to its own name');
248 }
249 }
250}