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