From 1b98dad9d09b65b0da1008689936a22a7f398cb6 Mon Sep 17 00:00:00 2001 From: luckyturtledev Date: Sat, 6 Jul 2024 16:16:38 +0200 Subject: [PATCH] add iterator to world --- src/activities/overworld/worldgen.rs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/activities/overworld/worldgen.rs b/src/activities/overworld/worldgen.rs index 73dfd21..6b8d664 100644 --- a/src/activities/overworld/worldgen.rs +++ b/src/activities/overworld/worldgen.rs @@ -56,10 +56,18 @@ pub struct Chunk { } impl Chunk { - fn get_tile(&self, local_chunk_coords: UVec2) -> Option<&Tile> { + pub fn get_tile(&self, local_chunk_coords: UVec2) -> Option<&Tile> { self.tiles .get((local_chunk_coords.y * CHUNK_SIZE + local_chunk_coords.x) as usize) } + + /// iterate over all tiles and its local chunk coords + pub fn iter_tiles(&self) -> impl Iterator { + self.tiles.iter().enumerate().map(|(i, tile)| { + let i = i as u32; + (UVec2::new(i % CHUNK_SIZE, i / CHUNK_SIZE), tile) + }) + } } #[derive(Debug, Default)] @@ -70,7 +78,7 @@ pub struct Overworld { impl Overworld { /// Return a [`Tile`] at the given world coordinates, or `None` if that tile has not /// been generated yet. - fn get_tile(&self, world_coords: IVec2) -> Option<&Tile> { + pub fn get_tile(&self, world_coords: IVec2) -> Option<&Tile> { let tile_coords = IVec2 { x: world_coords.x.div_euclid(CHUNK_SIZE as _), y: world_coords.y.div_euclid(CHUNK_SIZE as _) @@ -87,4 +95,15 @@ impl Overworld { fn get_or_generate_tile(&self, world_coords: IVec2) -> &Tile { unimplemented!() } + + /// iterate over all tiles and its global coords + pub fn iter_tiles(&self) -> impl Iterator { + self.chunks.iter().flat_map(|(chunk_coords, chunk)| { + chunk.iter_tiles().map(|(local_coords, tile)| { + // never fail because chunksize fits alswas into i32 + let local_coords: IVec2 = local_coords.try_into().unwrap(); + (local_coords + (*chunk_coords * CHUNK_SIZE as i32), tile) + }) + }) + } }