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