src/tilemap.rs 15.2 K · 472 lines · raw · history

1 use bevy::{
2 asset::RenderAssetUsages,
3 prelude::*,
4 render::render_resource::{Extent3d, TextureDimension, TextureFormat},
5 sprite_render::{AlphaMode2d, TileData, TilemapChunk, TilemapChunkTileData},
6 };
7
8 use crate::{
9 light::LightMap,
10 world::{MAX_HEIGHT, Plant, TILE_SIZE, Terrain, TileChanged, WorldMap, hash2},
11 worldgen::WorldGenerated,
12 zones::Zones,
13 };
14
15 pub const CHUNK_SIZE: u32 = 64;
16 const TEXTURE_SIZE: u32 = 16;
17 const RELIEF: f32 = 0.35;
18 const LIGHT: Vec3 = Vec3::new(-1.0, 1.0, 1.5);
19
20 type Texture = Vec<[u8; 4]>;
21
22 pub struct TilemapPlugin;
23
24 impl Plugin for TilemapPlugin {
25 fn build(&self, app: &mut App) {
26 app.add_systems(Startup, spawn_chunks).add_systems(
27 Update,
28 (
29 refresh_chunks.run_if(world_or_light_changed),
30 refresh_changed_chunks,
31 refresh_zone_chunks.run_if(resource_changed::<Zones>),
32 ),
33 );
34 }
35 }
36
37 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
38 enum Layer {
39 Terrain,
40 Zones,
41 Roofs,
42 Plants,
43 }
44
45 impl Layer {
46 fn z(self) -> f32 {
47 match self {
48 Layer::Terrain => 0.0,
49 Layer::Zones => 0.3,
50 Layer::Roofs => 0.85,
51 Layer::Plants => 0.5,
52 }
53 }
54
55 fn tiles(
56 self,
57 map: &WorldMap,
58 zones: &Zones,
59 light: &LightMap,
60 origin: UVec2,
61 ) -> Vec<Option<TileData>> {
62 match self {
63 Layer::Terrain => chunk_tiles(map, light, origin),
64 Layer::Zones => zone_tiles(zones, origin),
65 Layer::Roofs => roof_tiles(map, origin),
66 Layer::Plants => plant_tiles(map, light, origin),
67 }
68 }
69 }
70
71 #[derive(Component)]
72 struct Chunk {
73 origin: UVec2,
74 layer: Layer,
75 }
76
77 fn spawn_chunks(
78 mut commands: Commands,
79 map: Res<WorldMap>,
80 zones: Res<Zones>,
81 light: Res<LightMap>,
82 mut images: ResMut<Assets<Image>>,
83 ) {
84 let terrain = images.add(stack_tileset(
85 Terrain::ALL.iter().map(|&t| terrain_texture(t)).collect(),
86 ));
87 let plants = images.add(stack_tileset(
88 Plant::ALL.iter().map(|&p| plant_texture(p)).collect(),
89 ));
90 let zone = images.add(stack_tileset(vec![zone_texture()]));
91 let roof = images.add(stack_tileset(vec![roof_texture()]));
92 let chunks = (map.size + CHUNK_SIZE - 1) / CHUNK_SIZE;
93 for (layer, tileset) in [
94 (Layer::Terrain, terrain),
95 (Layer::Zones, zone),
96 (Layer::Plants, plants),
97 (Layer::Roofs, roof),
98 ] {
99 for cy in 0..chunks.y {
100 for cx in 0..chunks.x {
101 let origin = UVec2::new(cx, cy) * CHUNK_SIZE;
102 let center = (origin.as_vec2() + CHUNK_SIZE as f32 / 2.0) * TILE_SIZE;
103 commands.spawn((
104 Name::new(format!("{layer:?} chunk {cx},{cy}")),
105 Chunk { origin, layer },
106 TilemapChunk {
107 chunk_size: UVec2::splat(CHUNK_SIZE),
108 tile_display_size: UVec2::splat(TILE_SIZE as u32),
109 tileset: tileset.clone(),
110 alpha_mode: AlphaMode2d::Blend,
111 },
112 TilemapChunkTileData(layer.tiles(&map, &zones, &light, origin)),
113 Transform::from_translation(center.extend(layer.z())),
114 ));
115 }
116 }
117 }
118 }
119
120 fn refresh_chunks(
121 map: Res<WorldMap>,
122 zones: Res<Zones>,
123 light: Res<LightMap>,
124 mut chunks: Query<(&Chunk, &mut TilemapChunkTileData)>,
125 ) {
126 for (chunk, mut data) in &mut chunks {
127 data.0 = chunk.layer.tiles(&map, &zones, &light, chunk.origin);
128 }
129 }
130
131 fn world_or_light_changed(
132 mut generated: MessageReader<WorldGenerated>,
133 light: Res<LightMap>,
134 ) -> bool {
135 generated.read().count() > 0 || light.is_changed()
136 }
137
138 fn refresh_zone_chunks(
139 map: Res<WorldMap>,
140 zones: Res<Zones>,
141 light: Res<LightMap>,
142 mut chunks: Query<(&Chunk, &mut TilemapChunkTileData)>,
143 ) {
144 for (chunk, mut data) in &mut chunks {
145 if chunk.layer == Layer::Zones {
146 data.0 = chunk.layer.tiles(&map, &zones, &light, chunk.origin);
147 }
148 }
149 }
150
151 fn refresh_changed_chunks(
152 map: Res<WorldMap>,
153 zones: Res<Zones>,
154 light: Res<LightMap>,
155 mut changes: MessageReader<TileChanged>,
156 mut chunks: Query<(&Chunk, &mut TilemapChunkTileData)>,
157 ) {
158 let origins: Vec<UVec2> = changes
159 .read()
160 .map(|TileChanged(tile)| chunk_origin(*tile))
161 .collect();
162 for (chunk, mut data) in &mut chunks {
163 if origins.contains(&chunk.origin) {
164 data.0 = chunk.layer.tiles(&map, &zones, &light, chunk.origin);
165 }
166 }
167 }
168
169 pub fn chunk_origin(tile: UVec2) -> UVec2 {
170 tile / CHUNK_SIZE * CHUNK_SIZE
171 }
172
173 fn chunk_positions(origin: UVec2) -> impl Iterator<Item = UVec2> {
174 (0..CHUNK_SIZE).flat_map(move |y| (0..CHUNK_SIZE).map(move |x| origin + UVec2::new(x, y)))
175 }
176
177 pub fn chunk_tiles(map: &WorldMap, light: &LightMap, origin: UVec2) -> Vec<Option<TileData>> {
178 chunk_positions(origin)
179 .map(|pos| {
180 map.get(pos.as_ivec2()).map(|terrain| TileData {
181 tileset_index: terrain.index(),
182 color: tint(jitter(pos) * shade(map, pos), light.color(pos)),
183 ..default()
184 })
185 })
186 .collect()
187 }
188
189 pub fn zone_tiles(zones: &Zones, origin: UVec2) -> Vec<Option<TileData>> {
190 chunk_positions(origin)
191 .map(|pos| {
192 zones
193 .is_stockpile(pos)
194 .then(|| TileData::from_tileset_index(0))
195 })
196 .collect()
197 }
198
199 pub fn roof_tiles(map: &WorldMap, origin: UVec2) -> Vec<Option<TileData>> {
200 chunk_positions(origin)
201 .map(|pos| {
202 map.is_roofed(pos.as_ivec2())
203 .then(|| TileData::from_tileset_index(0))
204 })
205 .collect()
206 }
207
208 pub fn plant_tiles(map: &WorldMap, light: &LightMap, origin: UVec2) -> Vec<Option<TileData>> {
209 chunk_positions(origin)
210 .map(|pos| {
211 map.plant(pos.as_ivec2()).map(|plant| TileData {
212 tileset_index: plant.index(),
213 color: tint(jitter(pos) * hillshade(map, pos), light.color(pos)),
214 ..default()
215 })
216 })
217 .collect()
218 }
219
220 fn tint(v: f32, light: Vec3) -> Color {
221 Color::srgb(v * light.x, v * light.y, v * light.z)
222 }
223
224 fn jitter(pos: UVec2) -> f32 {
225 0.92 + (hash2(pos.x, pos.y) % 9) as f32 * 0.01
226 }
227
228 fn shade(map: &WorldMap, pos: UVec2) -> f32 {
229 match map.get(pos.as_ivec2()) {
230 Some(t) if t.is_water() => 1.0,
231 _ => hillshade(map, pos) * height_brightness(map, pos),
232 }
233 }
234
235 fn height_brightness(map: &WorldMap, pos: UVec2) -> f32 {
236 0.9 + 0.2 * map.height(pos.as_ivec2()).unwrap_or(0.0) / MAX_HEIGHT
237 }
238
239 pub fn hillshade(map: &WorldMap, pos: UVec2) -> f32 {
240 let p = pos.as_ivec2();
241 let center = map.height(p).unwrap_or(0.0);
242 let h = |d: IVec2| map.height(p + d).unwrap_or(center);
243 let dx = (h(IVec2::X) - h(IVec2::NEG_X)) / 2.0;
244 let dy = (h(IVec2::Y) - h(IVec2::NEG_Y)) / 2.0;
245 let normal = Vec3::new(-dx * RELIEF, -dy * RELIEF, 1.0).normalize();
246 let light = LIGHT.normalize();
247 (normal.dot(light) / light.z).clamp(0.6, 1.25)
248 }
249
250 fn terrain_texture(terrain: Terrain) -> Texture {
251 let base = terrain.color();
252 let layer = terrain.index() as u32;
253 (0..TEXTURE_SIZE * TEXTURE_SIZE)
254 .map(|i| {
255 let speck = terrain
256 .speck_color()
257 .filter(|_| hash2(i / 2 + i / 32, layer) % 5 == 0);
258 let jitter = (hash2(i, layer) % 16) as f32 / 255.0 - 8.0 / 255.0;
259 let c = speck.unwrap_or(base);
260 Srgba::new(c.red + jitter, c.green + jitter, c.blue + jitter, 1.0).to_u8_array()
261 })
262 .collect()
263 }
264
265 fn zone_texture() -> Texture {
266 (0..TEXTURE_SIZE * TEXTURE_SIZE)
267 .map(|i| {
268 let (x, y) = (i % TEXTURE_SIZE, i / TEXTURE_SIZE);
269 let edge = x == 0 || y == 0 || x == TEXTURE_SIZE - 1 || y == TEXTURE_SIZE - 1;
270 [90, 160, 230, if edge { 150 } else { 55 }]
271 })
272 .collect()
273 }
274
275 fn roof_texture() -> Texture {
276 (0..TEXTURE_SIZE * TEXTURE_SIZE)
277 .map(|i| {
278 let (x, y) = (i % TEXTURE_SIZE, i / TEXTURE_SIZE);
279 let stripe = (x + y) % 4 == 0;
280 [110, 80, 50, if stripe { 90 } else { 45 }]
281 })
282 .collect()
283 }
284
285 fn plant_texture(plant: Plant) -> Texture {
286 match plant {
287 Plant::Tree => tree_texture(),
288 }
289 }
290
291 fn tree_texture() -> Texture {
292 let leaves = Srgba::rgb_u8(38, 92, 42);
293 let highlight = Srgba::rgb_u8(66, 126, 58);
294 let trunk = Srgba::rgb_u8(92, 64, 40);
295 let canopy_center = Vec2::new(7.5, 6.5);
296 (0..TEXTURE_SIZE * TEXTURE_SIZE)
297 .map(|i| {
298 let (x, y) = (i % TEXTURE_SIZE, i / TEXTURE_SIZE);
299 let p = Vec2::new(x as f32, y as f32);
300 let from_center = p - canopy_center;
301 if from_center.length() <= 6.0 {
302 let lit = from_center.dot(Vec2::new(-1.0, -1.0)) > 3.0;
303 if lit { highlight } else { leaves }.to_u8_array()
304 } else if (7..=8).contains(&x) && y >= 12 && y <= 14 {
305 trunk.to_u8_array()
306 } else {
307 [0, 0, 0, 0]
308 }
309 })
310 .collect()
311 }
312
313 pub fn tileset_layer_count(textures: u32) -> u32 {
314 match textures {
315 0 | 1 => 2,
316 n if n % 6 == 0 => n + 1,
317 n => n,
318 }
319 }
320
321 fn stack_tileset(textures: Vec<Texture>) -> Image {
322 let layers = tileset_layer_count(textures.len() as u32);
323 let empty = vec![[0, 0, 0, 0]; (TEXTURE_SIZE * TEXTURE_SIZE) as usize];
324 let data = (0..layers as usize)
325 .flat_map(|i| textures.get(i).unwrap_or(&empty).clone())
326 .flatten()
327 .collect();
328 let mut image = Image::new(
329 Extent3d {
330 width: TEXTURE_SIZE,
331 height: TEXTURE_SIZE * layers,
332 depth_or_array_layers: 1,
333 },
334 TextureDimension::D2,
335 data,
336 TextureFormat::Rgba8UnormSrgb,
337 RenderAssetUsages::RENDER_WORLD,
338 );
339 image
340 .reinterpret_stacked_2d_as_array(layers)
341 .expect("tileset is a vertical stack of square layers");
342 image
343 }
344
345 #[cfg(test)]
346 mod tests {
347 use super::*;
348
349 #[test]
350 fn chunk_tiles_beyond_map_edge_are_empty() {
351 let map = WorldMap::filled(UVec2::new(CHUNK_SIZE + 2, 3), Terrain::Stone);
352 let tiles = chunk_tiles(&map, &LightMap::default(), UVec2::new(CHUNK_SIZE, 0));
353 assert_eq!(tiles.len(), (CHUNK_SIZE * CHUNK_SIZE) as usize);
354 assert!(tiles[0].is_some());
355 assert!(tiles[1].is_some());
356 assert!(tiles[2].is_none());
357 assert!(tiles[CHUNK_SIZE as usize * 3].is_none());
358 }
359
360 // Chunk entities live for the whole session. World changes (regeneration now, digging and
361 // building later) rewrite their tile data in place; TilemapChunk re-uploads it through change
362 // detection, so no entities, meshes or materials are recreated.
363 #[test]
364 fn regeneration_rewrites_tile_data_of_existing_chunks() {
365 let mut app = App::new();
366 app.insert_resource(WorldMap::filled(UVec2::splat(CHUNK_SIZE), Terrain::Grass))
367 .init_resource::<Zones>()
368 .init_resource::<LightMap>()
369 .add_message::<WorldGenerated>()
370 .add_systems(Update, refresh_chunks.run_if(on_message::<WorldGenerated>));
371 let map = app.world().resource::<WorldMap>().clone();
372 let chunk = app
373 .world_mut()
374 .spawn((
375 Chunk {
376 origin: UVec2::ZERO,
377 layer: Layer::Terrain,
378 },
379 TilemapChunkTileData(chunk_tiles(&map, &LightMap::default(), UVec2::ZERO)),
380 ))
381 .id();
382
383 *app.world_mut().resource_mut::<WorldMap>() =
384 WorldMap::filled(UVec2::splat(CHUNK_SIZE), Terrain::Stone);
385 app.world_mut().write_message(WorldGenerated);
386 app.update();
387
388 let data = app.world().get::<TilemapChunkTileData>(chunk).unwrap();
389 assert!(
390 data.0
391 .iter()
392 .all(|t| t.unwrap().tileset_index == Terrain::Stone.index())
393 );
394 }
395
396 #[test]
397 fn darkness_tints_tiles_and_fires_warm_them() {
398 let map = WorldMap::filled(UVec2::splat(CHUNK_SIZE), Terrain::Grass);
399 let fire = (
400 UVec2::new(10, 10),
401 crate::structures::StructureKind::Campfire,
402 );
403 let night = LightMap::compute(map.size, 0.0, [fire]);
404 let tiles = chunk_tiles(&map, &night, UVec2::ZERO);
405 let lum = |pos: UVec2| {
406 let c = tiles[(pos.y * CHUNK_SIZE + pos.x) as usize]
407 .unwrap()
408 .color
409 .to_srgba();
410 c.red + c.green + c.blue
411 };
412 assert!(lum(UVec2::new(10, 11)) > lum(UVec2::new(40, 40)) * 2.0);
413 }
414
415 #[test]
416 fn roof_layer_covers_roofed_tiles_only() {
417 let mut map = WorldMap::filled(UVec2::splat(4), Terrain::Grass);
418 map.set_roof(UVec2::new(2, 1), true);
419 let tiles = roof_tiles(&map, UVec2::ZERO);
420 assert!(tiles[(CHUNK_SIZE + 2) as usize].is_some());
421 assert_eq!(tiles.iter().filter(|t| t.is_some()).count(), 1);
422 }
423
424 #[test]
425 fn chunk_origin_rounds_down_to_chunk_grid() {
426 assert_eq!(chunk_origin(UVec2::new(0, 63)), UVec2::new(0, 0));
427 assert_eq!(chunk_origin(UVec2::new(64, 130)), UVec2::new(64, 128));
428 }
429
430 #[test]
431 fn tileset_has_a_layer_for_every_texture() {
432 let textures = Terrain::ALL.iter().map(|&t| terrain_texture(t)).collect();
433 let image = stack_tileset(textures);
434 assert!(image.texture_descriptor.size.depth_or_array_layers >= Terrain::ALL.len() as u32);
435 }
436
437 #[test]
438 fn plant_layer_only_has_tiles_where_plants_grow() {
439 let mut map = WorldMap::filled(UVec2::splat(4), Terrain::Grass);
440 map.set_plant(UVec2::new(1, 0), Some(Plant::Tree));
441 let tiles = plant_tiles(&map, &LightMap::default(), UVec2::ZERO);
442 assert!(tiles[0].is_none());
443 assert_eq!(tiles[1].unwrap().tileset_index, Plant::Tree.index());
444 }
445
446 // Light comes from the north-west (LIGHT has -x, +y), the convention for hillshaded maps.
447 #[test]
448 fn slopes_facing_the_light_are_brighter_than_slopes_facing_away() {
449 let mut map = WorldMap::filled(UVec2::new(5, 1), Terrain::Grass);
450 for (x, h) in [0.0, 5.0, 10.0, 5.0, 0.0].into_iter().enumerate() {
451 map.set_height(UVec2::new(x as u32, 0), h);
452 }
453 let flat = WorldMap::filled(UVec2::new(3, 1), Terrain::Grass);
454 let facing_west = hillshade(&map, UVec2::new(1, 0));
455 let facing_east = hillshade(&map, UVec2::new(3, 0));
456 let level = hillshade(&flat, UVec2::new(1, 0));
457 assert!(facing_west > level);
458 assert!(facing_east < level);
459 }
460
461 // wgpu's GLES backend (WebGL2) guesses the texture view dimension from the layer count:
462 // 1 layer => D2, 6 => Cube, multiples of 6 => CubeArray. The tilemap shader needs D2Array,
463 // so the tileset is padded with an unused layer to dodge those counts.
464 #[test]
465 fn tileset_layer_count_avoids_webgl_view_dimension_heuristics() {
466 for n in 0..50 {
467 let layers = tileset_layer_count(n);
468 assert!(layers >= n.max(2));
469 assert!(layers % 6 != 0, "{n} terrains -> {layers} layers");
470 }
471 }
472 }