bevy_tiles/
maps.rs

1use bevy::{
2    ecs::{component::Component, entity::Entity},
3    utils::HashMap,
4};
5
6use crate::{chunks::ChunkCoord, coords::calculate_chunk_coordinate, tiles::TileCoord};
7
8/// Holds handles to all the chunks in a map.
9/// # Note
10/// Manually updating this value, adding it, or removing it from an entity may
11/// cause issues, please only mutate map information via commands.
12#[derive(Component)]
13pub struct TileMap<const N: usize = 2> {
14    chunks: HashMap<ChunkCoord<N>, Entity>,
15    /// The size of a chunk in one direction.
16    chunk_size: usize,
17}
18
19impl<const N: usize> TileMap<N> {
20    pub(crate) fn with_chunk_size(chunk_size: usize) -> Self {
21        Self {
22            chunks: Default::default(),
23            chunk_size,
24        }
25    }
26
27    /// Gets the chunk entity from a tile coordinate.
28    pub fn get_from_tile(&self, tile_c: TileCoord<N>) -> Option<Entity> {
29        let chunk_c = calculate_chunk_coordinate(tile_c.0, self.chunk_size);
30        self.chunks
31            .get::<ChunkCoord<N>>(&ChunkCoord::<N>(chunk_c))
32            .cloned()
33    }
34
35    /// Gets the chunk entity from a chunk coordinate.
36    pub fn get_from_chunk(&self, chunk_c: ChunkCoord<N>) -> Option<Entity> {
37        self.chunks.get::<ChunkCoord<N>>(&chunk_c).cloned()
38    }
39
40    /// Get readonly access to the chunk table.
41    pub fn get_chunks(&self) -> &HashMap<ChunkCoord<N>, Entity> {
42        &self.chunks
43    }
44
45    pub(crate) fn get_chunks_mut(&mut self) -> &mut HashMap<ChunkCoord<N>, Entity> {
46        &mut self.chunks
47    }
48
49    /// Get the size of chunks in this tilemap.
50    pub fn get_chunk_size(&self) -> usize {
51        self.chunk_size
52    }
53}