A world of blocks: the source
Open the live demo · Read the guide · View on GitHub
Regions the guide quotes: world (line 50), collision (line 61), mesh (line 105), edit (line 129), restore (line 154), check (line 203).
1/// A world of blocks drawn from a seed, dug into and built on while the page
2/// runs: each edit meshes its chunk again, replaces that chunk's collision
3/// boxes, and is kept as a delta against the terrain, which is all a save
4/// holds.
5///
6/// Quoted by `voxel_world.md` and shown whole in the Source tab.
7library;
9import 'package:flutter3d/flutter3d.dart';
10import 'package:flutter3d_physics/flutter3d_physics.dart';
11import 'package:flutter3d_showcase/src/demo/demo.dart';
12import 'package:flutter3d_showcase/src/demo/run_physics.dart';
13import 'package:flutter3d_voxel/flutter3d_voxel.dart';
15/// The `voxel-world` page: a world of blocks from a seed, dug and built on as
16/// the page runs. Its check is ground under every column, collision boxes as
17/// high as the blocks, and a dug block gone from the collision and the chunk.
18final class VoxelWorldDemo extends ShowcaseDemo {
19 /// Whether the page keeps digging and building.
20 bool digging = true;
22 late final GraphicsDevice _device;
23 late final Scene _scene;
24 late final VoxelWorld _voxels;
25 late final CollisionWorld _world;
26 late final VoxelCollision _collision;
27 late final Map<String, Object?> _save;
28 final Map<ChunkKey, List<MeshNode>> _nodes = <ChunkKey, List<MeshNode>>{};
30 /// The edits the page makes one at a time: a pit dug in the middle, then a
31 /// tower of a material the terrain never lays.
32 late final List<(int, int, int, int)> _plan;
33 int _next = 0;
34 double _clock = 0.0;
36 static const double _tick = 0.15;
39 void configureView(DemoContext context) {
40 context.orbit
41 ..distance = 44.0
42 ..pitch = 0.75
43 ..yaw = 0.6;
44 context.orbit.target.setValues(16.0, 6.0, 16.0);
45 }
48 Scene build(DemoContext context) {
49 _device = context.device;
50 // Two chunks by one by two: 32 by 16 by 32 voxels of rolling ground,
51 // drawn from seed 7 and nothing else.
52 _voxels = VoxelWorld(
53 chunksX: 2,
54 chunksY: 1,
55 chunksZ: 2,
56 terrain: const VoxelTerrain(seed: 7),
57 );
58 // Taken before any edit: the terrain's few numbers and no edits at all.
59 _save = _voxels.toJson();
61 // The chunks as boxes in an ordinary collision world, on the run's
62 // physics.
63 _world = onRunPhysics(CollisionWorld());
64 _collision = VoxelCollision(_voxels, _world);
65 _world.update();
67 _plan = <(int, int, int, int)>[
68 for (var depth = 0; depth < 4; depth++)
69 for (var x = 14; x <= 18; x++)
70 for (var z = 14; z <= 18; z++)
71 (x, _top(x, z) - 1 - depth, z, Voxels.empty),
72 for (var y = 0; y < 6; y++) (8, _top(8, 8) + y, 8, Voxels.firstPlaced),
73 ];
75 _scene = Scene()
76 ..ambientColor = LinearColor(0.55, 0.62, 0.75)
77 ..ambientIntensity = 0.35 * LightNode.legacyUnit
78 ..add(
79 LightNode(name: 'sun', intensity: 2.6 * LightNode.legacyUnit)
80 ..setLocalForward(Vector3(-0.4, -1.0, -0.25)),
81 );
82 for (final ChunkKey chunk in _voxels.chunks) {
83 _mesh(chunk);
84 }
85 return _scene;
86 }
88 /// The height of the first air above the column at [x], [z].
89 int _top(int x, int z) {
90 var y = 0;
91 while (_voxels.isSolid(x, y, z)) {
92 y++;
93 }
94 return y;
95 }
97 static Vector4 _colorOf(int material) => switch (material) {
98 Voxels.stone => Vector4(0.5, 0.5, 0.52, 1.0),
99 Voxels.dirt => Vector4(0.45, 0.32, 0.2, 1.0),
100 Voxels.grass => Vector4(0.35, 0.62, 0.28, 1.0),
101 Voxels.sand => Vector4(0.86, 0.78, 0.55, 1.0),
102 _ => Vector4(0.8, 0.36, 0.22, 1.0),
103 };
105 /// [chunk]'s faces, a greedy mesh per material, in place of what it had.
106 void _mesh(ChunkKey chunk) {
107 for (final MeshNode old in _nodes.remove(chunk) ?? const <MeshNode>[]) {
108 _scene.remove(old);
109 }
110 final List<MeshNode> nodes = <MeshNode>[
111 for (final MapEntry(key: material, value: data) in meshChunk(
112 _voxels,
113 chunk,
114 ).entries)
115 MeshNode(
116 DeviceMesh.upload(_device, data),
117 RenderMaterial(
118 name: 'voxel $material',
119 baseColor: _fromSrgb(_colorOf(material)),
120 roughness: 0.9,
121 ),
122 name: 'chunk ${chunk.x} ${chunk.z} material $material',
123 ),
124 ];
125 nodes.forEach(_scene.add);
126 _nodes[chunk] = nodes;
127 }
129 /// What an edit costs: the chunks whose faces it touched are meshed again,
130 /// and the chunks it changed get new boxes.
131 void _apply() {
132 final VoxelChanges changes = _voxels.drainChanges();
133 if (changes.isEmpty) return;
134 changes.surfaces.forEach(_mesh);
135 _collision.refresh(changes.chunks);
136 _world.update();
137 }
140 void update(DemoContext context, double dt) {
141 if (!digging) return;
142 _clock += dt;
143 if (_clock < _tick) return;
144 _clock = 0.0;
145 if (_next < _plan.length) {
146 final (int x, int y, int z, int material) = _plan[_next++];
147 _voxels.edit(x, y, z, material);
148 } else {
149 _restore();
150 }
151 _apply();
152 }
154 /// Back to the save taken at the start: only the voxels that differ from
155 /// it are touched.
156 void _restore() {
157 _voxels.restoreEdits(_save);
158 _next = 0;
159 }
162 List<DemoControl> controls(DemoContext context) => <DemoControl>[
163 ToggleControl(
164 'Dig and build',
165 value: () => digging,
166 onChanged: (bool v) => digging = v,
167 ),
168 ToggleControl(
169 'Put back the save',
170 value: () => false,
171 onChanged: (bool v) {
172 if (!v) return;
173 _restore();
174 _apply();
175 },
176 ),
177 ];
179 /// How high the collision boxes stand under [x], [z], by a ray straight
180 /// down.
181 double _groundAt(int x, int z) {
182 final RayHit hit = RayHit();
183 _world.rayCast(
184 Vector3(x + 0.5, 40.0, z + 0.5),
185 Vector3(0.0, -1.0, 0.0),
186 60.0,
187 hit,
188 );
189 if (!hit.didHit) throw StateError('no ground under $x, $z');
190 return hit.point.y;
191 }
193 int _triangles(ChunkKey chunk) => meshChunk(
194 _voxels,
195 chunk,
196 ).values.fold(0, (int sum, MeshData data) => sum + data.indices.length ~/ 3);
199 void verify(Scene scene, FrameResult frame) {
200 if (frame.drawCalls < 1) {
201 throw StateError('no chunk of the world reached the frame');
202 }
203 // A column well away from the pit: dig its top block out.
204 const int x = 4, z = 26;
205 const ChunkKey chunk = ChunkKey(x: 0, y: 0, z: 1);
206 final int top = _top(x, z);
207 final int edits = _voxels.editCount;
208 final int before = _triangles(chunk);
209 if ((_groundAt(x, z) - top).abs() > 1e-3) {
210 throw StateError('the boxes should stand as high as the blocks');
211 }
212 _voxels.edit(x, top - 1, z, Voxels.empty);
213 _apply();
214 if ((_groundAt(x, z) - (top - 1)).abs() > 1e-3) {
215 throw StateError('the dug block should be gone from the collision too');
216 }
217 if (_triangles(chunk) == before) {
218 throw StateError('the dug block should change the chunk\'s mesh');
219 }
220 // Put back what the terrain had, and it is no edit at all.
221 _voxels.edit(x, top - 1, z, _voxels.baseAt(x, top - 1, z));
222 _apply();
223 if (_voxels.editCount != edits) {
224 throw StateError('a block edited back to the terrain is still an edit');
225 }
227 // A save is the terrain and the edits; read back, it is the same world.
228 _voxels.edit(x, top, z, Voxels.firstPlaced);
229 final VoxelWorld copy = VoxelWorld.fromJson(_voxels.toJson());
230 if (copy.digest != _voxels.digest) {
231 throw StateError('the world read back from its save is another world');
232 }
233 _restore();
234 _apply();
235 if (_voxels.editCount != 0 ||
236 _voxels.digest !=
237 VoxelWorld(
238 chunksX: 2,
239 chunksY: 1,
240 chunksZ: 2,
241 terrain: const VoxelTerrain(seed: 7),
242 ).digest) {
243 throw StateError('restoring the first save should leave the terrain');
244 }
245 }
246}
248/// A `Vector4` holding a colour sRGB-encoded, as the linear colour it names.
249LinearColor _fromSrgb(Vector4 c) => LinearColor.fromSrgb(c.x, c.y, c.z, c.w);