retroglyph-window 0.3.1

Shared winit windowing layer for retroglyph's windowed backends
Documentation
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Tileset configuration: codepage mappings, options, builder, and error types.
//!
//! This module defines the public API for configuring PNG sprite sheet tilesets
//! that overlay or replace [`BitmapFont`](crate::font::BitmapFont) glyphs.
//! A tileset is a sprite sheet PNG sliced into equally sized tiles, each
//! mapped to a Unicode codepoint via a [`Codepage`]; [`SpriteCache`](crate::sprite_cache::SpriteCache)
//! decodes and indexes those tiles for lookup by glyph at draw time.

use core::fmt;

/// Errors that can occur during tileset validation or decoding.
#[derive(Debug)]
pub enum TilesetError {
    /// PNG decode failed.
    PngDecode(String),
    /// The image dimensions are not evenly divisible by the declared tile size.
    InvalidDimensions(u32, u32, u16, u16),
    /// The codepage mapping table has zero entries.
    EmptyCodepage,
    /// The pixel format is not RGBA8 or RGB8.
    UnsupportedPixelFormat(String),
    /// `tile_width` or `tile_height` is zero.
    ZeroTileSize,
    /// `spacing_cells_x` or `spacing_cells_y` is zero.
    ZeroSpacing,
}

impl fmt::Display for TilesetError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::PngDecode(e) => write!(f, "png decode failed: {e}"),
            Self::InvalidDimensions(iw, ih, tw, th) => {
                write!(f, "image {iw}x{ih} is not divisible by tile size {tw}x{th}")
            }
            Self::EmptyCodepage => write!(f, "codepage mapping has no entries"),
            Self::UnsupportedPixelFormat(fmt_name) => {
                write!(
                    f,
                    "unsupported pixel format: {fmt_name}; expected RGBA8 or RGB8"
                )
            }
            Self::ZeroTileSize => {
                write!(f, "tile_width and tile_height must be non-zero")
            }
            Self::ZeroSpacing => {
                write!(f, "spacing_cells_x and spacing_cells_y must be non-zero")
            }
        }
    }
}

impl std::error::Error for TilesetError {}

/// Maps row-major tile indices in a sprite sheet to Unicode codepoints.
///
/// `#[non_exhaustive]` allows adding new variants (e.g. `Cp1252`) without a
/// semver break.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Codepage {
    /// Standard CP437 layout: the i-th tile maps to `CP437_TO_UNICODE[i]`.
    ///
    /// Only the first 256 tiles in the sheet are mapped; extras are ignored.
    Cp437,
    /// Starting at `start`, tile index `i` maps to `char::from_u32(start as u32 + i)`.
    ///
    /// Tiles that would map to a surrogate or exceed `char::MAX` are skipped.
    Unicode {
        /// Codepoint of the first tile; subsequent tiles increment by 1.
        start: char,
    },
    /// Positional mapping: tile index `i` maps to `char::from_u32(i)`.
    ///
    /// This is the simplest option when you don't care about Unicode semantics
    /// and just want to reference tiles by a zero-based index. Use
    /// [`Tile::glyph`](retroglyph_core::Tile::glyph) values 0, 1, 2, … to address
    /// individual sprites in sheet order.
    ///
    /// Tiles whose index falls in the surrogate range (0xD800–0xDFFF) are
    /// skipped; all others are valid.
    Identity,
    /// Explicit mapping: tile `i` maps to `table[i]`.
    ///
    /// Tiles beyond `table.len()` are ignored.
    Custom(Vec<char>),
}

impl Codepage {
    /// Returns the codepoint for tile index `i`, or `None` if out of range
    /// or invalid (surrogates, indices past `char::MAX`).
    #[must_use]
    #[allow(clippy::cast_possible_truncation)]
    pub fn codepoint(&self, i: usize) -> Option<char> {
        match self {
            Self::Cp437 => CP437_TO_UNICODE.get(i).copied(),
            Self::Unicode { start } => {
                let scalar = (*start as u32).checked_add(i as u32)?;
                char::from_u32(scalar)
            }
            Self::Identity => char::from_u32(i as u32),
            Self::Custom(table) => table.get(i).copied(),
        }
    }

    /// Number of tiles this codepage defines, or `None` for unbounded variants.
    #[must_use]
    pub const fn len(&self) -> Option<usize> {
        match self {
            Self::Cp437 => Some(256),
            Self::Unicode { .. } | Self::Identity => None,
            Self::Custom(t) => Some(t.len()),
        }
    }

    /// Returns `true` if the codepage defines zero tiles.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == Some(0)
    }
}

/// Standard IBM CP437 to Unicode mapping, 256 entries.
pub const CP437_TO_UNICODE: [char; 256] = [
    '\u{0000}', '\u{263A}', '\u{263B}', '\u{2665}', '\u{2666}', '\u{2663}', '\u{2660}', '\u{2022}',
    '\u{25D8}', '\u{25CB}', '\u{25D9}', '\u{2642}', '\u{2640}', '\u{266A}', '\u{266B}', '\u{263C}',
    '\u{25BA}', '\u{25C4}', '\u{2195}', '\u{203C}', '\u{00B6}', '\u{00A7}', '\u{25AC}', '\u{21A8}',
    '\u{2191}', '\u{2193}', '\u{2192}', '\u{2190}', '\u{221F}', '\u{2194}', '\u{25B2}', '\u{25BC}',
    ' ', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2',
    '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E',
    'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
    'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
    'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~',
    '\u{2302}', '\u{00C7}', '\u{00FC}', '\u{00E9}', '\u{00E2}', '\u{00E4}', '\u{00E0}', '\u{00E5}',
    '\u{00E7}', '\u{00EA}', '\u{00EB}', '\u{00E8}', '\u{00EF}', '\u{00EE}', '\u{00EC}', '\u{00C4}',
    '\u{00C5}', '\u{00C9}', '\u{00E6}', '\u{00C6}', '\u{00F4}', '\u{00F6}', '\u{00F2}', '\u{00FB}',
    '\u{00F9}', '\u{00FF}', '\u{00D6}', '\u{00DC}', '\u{00A2}', '\u{00A3}', '\u{00A5}', '\u{20A7}',
    '\u{0192}', '\u{00E1}', '\u{00ED}', '\u{00F3}', '\u{00FA}', '\u{00F1}', '\u{00D1}', '\u{00AA}',
    '\u{00BA}', '\u{00BF}', '\u{2310}', '\u{00AC}', '\u{00BD}', '\u{00BC}', '\u{00A1}', '\u{00AB}',
    '\u{00BB}', '\u{2591}', '\u{2592}', '\u{2593}', '\u{2502}', '\u{2524}', '\u{2561}', '\u{2562}',
    '\u{2556}', '\u{2555}', '\u{2563}', '\u{2551}', '\u{2557}', '\u{255D}', '\u{255C}', '\u{255B}',
    '\u{2510}', '\u{2514}', '\u{2534}', '\u{252C}', '\u{251C}', '\u{2500}', '\u{253C}', '\u{255E}',
    '\u{255F}', '\u{255A}', '\u{2554}', '\u{2569}', '\u{2566}', '\u{2560}', '\u{2550}', '\u{256C}',
    '\u{2567}', '\u{2568}', '\u{2564}', '\u{2565}', '\u{2559}', '\u{2558}', '\u{2552}', '\u{2553}',
    '\u{256B}', '\u{256A}', '\u{2518}', '\u{250C}', '\u{2588}', '\u{2584}', '\u{258C}', '\u{2590}',
    '\u{2580}', '\u{03B1}', '\u{00DF}', '\u{0393}', '\u{03C0}', '\u{03A3}', '\u{03C3}', '\u{00B5}',
    '\u{03C4}', '\u{03A6}', '\u{0398}', '\u{03A9}', '\u{03B4}', '\u{221E}', '\u{03C6}', '\u{03B5}',
    '\u{2229}', '\u{2261}', '\u{00B1}', '\u{2265}', '\u{2264}', '\u{2320}', '\u{2321}', '\u{00F7}',
    '\u{2248}', '\u{00B0}', '\u{2219}', '\u{00B7}', '\u{221A}', '\u{207F}', '\u{00B2}', '\u{25A0}',
    '\u{00A0}',
];

/// Options for loading a single tileset (sprite sheet).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TilesetOptions {
    /// Raw bytes of the PNG file.
    pub bytes: Vec<u8>,
    /// Width of a single tile in pixels.
    pub tile_width: u16,
    /// Height of a single tile in pixels.
    pub tile_height: u16,
    /// Number of tiles per row in the sprite sheet.
    ///
    /// If `None`, derived as `image_width / tile_width`.
    pub columns: Option<u16>,
    /// Codepoint mapping from tile index to Unicode character.
    pub codepage: Codepage,
    /// Number of grid cells this sprite spans horizontally. Must be >= 1.
    pub spacing_cells_x: u16,
    /// Number of grid cells this sprite spans vertically. Must be >= 1.
    pub spacing_cells_y: u16,
    /// If set, any pixel matching this RGB colour is made fully transparent
    /// (alpha = 0) when decoding the tileset.
    ///
    /// Useful for spritesheets that use a solid colour background instead
    /// of an alpha channel.  Equivalent to bracket-lib's `with_font_bg()`
    /// or doryen-rs's top-left-pixel key colour auto-detection.
    pub transparent_color: Option<(u8, u8, u8)>,
}

impl TilesetOptions {
    /// Starts building a tileset from raw PNG bytes.
    ///
    /// Pass `include_bytes!("...").to_vec()` to embed the asset at compile
    /// time, or `std::fs::read(path)?` to load it at runtime.
    #[must_use]
    pub const fn from_bytes(bytes: Vec<u8>) -> TilesetBuilder {
        TilesetBuilder {
            bytes,
            tile_width: 0,
            tile_height: 0,
            columns: None,
            codepage: Codepage::Cp437,
            spacing_cells_x: 1,
            spacing_cells_y: 1,
            transparent_color: None,
        }
    }
}

/// Builder for [`TilesetOptions`].
///
/// Construct via [`TilesetOptions::from_bytes`].
///
/// [`columns`](TilesetBuilder::columns) defaults to `image_width / tile_width`,
/// so you usually don't need to set it explicitly. [`codepage`](TilesetBuilder::codepage)
/// defaults to [`Codepage::Cp437`].
///
/// # Examples
///
/// Standard CP437 tileset:
///
/// ```ignore
/// use retroglyph_window::tileset::TilesetOptions;
///
/// let png: Vec<u8> = std::fs::read("assets/cp437_16x16.png").unwrap();
/// let opts = TilesetOptions::from_bytes(png)
///     .tile_size(16, 16) // codepage defaults to Cp437
///     .build()
///     .unwrap();
/// ```
///
/// Private-use sprite sheet addressed by index:
///
/// ```ignore
/// use retroglyph_window::tileset::{Codepage, TilesetOptions};
///
/// let png: Vec<u8> = std::fs::read("assets/sprites.png").unwrap();
/// let opts = TilesetOptions::from_bytes(png)
///     .tile_size(32, 32)
///     .codepage(Codepage::Identity) // tile 0 = '\0', tile 1 = '\x01', …
///     .spacing(2, 2)                // each sprite occupies 2×2 grid cells
///     .build()
///     .unwrap();
/// ```
///
/// Unicode private-use area sprite sheet:
///
/// ```ignore
/// use retroglyph_window::tileset::TilesetOptions;
///
/// let png: Vec<u8> = std::fs::read("assets/monsters.png").unwrap();
/// let opts = TilesetOptions::from_bytes(png)
///     .tile_size(16, 16)
///     .start_codepoint('\u{E000}') // maps to Unicode PUA starting at U+E000
///     .build()
///     .unwrap();
/// ```
pub struct TilesetBuilder {
    bytes: Vec<u8>,
    tile_width: u16,
    tile_height: u16,
    columns: Option<u16>,
    codepage: Codepage,
    spacing_cells_x: u16,
    spacing_cells_y: u16,
    transparent_color: Option<(u8, u8, u8)>,
}

impl TilesetBuilder {
    /// Sets the pixel dimensions of each tile.
    #[must_use]
    pub const fn tile_size(mut self, width: u16, height: u16) -> Self {
        self.tile_width = width;
        self.tile_height = height;
        self
    }

    /// Sets the number of tiles per row in the sprite sheet.
    ///
    /// Useful for sheets with padding. If not set, derived from image width.
    #[must_use]
    pub const fn columns(mut self, cols: u16) -> Self {
        self.columns = Some(cols);
        self
    }

    /// Sets the codepoint mapping.
    #[must_use]
    pub fn codepage(mut self, codepage: Codepage) -> Self {
        self.codepage = codepage;
        self
    }

    /// Sets the codepoint of the first tile; subsequent tiles increment by 1.
    ///
    /// Shorthand for `codepage(Codepage::Unicode { start })`.
    #[must_use]
    pub fn start_codepoint(mut self, start: char) -> Self {
        self.codepage = Codepage::Unicode { start };
        self
    }

    /// Number of grid cells each sprite occupies (width x height).
    ///
    /// Defaults to (1, 1). A value of (2, 2) means the sprite spans 2x2 cells.
    #[must_use]
    pub const fn spacing(mut self, x: u16, y: u16) -> Self {
        self.spacing_cells_x = x;
        self.spacing_cells_y = y;
        self
    }

    /// Pixels matching `(r, g, b)` are made fully transparent (alpha = 0).
    ///
    /// Use this for spritesheets that use a solid colour background instead
    /// of an alpha channel.
    #[must_use]
    pub const fn transparent_color(mut self, r: u8, g: u8, b: u8) -> Self {
        self.transparent_color = Some((r, g, b));
        self
    }

    /// Validates and builds [`TilesetOptions`].
    ///
    /// # Errors
    ///
    /// Returns [`TilesetError::ZeroTileSize`] if tile dimensions are 0,
    /// [`TilesetError::ZeroSpacing`] if spacing is 0, or
    /// [`TilesetError::EmptyCodepage`] if `Custom` codepage is empty.
    pub fn build(self) -> Result<TilesetOptions, TilesetError> {
        if self.tile_width == 0 || self.tile_height == 0 {
            return Err(TilesetError::ZeroTileSize);
        }
        if self.spacing_cells_x == 0 || self.spacing_cells_y == 0 {
            return Err(TilesetError::ZeroSpacing);
        }
        if let Codepage::Custom(ref t) = self.codepage
            && t.is_empty()
        {
            return Err(TilesetError::EmptyCodepage);
        }
        Ok(TilesetOptions {
            bytes: self.bytes,
            tile_width: self.tile_width,
            tile_height: self.tile_height,
            columns: self.columns,
            codepage: self.codepage,
            spacing_cells_x: self.spacing_cells_x,
            spacing_cells_y: self.spacing_cells_y,
            transparent_color: self.transparent_color,
        })
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tileset_builder_rejects_zero_tile_size() {
        let opts = TilesetOptions::from_bytes(vec![]).tile_size(0, 16).build();
        assert!(matches!(opts, Err(TilesetError::ZeroTileSize)));
    }

    #[test]
    fn tileset_builder_rejects_zero_spacing() {
        let opts = TilesetOptions::from_bytes(vec![])
            .tile_size(16, 16)
            .spacing(0, 1)
            .build();
        assert!(matches!(opts, Err(TilesetError::ZeroSpacing)));
    }

    #[test]
    fn tileset_builder_rejects_empty_custom_codepage() {
        let opts = TilesetOptions::from_bytes(vec![])
            .tile_size(16, 16)
            .codepage(Codepage::Custom(vec![]))
            .build();
        assert!(matches!(opts, Err(TilesetError::EmptyCodepage)));
    }

    #[test]
    fn tileset_builder_valid() {
        let opts = TilesetOptions::from_bytes(vec![0u8; 64])
            .tile_size(16, 16)
            .start_codepoint('\u{E000}')
            .spacing(2, 2)
            .build()
            .unwrap();
        assert_eq!(opts.tile_width, 16);
        assert_eq!(opts.spacing_cells_x, 2);
        assert!(matches!(
            opts.codepage,
            Codepage::Unicode { start: '\u{E000}' }
        ));
    }

    #[test]
    fn cp437_codepage_spot_checks() {
        assert_eq!(Codepage::Cp437.codepoint(32), Some(' '));
        assert_eq!(Codepage::Cp437.codepoint(64), Some('@'));
        assert_eq!(Codepage::Cp437.codepoint(176), Some('\u{2591}'));
        assert_eq!(Codepage::Cp437.codepoint(256), None);
    }

    #[test]
    fn identity_codepage_positional() {
        assert_eq!(Codepage::Identity.codepoint(0), Some('\0'));
        assert_eq!(Codepage::Identity.codepoint(65), Some('A'));
        // Surrogate range must be skipped.
        assert_eq!(Codepage::Identity.codepoint(0xD800), None);
        assert_eq!(Codepage::Identity.codepoint(0xDFFF), None);
        // Above surrogates is fine.
        assert_eq!(Codepage::Identity.codepoint(0xE000), Some('\u{E000}'));
    }

    #[test]
    fn unicode_codepage_offset() {
        let cp = Codepage::Unicode { start: '\u{E000}' };
        assert_eq!(cp.codepoint(0), Some('\u{E000}'));
        assert_eq!(cp.codepoint(5), Some('\u{E005}'));
    }

    #[test]
    fn custom_codepage_bounds() {
        let cp = Codepage::Custom(vec!['A', 'B', 'C']);
        assert_eq!(cp.codepoint(0), Some('A'));
        assert_eq!(cp.codepoint(2), Some('C'));
        assert_eq!(cp.codepoint(3), None);
    }
}