Skip to main content

euv_core/game/tilemap/
impl.rs

1use super::*;
2
3/// Tile lookup, mutation, static chunk-cache batching, and world-space queries for `TileMap`.
4impl TileMap {
5    /// Creates an empty `columns x rows` tilemap with cell size `tile_size`.
6    ///
7    /// # Arguments
8    ///
9    /// - `usize` - Number of columns.
10    /// - `usize` - Number of rows.
11    /// - `f32` - Tile width/height in world units.
12    ///
13    /// # Returns
14    ///
15    /// - `Self` - Initialized tilemap with default air entry at index `0`.
16    #[must_use]
17    pub fn empty(columns: usize, rows: usize, tile_size: f32) -> Self {
18        let c: usize = columns.max(1);
19        let r: usize = rows.max(1);
20        Self {
21            columns: c,
22            rows: r,
23            tile_size: tile_size.max(4.0),
24            cells: vec![0; c.saturating_mul(r)],
25            palette: vec![TilePaletteEntry::new(
26                COLOR_TRANSPARENT,
27                COLOR_TRANSPARENT,
28                false,
29            )],
30            cached_chunks: Vec::new(),
31            cache_revision: 1,
32            built_revision: 0,
33        }
34    }
35
36    /// Registers a new palette entry and returns its assigned tile ID.
37    ///
38    /// # Arguments
39    ///
40    /// - `&Self` - Mutable tilemap.
41    /// - `TilePaletteEntry` - Visual and solidity properties.
42    ///
43    /// # Returns
44    ///
45    /// - `u16` - Assigned tile identifier.
46    pub fn add_palette_entry(&mut self, entry: TilePaletteEntry) -> u16 {
47        let id: u16 = self.get_palette().len() as u16;
48        self.get_mut_palette().push(entry);
49        let next_rev: u64 = self.get_cache_revision().wrapping_add(1).max(1);
50        self.set_cache_revision(next_rev);
51        id
52    }
53
54    /// Sets the tile identifier at grid coordinate `(col, row)`.
55    ///
56    /// # Arguments
57    ///
58    /// - `&Self` - Mutable tilemap.
59    /// - `usize` - Column index.
60    /// - `usize` - Row index.
61    /// - `u16` - Tile identifier.
62    pub fn set_tile(&mut self, col: usize, row: usize, tile_id: u16) {
63        if col < self.get_columns() && row < self.get_rows() {
64            let idx: usize = row * self.get_columns() + col;
65            if self.get_cells()[idx] != tile_id {
66                self.get_mut_cells()[idx] = tile_id;
67                let next_rev: u64 = self.get_cache_revision().wrapping_add(1).max(1);
68                self.set_cache_revision(next_rev);
69            }
70        }
71    }
72
73    /// Returns `true` when the retained 16x16 static chunk cache matches the current tilemap revision.
74    ///
75    /// # Arguments
76    ///
77    /// - `&Self` - Tilemap reference.
78    ///
79    /// # Returns
80    ///
81    /// - `bool` - Whether cached chunk batches are up to date.
82    #[must_use]
83    pub fn has_fresh_chunk_cache(&self) -> bool {
84        self.get_built_revision() == self.get_cache_revision() && self.get_built_revision() != 0
85    }
86
87    /// Returns the retained cached static chunk batches slice if built.
88    ///
89    /// # Arguments
90    ///
91    /// - `&Self` - Tilemap reference.
92    ///
93    /// # Returns
94    ///
95    /// - `&[TileMapChunkBatch]` - Cached chunk run batches.
96    #[must_use]
97    pub fn cached_chunks(&self) -> &[TileMapChunkBatch] {
98        let Self { cached_chunks, .. } = self;
99        cached_chunks.as_slice()
100    }
101
102    /// Rebuilds the retained 16x16 static chunk run cache merging contiguous same-color horizontal tiles to reduce draw command counts.
103    ///
104    /// # Arguments
105    ///
106    /// - `&Self` - Mutable tilemap.
107    pub fn rebuild_chunk_cache(&mut self) {
108        let cols: usize = self.get_columns();
109        let rows: usize = self.get_rows();
110        let chunk_dim: usize = 16;
111        let chunk_cols: usize = cols.div_ceil(chunk_dim);
112        let chunk_rows: usize = rows.div_ceil(chunk_dim);
113        let rev: u64 = self.get_cache_revision();
114        let Self {
115            cells,
116            palette,
117            cached_chunks,
118            built_revision,
119            ..
120        } = self;
121        cached_chunks.clear();
122        let total_chunks: usize = chunk_cols.saturating_mul(chunk_rows);
123        if cached_chunks.capacity() < total_chunks {
124            cached_chunks.reserve(total_chunks - cached_chunks.capacity());
125        }
126        for cr in 0..chunk_rows {
127            let min_r: usize = cr * chunk_dim;
128            let max_r: usize = (min_r + chunk_dim).min(rows);
129            for cc in 0..chunk_cols {
130                let min_c: usize = cc * chunk_dim;
131                let max_c: usize = (min_c + chunk_dim).min(cols);
132                let mut runs: Vec<TileRunBatch> = Vec::new();
133                for r in min_r..max_r {
134                    let row_off: usize = r * cols;
135                    let mut c: usize = min_c;
136                    while c < max_c {
137                        let tid: u16 = cells[row_off + c];
138                        if tid == 0 {
139                            c += 1;
140                            continue;
141                        }
142                        let Some(entry) = palette.get(tid as usize) else {
143                            c += 1;
144                            continue;
145                        };
146                        let color: Color = entry.get_color();
147                        let start_c: usize = c;
148                        c += 1;
149                        while c < max_c {
150                            let next_tid: u16 = cells[row_off + c];
151                            if next_tid == 0 {
152                                break;
153                            }
154                            let same_color: bool = palette
155                                .get(next_tid as usize)
156                                .is_some_and(|e: &TilePaletteEntry| e.get_color() == color);
157                            if !same_color {
158                                break;
159                            }
160                            c += 1;
161                        }
162                        runs.push(TileRunBatch::new(start_c, r, c - start_c, color));
163                    }
164                }
165                if !runs.is_empty() {
166                    cached_chunks.push(TileMapChunkBatch {
167                        chunk_col: cc,
168                        chunk_row: cr,
169                        min_col: min_c,
170                        max_col: max_c,
171                        min_row: min_r,
172                        max_row: max_r,
173                        runs,
174                    });
175                }
176            }
177        }
178        *built_revision = rev;
179    }
180
181    /// Reads the tile identifier at `(col, row)`, returning `0` when out of bounds.
182    ///
183    /// # Arguments
184    ///
185    /// - `&Self` - Tilemap reference.
186    /// - `usize` - Column index.
187    /// - `usize` - Row index.
188    ///
189    /// # Returns
190    ///
191    /// - `u16` - Tile ID at `(col, row)`.
192    #[must_use]
193    pub fn tile_at(&self, col: usize, row: usize) -> u16 {
194        if col < self.get_columns() && row < self.get_rows() {
195            self.get_cells()[row * self.get_columns() + col]
196        } else {
197            0
198        }
199    }
200
201    /// Returns `true` if the world-space point `world_pt` falls inside a solid tile.
202    ///
203    /// # Arguments
204    ///
205    /// - `&Self` - Tilemap reference.
206    /// - `Point` - World-space query coordinate.
207    ///
208    /// # Returns
209    ///
210    /// - `bool` - Whether the tile at `world_pt` is solid.
211    #[must_use]
212    pub fn is_solid_at_world(&self, world_pt: Point) -> bool {
213        if world_pt.get_x() < 0.0 || world_pt.get_y() < 0.0 {
214            return false;
215        }
216        let col: usize = (world_pt.get_x() / self.get_tile_size()).floor() as usize;
217        let row: usize = (world_pt.get_y() / self.get_tile_size()).floor() as usize;
218        let tid: u16 = self.tile_at(col, row);
219        self.get_palette()
220            .get(tid as usize)
221            .map(TilePaletteEntry::get_solid)
222            .unwrap_or(false)
223    }
224
225    /// Returns total world-space dimensions `(width, height)` of the tilemap.
226    ///
227    /// # Arguments
228    ///
229    /// - `&Self` - Tilemap reference.
230    ///
231    /// # Returns
232    ///
233    /// - `Rect` - World bounds rectangle starting at `(0, 0)`.
234    #[must_use]
235    pub fn world_bounds(&self) -> Rect {
236        Rect::new(
237            0.0,
238            0.0,
239            (self.get_columns() as f32) * self.get_tile_size(),
240            (self.get_rows() as f32) * self.get_tile_size(),
241        )
242    }
243}
244
245/// Frame slicing and zero-copy `Arc<[u8]>` pixel access helpers for `SpriteSheet`.
246impl SpriteSheet {
247    /// Creates a `SpriteSheet` over `texture` with fixed `(frame_width, frame_height)` cells.
248    ///
249    /// # Arguments
250    ///
251    /// - `ImageBuffer` - Backing zero-copy `Arc<[u8]>` RGBA8 sprite atlas image.
252    /// - `u32` - Width of each frame in pixels.
253    /// - `u32` - Height of each frame in pixels.
254    ///
255    /// # Returns
256    ///
257    /// - `Self` - Constructed sprite sheet.
258    #[must_use]
259    pub fn from_grid(texture: ImageBuffer, frame_width: u32, frame_height: u32) -> Self {
260        let fw: u32 = frame_width.max(1);
261        let fh: u32 = frame_height.max(1);
262        let cols: u32 = (texture.get_width() / fw).max(1);
263        Self {
264            texture,
265            frame_width: fw,
266            frame_height: fh,
267            columns: cols,
268        }
269    }
270
271    /// Returns a zero-copy reference to the backing `Arc<[u8]>` sprite sheet pixels.
272    ///
273    /// # Arguments
274    ///
275    /// - `&Self` - Sprite sheet reference.
276    ///
277    /// # Returns
278    ///
279    /// - `&Arc<[u8]>` - Shared immutable RGBA8 sprite sheet pixel slice.
280    #[must_use]
281    pub fn shared_pixels(&self) -> &Arc<[u8]> {
282        self.get_texture().pixels_arc()
283    }
284
285    /// Computes the source pixel sub-rectangle for frame index `frame_index`.
286    ///
287    /// # Arguments
288    ///
289    /// - `&Self` - Sprite sheet reference.
290    /// - `u32` - Zero-based frame index.
291    ///
292    /// # Returns
293    ///
294    /// - `Rect` - Pixel sub-rectangle `(x, y, frame_width, frame_height)`.
295    #[must_use]
296    pub fn frame_rect(&self, frame_index: u32) -> Rect {
297        let col: u32 = frame_index % self.get_columns().max(1);
298        let row: u32 = frame_index / self.get_columns().max(1);
299        Rect::new(
300            (col * self.get_frame_width()) as f32,
301            (row * self.get_frame_height()) as f32,
302            self.get_frame_width() as f32,
303            self.get_frame_height() as f32,
304        )
305    }
306}
307
308/// Playback stepping and current-frame queries for `SpriteAnimator`.
309impl SpriteAnimator {
310    /// Advances animation playback clock by `dt_secs` and returns the active frame index.
311    ///
312    /// # Arguments
313    ///
314    /// - `&Self` - Mutable sprite animator.
315    /// - `f32` - Elapsed time delta in seconds.
316    ///
317    /// # Returns
318    ///
319    /// - `u32` - Active sprite sheet frame index.
320    pub fn tick(&mut self, dt_secs: f32) -> u32 {
321        let next: f32 = self.get_elapsed_secs() + dt_secs.max(0.0);
322        self.set_elapsed_secs(next);
323        self.current_frame()
324    }
325
326    /// Computes the active frame index from `elapsed_secs`.
327    ///
328    /// # Arguments
329    ///
330    /// - `&Self` - Sprite animator reference.
331    ///
332    /// # Returns
333    ///
334    /// - `u32` - Current sprite sheet frame index.
335    #[must_use]
336    pub fn current_frame(&self) -> u32 {
337        let count: u32 = self.get_frame_count().max(1);
338        let raw: u32 = (self.get_elapsed_secs() * self.get_fps().max(0.1)).floor() as u32;
339        let offset: u32 = if self.get_looping() {
340            raw % count
341        } else {
342            raw.min(count - 1)
343        };
344        self.get_start_frame().saturating_add(offset)
345    }
346}