src/world.rs 16 K · 529 lines · raw · history

1 use serde::{Deserialize, Serialize};
2 use std::collections::HashSet;
3
4 use bevy::prelude::*;
5
6 pub const MIN_WEAR: f32 = 0.05;
7 pub const TILE_SIZE: f32 = 16.0;
8 pub const MAX_HEIGHT: f32 = 100.0;
9 pub const UPHILL_COST_PER_METER: f32 = 20.0;
10 pub const CHEAPEST_MOVE_COST: u32 = 60;
11
12 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
13 pub enum Terrain {
14 Grass,
15 Soil,
16 Sand,
17 ShallowWater,
18 DeepWater,
19 Stone,
20 IronOre,
21 GoldOre,
22 Gravel,
23 Path,
24 Paved,
25 WoodFloor,
26 Bridge,
27 }
28
29 impl Terrain {
30 pub const ALL: [Terrain; 13] = [
31 Terrain::Grass,
32 Terrain::Soil,
33 Terrain::Sand,
34 Terrain::ShallowWater,
35 Terrain::DeepWater,
36 Terrain::Stone,
37 Terrain::IronOre,
38 Terrain::GoldOre,
39 Terrain::Gravel,
40 Terrain::Path,
41 Terrain::Paved,
42 Terrain::WoodFloor,
43 Terrain::Bridge,
44 ];
45
46 pub fn index(self) -> u16 {
47 self as u16
48 }
49
50 pub fn move_cost(self) -> Option<u32> {
51 match self {
52 Terrain::Paved | Terrain::WoodFloor => Some(CHEAPEST_MOVE_COST),
53 Terrain::Path | Terrain::Bridge => Some(80),
54 Terrain::Grass | Terrain::Soil => Some(100),
55 Terrain::Sand | Terrain::Gravel => Some(130),
56 Terrain::ShallowWater => Some(300),
57 Terrain::DeepWater | Terrain::Stone | Terrain::IronOre | Terrain::GoldOre => None,
58 }
59 }
60
61 pub fn is_water(self) -> bool {
62 matches!(self, Terrain::ShallowWater | Terrain::DeepWater)
63 }
64
65 pub fn is_rock(self) -> bool {
66 matches!(self, Terrain::Stone | Terrain::IronOre | Terrain::GoldOre)
67 }
68
69 pub fn color(self) -> Srgba {
70 match self {
71 Terrain::Grass => Srgba::rgb_u8(92, 140, 64),
72 Terrain::Soil => Srgba::rgb_u8(122, 92, 60),
73 Terrain::Sand => Srgba::rgb_u8(214, 196, 140),
74 Terrain::ShallowWater => Srgba::rgb_u8(72, 132, 184),
75 Terrain::DeepWater => Srgba::rgb_u8(36, 76, 140),
76 Terrain::Stone | Terrain::IronOre | Terrain::GoldOre => Srgba::rgb_u8(118, 118, 124),
77 Terrain::Gravel => Srgba::rgb_u8(150, 146, 138),
78 Terrain::Path => Srgba::rgb_u8(160, 128, 86),
79 Terrain::Paved => Srgba::rgb_u8(168, 164, 156),
80 Terrain::WoodFloor => Srgba::rgb_u8(150, 108, 66),
81 Terrain::Bridge => Srgba::rgb_u8(132, 96, 60),
82 }
83 }
84
85 pub fn speck_color(self) -> Option<Srgba> {
86 match self {
87 Terrain::IronOre => Some(Srgba::rgb_u8(178, 104, 72)),
88 Terrain::GoldOre => Some(Srgba::rgb_u8(236, 196, 60)),
89 Terrain::Path => Some(Srgba::rgb_u8(130, 104, 70)),
90 _ => None,
91 }
92 }
93 }
94
95 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
96 pub enum Plant {
97 Tree,
98 BerryBush,
99 Crop,
100 Herb,
101 }
102
103 impl Plant {
104 pub const ALL: [Plant; 4] = [Plant::Tree, Plant::BerryBush, Plant::Crop, Plant::Herb];
105
106 pub fn extra_move_cost(self) -> u32 {
107 match self {
108 Plant::Tree => 100,
109 Plant::BerryBush => 60,
110 Plant::Herb => 20,
111 Plant::Crop => 30,
112 }
113 }
114
115 pub fn ripening_ticks(self) -> Option<f32> {
116 let days = match self {
117 Plant::Tree => return None,
118 Plant::BerryBush => 2.0,
119 Plant::Herb => 3.0,
120 Plant::Crop => 1.5,
121 };
122 Some(days * 24.0 * crate::sim::TICKS_PER_HOUR as f32)
123 }
124
125 pub fn is_ripe(self, growth: f32) -> bool {
126 self.ripening_ticks().is_some() && growth >= 1.0
127 }
128 }
129
130 #[derive(Component, Default, Debug, Clone, Copy, PartialEq)]
131 pub struct TilePos(pub UVec2);
132
133 #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
134 pub struct MapLayers {
135 size: UVec2,
136 terrain: Vec<(u8, u32)>,
137 plants: Vec<(u8, u32)>,
138 walls: Vec<(u8, u32)>,
139 roofs: Vec<(u8, u32)>,
140 growth: Vec<(u32, f32)>,
141 wear: Vec<(u32, f32)>,
142 }
143
144 fn run_length(values: impl Iterator<Item = u8>) -> Vec<(u8, u32)> {
145 let mut runs: Vec<(u8, u32)> = Vec::new();
146 for v in values {
147 match runs.last_mut() {
148 Some((last, count)) if *last == v => *count += 1,
149 _ => runs.push((v, 1)),
150 }
151 }
152 runs
153 }
154
155 #[derive(Message, Debug, Clone, Copy, PartialEq)]
156 pub struct TileChanged(pub UVec2);
157
158 #[derive(Resource, Clone, Debug)]
159 pub struct WorldMap {
160 pub size: UVec2,
161 tiles: Vec<Terrain>,
162 plants: Vec<Option<Plant>>,
163 heights: Vec<f32>,
164 walls: Vec<bool>,
165 roofs: Vec<bool>,
166 growth: Vec<f32>,
167 wear: Vec<f32>,
168 worn: HashSet<UVec2>,
169 growing: HashSet<UVec2>,
170 shape_version: u64,
171 }
172
173 impl WorldMap {
174 pub fn filled(size: UVec2, terrain: Terrain) -> Self {
175 let n = size.element_product() as usize;
176 Self {
177 size,
178 tiles: vec![terrain; n],
179 plants: vec![None; n],
180 heights: vec![0.0; n],
181 walls: vec![false; n],
182 roofs: vec![false; n],
183 growth: vec![0.0; n],
184 wear: vec![0.0; n],
185 worn: HashSet::new(),
186 growing: HashSet::new(),
187 shape_version: 0,
188 }
189 }
190
191 pub fn in_bounds(&self, pos: IVec2) -> bool {
192 pos.x >= 0 && pos.y >= 0 && (pos.x as u32) < self.size.x && (pos.y as u32) < self.size.y
193 }
194
195 fn index(&self, pos: UVec2) -> usize {
196 (pos.y * self.size.x + pos.x) as usize
197 }
198
199 pub fn get(&self, pos: IVec2) -> Option<Terrain> {
200 self.in_bounds(pos)
201 .then(|| self.tiles[self.index(pos.as_uvec2())])
202 }
203
204 pub fn set(&mut self, pos: UVec2, terrain: Terrain) {
205 let i = self.index(pos);
206 if self.tiles[i].move_cost().is_some() != terrain.move_cost().is_some() {
207 self.shape_version += 1;
208 }
209 self.tiles[i] = terrain;
210 }
211
212 pub fn plant(&self, pos: IVec2) -> Option<Plant> {
213 self.in_bounds(pos)
214 .then(|| self.plants[self.index(pos.as_uvec2())])
215 .flatten()
216 }
217
218 pub fn set_plant(&mut self, pos: UVec2, plant: Option<Plant>) {
219 let i = self.index(pos);
220 self.plants[i] = plant;
221 if plant.is_some_and(|p| p.ripening_ticks().is_some()) {
222 self.growing.insert(pos);
223 } else {
224 self.growing.remove(&pos);
225 }
226 }
227
228 pub fn growing_plants(&self) -> Vec<UVec2> {
229 let mut tiles: Vec<UVec2> = self.growing.iter().copied().collect();
230 tiles.sort_by_key(|t| (t.y, t.x));
231 tiles
232 }
233
234 pub fn height(&self, pos: IVec2) -> Option<f32> {
235 self.in_bounds(pos)
236 .then(|| self.heights[self.index(pos.as_uvec2())])
237 }
238
239 pub fn set_height(&mut self, pos: UVec2, height: f32) {
240 let i = self.index(pos);
241 self.heights[i] = height;
242 }
243
244 pub fn is_wall(&self, pos: IVec2) -> bool {
245 self.in_bounds(pos) && self.walls[self.index(pos.as_uvec2())]
246 }
247
248 pub fn set_wall(&mut self, pos: UVec2, wall: bool) {
249 let i = self.index(pos);
250 if self.walls[i] != wall {
251 self.walls[i] = wall;
252 self.shape_version += 1;
253 }
254 }
255
256 pub fn growth(&self, pos: IVec2) -> f32 {
257 if self.in_bounds(pos) {
258 self.growth[self.index(pos.as_uvec2())]
259 } else {
260 0.0
261 }
262 }
263
264 pub fn set_growth(&mut self, pos: UVec2, growth: f32) {
265 let i = self.index(pos);
266 self.growth[i] = growth.clamp(0.0, 1.0);
267 }
268
269 pub fn wear(&self, pos: IVec2) -> f32 {
270 if self.in_bounds(pos) {
271 self.wear[self.index(pos.as_uvec2())]
272 } else {
273 0.0
274 }
275 }
276
277 pub fn set_wear(&mut self, pos: UVec2, wear: f32) {
278 let i = self.index(pos);
279 let wear = if wear < MIN_WEAR { 0.0 } else { wear };
280 self.wear[i] = wear;
281 if wear > 0.0 {
282 self.worn.insert(pos);
283 } else {
284 self.worn.remove(&pos);
285 }
286 }
287
288 pub fn layers(&self) -> MapLayers {
289 let sparse = |values: &[f32]| {
290 values
291 .iter()
292 .enumerate()
293 .filter(|(_, v)| **v != 0.0)
294 .map(|(i, v)| (i as u32, *v))
295 .collect()
296 };
297 MapLayers {
298 size: self.size,
299 terrain: run_length(self.tiles.iter().map(|t| t.index() as u8)),
300 plants: run_length(self.plants.iter().map(|p| p.map_or(0, |p| p as u8 + 1))),
301 walls: run_length(self.walls.iter().map(|&w| w as u8)),
302 roofs: run_length(self.roofs.iter().map(|&r| r as u8)),
303 growth: sparse(&self.growth),
304 wear: sparse(&self.wear),
305 }
306 }
307
308 pub fn restore(&mut self, layers: &MapLayers) -> Result<(), String> {
309 let n = self.tiles.len();
310 let unpacked = |runs: &[(u8, u32)]| {
311 let values: Vec<u8> = runs
312 .iter()
313 .flat_map(|&(v, count)| std::iter::repeat_n(v, count as usize))
314 .collect();
315 if values.len() == n {
316 Ok(values)
317 } else {
318 Err("map layer has the wrong size".to_string())
319 }
320 };
321 if layers.size != self.size {
322 return Err("map size differs".into());
323 }
324 let terrain = unpacked(&layers.terrain)?;
325 let plants = unpacked(&layers.plants)?;
326 let walls = unpacked(&layers.walls)?;
327 let roofs = unpacked(&layers.roofs)?;
328 for (i, pos) in self.positions().enumerate() {
329 let terrain = Terrain::ALL
330 .get(terrain[i] as usize)
331 .ok_or("unknown terrain")?;
332 self.set(pos, *terrain);
333 let plant = match plants[i] {
334 0 => None,
335 p => Some(*Plant::ALL.get(p as usize - 1).ok_or("unknown plant")?),
336 };
337 self.set_plant(pos, plant);
338 self.set_wall(pos, walls[i] != 0);
339 self.set_roof(pos, roofs[i] != 0);
340 self.set_growth(pos, 0.0);
341 self.set_wear(pos, 0.0);
342 }
343 let width = self.size.x;
344 let at = |i: u32| UVec2::new(i % width, i / width);
345 for &(i, growth) in &layers.growth {
346 self.set_growth(at(i), growth);
347 }
348 for &(i, wear) in &layers.wear {
349 self.set_wear(at(i), wear);
350 }
351 Ok(())
352 }
353
354 pub fn worn_tiles(&self) -> Vec<UVec2> {
355 let mut tiles: Vec<UVec2> = self.worn.iter().copied().collect();
356 tiles.sort_by_key(|t| (t.y, t.x));
357 tiles
358 }
359
360 pub fn ripe_plant(&self, pos: IVec2) -> Option<Plant> {
361 self.plant(pos).filter(|p| p.is_ripe(self.growth(pos)))
362 }
363
364 pub fn is_roofed(&self, pos: IVec2) -> bool {
365 self.in_bounds(pos) && self.roofs[self.index(pos.as_uvec2())]
366 }
367
368 pub fn set_roof(&mut self, pos: UVec2, roof: bool) {
369 let i = self.index(pos);
370 if self.roofs[i] != roof {
371 self.roofs[i] = roof;
372 self.shape_version += 1;
373 }
374 }
375
376 pub fn shape_version(&self) -> u64 {
377 self.shape_version
378 }
379
380 pub fn move_cost(&self, pos: IVec2) -> Option<u32> {
381 if self.is_wall(pos) {
382 return None;
383 }
384 let terrain = self.get(pos)?.move_cost()?;
385 Some(terrain + self.plant(pos).map_or(0, Plant::extra_move_cost))
386 }
387
388 pub fn step_cost(&self, from: IVec2, to: IVec2) -> Option<u32> {
389 let climb = (self.height(to)? - self.height(from)?).max(0.0);
390 Some(self.move_cost(to)? + (climb * UPHILL_COST_PER_METER).round() as u32)
391 }
392
393 pub fn positions(&self) -> impl Iterator<Item = UVec2> + use<> {
394 let size = self.size;
395 (0..size.y).flat_map(move |y| (0..size.x).map(move |x| UVec2::new(x, y)))
396 }
397
398 pub fn world_size(&self) -> Vec2 {
399 self.size.as_vec2() * TILE_SIZE
400 }
401
402 pub fn tile_center(pos: UVec2) -> Vec2 {
403 (pos.as_vec2() + 0.5) * TILE_SIZE
404 }
405
406 pub fn tile_at(&self, world: Vec2) -> Option<UVec2> {
407 let pos = (world / TILE_SIZE).floor().as_ivec2();
408 self.in_bounds(pos).then(|| pos.as_uvec2())
409 }
410 }
411
412 pub fn hash2(x: u32, y: u32) -> u32 {
413 let mut h = x.wrapping_mul(0x9E37_79B1) ^ y.wrapping_mul(0x85EB_CA77);
414 h ^= h >> 15;
415 h = h.wrapping_mul(0x2C1B_3C6D);
416 h ^= h >> 12;
417 h = h.wrapping_mul(0x297A_2D39);
418 h ^ (h >> 15)
419 }
420
421 #[cfg(test)]
422 mod tests {
423 use super::*;
424
425 // Growth runs ten times a game hour; it visits only tracked growing plants because a
426 // full-map pass that often dominated frame time at high speeds.
427 #[test]
428 fn only_ripening_plants_are_tracked_as_growing() {
429 let mut map = WorldMap::filled(UVec2::splat(4), Terrain::Grass);
430 map.set_plant(UVec2::new(1, 1), Some(Plant::Tree));
431 map.set_plant(UVec2::new(2, 2), Some(Plant::BerryBush));
432 map.set_plant(UVec2::new(3, 3), Some(Plant::Crop));
433 assert_eq!(
434 map.growing_plants(),
435 vec![UVec2::new(2, 2), UVec2::new(3, 3)]
436 );
437 map.set_plant(UVec2::new(2, 2), None);
438 assert_eq!(map.growing_plants(), vec![UVec2::new(3, 3)]);
439 }
440
441 #[test]
442 fn get_out_of_bounds_is_none() {
443 let map = WorldMap::filled(UVec2::new(4, 3), Terrain::Grass);
444 assert_eq!(map.get(IVec2::new(-1, 0)), None);
445 assert_eq!(map.get(IVec2::new(4, 0)), None);
446 assert_eq!(map.get(IVec2::new(0, 3)), None);
447 assert_eq!(map.get(IVec2::new(3, 2)), Some(Terrain::Grass));
448 }
449
450 #[test]
451 fn tiles_are_stored_row_major_from_bottom_left() {
452 let mut map = WorldMap::filled(UVec2::new(4, 3), Terrain::Grass);
453 map.set(UVec2::new(1, 2), Terrain::Stone);
454 assert_eq!(map.tiles[2 * 4 + 1], Terrain::Stone);
455 }
456
457 #[test]
458 fn tile_at_inverts_tile_center() {
459 let map = WorldMap::filled(UVec2::new(32, 128), Terrain::Grass);
460 for pos in [UVec2::ZERO, UVec2::new(17, 99), map.size - 1] {
461 assert_eq!(map.tile_at(WorldMap::tile_center(pos)), Some(pos));
462 }
463 }
464
465 #[test]
466 fn tile_at_outside_world_is_none() {
467 let map = WorldMap::filled(UVec2::new(32, 128), Terrain::Grass);
468 assert_eq!(map.tile_at(Vec2::new(-0.1, 0.0)), None);
469 assert_eq!(map.tile_at(map.world_size()), None);
470 }
471
472 #[test]
473 fn trees_slow_movement_but_do_not_block_it() {
474 let mut map = WorldMap::filled(UVec2::new(2, 1), Terrain::Grass);
475 let open = map.move_cost(IVec2::ZERO).unwrap();
476 map.set_plant(UVec2::ZERO, Some(Plant::Tree));
477 assert!(map.move_cost(IVec2::ZERO).unwrap() > open);
478 }
479
480 #[test]
481 fn bushes_and_crops_ripen_but_trees_do_not() {
482 assert!(Plant::BerryBush.is_ripe(1.0));
483 assert!(!Plant::Crop.is_ripe(0.9));
484 assert!(!Plant::Tree.is_ripe(1.0));
485 }
486
487 // A* uses CHEAPEST_MOVE_COST in its distance estimate; if any terrain were cheaper the
488 // estimate would overshoot and colonists could take needlessly long routes.
489 #[test]
490 fn no_terrain_is_cheaper_than_the_pathfinding_estimate() {
491 for terrain in Terrain::ALL {
492 if let Some(cost) = terrain.move_cost() {
493 assert!(cost >= CHEAPEST_MOVE_COST, "{terrain:?}");
494 }
495 }
496 }
497
498 #[test]
499 fn walls_block_movement() {
500 let mut map = WorldMap::filled(UVec2::new(2, 1), Terrain::Grass);
501 map.set_wall(UVec2::ZERO, true);
502 assert_eq!(map.move_cost(IVec2::ZERO), None);
503 assert!(map.move_cost(IVec2::X).is_some());
504 }
505
506 #[test]
507 fn walking_uphill_costs_more_than_downhill_or_flat() {
508 let mut map = WorldMap::filled(UVec2::new(3, 1), Terrain::Grass);
509 map.set_height(UVec2::new(1, 0), 5.0);
510 let (low, high, flat) = (IVec2::new(0, 0), IVec2::new(1, 0), IVec2::new(2, 0));
511 let up = map.step_cost(low, high).unwrap();
512 let down = map.step_cost(high, low).unwrap();
513 assert!(up > down);
514 assert_eq!(down, map.step_cost(low, flat).unwrap());
515 }
516
517 #[test]
518 fn rock_and_water_classification() {
519 assert!(Terrain::IronOre.is_rock() && Terrain::IronOre.move_cost().is_none());
520 assert!(Terrain::ShallowWater.is_water() && !Terrain::ShallowWater.is_rock());
521 }
522
523 #[test]
524 fn terrain_index_matches_position_in_all() {
525 for (i, t) in Terrain::ALL.iter().enumerate() {
526 assert_eq!(t.index() as usize, i);
527 }
528 }
529 }