//! Destructible heightmap terrain. //! //! The world is described by one surface height per sample (2 px wide). //! Carving raises the surface value (y grows downwards), collapsing relaxes //! slopes of sand in a fixed, deterministic order. use alloc::vec; use alloc::vec::Vec; use crate::fixed::{self, clamp, from_int, mul, to_int, Fx}; use crate::rng::Pcg32; /// World width in logical pixels. pub const WORLD_W: i32 = 2048; /// World height in logical pixels. pub const WORLD_H: i32 = 1152; /// Width of one heightmap sample in pixels. pub const SAMPLE_PX: i32 = 2; /// Number of heightmap samples. pub const SAMPLES: usize = (WORLD_W / SAMPLE_PX) as usize; /// Terrain material, controls collapse behaviour. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum Material { Air = 0, Sand = 1, Rock = 2, Ice = 3, } impl Material { fn from_u8(v: u8) -> Self { match v { 0 => Material::Air, 2 => Material::Rock, 3 => Material::Ice, _ => Material::Sand, } } } /// Heightmap plus per-sample material. #[derive(Clone, Debug)] pub struct Terrain { heights: Vec, materials: Vec, } impl Terrain { /// Deterministically generates a map from a seed. pub fn generate(seed: u64) -> Self { let mut rng = Pcg32::new(seed, 7); let phase1 = rng.below(360_000); let phase2 = rng.below(360_000); let phase3 = rng.below(360_000); let base = from_int(WORLD_H * 3 / 5); let mut heights = vec![0u16; SAMPLES]; let mut materials = vec![Material::Air as u8; SAMPLES]; for i in 0..SAMPLES { let x = i as i32; let h = base - mul( from_int(90), fixed::sin((x * 13 + phase1 as i32) as u32 % 360_000), ) - mul( from_int(40), fixed::sin((x * 29 + phase2 as i32) as u32 % 360_000), ) - mul( from_int(15), fixed::sin((x * 53 + phase3 as i32) as u32 % 360_000), ); heights[i] = to_int(clamp(h, from_int(240), from_int(WORLD_H - 120))) as u16; let depth_below_surface = WORLD_H - heights[i] as i32; materials[i] = if depth_below_surface < 120 { Material::Sand as u8 } else if rng.below(100) < 8 { Material::Ice as u8 } else { Material::Rock as u8 }; } Self { heights, materials } } /// Creates a flat map (used by tests and tutorials). pub fn flat(surface_y: i32) -> Self { Self { heights: vec![surface_y as u16; SAMPLES], materials: vec![Material::Rock as u8; SAMPLES], } } /// Number of heightmap samples. pub fn len(&self) -> usize { self.heights.len() } /// True if the heightmap has no samples (never happens in practice). pub fn is_empty(&self) -> bool { self.heights.is_empty() } /// Surface height at sample index. pub fn height_at(&self, idx: usize) -> u16 { self.heights[idx.min(SAMPLES - 1)] } /// Material at sample index. pub fn material_at(&self, idx: usize) -> Material { Material::from_u8(self.materials[idx.min(SAMPLES - 1)]) } /// Surface y for a world x coordinate (2 px granularity). pub fn surface_y(&self, x: Fx) -> Fx { let idx = self.index_of(x); from_int(self.heights[idx] as i32) } /// True if the given world point is inside solid ground. pub fn is_solid(&self, x: Fx, y: Fx) -> bool { if x < 0 || x >= from_int(WORLD_W) { return false; } y >= self.surface_y(x) } /// Sample index for a world x coordinate. pub fn index_of(&self, x: Fx) -> usize { let px = to_int(x).clamp(0, WORLD_W - 1); (px / SAMPLE_PX) as usize } /// Carves a circular crater and returns the number of removed height units. pub fn carve_circle(&mut self, cx: Fx, cy: Fx, radius: Fx) -> u32 { let r = to_int(radius).max(1); let ccx = to_int(cx); let ccy = to_int(cy); let mut removed = 0u32; let start = ((ccx - r) / SAMPLE_PX).max(0) as usize; let end = (((ccx + r) / SAMPLE_PX) + 1).min(SAMPLES as i32) as usize; for i in start..end { let sample_x = i as i32 * SAMPLE_PX; let dx = sample_x - ccx; if dx.abs() > r { continue; } // Circle depth in pixels at this sample. let depth = fixed::sqrt(from_int(r * r - dx * dx)); let old = self.heights[i] as i32; // Only material below the blast centre is removed. let from = old.max(ccy); let to = (from + to_int(depth)).min(WORLD_H); if to > from { self.heights[i] = to as u16; self.materials[i] = Material::Sand as u8; removed += (to - from) as u32; } } removed } /// Relaxes sand slopes: two deterministic passes left to right. pub fn collapse(&mut self) { let max_slope: i32 = 6; for _ in 0..2 { for i in 0..SAMPLES - 1 { if self.materials[i] != Material::Sand as u8 { continue; } let a = self.heights[i] as i32; let b = self.heights[i + 1] as i32; if b - a > max_slope { let shift = ((b - a - max_slope) / 2).max(1); self.heights[i] = (a + shift).clamp(0, WORLD_H) as u16; self.heights[i + 1] = (b - shift).clamp(0, WORLD_H) as u16; } else if a - b > max_slope { let shift = ((a - b - max_slope) / 2).max(1); self.heights[i] = (a - shift).clamp(0, WORLD_H) as u16; self.heights[i + 1] = (b + shift).clamp(0, WORLD_H) as u16; } } } } /// Flattens the surface under a tank so it can stand. pub fn flatten_under(&mut self, cx: Fx, width_px: i32) { let idx = self.index_of(cx); let half = (width_px / 2 / SAMPLE_PX).max(1) as usize; let lo = idx.saturating_sub(half); let hi = (idx + half).min(SAMPLES - 1); let target = self.heights[idx]; for i in lo..=hi { self.heights[i] = target; } } /// Serialises the heightmap for hashing (little endian, fixed order). pub fn feed_hash(&self, mut f: impl FnMut(u8)) { for h in &self.heights { f((*h & 0xFF) as u8); f((*h >> 8) as u8); } for m in &self.materials { f(*m); } } } #[cfg(test)] mod tests { use super::*; #[test] fn generation_is_deterministic() { let a = Terrain::generate(1234); let b = Terrain::generate(1234); assert_eq!(a.heights, b.heights); assert_eq!(a.materials, b.materials); let c = Terrain::generate(99); assert_ne!(a.heights, c.heights); } #[test] fn heights_stay_in_world_bounds() { for seed in 0..50u64 { let t = Terrain::generate(seed); for i in 0..t.len() { assert!(t.height_at(i) as i32 <= WORLD_H); assert!(t.height_at(i) as i32 >= 0); } } } #[test] fn carving_removes_material() { let mut t = Terrain::flat(600); let removed = t.carve_circle(from_int(1000), from_int(600), from_int(60)); assert!(removed > 0); assert!(t.height_at(t.index_of(from_int(1000))) > 600); } #[test] fn carving_never_exceeds_world_height() { let mut t = Terrain::flat(WORLD_H - 10); t.carve_circle(from_int(500), from_int(WORLD_H - 10), from_int(400)); for i in 0..t.len() { assert!(t.height_at(i) as i32 <= WORLD_H); } } #[test] fn collapse_reduces_steep_sand_slopes() { let mut t = Terrain::flat(600); for i in 500..520 { t.heights[i] = 900; t.materials[i] = Material::Sand as u8; } let before = t.heights[519] as i32 - t.heights[520] as i32; t.collapse(); let after = t.heights[519] as i32 - t.heights[520] as i32; assert!(after < before, "slope did not relax: {before} -> {after}"); } #[test] fn flatten_makes_a_level_platform() { let mut t = Terrain::generate(5); t.flatten_under(from_int(1024), 40); let idx = t.index_of(from_int(1024)); assert_eq!(t.height_at(idx - 5), t.height_at(idx + 5)); } }