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 char_item: usize = columns.max(1);
19        let red_val: usize = rows.max(1);
20        Self {
21            columns: char_item,
22            rows: red_val,
23            tile_size: tile_size.max(4.0),
24            cells: vec![0; char_item.saturating_mul(red_val)],
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 red_val in min_r..max_r {
134                    let row_off: usize = red_val * cols;
135                    let mut char_item: usize = min_c;
136                    while char_item < max_c {
137                        let tid: u16 = cells[row_off + char_item];
138                        if tid == 0 {
139                            char_item += 1;
140                            continue;
141                        }
142                        let Some(entry) = palette.get(tid as usize) else {
143                            char_item += 1;
144                            continue;
145                        };
146                        let color: Color = entry.get_color();
147                        let start_c: usize = char_item;
148                        char_item += 1;
149                        while char_item < max_c {
150                            let next_tid: u16 = cells[row_off + char_item];
151                            if next_tid == 0 {
152                                break;
153                            }
154                            let same_color: bool = palette.get(next_tid as usize).is_some_and(
155                                |event_ref: &TilePaletteEntry| event_ref.get_color() == color,
156                            );
157                            if !same_color {
158                                break;
159                            }
160                            char_item += 1;
161                        }
162                        runs.push(TileRunBatch::new(
163                            start_c,
164                            red_val,
165                            char_item - start_c,
166                            color,
167                        ));
168                    }
169                }
170                if !runs.is_empty() {
171                    cached_chunks.push(TileMapChunkBatch {
172                        chunk_col: cc,
173                        chunk_row: cr,
174                        min_col: min_c,
175                        max_col: max_c,
176                        min_row: min_r,
177                        max_row: max_r,
178                        runs,
179                    });
180                }
181            }
182        }
183        *built_revision = rev;
184    }
185
186    /// Reads the tile identifier at `(col, row)`, returning `0` when out of bounds.
187    ///
188    /// # Arguments
189    ///
190    /// - `&Self` - Tilemap reference.
191    /// - `usize` - Column index.
192    /// - `usize` - Row index.
193    ///
194    /// # Returns
195    ///
196    /// - `u16` - Tile ID at `(col, row)`.
197    #[must_use]
198    pub fn tile_at(&self, col: usize, row: usize) -> u16 {
199        if col < self.get_columns() && row < self.get_rows() {
200            self.get_cells()[row * self.get_columns() + col]
201        } else {
202            0
203        }
204    }
205
206    /// Returns `true` if the world-space point `world_pt` falls inside a solid tile.
207    ///
208    /// # Arguments
209    ///
210    /// - `&Self` - Tilemap reference.
211    /// - `Point` - World-space query coordinate.
212    ///
213    /// # Returns
214    ///
215    /// - `bool` - Whether the tile at `world_pt` is solid.
216    #[must_use]
217    pub fn is_solid_at_world(&self, world_pt: Point) -> bool {
218        if world_pt.get_x() < 0.0 || world_pt.get_y() < 0.0 {
219            return false;
220        }
221        let col: usize = (world_pt.get_x() / self.get_tile_size()).floor() as usize;
222        let row: usize = (world_pt.get_y() / self.get_tile_size()).floor() as usize;
223        let tid: u16 = self.tile_at(col, row);
224        self.get_palette()
225            .get(tid as usize)
226            .map(TilePaletteEntry::get_solid)
227            .unwrap_or(false)
228    }
229
230    /// Returns total world-space dimensions `(width, height)` of the tilemap.
231    ///
232    /// # Arguments
233    ///
234    /// - `&Self` - Tilemap reference.
235    ///
236    /// # Returns
237    ///
238    /// - `Rect` - World bounds rectangle starting at `(0, 0)`.
239    #[must_use]
240    pub fn world_bounds(&self) -> Rect {
241        Rect::new(
242            0.0,
243            0.0,
244            (self.get_columns() as f32) * self.get_tile_size(),
245            (self.get_rows() as f32) * self.get_tile_size(),
246        )
247    }
248}
249
250/// Frame slicing and zero-copy `Arc<[u8]>` pixel access helpers for `SpriteSheet`.
251impl SpriteSheet {
252    /// Creates a `SpriteSheet` over `texture` with fixed `(frame_width, frame_height)` cells.
253    ///
254    /// # Arguments
255    ///
256    /// - `ImageBuffer` - Backing zero-copy `Arc<[u8]>` RGBA8 sprite atlas image.
257    /// - `u32` - Width of each frame in pixels.
258    /// - `u32` - Height of each frame in pixels.
259    ///
260    /// # Returns
261    ///
262    /// - `Self` - Constructed sprite sheet.
263    #[must_use]
264    pub fn from_grid(texture: ImageBuffer, frame_width: u32, frame_height: u32) -> Self {
265        let fw: u32 = frame_width.max(1);
266        let fh: u32 = frame_height.max(1);
267        let cols: u32 = (texture.get_width() / fw).max(1);
268        Self {
269            texture,
270            frame_width: fw,
271            frame_height: fh,
272            columns: cols,
273        }
274    }
275
276    /// Returns a zero-copy reference to the backing `Arc<[u8]>` sprite sheet pixels.
277    ///
278    /// # Arguments
279    ///
280    /// - `&Self` - Sprite sheet reference.
281    ///
282    /// # Returns
283    ///
284    /// - `&Arc<[u8]>` - Shared immutable RGBA8 sprite sheet pixel slice.
285    #[must_use]
286    pub fn shared_pixels(&self) -> &Arc<[u8]> {
287        self.get_texture().pixels_arc()
288    }
289
290    /// Computes the source pixel sub-rectangle for frame index `frame_index`.
291    ///
292    /// # Arguments
293    ///
294    /// - `&Self` - Sprite sheet reference.
295    /// - `u32` - Zero-based frame index.
296    ///
297    /// # Returns
298    ///
299    /// - `Rect` - Pixel sub-rectangle `(x, y, frame_width, frame_height)`.
300    #[must_use]
301    pub fn frame_rect(&self, frame_index: u32) -> Rect {
302        let col: u32 = frame_index % self.get_columns().max(1);
303        let row: u32 = frame_index / self.get_columns().max(1);
304        Rect::new(
305            (col * self.get_frame_width()) as f32,
306            (row * self.get_frame_height()) as f32,
307            self.get_frame_width() as f32,
308            self.get_frame_height() as f32,
309        )
310    }
311}
312
313/// Playback stepping and current-frame queries for `SpriteAnimator`.
314impl SpriteAnimator {
315    /// Advances animation playback clock by `dt_secs` and returns the active frame index.
316    ///
317    /// # Arguments
318    ///
319    /// - `&Self` - Mutable sprite animator.
320    /// - `f32` - Elapsed time delta in seconds.
321    ///
322    /// # Returns
323    ///
324    /// - `u32` - Active sprite sheet frame index.
325    pub fn tick(&mut self, dt_secs: f32) -> u32 {
326        let next: f32 = self.get_elapsed_secs() + dt_secs.max(0.0);
327        self.set_elapsed_secs(next);
328        self.current_frame()
329    }
330
331    /// Computes the active frame index from `elapsed_secs`.
332    ///
333    /// # Arguments
334    ///
335    /// - `&Self` - Sprite animator reference.
336    ///
337    /// # Returns
338    ///
339    /// - `u32` - Current sprite sheet frame index.
340    #[must_use]
341    pub fn current_frame(&self) -> u32 {
342        let count: u32 = self.get_frame_count().max(1);
343        let raw: u32 = (self.get_elapsed_secs() * self.get_fps().max(0.1)).floor() as u32;
344        let offset: u32 = if self.get_looping() {
345            raw % count
346        } else {
347            raw.min(count - 1)
348        };
349        self.get_start_frame().saturating_add(offset)
350    }
351}