Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_font/
lib.rs

1//! Bitmap-font atlases for the PS1.
2//!
3//! One crate, two types, three steps:
4//!
5//! 1. Declare (or pick) a [`BitmapFont`] -- a `static` descriptor
6//!    that carries glyph dimensions, a 1-bit-per-pixel bitmap, and
7//!    layout metadata (advance, line height, bit order). The
8//!    built-in fonts in [`fonts`] cover Public-Domain IBM-VGA-style
9//!    8×8 for ASCII / Latin-1 / box-drawing.
10//!
11//! 2. Upload it into VRAM once with [`FontAtlas::upload`] -- the
12//!    crate picks a sensible atlas layout, expands the 1bpp source
13//!    into a 4bpp CLUT texture, uploads that + a two-entry CLUT
14//!    (transparent + white), and returns a handle.
15//!
16//! 3. Call one of the [`FontAtlas`] draw methods every frame. The
17//!    same atlas supports both the fast rectangle path and the
18//!    flexible quad path -- choose based on what the call needs.
19//!
20//! ## Draw-path cheat sheet
21//!
22//! | Method | Hardware | Cost / glyph | Does |
23//! |---|---|---|---|
24//! | [`FontAtlas::draw_text`] | GP0 0x64 textured rect | 4 words | 1:1 axis-aligned, single tint |
25//! | [`FontAtlas::draw_text_scaled`] | GP0 0x2C textured quad | 9 words | Integer scale (2×, 3×, …), single tint |
26//! | [`FontAtlas::draw_text_scaled_q8`] | GP0 0x2C textured quad | 9 words | Q8 fractional scale (1.5× = 384), single tint |
27//! | [`FontAtlas::draw_text_rotated`] | GP0 0x2C textured quad | 9 words | Arbitrary angle rotation, single tint |
28//! | [`FontAtlas::draw_text_affine`] | GP0 0x2C textured quad | 9 words | Arbitrary 2×2 matrix, single tint |
29//! | [`FontAtlas::draw_text_gradient`] | GP0 0x3C gouraud-textured quad | 12 words | 1:1, top/bottom gradient |
30//! | [`FontAtlas::draw_text_scaled_gradient`] | GP0 0x3C gouraud-textured quad | 12 words | Scaled + top/bottom gradient |
31//!
32//! `draw_text` is the fast default. Everything below it is a quad
33//! primitive that pays ~2–3× the GP0 bandwidth for transforms or
34//! per-corner colour. At PS1 scale, this matters for text-heavy UIs
35//! (credit crawls, RPG dialogue walls) and doesn't for a HUD of a
36//! few dozen glyphs. Callers pick consciously.
37//!
38//! All methods share the same atlas and CLUT -- no duplicate VRAM.
39//! `draw_text_*` variants can freely mix in one frame, and tints
40//! compose with the PSX per-texel multiplier (`output = texel *
41//! tint / 128`).
42//!
43//! ## Generic over glyph dimensions
44//!
45//! Nothing in [`BitmapFont`] or [`FontAtlas`] hard-codes 8×8.
46//! Declare a second font at 6×12 or 8×16, drop it into VRAM at a
47//! different tpage, and you can mix sizes on the same screen.
48//! What's size-dependent:
49//!
50//! - **Atlas layout**: the uploader picks `glyphs_per_row` so the
51//!   atlas fits within its tpage.
52//! - **Upload buffer**: the stack-only scratch buffer inside
53//!   [`FontAtlas::upload`] is 16 KiB, enough for 128 glyphs at 16×16
54//!   or 64 glyphs at 32×16. Larger atlases panic today; use
55//!   [`upload_fonts`] with caller-owned scratch for them.
56//!
57//! ## Why 4bpp and not 15bpp direct
58//!
59//! 4bpp uses 1/4 the VRAM of 15bpp and opens the standard PSX
60//! "colour a monochrome glyph via tint" trick. A 96-glyph ASCII
61//! 8×8 atlas fits in 6×8 halfwords = 96 halfwords = 192 bytes of
62//! VRAM. Direct-15bpp would be 768 bytes, and you'd lose the free
63//! recolouring.
64//!
65//! ## Coordinate conventions
66//!
67//! - `draw_text` / `draw_text_scaled` / `draw_text_gradient`:
68//!   `(x, y)` is the **top-left** of the string's first glyph.
69//! - `draw_text_rotated`: `(cx, cy)` is the rotation **pivot** --
70//!   the centre of the baseline. Positive angles rotate
71//!   counter-clockwise in screen coords.
72//! - `draw_text_affine`: `origin` is the point the 2×2 transform
73//!   maps to the top-left of the first glyph. The matrix is applied
74//!   in glyph-local space before translating to `origin`.
75//!
76//! ## Fixed-point conventions (rotation + affine)
77//!
78//! Rotation uses a Q0.12 angle: `u16` in `[0, 4096)` mapping to
79//! `[0°, 360°)`. Sin/cos come from the shared SDK sin LUT in
80//! [`psx_math::sincos`] -- see that crate for the precision /
81//! Q-format specifics.
82//!
83//! Affine matrices are Q3.12 -- `i16` with 12 fractional bits, so
84//! `4096` = 1.0, `-4096` = -1.0, `8192` = 2.0, and the usable
85//! range is `±7.999…`. That's enough headroom for any visually
86//! reasonable 2×2 transform a bitmap font would want.
87
88#![no_std]
89#![deny(unsafe_op_in_unsafe_fn)]
90#![warn(missing_docs)]
91
92use psx_hw::gpu::{gp0, pack_color, pack_texcoord, pack_vertex, pack_xy, packet};
93use psx_io::gpu::{wait_command_ready, write_command};
94use psx_math::sincos;
95use psx_vram::{
96    upload_16bpp, upload_clut, Clut, Color555, TextureDepth, TexturePage, VramHandle, VramRect,
97    VramRegionSource,
98};
99
100pub mod fonts;
101pub mod hex;
102
103pub use hex::{format_u16, HexU16};
104
105// ======================================================================
106// BitmapFont -- the static descriptor
107// ======================================================================
108
109/// Bit-packing convention within each bitmap byte.
110///
111/// - [`BitOrder::Lsb`]: bit 0 of each byte is the **leftmost** pixel.
112///   Matches the dhepper/font8x8 convention our built-in fonts use.
113/// - [`BitOrder::Msb`]: bit 7 is the leftmost pixel. Matches the IBM
114///   VGA BIOS ROM / Linux `fbcon` `font_8x8.c` / GRUB conventions.
115///
116/// Fonts imported from different sources carry different bit orders;
117/// the uploader handles both transparently.
118#[derive(Copy, Clone, Debug, PartialEq, Eq)]
119pub enum BitOrder {
120    /// Bit 0 is the leftmost pixel.
121    Lsb,
122    /// Bit 7 is the leftmost pixel.
123    Msb,
124}
125
126/// A bitmap font as a static data descriptor.
127///
128/// All fields are compile-time constants so fonts can live in
129/// `.rodata` and a `BitmapFont` value can be declared as a `const`
130/// right next to its bitmap. The type stays size-agnostic -- 6×8,
131/// 8×8, 8×16, 12×16 all work; the uploader reads `glyph_w` /
132/// `glyph_h` and lays out the atlas from there.
133///
134/// Glyph `i` in the `bitmap` slice occupies
135/// `bitmap[i * row_bytes * glyph_h .. i * row_bytes * glyph_h +
136/// row_bytes * glyph_h]`, where `row_bytes = ceil(glyph_w / 8)`.
137/// For 8-wide glyphs that's one byte per row. Wider glyphs (12,
138/// 16 px) use multiple bytes per row, MSB-first within the row
139/// (i.e., byte 0 covers columns 0..=7, byte 1 covers columns
140/// 8..=15, regardless of [`BitOrder`] within each byte).
141///
142/// The `first_char` / `glyph_count` window is a codepoint range --
143/// code `c` is looked up at offset `c - first_char` in the bitmap
144/// as long as `first_char <= c < first_char + glyph_count`.
145/// Anything outside falls back to the missing-glyph box.
146#[derive(Copy, Clone, Debug)]
147pub struct BitmapFont {
148    /// Glyph cell width in pixels.
149    pub glyph_w: u8,
150    /// Glyph cell height in pixels.
151    pub glyph_h: u8,
152    /// First codepoint covered. For a basic-Latin font this is
153    /// usually `0x00` (null) or `0x20` (space).
154    pub first_char: u16,
155    /// Number of glyphs in this font. The range
156    /// `first_char..first_char + glyph_count` is the supported set.
157    pub glyph_count: u16,
158    /// Row-major bitmap bytes. `glyph_count * glyph_h *
159    /// ceil(glyph_w / 8)` bytes total.
160    pub bitmap: &'static [u8],
161    /// Optional per-glyph pixel advances. Proportional TTF imports fill this;
162    /// fixed-cell bitmap fonts leave it `None` and use `advance_x`.
163    pub glyph_advances: Option<&'static [u8]>,
164    /// Pixel step between adjacent characters on a text line.
165    /// Usually `== glyph_w` for fixed-width fonts. Proportional fonts use this
166    /// as the fallback for missing/out-of-range glyphs.
167    pub advance_x: u8,
168    /// Pixel step between text lines. Usually `== glyph_h`.
169    pub line_height: u8,
170    /// Bit packing within each bitmap byte.
171    pub bit_order: BitOrder,
172}
173
174impl BitmapFont {
175    /// Bytes per row of a single glyph in the source bitmap.
176    /// Derived from [`BitmapFont::glyph_w`] -- 1 byte for ≤ 8-wide
177    /// fonts, 2 bytes for 9..16-wide, etc.
178    pub const fn row_bytes(&self) -> usize {
179        (self.glyph_w as usize).div_ceil(8)
180    }
181
182    /// Total bitmap bytes per glyph.
183    pub const fn glyph_stride(&self) -> usize {
184        self.row_bytes() * self.glyph_h as usize
185    }
186
187    /// Glyph index for `ch` if the font covers its codepoint.
188    pub fn glyph_index(&self, ch: char) -> Option<u16> {
189        let cp = ch as u32;
190        let first = self.first_char as u32;
191        let end = first.saturating_add(self.glyph_count as u32);
192        if cp >= first && cp < end {
193            Some((cp - first) as u16)
194        } else {
195            None
196        }
197    }
198
199    /// Pixel advance for `ch`, falling back to [`BitmapFont::advance_x`] when
200    /// the font has no per-glyph table or `ch` is outside the covered range.
201    pub fn glyph_advance(&self, ch: char) -> u8 {
202        self.glyph_index(ch)
203            .and_then(|index| {
204                self.glyph_advances
205                    .and_then(|advances| advances.get(index as usize).copied())
206            })
207            .unwrap_or(self.advance_x)
208    }
209
210    /// Pixel width of `text` with this font's advance metrics.
211    pub fn text_width(&self, text: &str) -> u16 {
212        text.chars()
213            .map(|ch| self.glyph_advance(ch) as u16)
214            .fold(0u16, u16::saturating_add)
215    }
216
217    /// Pixel width of `text` with an extra signed spacing value inserted
218    /// between adjacent characters. The spacing is in final screen pixels,
219    /// so callers that scale glyphs can decide whether or not to scale the
220    /// spacing separately.
221    pub fn text_width_with_spacing(&self, text: &str, letter_spacing: i8) -> u16 {
222        let mut chars = text.chars();
223        let Some(first) = chars.next() else {
224            return 0;
225        };
226        let mut width = i32::from(self.glyph_advance(first));
227        for ch in chars {
228            width = width
229                .saturating_add(i32::from(letter_spacing))
230                .saturating_add(i32::from(self.glyph_advance(ch)));
231        }
232        width.clamp(0, i32::from(u16::MAX)) as u16
233    }
234
235    /// Fetch row `r` of glyph `i` as 4 bytes LSB-packed little-
236    /// endian -- the row comes out as a `u32` with pixel 0 in bit
237    /// 0, pixel 1 in bit 1, … up to pixel 31 (enough for any
238    /// realistic cell width). Handles [`BitOrder`] normalisation
239    /// in one place so callers don't have to branch.
240    pub fn glyph_row_packed(&self, i: u16, r: u8) -> u32 {
241        let base = i as usize * self.glyph_stride() + r as usize * self.row_bytes();
242        let mut out: u32 = 0;
243        for byte_idx in 0..self.row_bytes() {
244            let raw = self.bitmap[base + byte_idx] as u32;
245            let normalised = match self.bit_order {
246                BitOrder::Lsb => raw,
247                BitOrder::Msb => raw.reverse_bits() >> 24,
248            };
249            out |= normalised << (byte_idx * 8);
250        }
251        out
252    }
253}
254
255// ======================================================================
256// FontAtlas -- the VRAM handle
257// ======================================================================
258
259/// A [`BitmapFont`] installed in VRAM and ready to draw from.
260///
261/// Hold on to the returned handle for the lifetime you want glyphs
262/// to stay drawable. Uploading costs ~1 GP0 0xA0 transfer of
263/// `glyph_count × glyph_w × glyph_h / 4` bytes (plus 2 halfwords
264/// for the CLUT); draw calls cost 4 GP0 words per glyph.
265#[derive(Copy, Clone, Debug)]
266pub struct FontAtlas {
267    font: &'static BitmapFont,
268    tpage: TexturePage,
269    /// Pre-encoded CLUT word. Storing the two-byte packet value instead of
270    /// the four-byte coordinate handle pays for `uv_origin` without growing
271    /// `FontAtlas` in PS1 RAM, and removes repeated encoding from draw calls.
272    clut_word: u16,
273    /// How many glyphs per row of the atlas texture. Picked at
274    /// upload time so the texture fits within a single 4bpp tpage.
275    glyphs_per_row: u16,
276    /// Page-local texel origin of this atlas inside a packed tpage.
277    uv_origin: (u8, u8),
278}
279
280// The packed origin replaces the space recovered by caching the CLUT packet
281// word, so adding shared-page placement must not grow every resident atlas.
282#[cfg(target_arch = "mips")]
283const _: () = assert!(core::mem::size_of::<FontAtlas>() == 16);
284
285fn scale_q8_i16(value: i16, scale_q8: u16) -> i16 {
286    let scaled = i32::from(value)
287        .saturating_mul(i32::from(scale_q8))
288        .saturating_add(128)
289        >> 8;
290    scaled.clamp(1, i32::from(i16::MAX)) as i16
291}
292
293fn round_q8_to_i16(value_q8: i32) -> i16 {
294    let rounded = if value_q8 >= 0 {
295        value_q8.saturating_add(128) >> 8
296    } else {
297        -(value_q8.saturating_neg().saturating_add(128) >> 8)
298    };
299    rounded.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16
300}
301
302#[inline]
303fn reset_texture_window() {
304    wait_command_ready();
305    write_command(gp0::tex_window(0, 0, 0, 0));
306}
307
308/// GPU semi-transparency equation for [`FontAtlas::draw_text_blended`].
309///
310/// The PSX blends a semi-transparent primitive against the framebuffer
311/// with one of four fixed equations. The choice is *not* per-primitive:
312/// the primitive only carries a "blend me" bit, and the equation comes
313/// from the two-bit ABR field of the current GP0(E1h) draw mode. These
314/// are the same four the rest of the SDK exposes as `psx_gpu::BlendMode`,
315/// restated here so the font crate does not take a dependency on the
316/// primitive layer to name two bits.
317#[derive(Copy, Clone, Debug, PartialEq, Eq)]
318pub enum TextBlend {
319    /// `(background + foreground) / 2`. A fixed 50% wash; the tint still
320    /// recolours, but it cannot fade a glyph away -- at tint zero the
321    /// glyph still halves whatever is behind it.
322    Average,
323    /// `background + foreground`, clamped per channel. The mode to reach
324    /// for when text has to fade: scaling the tint toward black scales
325    /// the contribution toward nothing, so the glyph dissolves instead
326    /// of darkening. Reads as emissive, which suits HUD and combat text.
327    Add,
328    /// `background - foreground`, clamped per channel. Darkens whatever
329    /// is behind the glyph, so it works as a drop shadow over a light
330    /// background as well as a dark one.
331    Subtract,
332    /// `background + foreground / 4`, clamped per channel. A quarter-
333    /// strength [`Self::Add`] for a subtler glow.
334    AddQuarter,
335}
336
337impl TextBlend {
338    /// The two-bit draw-mode semi-transparency ("ABR") field selecting
339    /// this equation.
340    #[doc(alias = "ABR")]
341    pub const fn semi_transparency_bits(self) -> u8 {
342        match self {
343            Self::Average => 0,
344            Self::Add => 1,
345            Self::Subtract => 2,
346            Self::AddQuarter => 3,
347        }
348    }
349}
350
351/// GP0 command byte for a variable-size textured rectangle with the
352/// semi-transparency bit (25) set. The opaque path uses `0x6400_0000`.
353const SEMI_TRANSPARENT_RECT_CMD: u32 = packet::TEXTURED_RECT | packet::SEMI_TRANSPARENT;
354
355/// GP0 command byte for a variable-size MONOCHROME rectangle with the
356/// semi-transparency bit (25) set. The opaque form is `0x6000_0000`.
357///
358/// Untextured, so it costs three data words however large it is --
359/// which is what makes a backing plate cheaper than a second pass over
360/// the glyphs it sits behind.
361const SEMI_TRANSPARENT_FLAT_RECT_CMD: u32 = packet::FLAT_RECT | packet::SEMI_TRANSPARENT;
362
363/// The GP0(E1h) word that installs `tpage` with `blend`'s equation in
364/// the ABR field. Split out from the draw call so the bit layout is
365/// checkable on the host, where no GPU exists to observe.
366const fn blended_draw_mode_word(tpage: TexturePage, blend: TextBlend) -> u32 {
367    gp0::draw_mode(
368        (tpage.x() / 64) as u32,
369        if tpage.y() == 256 { 1 } else { 0 },
370        blend.semi_transparency_bits() as u32,
371        tpage.depth() as u32,
372        false,
373        true,
374    )
375}
376
377#[inline]
378fn pack_uv_word(u: u8, v: u8, high_word: u16) -> u32 {
379    u as u32 | ((v as u32) << 8) | ((high_word as u32) << 16)
380}
381
382#[inline]
383fn write_textured_quad_packet(
384    verts: [(i16, i16); 4],
385    uvs: [(u8, u8); 4],
386    color_cmd: u32,
387    clut_word: u16,
388    tpage_word: u16,
389) {
390    wait_command_ready();
391    write_command(color_cmd);
392    write_command(pack_vertex(verts[0].0, verts[0].1));
393    write_command(pack_uv_word(uvs[0].0, uvs[0].1, clut_word));
394    write_command(pack_vertex(verts[1].0, verts[1].1));
395    write_command(pack_uv_word(uvs[1].0, uvs[1].1, tpage_word));
396    write_command(pack_vertex(verts[2].0, verts[2].1));
397    write_command(pack_uv_word(uvs[2].0, uvs[2].1, 0));
398    write_command(pack_vertex(verts[3].0, verts[3].1));
399    write_command(pack_uv_word(uvs[3].0, uvs[3].1, 0));
400}
401
402#[inline]
403fn write_textured_gouraud_quad_packet(
404    verts: [(i16, i16); 4],
405    uvs: [(u8, u8); 4],
406    colors: [(u8, u8, u8); 4],
407    color0_cmd: u32,
408    clut_word: u16,
409    tpage_word: u16,
410) {
411    wait_command_ready();
412    write_command(color0_cmd);
413    write_command(pack_vertex(verts[0].0, verts[0].1));
414    write_command(pack_uv_word(uvs[0].0, uvs[0].1, clut_word));
415    write_command(pack_color(colors[1].0, colors[1].1, colors[1].2));
416    write_command(pack_vertex(verts[1].0, verts[1].1));
417    write_command(pack_uv_word(uvs[1].0, uvs[1].1, tpage_word));
418    write_command(pack_color(colors[2].0, colors[2].1, colors[2].2));
419    write_command(pack_vertex(verts[2].0, verts[2].1));
420    write_command(pack_uv_word(uvs[2].0, uvs[2].1, 0));
421    write_command(pack_color(colors[3].0, colors[3].1, colors[3].2));
422    write_command(pack_vertex(verts[3].0, verts[3].1));
423    write_command(pack_uv_word(uvs[3].0, uvs[3].1, 0));
424}
425
426/// VRAM reservations backing a set of fonts uploaded together by
427/// [`upload_fonts`]. Free both handles through the allocator to reclaim the
428/// VRAM when the owning scene is torn down.
429#[derive(Copy, Clone, Debug)]
430pub struct FontSetVram {
431    /// The contiguous page-run reservation that holds every atlas.
432    pub pages: VramHandle,
433    /// The shared 2-entry CLUT reservation.
434    pub clut: VramHandle,
435}
436
437/// Atlas cell width: the glyph width rounded up to a whole halfword (4
438/// texels at 4bpp), so every glyph starts on a halfword boundary. See the
439/// note in [`FontAtlas::upload`] for why that matters on real hardware.
440pub(crate) fn cell_width(font: &BitmapFont) -> u16 {
441    (font.glyph_w as u16).max(1).div_ceil(4) * 4
442}
443
444/// Atlas layout for `font`: `(glyphs_per_row, atlas_w_texels, atlas_h_texels,
445/// halfwords_per_row)`. Mirrors the layout [`FontAtlas::upload`] computes.
446fn font_atlas_dims(font: &BitmapFont) -> (u16, u16, u16, u16) {
447    let cell_w = cell_width(font);
448    let glyph_h = font.glyph_h as u16;
449    let max_cols = (FontAtlas::MAX_ATLAS_W_TEXELS / cell_w).max(1);
450    let glyphs_per_row = font.glyph_count.min(max_cols).max(1);
451    let glyph_rows = font.glyph_count.div_ceil(glyphs_per_row);
452    let atlas_w = glyphs_per_row * cell_w;
453    let atlas_h = glyph_rows * glyph_h;
454    // Even stride: `upload_16bpp` moves whole words and rejects an odd
455    // pixel count, and cell padding can leave an odd halfword row (KENNEY
456    //_PIXEL lands on 63). The spare column stays zero.
457    let halfwords_per_row = atlas_w.div_ceil(4).next_multiple_of(2);
458    (glyphs_per_row, atlas_w, atlas_h, halfwords_per_row)
459}
460
461/// The four corner UVs (texel coords) of a glyph cell whose top-left is
462/// `(u, v)` and size is `gw × gh`, with the far edge **saturated at 255**
463/// instead of wrapping. Corner order matches the quad-path vertices: top-left,
464/// top-right, bottom-left, bottom-right.
465///
466/// A full-width 256-texel atlas (e.g. 16 columns of 16px glyphs) puts the
467/// rightmost column at `u = 240`, so the far U is `240 + 16 = 256`, which
468/// wraps to `0` in the `u8` UV field and makes the GPU interpolate U from 240
469/// down to 0 across the quad -- smearing that glyph (the classic 256-wide
470/// texture right-edge bug). Saturating pins the far edge to the last texel.
471fn glyph_quad_uvs(u: u8, v: u8, gw: u8, gh: u8) -> [(u8, u8); 4] {
472    let u1 = u.saturating_add(gw);
473    let v1 = v.saturating_add(gh);
474    [(u, v), (u1, v), (u, v1), (u1, v1)]
475}
476
477/// Halfwords spanned by one 4bpp texture page (64 halfwords = 256 texels).
478const FONT_PAGE_HALFWORDS: usize = 64;
479
480/// Maximum number of font atlases accepted by one packed upload. The game
481/// manifest currently caps a scene at eight; keeping this bound at sixteen
482/// also matches the number of 4bpp page columns in 1024-wide VRAM.
483const MAX_PACKED_FONT_ATLASES: usize = 16;
484
485#[derive(Copy, Clone, Debug, PartialEq, Eq)]
486struct AtlasPlacement {
487    page: u16,
488    x_halfwords: u16,
489    y: u16,
490}
491
492/// VRAM and scratch requirements for one packed font-set upload.
493#[derive(Copy, Clone, Debug, PartialEq, Eq)]
494pub struct FontPackMetrics {
495    /// Minimum contiguous page run requested by the bounded packer.
496    pub pages: u16,
497    /// Rows transferred by the single combined `GP0(A0h)` upload.
498    pub upload_rows: u16,
499    /// Caller-owned scratch halfwords required for that upload.
500    pub scratch_halfwords: usize,
501}
502
503#[inline]
504fn placements_overlap(
505    a: AtlasPlacement,
506    a_w: u16,
507    a_h: u16,
508    b: AtlasPlacement,
509    b_w: u16,
510    b_h: u16,
511) -> bool {
512    a.page == b.page
513        && a.x_halfwords < b.x_halfwords + b_w
514        && b.x_halfwords < a.x_halfwords + a_w
515        && a.y < b.y + b_h
516        && b.y < a.y + a_h
517}
518
519/// Plan page-local atlas rectangles with a deterministic, bounded
520/// bottom-left bin layout. Tall atlases are placed first; candidate corners
521/// come only from page edges and already-placed rectangle edges, avoiding a
522/// texel-by-texel search on the PS1 boot path.
523fn plan_font_pack(
524    fonts: &[&'static BitmapFont],
525    placements: &mut [Option<AtlasPlacement>; MAX_PACKED_FONT_ATLASES],
526) -> Option<FontPackMetrics> {
527    if fonts.is_empty() || fonts.len() > MAX_PACKED_FONT_ATLASES {
528        return None;
529    }
530    placements.fill(None);
531
532    let mut page_count = 0u16;
533    for _ in 0..fonts.len() {
534        // Height-first, then width-first is a shelf/bin heuristic that keeps
535        // the page count low while preserving the caller's output ordering.
536        let mut selected = None;
537        let mut selected_key = (0u16, 0u16);
538        for (index, &font) in fonts.iter().enumerate() {
539            if placements[index].is_some() {
540                continue;
541            }
542            let (_, _, height, width) = font_atlas_dims(font);
543            if width == 0 || width as usize > FONT_PAGE_HALFWORDS || height == 0 || height > 256 {
544                return None;
545            }
546            let key = (height, width);
547            if selected.is_none() || key > selected_key {
548                selected = Some(index);
549                selected_key = key;
550            }
551        }
552        let index = selected?;
553        let (_, _, height, width) = font_atlas_dims(fonts[index]);
554
555        let mut chosen = None;
556        // Include one new page; allocations below may grow page_count.
557        let available_pages = page_count;
558        for page in 0..=available_pages {
559            if page == page_count && page_count >= 16 {
560                break;
561            }
562            let mut page_best = None;
563
564            // In a bottom-left-stable layout, a rectangle's left/bottom edge
565            // touches either the page edge or another rectangle's right/bottom
566            // edge. Enumerating those corners is exhaustive for this policy.
567            for y_source in 0..=fonts.len() {
568                let y = if y_source == 0 {
569                    0
570                } else {
571                    let prior_index = y_source - 1;
572                    let Some(prior) = placements[prior_index] else {
573                        continue;
574                    };
575                    if prior.page != page {
576                        continue;
577                    }
578                    let (_, _, prior_h, _) = font_atlas_dims(fonts[prior_index]);
579                    prior.y + prior_h
580                };
581                if y + height > 256 {
582                    continue;
583                }
584                for x_source in 0..=fonts.len() {
585                    let x_halfwords = if x_source == 0 {
586                        0
587                    } else {
588                        let prior_index = x_source - 1;
589                        let Some(prior) = placements[prior_index] else {
590                            continue;
591                        };
592                        if prior.page != page {
593                            continue;
594                        }
595                        let (_, _, _, prior_w) = font_atlas_dims(fonts[prior_index]);
596                        prior.x_halfwords + prior_w
597                    };
598                    if x_halfwords + width > FONT_PAGE_HALFWORDS as u16 {
599                        continue;
600                    }
601                    let candidate = AtlasPlacement {
602                        page,
603                        x_halfwords,
604                        y,
605                    };
606                    let overlaps = placements.iter().enumerate().any(|(prior_index, prior)| {
607                        let Some(prior) = prior else {
608                            return false;
609                        };
610                        let (_, _, prior_h, prior_w) = font_atlas_dims(fonts[prior_index]);
611                        placements_overlap(candidate, width, height, *prior, prior_w, prior_h)
612                    });
613                    if overlaps {
614                        continue;
615                    }
616                    if page_best.is_none_or(|best: AtlasPlacement| {
617                        (candidate.y, candidate.x_halfwords) < (best.y, best.x_halfwords)
618                    }) {
619                        page_best = Some(candidate);
620                    }
621                }
622            }
623            if let Some(best) = page_best {
624                chosen = Some(best);
625                if page == page_count {
626                    page_count += 1;
627                }
628                break;
629            }
630        }
631        placements[index] = Some(chosen?);
632    }
633
634    let upload_rows = placements
635        .iter()
636        .enumerate()
637        .filter_map(|(index, placement)| {
638            let placement = placement.as_ref()?;
639            let (_, _, height, _) = font_atlas_dims(fonts[index]);
640            Some(placement.y + height)
641        })
642        .max()?;
643    let scratch_halfwords = usize::from(page_count)
644        .checked_mul(FONT_PAGE_HALFWORDS)?
645        .checked_mul(usize::from(upload_rows))?;
646    Some(FontPackMetrics {
647        pages: page_count,
648        upload_rows,
649        scratch_halfwords,
650    })
651}
652
653/// Return the page-run and scratch requirements for [`upload_fonts`] without
654/// reserving VRAM or touching the GPU.
655pub fn font_pack_metrics(fonts: &[&'static BitmapFont]) -> Option<FontPackMetrics> {
656    let mut placements = [None; MAX_PACKED_FONT_ATLASES];
657    plan_font_pack(fonts, &mut placements)
658}
659
660fn pack_font_bits(
661    fonts: &[&'static BitmapFont],
662    placements: &[Option<AtlasPlacement>; MAX_PACKED_FONT_ATLASES],
663    metrics: FontPackMetrics,
664    scratch: &mut [u16],
665) -> Option<()> {
666    if metrics.scratch_halfwords > scratch.len() {
667        return None;
668    }
669    let stride = usize::from(metrics.pages) * FONT_PAGE_HALFWORDS;
670    scratch[..metrics.scratch_halfwords].fill(0);
671    for (slot, &font) in fonts.iter().enumerate() {
672        let placement = placements[slot]?;
673        let (glyphs_per_row, _, _, _) = font_atlas_dims(font);
674        let col0 =
675            usize::from(placement.page) * FONT_PAGE_HALFWORDS + usize::from(placement.x_halfwords);
676        for gi in 0..font.glyph_count {
677            let atlas_col = gi % glyphs_per_row;
678            let atlas_row = gi / glyphs_per_row;
679            let base_x = atlas_col * cell_width(font);
680            let base_y = placement.y + atlas_row * font.glyph_h as u16;
681            for row in 0..font.glyph_h {
682                let row_bits = font.glyph_row_packed(gi, row);
683                for col in 0..font.glyph_w as u16 {
684                    if (row_bits >> col) & 1 == 0 {
685                        continue;
686                    }
687                    let x = base_x + col;
688                    let y = base_y + row as u16;
689                    let hw_idx = y as usize * stride + col0 + (x as usize / 4);
690                    let nibble_shift = (x & 3) * 4;
691                    scratch[hw_idx] |= 1u16 << nibble_shift; // CLUT index 1 = white
692                }
693            }
694        }
695    }
696    Some(())
697}
698
699/// Upload several fonts in a **single** `GP0(A0h)` image transfer.
700///
701/// Repeated per-font VRAM uploads desync the GPU command stream on some
702/// targets and corrupt subsequent (world) rendering; packing every glyph
703/// atlas side-by-side into one reserved page run and emitting one transfer
704/// avoids that entirely. Multiple atlas rectangles share each 256x256 4bpp
705/// tpage through page-local UV origins; all fonts share one 2-entry CLUT
706/// (transparent, white) which `tint` recolours per draw.
707///
708/// `scratch` is a caller-owned buffer (put it in `static mut` BSS, **not** on
709/// the stack); query [`font_pack_metrics`] for the exact required length.
710/// `out` receives one `Some(FontAtlas)` per font; trailing slots
711/// are set to `None`. Returns the handles to free the set later, or `None`
712/// (uploading nothing) if a font is too wide, `scratch`/`out` is too small,
713/// or the allocator is out of space. Every failure clears all of `out`, so a
714/// caller can never mistake stale or partially prepared handles for the set.
715pub fn upload_fonts<R: VramRegionSource>(
716    fonts: &[&'static BitmapFont],
717    alloc: &mut R,
718    scratch: &mut [u16],
719    out: &mut [Option<FontAtlas>],
720) -> Option<FontSetVram> {
721    let n = fonts.len();
722    out.fill(None);
723    if n == 0 || n > out.len() {
724        return None;
725    }
726    let mut placements = [None; MAX_PACKED_FONT_ATLASES];
727    let metrics = plan_font_pack(fonts, &mut placements)?;
728    if metrics.scratch_halfwords > scratch.len() {
729        return None;
730    }
731
732    let (base, pages) = alloc.alloc_page_run(metrics.pages, TextureDepth::Bit4, 0)?;
733    // CLUT allocation can't fail at boot (the band is empty); if it ever does
734    // the page run is left reserved, which is harmless at boot.
735    let (clut, clut_handle) = alloc.alloc_clut(2)?;
736
737    pack_font_bits(fonts, &placements, metrics, scratch)?;
738    for (slot, &font) in fonts.iter().enumerate() {
739        let placement = placements[slot]?;
740        let (glyphs_per_row, _, _, _) = font_atlas_dims(font);
741        out[slot] = Some(FontAtlas {
742            font,
743            tpage: TexturePage::new(
744                base.x() + placement.page * FONT_PAGE_HALFWORDS as u16,
745                base.y(),
746                TextureDepth::Bit4,
747            ),
748            clut_word: clut.uv_word(),
749            glyphs_per_row,
750            uv_origin: ((placement.x_halfwords * 4) as u8, placement.y as u8),
751        });
752    }
753    for slot in out.iter_mut().skip(n) {
754        *slot = None;
755    }
756
757    // One image transfer for the whole combined atlas, then the shared CLUT.
758    let stride = usize::from(metrics.pages) * FONT_PAGE_HALFWORDS;
759    upload_16bpp(
760        VramRect::new(base.x(), base.y(), stride as u16, metrics.upload_rows),
761        &scratch[..metrics.scratch_halfwords],
762    );
763    upload_clut(clut, &[Color555::TRANSPARENT, Color555::rgb5(31, 31, 31)]);
764
765    Some(FontSetVram {
766        pages,
767        clut: clut_handle,
768    })
769}
770
771impl FontAtlas {
772    /// Maximum texels a 4bpp tpage covers horizontally. 64 pixels
773    /// is the PSX-SPX value (tpage is 256×256 in texel units, but
774    /// in 4bpp mode the effective horizontal texel range per page
775    /// maps onto 64 VRAM halfwords = 64 × 4 = 256 texels).
776    const MAX_ATLAS_W_TEXELS: u16 = 256;
777    /// Stack buffer for the packed 4bpp atlas. 8192 halfwords =
778    /// 16 KiB leaves real call-frame headroom inside the SDK's 32 KiB
779    /// minimum stack reserve while covering the common cases:
780    /// - 128 glyphs at 8×8   (2048 hw)
781    /// - 128 glyphs at 8×16  (4096 hw)
782    /// - 64 glyphs  at 16×16 (4096 hw)
783    /// - 128 glyphs at 12×16 (5040 hw)
784    /// - 128 glyphs at 16×16 (8192 hw)
785    /// - 64 glyphs  at 32×16 (8192 hw) -- the largest supported
786    ///
787    /// A full 32 KiB local is not safe: the linker guarantees 32 KiB for the
788    /// *whole* call stack, so the uploader's caller/interrupt frames would
789    /// cross into static RAM. Larger imports should use [`upload_fonts`] and
790    /// provide scratch storage with an explicitly audited lifetime.
791    const MAX_PACK_HALFWORDS: usize = 8192;
792
793    /// Upload `font` as a 4bpp CLUT texture at `tpage`, with a
794    /// 2-entry CLUT (transparent, white) at `clut`.
795    ///
796    /// The caller picks the tpage / clut locations -- typically
797    /// `TexturePage::new(768, 0, TextureDepth::Bit4)` for the standard
798    /// off-display region, and a `Clut::new(768, 480)` for the
799    /// CLUT row. Both must live inside VRAM and not overlap the
800    /// active framebuffer.
801    ///
802    /// Atlas layout picks `glyphs_per_row` so the texture's pixel
803    /// width stays within `MAX_ATLAS_W_TEXELS`. For 8-wide fonts
804    /// that's 32 glyphs per row; 16-wide fonts get 16 per row.
805    pub fn upload(font: &'static BitmapFont, tpage: TexturePage, clut: Clut) -> Self {
806        assert!(
807            matches!(tpage.depth(), TextureDepth::Bit4),
808            "FontAtlas::upload requires a 4bpp tpage",
809        );
810
811        let glyph_w = font.glyph_w as u16;
812        let glyph_h = font.glyph_h as u16;
813        let glyph_count = font.glyph_count;
814
815        // Cells are padded to a whole halfword (4 texels at 4bpp) so every
816        // glyph STARTS on a halfword boundary. A 5-wide font otherwise puts
817        // each glyph at an arbitrary nibble, and on real hardware the demo
818        // disc's SPLEEN 5x8 description text rendered lowercase 'f' as a
819        // bare crossbar while every emulator drew it whole (hwtest 0xB3-
820        // 0xB5, 2026-08-07 console capture). The padding costs VRAM and
821        // changes nothing about the drawn pixels: `draw_text` still emits
822        // glyph_w-wide rects, only the atlas coordinates move.
823        let cell_w = glyph_w.div_ceil(4) * 4;
824
825        // Atlas width = glyphs_per_row × cell_w, capped at the
826        // MAX to stay within a single 4bpp tpage.
827        let max_cols = (Self::MAX_ATLAS_W_TEXELS / cell_w).max(1);
828        let glyphs_per_row = glyph_count.min(max_cols);
829        let glyph_rows = glyph_count.div_ceil(glyphs_per_row);
830        let atlas_w = glyphs_per_row * cell_w;
831        let atlas_h = glyph_rows * glyph_h;
832
833        // Pack 1bpp source → 4bpp VRAM texture into a stack buffer.
834        // Each 16-bit halfword holds 4 texels (nibble 0 = leftmost).
835        // The stride is rounded to an even number of halfwords because
836        // `upload_16bpp` moves whole words and rejects an odd pixel count;
837        // cell padding can otherwise leave an odd row (KENNEY_PIXEL lands
838        // on 63). The spare column stays zero.
839        let halfwords_per_row = atlas_w.div_ceil(4).next_multiple_of(2);
840        let total_halfwords = halfwords_per_row as usize * atlas_h as usize;
841        assert!(
842            total_halfwords <= Self::MAX_PACK_HALFWORDS,
843            "font atlas too large for stack buffer",
844        );
845        let mut packed = [0u16; Self::MAX_PACK_HALFWORDS];
846
847        for gi in 0..glyph_count {
848            let atlas_col = gi % glyphs_per_row;
849            let atlas_row = gi / glyphs_per_row;
850            let base_x = atlas_col * cell_w;
851            let base_y = atlas_row * glyph_h;
852            for row in 0..glyph_h as u8 {
853                let row_bits = font.glyph_row_packed(gi, row);
854                for col in 0..glyph_w {
855                    let bit = (row_bits >> col) & 1;
856                    let x = base_x + col;
857                    let y = base_y + row as u16;
858                    // 4 texels per halfword; pick nibble by x & 3.
859                    let hw_idx = y as usize * halfwords_per_row as usize + (x as usize / 4);
860                    let nibble_shift = (x & 3) * 4;
861                    packed[hw_idx] |= (bit as u16) << nibble_shift;
862                }
863            }
864        }
865
866        // upload_16bpp takes pixel count = w*h, which for a 4bpp
867        // texture uploaded as a 16bpp rect works out to
868        // halfwords_per_row × atlas_h halfwords = the 4bpp pixel
869        // count. Upload is by halfwords regardless of bit-depth;
870        // the GPU doesn't inspect bits inside words.
871        //
872        // VRAM rect semantics expose the *halfword* footprint when
873        // depth is 4bpp -- so width is `atlas_w / 4`, not `atlas_w`.
874        let vram_rect = VramRect::new(tpage.x(), tpage.y(), halfwords_per_row, atlas_h);
875        upload_16bpp(vram_rect, &packed[..total_halfwords]);
876
877        // Upload 2-entry CLUT: idx 0 = transparent, idx 1 = white.
878        // The white texel will be tinted per-draw_call via the
879        // sprite's per-vertex colour (GP0 0x64 tint byte).
880        let clut_entries = [Color555::TRANSPARENT, Color555::rgb5(31, 31, 31)];
881        upload_clut(clut, &clut_entries);
882
883        Self {
884            font,
885            tpage,
886            clut_word: clut.uv_word(),
887            glyphs_per_row,
888            uv_origin: (0, 0),
889        }
890    }
891
892    /// Pixel width of `text` when rendered with this atlas.
893    pub fn text_width(&self, text: &str) -> u16 {
894        self.font.text_width(text)
895    }
896
897    /// Pixel advance of one character, the per-glyph term
898    /// [`FontAtlas::text_width`] sums.
899    ///
900    /// Exposed so a caller scanning a string can carry a running width
901    /// instead of re-measuring every prefix: word wrap is quadratic
902    /// otherwise, which on R3000 is the most expensive thing a text layout
903    /// does. `text_width(s)` stays exactly
904    /// `s.chars().map(glyph_advance).fold(0, u16::saturating_add)`.
905    pub fn glyph_advance(&self, ch: char) -> u8 {
906        self.font.glyph_advance(ch)
907    }
908
909    /// Pixel width of `text` using this atlas's font metrics plus signed
910    /// spacing inserted between adjacent characters.
911    pub fn text_width_with_spacing(&self, text: &str, letter_spacing: i8) -> u16 {
912        self.font.text_width_with_spacing(text, letter_spacing)
913    }
914
915    /// Pixel height of a single text line. Usually `== glyph_h`.
916    pub fn line_height(&self) -> u16 {
917        self.font.line_height as u16
918    }
919
920    /// Look up the atlas UV for a character, returning the
921    /// top-left `(u, v)` of the glyph in texel coords, or `None`
922    /// if the char is outside the font's range.
923    ///
924    /// Shared by every draw method so the codepoint-window logic
925    /// lives in one place.
926    #[inline]
927    fn glyph_uv(&self, ch: char) -> Option<(u8, u8)> {
928        let cp = ch as u32;
929        let first = self.font.first_char as u32;
930        if cp < first || cp >= first + self.font.glyph_count as u32 {
931            return None;
932        }
933        let idx = (cp - first) as u16;
934        let col = idx % self.glyphs_per_row;
935        let row = idx / self.glyphs_per_row;
936        let u = u16::from(self.uv_origin.0) + col * cell_width(self.font);
937        let v = u16::from(self.uv_origin.1) + row * self.font.glyph_h as u16;
938        Some((u as u8, v as u8))
939    }
940
941    /// Draw `text` at screen-space `(x, y)` with the given tint.
942    ///
943    /// `(0x80, 0x80, 0x80)` = unmodulated white; any other value
944    /// recolours every glyph via the PSX per-texel multiplier
945    /// (`output = texel * tint / 128`).
946    ///
947    /// **Fast path** -- uses textured rectangles (GP0 0x64, 4 words
948    /// per glyph). For any transform or per-vertex colour needs,
949    /// reach for [`Self::draw_text_scaled`], [`Self::draw_text_rotated`],
950    /// [`Self::draw_text_affine`], or [`Self::draw_text_gradient`].
951    ///
952    /// Characters outside the font's codepoint range are skipped --
953    /// they still advance the cursor so the rest of the string
954    /// lines up as the caller intended. Iteration is per-`char`,
955    /// so any `&str` is valid input; a Latin-1 atlas with
956    /// `first_char = 0xA0` picks up `é`, `ü`, etc. automatically.
957    ///
958    /// Sets the GP0(0xE1) draw-mode tpage to our atlas once at the
959    /// start of the call -- if the caller was rendering with a
960    /// different tpage, they'll need to re-apply theirs after
961    /// draw_text returns.
962    ///
963    /// # Example
964    ///
965    /// ```ignore
966    /// atlas.draw_text(8, 8, "SCORE 0042", (0x80, 0x80, 0x80));
967    /// ```
968    pub fn draw_text(&self, x: i16, y: i16, text: &str, tint: (u8, u8, u8)) {
969        self.draw_text_with_spacing(x, y, text, 0, tint);
970    }
971
972    /// Emit ordered GP0 packets for deferred, axis-aligned text drawing.
973    ///
974    /// The sink receives one two-word draw-mode/texture-window packet followed
975    /// by one four-word textured rectangle per supported glyph. Atlas padding,
976    /// packed-page origin, CLUT and character advances are owned by this atlas,
977    /// just as they are for immediate drawing. No GPU access occurs here.
978    ///
979    /// The sink must copy each borrowed packet before returning. Returning
980    /// `false` stops emission immediately, allowing a fixed packet arena to
981    /// reject a full run without writing beyond its capacity. Earlier packets
982    /// remain accepted; the return value says whether the entire run fit.
983    pub fn emit_text_packets(
984        &self,
985        x: i16,
986        y: i16,
987        text: &str,
988        tint: (u8, u8, u8),
989        mut emit: impl FnMut(&[u32]) -> bool,
990    ) -> bool {
991        let material =
992            psx_gpu::material::TextureMaterial::opaque(self.clut_word, self.tpage.uv_word(0), tint);
993        if !emit(&[material.draw_mode_word(), material.texture_window_word()]) {
994            return false;
995        }
996        let mut cursor_x = x;
997        for ch in text.chars() {
998            if let Some((u, v)) = self.glyph_uv(ch) {
999                if !emit(&[
1000                    material.textured_rect_header(),
1001                    pack_vertex(cursor_x, y),
1002                    pack_texcoord(u, v, self.clut_word),
1003                    pack_xy(self.font.glyph_w as u16, self.font.glyph_h as u16),
1004                ]) {
1005                    return false;
1006                }
1007            }
1008            cursor_x = cursor_x.wrapping_add(self.font.glyph_advance(ch) as i16);
1009        }
1010        true
1011    }
1012
1013    /// Draw `text` with signed spacing inserted between adjacent characters.
1014    /// `letter_spacing` is measured in final screen pixels and is not applied
1015    /// after the last character.
1016    pub fn draw_text_with_spacing(
1017        &self,
1018        x: i16,
1019        y: i16,
1020        text: &str,
1021        letter_spacing: i8,
1022        tint: (u8, u8, u8),
1023    ) {
1024        // Our atlas tpage takes over the current draw-mode slot; the
1025        // per-glyph GP0 0x64 rectangles all sample from it.
1026        self.tpage.apply_as_draw_mode();
1027
1028        let font = self.font;
1029        let clut_word = self.clut_word;
1030        let color_cmd = packet::TEXTURED_RECT | pack_color(tint.0, tint.1, tint.2);
1031        let glyph_size = pack_xy(font.glyph_w as u16, font.glyph_h as u16);
1032        let gap = i16::from(letter_spacing);
1033        let mut cursor_x = x;
1034        for ch in text.chars() {
1035            let Some((u, v)) = self.glyph_uv(ch) else {
1036                cursor_x = cursor_x
1037                    .wrapping_add(font.glyph_advance(ch) as i16)
1038                    .wrapping_add(gap);
1039                continue;
1040            };
1041
1042            wait_command_ready();
1043            // GP0 0x64 = variable-size textured rectangle, no blend,
1044            // opaque. First word: 0x64_BB_GG_RR (color is the tint
1045            // multiplier -- NOT a fill colour: CLUT index 1's white
1046            // texel gets modulated by this).
1047            write_command(color_cmd);
1048            write_command(pack_vertex(cursor_x, y));
1049            // Second word packs (U, V, CLUT) -- our `pack_texcoord`
1050            // takes (u, v, extra) where `extra` is the CLUT field
1051            // (high halfword). The tpage is implied by the current
1052            // draw mode.
1053            write_command(pack_texcoord(u, v, clut_word));
1054            // Third word: rectangle size.
1055            write_command(glyph_size);
1056
1057            cursor_x = cursor_x
1058                .wrapping_add(font.glyph_advance(ch) as i16)
1059                .wrapping_add(gap);
1060        }
1061    }
1062
1063    /// Draw `text` with the GPU's semi-transparency enabled, blending
1064    /// each glyph against the framebuffer with `blend`'s equation.
1065    ///
1066    /// **Fast path** -- same GP0 0x64 textured rectangle and same 4
1067    /// words per glyph as [`Self::draw_text`], with the primitive's
1068    /// semi-transparency bit set and the draw mode's ABR field carrying
1069    /// the equation. The only extra cost is the one draw-mode word at
1070    /// the start and the one that restores the opaque mode at the end.
1071    ///
1072    /// Why this exists: the opaque path can only recolour a glyph, and
1073    /// a tint ramped toward black draws a *black* glyph, not an absent
1074    /// one. [`TextBlend::Add`] plus a ramped tint is the PS1's real
1075    /// fade -- at tint zero the glyph contributes nothing and vanishes.
1076    ///
1077    /// Restores the atlas's opaque draw mode before returning, so a
1078    /// blended run cannot leave a stray blend equation on the GPU for
1079    /// whatever draws next. As with [`Self::draw_text`], the tpage slot
1080    /// is left pointing at this atlas.
1081    pub fn draw_text_blended(
1082        &self,
1083        x: i16,
1084        y: i16,
1085        text: &str,
1086        tint: (u8, u8, u8),
1087        blend: TextBlend,
1088    ) {
1089        self.draw_text_blended_with_spacing(x, y, text, 0, tint, blend);
1090    }
1091
1092    /// [`Self::draw_text_blended`] with signed inter-character spacing,
1093    /// measured in screen pixels and not applied after the last glyph.
1094    pub fn draw_text_blended_with_spacing(
1095        &self,
1096        x: i16,
1097        y: i16,
1098        text: &str,
1099        letter_spacing: i8,
1100        tint: (u8, u8, u8),
1101        blend: TextBlend,
1102    ) {
1103        wait_command_ready();
1104        write_command(blended_draw_mode_word(self.tpage, blend));
1105        reset_texture_window();
1106
1107        let font = self.font;
1108        let clut_word = self.clut_word;
1109        // 0x66 rather than 0x64: same variable-size textured rectangle,
1110        // with bit 25 (semi-transparency) set so the ABR field above
1111        // actually applies.
1112        let color_cmd = SEMI_TRANSPARENT_RECT_CMD | pack_color(tint.0, tint.1, tint.2);
1113        let glyph_size = pack_xy(font.glyph_w as u16, font.glyph_h as u16);
1114        let gap = i16::from(letter_spacing);
1115        let mut cursor_x = x;
1116        for ch in text.chars() {
1117            let Some((u, v)) = self.glyph_uv(ch) else {
1118                cursor_x = cursor_x
1119                    .wrapping_add(font.glyph_advance(ch) as i16)
1120                    .wrapping_add(gap);
1121                continue;
1122            };
1123
1124            wait_command_ready();
1125            write_command(color_cmd);
1126            write_command(pack_vertex(cursor_x, y));
1127            write_command(pack_texcoord(u, v, clut_word));
1128            write_command(glyph_size);
1129
1130            cursor_x = cursor_x
1131                .wrapping_add(font.glyph_advance(ch) as i16)
1132                .wrapping_add(gap);
1133        }
1134
1135        // Leave the GPU in the opaque mode every other draw path assumes.
1136        self.tpage.apply_as_draw_mode();
1137    }
1138
1139    /// Draw a flat semi-transparent rectangle in `blend`'s equation --
1140    /// a backing plate for a run of text drawn on top of it.
1141    ///
1142    /// This is a method on the atlas rather than a free function
1143    /// because the blend equation is carried by the GP0(E1h) draw-mode
1144    /// word, which also names a texture page. Setting one means setting
1145    /// the other, so whatever changes the equation has to know which
1146    /// page the glyphs that follow will want back -- and the atlas is
1147    /// what knows that. It restores the atlas's opaque draw mode on the
1148    /// way out, exactly as [`Self::draw_text_blended`] does.
1149    ///
1150    /// [`TextBlend::Subtract`] is the equation to reach for behind
1151    /// text: it darkens whatever is under it and, because it scales
1152    /// with the tint, it fades to nothing along with the text it seats.
1153    /// [`TextBlend::Average`] cannot fade -- at tint zero it still
1154    /// halves the background, so a plate drawn with it outlives the
1155    /// glyphs and is left behind as a grey box.
1156    pub fn draw_backdrop_blended(
1157        &self,
1158        x: i16,
1159        y: i16,
1160        w: u16,
1161        h: u16,
1162        tint: (u8, u8, u8),
1163        blend: TextBlend,
1164    ) {
1165        if w == 0 || h == 0 {
1166            return;
1167        }
1168        wait_command_ready();
1169        write_command(blended_draw_mode_word(self.tpage, blend));
1170        write_command(SEMI_TRANSPARENT_FLAT_RECT_CMD | pack_color(tint.0, tint.1, tint.2));
1171        write_command(pack_vertex(x, y));
1172        write_command(pack_xy(w, h));
1173        self.tpage.apply_as_draw_mode();
1174    }
1175
1176    /// Draw `text` at screen-space `(x, y)` scaled by `(scale_x,
1177    /// scale_y)`. `scale=(1, 1)` matches [`Self::draw_text`]'s
1178    /// output, but via the quad path instead of the rect path --
1179    /// so prefer `draw_text` for native-size.
1180    ///
1181    /// **Quad path** -- uses textured quads (GP0 0x2C, 9 words per
1182    /// glyph). PSX samples textures with nearest-neighbour, so
1183    /// integer scales (2×, 3×, 4×) produce crisp pixel-doubled
1184    /// output. Use [`Self::draw_text_scaled_q8`] for fractional
1185    /// screen-space sizes.
1186    ///
1187    /// # Example
1188    ///
1189    /// ```ignore
1190    /// atlas.draw_text_scaled(80, 100, "GAME OVER", 3, 3, (220, 40, 40));
1191    /// ```
1192    pub fn draw_text_scaled(
1193        &self,
1194        x: i16,
1195        y: i16,
1196        text: &str,
1197        scale_x: u8,
1198        scale_y: u8,
1199        tint: (u8, u8, u8),
1200    ) {
1201        self.draw_text_scaled_with_spacing(x, y, text, scale_x, scale_y, 0, tint);
1202    }
1203
1204    /// Draw `text` with Q8 fixed-point scale factors (`256` = 1.0x).
1205    /// This keeps the font atlas monochrome while allowing fractional
1206    /// screen-space glyph sizes such as 1.5x (`384`).
1207    pub fn draw_text_scaled_q8(
1208        &self,
1209        x: i16,
1210        y: i16,
1211        text: &str,
1212        scale_x_q8: u16,
1213        scale_y_q8: u16,
1214        tint: (u8, u8, u8),
1215    ) {
1216        self.draw_text_scaled_with_spacing_q8(x, y, text, scale_x_q8, scale_y_q8, 0, tint);
1217    }
1218
1219    /// Draw scaled text with signed spacing inserted between adjacent
1220    /// characters. `letter_spacing` is measured in final screen pixels, not
1221    /// source-glyph pixels.
1222    pub fn draw_text_scaled_with_spacing(
1223        &self,
1224        x: i16,
1225        y: i16,
1226        text: &str,
1227        scale_x: u8,
1228        scale_y: u8,
1229        letter_spacing: i8,
1230        tint: (u8, u8, u8),
1231    ) {
1232        assert!(scale_x > 0 && scale_y > 0, "scale must be > 0 in both axes");
1233        self.draw_text_scaled_with_spacing_q8(
1234            x,
1235            y,
1236            text,
1237            u16::from(scale_x) * 256,
1238            u16::from(scale_y) * 256,
1239            letter_spacing,
1240            tint,
1241        );
1242    }
1243
1244    /// Draw scaled text with Q8 fixed-point scale and signed spacing inserted
1245    /// between adjacent characters. `letter_spacing` is measured in final
1246    /// screen pixels, not source-glyph pixels.
1247    pub fn draw_text_scaled_with_spacing_q8(
1248        &self,
1249        x: i16,
1250        y: i16,
1251        text: &str,
1252        scale_x_q8: u16,
1253        scale_y_q8: u16,
1254        letter_spacing: i8,
1255        tint: (u8, u8, u8),
1256    ) {
1257        assert!(
1258            scale_x_q8 > 0 && scale_y_q8 > 0,
1259            "scale must be > 0 in both axes"
1260        );
1261        if text.is_empty() {
1262            return;
1263        }
1264        let font = self.font;
1265        let gw = font.glyph_w as i16;
1266        let gh = font.glyph_h as i16;
1267        let sw = scale_q8_i16(gw, scale_x_q8);
1268        let sh = scale_q8_i16(gh, scale_y_q8);
1269        let clut = self.clut_word;
1270        let tpage = self.tpage.uv_word(0);
1271        let color_cmd = gp0::polygon_opcode(false, true, true, false, false)
1272            | pack_color(tint.0, tint.1, tint.2);
1273        let gap_q8 = i32::from(letter_spacing) << 8;
1274        let mut cursor_x_q8 = i32::from(x) << 8;
1275        reset_texture_window();
1276        for ch in text.chars() {
1277            let cursor_x = round_q8_to_i16(cursor_x_q8);
1278            let Some((u, v)) = self.glyph_uv(ch) else {
1279                cursor_x_q8 = cursor_x_q8
1280                    .saturating_add(i32::from(font.glyph_advance(ch)) * i32::from(scale_x_q8))
1281                    .saturating_add(gap_q8);
1282                continue;
1283            };
1284            let verts = [
1285                (cursor_x, y),
1286                (cursor_x + sw, y),
1287                (cursor_x, y + sh),
1288                (cursor_x + sw, y + sh),
1289            ];
1290            let uvs = glyph_quad_uvs(u, v, font.glyph_w, font.glyph_h);
1291            write_textured_quad_packet(verts, uvs, color_cmd, clut, tpage);
1292            cursor_x_q8 = cursor_x_q8
1293                .saturating_add(i32::from(font.glyph_advance(ch)) * i32::from(scale_x_q8))
1294                .saturating_add(gap_q8);
1295        }
1296    }
1297
1298    /// Draw `text` rotated around the pivot `(cx, cy)` by
1299    /// `angle_q12` (Q0.12, one revolution = 4096). The string is
1300    /// centred on the pivot at angle 0 -- its natural extent is
1301    /// `text_width × glyph_h`, anchored so `(cx, cy)` sits at the
1302    /// centre of the baseline.
1303    ///
1304    /// **Quad path** -- 9 GP0 words per glyph. Sin/cos come from a
1305    /// compact 256-entry Q1.12 table ([`sincos`]), good to ~1.4° --
1306    /// imperceptible at 8px glyph scale.
1307    ///
1308    /// See crate-level docs for the Q0.12 angle convention.
1309    ///
1310    /// # Example
1311    ///
1312    /// ```ignore
1313    /// // Spin a title once per second (frame_idx updates each vsync).
1314    /// let angle = ((frame_idx * 68) & 0xFFF) as u16; // ~4096/60 ≈ 68
1315    /// atlas.draw_text_rotated(160, 120, "SPIN", angle, (255, 255, 255));
1316    /// ```
1317    pub fn draw_text_rotated(
1318        &self,
1319        cx: i16,
1320        cy: i16,
1321        text: &str,
1322        angle_q12: u16,
1323        tint: (u8, u8, u8),
1324    ) {
1325        if text.is_empty() {
1326            return;
1327        }
1328        let font = self.font;
1329        let gw = font.glyph_w as i32;
1330        let gh = font.glyph_h as i32;
1331        let total_w = font.text_width(text) as i32;
1332        // Centre the string on the pivot -- baseline (top edge of
1333        // first glyph) is `gh/2` above the pivot so that the glyph
1334        // midline runs through `(cx, cy)`.
1335        let origin_x = -total_w / 2;
1336        let origin_y = -gh / 2;
1337        let s = sincos::sin_q12(angle_q12);
1338        let c = sincos::cos_q12(angle_q12);
1339        let clut = self.clut_word;
1340        let tpage = self.tpage.uv_word(0);
1341        let color_cmd = gp0::polygon_opcode(false, true, true, false, false)
1342            | pack_color(tint.0, tint.1, tint.2);
1343
1344        // Transform helper: local (lx, ly) → screen (sx, sy), with
1345        // Q1.12 rotation matrix and integer translate to (cx, cy).
1346        let rot = |lx: i32, ly: i32| -> (i16, i16) {
1347            let rx = (lx * c - ly * s) >> 12;
1348            let ry = (lx * s + ly * c) >> 12;
1349            ((cx as i32 + rx) as i16, (cy as i32 + ry) as i16)
1350        };
1351
1352        let mut cursor_x = 0i32;
1353        reset_texture_window();
1354        for ch in text.chars() {
1355            let Some((u, v)) = self.glyph_uv(ch) else {
1356                cursor_x += font.glyph_advance(ch) as i32;
1357                continue;
1358            };
1359            let lx0 = origin_x + cursor_x;
1360            let lx1 = lx0 + gw;
1361            let ly0 = origin_y;
1362            let ly1 = origin_y + gh;
1363            let verts = [rot(lx0, ly0), rot(lx1, ly0), rot(lx0, ly1), rot(lx1, ly1)];
1364            let uvs = glyph_quad_uvs(u, v, font.glyph_w, font.glyph_h);
1365            write_textured_quad_packet(verts, uvs, color_cmd, clut, tpage);
1366            cursor_x += font.glyph_advance(ch) as i32;
1367        }
1368    }
1369
1370    /// Draw `text` through an arbitrary 2×2 affine transform.
1371    ///
1372    /// The matrix `m` is Q3.12 fixed-point -- `m = [[4096, 0], [0,
1373    /// 4096]]` is the identity (native size, axis-aligned). Each
1374    /// glyph's local corner `(lx, ly)` maps onto screen space as
1375    /// `(origin.0 + (m[0][0]*lx + m[0][1]*ly) >> 12,
1376    ///   origin.1 + (m[1][0]*lx + m[1][1]*ly) >> 12)`.
1377    ///
1378    /// Covers rotation, non-uniform scale, shear, reflection, and
1379    /// any combination -- the other quad-path methods are all
1380    /// specializations of this one.
1381    ///
1382    /// **Quad path** -- 9 GP0 words per glyph.
1383    ///
1384    /// # Example: horizontal shear
1385    ///
1386    /// ```ignore
1387    /// // Skew 30° right: x' = x + 0.577·y. 0.577 × 4096 ≈ 2365.
1388    /// let m = [[4096, 2365], [0, 4096]];
1389    /// atlas.draw_text_affine((40, 40), "SKEW", m, (200, 200, 200));
1390    /// ```
1391    pub fn draw_text_affine(
1392        &self,
1393        origin: (i16, i16),
1394        text: &str,
1395        m: [[i16; 2]; 2],
1396        tint: (u8, u8, u8),
1397    ) {
1398        if text.is_empty() {
1399            return;
1400        }
1401        let font = self.font;
1402        let gw = font.glyph_w as i32;
1403        let gh = font.glyph_h as i32;
1404        let (m00, m01) = (m[0][0] as i32, m[0][1] as i32);
1405        let (m10, m11) = (m[1][0] as i32, m[1][1] as i32);
1406        let clut = self.clut_word;
1407        let tpage = self.tpage.uv_word(0);
1408        let color_cmd = gp0::polygon_opcode(false, true, true, false, false)
1409            | pack_color(tint.0, tint.1, tint.2);
1410
1411        let tx = |lx: i32, ly: i32| -> (i16, i16) {
1412            let sx = origin.0 as i32 + ((m00 * lx + m01 * ly) >> 12);
1413            let sy = origin.1 as i32 + ((m10 * lx + m11 * ly) >> 12);
1414            (sx as i16, sy as i16)
1415        };
1416
1417        let mut cursor_x = 0i32;
1418        reset_texture_window();
1419        for ch in text.chars() {
1420            let Some((u, v)) = self.glyph_uv(ch) else {
1421                cursor_x += font.glyph_advance(ch) as i32;
1422                continue;
1423            };
1424            let lx0 = cursor_x;
1425            let lx1 = lx0 + gw;
1426            let ly0 = 0;
1427            let ly1 = gh;
1428            let verts = [tx(lx0, ly0), tx(lx1, ly0), tx(lx0, ly1), tx(lx1, ly1)];
1429            let uvs = glyph_quad_uvs(u, v, font.glyph_w, font.glyph_h);
1430            write_textured_quad_packet(verts, uvs, color_cmd, clut, tpage);
1431            cursor_x += font.glyph_advance(ch) as i32;
1432        }
1433    }
1434
1435    /// Draw `text` with a top-to-bottom colour gradient.
1436    ///
1437    /// Top of each glyph is tinted `top`; bottom is tinted
1438    /// `bottom`. The GPU gouraud-interpolates down each glyph,
1439    /// producing a smooth vertical gradient across the whole line.
1440    ///
1441    /// **Gouraud quad path** -- 12 GP0 words per glyph (GP0 0x3C).
1442    /// Use when you want a rainbow title, a torch-lit dialogue
1443    /// box, or any per-vertex colour effect; prefer the single-
1444    /// tint [`Self::draw_text`] otherwise.
1445    ///
1446    /// # Example
1447    ///
1448    /// ```ignore
1449    /// // Classic "red hot" gradient.
1450    /// atlas.draw_text_gradient(
1451    ///     40, 10, "INFERNO",
1452    ///     (255, 240, 80),  // bright yellow at the top
1453    ///     (180, 30, 20),   // deep red at the bottom
1454    /// );
1455    /// ```
1456    pub fn draw_text_gradient(
1457        &self,
1458        x: i16,
1459        y: i16,
1460        text: &str,
1461        top: (u8, u8, u8),
1462        bottom: (u8, u8, u8),
1463    ) {
1464        self.draw_text_scaled_gradient(x, y, text, 1, 1, top, bottom);
1465    }
1466
1467    /// Draw `text` with a top-to-bottom gradient, scaled by
1468    /// `(scale_x, scale_y)`. Combines [`Self::draw_text_scaled`]
1469    /// and [`Self::draw_text_gradient`] in one draw -- a 3× title
1470    /// with a fire-colour sweep costs the same 12 words per glyph
1471    /// as a 1× gradient.
1472    ///
1473    /// Nearest-neighbour sampling still applies, so integer
1474    /// scales produce crisp pixel-doubled output.
1475    ///
1476    /// # Example
1477    ///
1478    /// ```ignore
1479    /// // 3× "TITLE" with yellow→red gradient.
1480    /// atlas.draw_text_scaled_gradient(
1481    ///     64, 10, "TITLE", 3, 3,
1482    ///     (255, 220, 80), (200, 40, 20),
1483    /// );
1484    /// ```
1485    pub fn draw_text_scaled_gradient(
1486        &self,
1487        x: i16,
1488        y: i16,
1489        text: &str,
1490        scale_x: u8,
1491        scale_y: u8,
1492        top: (u8, u8, u8),
1493        bottom: (u8, u8, u8),
1494    ) {
1495        assert!(scale_x > 0 && scale_y > 0, "scale must be > 0 in both axes");
1496        if text.is_empty() {
1497            return;
1498        }
1499        let font = self.font;
1500        let gw = font.glyph_w as i16;
1501        let gh = font.glyph_h as i16;
1502        let sw = gw * scale_x as i16;
1503        let sh = gh * scale_y as i16;
1504        let clut = self.clut_word;
1505        let tpage = self.tpage.uv_word(0);
1506        let color0_cmd =
1507            gp0::polygon_opcode(true, true, true, false, false) | pack_color(top.0, top.1, top.2);
1508        let mut cursor_x = x;
1509        reset_texture_window();
1510        for ch in text.chars() {
1511            let Some((u, v)) = self.glyph_uv(ch) else {
1512                cursor_x = cursor_x.wrapping_add(font.glyph_advance(ch) as i16 * scale_x as i16);
1513                continue;
1514            };
1515            let verts = [
1516                (cursor_x, y),
1517                (cursor_x + sw, y),
1518                (cursor_x, y + sh),
1519                (cursor_x + sw, y + sh),
1520            ];
1521            let uvs = glyph_quad_uvs(u, v, font.glyph_w, font.glyph_h);
1522            let colors = [top, top, bottom, bottom];
1523            write_textured_gouraud_quad_packet(verts, uvs, colors, color0_cmd, clut, tpage);
1524            cursor_x = cursor_x.wrapping_add(font.glyph_advance(ch) as i16 * scale_x as i16);
1525        }
1526    }
1527
1528    /// Draw `text` with per-vertex glyph colours, Q8 scaling, and
1529    /// authored letter spacing.
1530    ///
1531    /// `colors` are ordered top-left, top-right, bottom-left,
1532    /// bottom-right, matching `psx_gpu::draw_quad_textured_gouraud`.
1533    /// This is the general-purpose path behind gradient UI text:
1534    /// vertical gradients use `[top, top, bottom, bottom]`, horizontal
1535    /// gradients use `[left, right, left, right]`.
1536    pub fn draw_text_scaled_gouraud_with_spacing_q8(
1537        &self,
1538        x: i16,
1539        y: i16,
1540        text: &str,
1541        scale_x_q8: u16,
1542        scale_y_q8: u16,
1543        letter_spacing: i8,
1544        colors: [(u8, u8, u8); 4],
1545    ) {
1546        assert!(
1547            scale_x_q8 > 0 && scale_y_q8 > 0,
1548            "scale must be > 0 in both axes"
1549        );
1550        if text.is_empty() {
1551            return;
1552        }
1553        let font = self.font;
1554        let gw = font.glyph_w as i16;
1555        let gh = font.glyph_h as i16;
1556        let sw = scale_q8_i16(gw, scale_x_q8);
1557        let sh = scale_q8_i16(gh, scale_y_q8);
1558        let clut = self.clut_word;
1559        let tpage = self.tpage.uv_word(0);
1560        let color0_cmd = gp0::polygon_opcode(true, true, true, false, false)
1561            | pack_color(colors[0].0, colors[0].1, colors[0].2);
1562        let gap_q8 = i32::from(letter_spacing) << 8;
1563        let mut cursor_x_q8 = i32::from(x) << 8;
1564        reset_texture_window();
1565        for ch in text.chars() {
1566            let cursor_x = round_q8_to_i16(cursor_x_q8);
1567            let Some((u, v)) = self.glyph_uv(ch) else {
1568                cursor_x_q8 = cursor_x_q8
1569                    .saturating_add(i32::from(font.glyph_advance(ch)) * i32::from(scale_x_q8))
1570                    .saturating_add(gap_q8);
1571                continue;
1572            };
1573            let verts = [
1574                (cursor_x, y),
1575                (cursor_x + sw, y),
1576                (cursor_x, y + sh),
1577                (cursor_x + sw, y + sh),
1578            ];
1579            let uvs = glyph_quad_uvs(u, v, font.glyph_w, font.glyph_h);
1580            write_textured_gouraud_quad_packet(verts, uvs, colors, color0_cmd, clut, tpage);
1581            cursor_x_q8 = cursor_x_q8
1582                .saturating_add(i32::from(font.glyph_advance(ch)) * i32::from(scale_x_q8))
1583                .saturating_add(gap_q8);
1584        }
1585    }
1586
1587    /// Access the underlying [`BitmapFont`]. Useful for UI code
1588    /// that needs glyph dimensions for its own layout math.
1589    pub fn font(&self) -> &'static BitmapFont {
1590        self.font
1591    }
1592
1593    /// Texture page the atlas is installed at -- useful if the caller
1594    /// wants to restore it after drawing with a different tpage. Always
1595    /// 4bpp, always inside a valid VRAM page-aligned slot.
1596    #[doc(alias = "tpage")]
1597    pub fn texture_page(&self) -> TexturePage {
1598        self.tpage
1599    }
1600}
1601
1602// ======================================================================
1603// Tests (host-side -- pure data-transform checks)
1604// ======================================================================
1605
1606// ======================================================================
1607// TextSink -- one text interface for UI code
1608// ======================================================================
1609
1610/// The minimum a widget needs from a text renderer: draw a run at a position
1611/// in a colour, and measure it.
1612///
1613/// UI code written against this works with any renderer -- [`FontAtlas`], a
1614/// scaled bitmap font, or a game's own atlas -- instead of being written twice
1615/// because two renderers happen to have different inherent methods. That is the
1616/// situation this exists to prevent: a caller with a list, a menu or a dialog to
1617/// draw should not care which one is behind it.
1618///
1619/// Coordinates are screen pixels with the origin top-left, matching the rest of
1620/// the SDK's immediate-mode drawing.
1621pub trait TextSink {
1622    /// Draw `text` with its top-left corner at `(x, y)`.
1623    fn draw(&self, x: i16, y: i16, text: &str, tint: (u8, u8, u8));
1624
1625    /// Width of `text` in screen pixels, using the same metrics `draw` will.
1626    fn width(&self, text: &str) -> i16;
1627
1628    /// Baseline-to-baseline distance for stacked rows.
1629    fn line_height(&self) -> i16;
1630
1631    /// Draw `text` centred on `x`. Provided so every caller does not repeat the
1632    /// half-width arithmetic, and so a renderer with non-integer metrics can
1633    /// override the rounding.
1634    fn draw_centered(&self, x: i16, y: i16, text: &str, tint: (u8, u8, u8)) {
1635        self.draw(x - self.width(text) / 2, y, text, tint);
1636    }
1637}
1638
1639impl TextSink for FontAtlas {
1640    fn draw(&self, x: i16, y: i16, text: &str, tint: (u8, u8, u8)) {
1641        FontAtlas::draw_text(self, x, y, text, tint);
1642    }
1643
1644    fn width(&self, text: &str) -> i16 {
1645        FontAtlas::text_width(self, text) as i16
1646    }
1647
1648    fn line_height(&self) -> i16 {
1649        self.font().line_height as i16
1650    }
1651}
1652
1653#[cfg(test)]
1654mod tests {
1655    extern crate std;
1656
1657    use super::{
1658        blended_draw_mode_word, TextBlend, SEMI_TRANSPARENT_FLAT_RECT_CMD,
1659        SEMI_TRANSPARENT_RECT_CMD,
1660    };
1661    use psx_vram::{TextureDepth, TexturePage};
1662
1663    /// The blend equation is selected by the draw mode, not the
1664    /// primitive, so these two bits are the whole mechanism. Pin them
1665    /// against the hardware's documented ABR encoding.
1666    #[test]
1667    fn text_blend_maps_to_the_hardware_abr_field() {
1668        assert_eq!(TextBlend::Average.semi_transparency_bits(), 0);
1669        assert_eq!(TextBlend::Add.semi_transparency_bits(), 1);
1670        assert_eq!(TextBlend::Subtract.semi_transparency_bits(), 2);
1671        assert_eq!(TextBlend::AddQuarter.semi_transparency_bits(), 3);
1672    }
1673
1674    /// The blended draw mode must differ from the opaque one in the ABR
1675    /// field and NOWHERE else: same page, same depth, same flags. A
1676    /// stray bit here would silently repoint the atlas or change its
1677    /// colour depth mid-string.
1678    #[test]
1679    fn blended_draw_mode_only_moves_the_abr_bits() {
1680        for tpage in [
1681            TexturePage::new(0, 0, TextureDepth::Bit4),
1682            TexturePage::new(640, 256, TextureDepth::Bit4),
1683            TexturePage::new(896, 0, TextureDepth::Bit8),
1684        ] {
1685            let opaque = blended_draw_mode_word(tpage, TextBlend::Average);
1686            for blend in [
1687                TextBlend::Average,
1688                TextBlend::Add,
1689                TextBlend::Subtract,
1690                TextBlend::AddQuarter,
1691            ] {
1692                let word = blended_draw_mode_word(tpage, blend);
1693                assert_eq!(
1694                    (word >> 5) & 3,
1695                    u32::from(blend.semi_transparency_bits()),
1696                    "{blend:?} ABR field"
1697                );
1698                assert_eq!(
1699                    word & !(3 << 5),
1700                    opaque & !(3 << 5),
1701                    "{blend:?} changed something other than ABR"
1702                );
1703            }
1704            // The low nine bits are the same page/blend/depth encoding
1705            // the SDK embeds in a textured primitive's UV word, so the
1706            // rect path and the quad path address one atlas identically.
1707            for blend in [TextBlend::Average, TextBlend::Add, TextBlend::Subtract] {
1708                assert_eq!(
1709                    blended_draw_mode_word(tpage, blend) & 0x1ff,
1710                    u32::from(tpage.uv_word(blend.semi_transparency_bits())),
1711                    "{blend:?} page/blend/depth encoding"
1712                );
1713            }
1714        }
1715    }
1716
1717    /// The blended rectangle differs from the opaque one only by the
1718    /// semi-transparency bit. If these ever diverge further, the blended
1719    /// path has stopped being the same 4-word primitive.
1720    #[test]
1721    fn blended_rect_command_is_the_opaque_one_plus_bit_25() {
1722        const OPAQUE_RECT_CMD: u32 = packet::TEXTURED_RECT;
1723        assert_eq!(SEMI_TRANSPARENT_RECT_CMD, OPAQUE_RECT_CMD | (1 << 25));
1724    }
1725
1726    /// The backdrop is the MONOCHROME rectangle, not the textured one:
1727    /// same bit-25 rule, one opcode lower, and three data words instead
1728    /// of four however large the plate is. That word count is the whole
1729    /// reason a plate is cheaper than a second pass over the glyphs.
1730    #[test]
1731    fn blended_backdrop_command_is_the_flat_rect_plus_bit_25() {
1732        const OPAQUE_FLAT_RECT_CMD: u32 = packet::FLAT_RECT;
1733        assert_eq!(
1734            SEMI_TRANSPARENT_FLAT_RECT_CMD,
1735            OPAQUE_FLAT_RECT_CMD | (1 << 25)
1736        );
1737        // Untextured, so it must NOT carry the textured rect's opcode.
1738        assert_ne!(SEMI_TRANSPARENT_FLAT_RECT_CMD, SEMI_TRANSPARENT_RECT_CMD);
1739    }
1740
1741    /// The wrap scan in `psx-engine`'s UI carries a running sum of
1742    /// `glyph_advance` instead of re-measuring each prefix with
1743    /// `text_width`. That is only bit-exact while `text_width` stays the
1744    /// saturating fold of the per-character advances, so pin it here --
1745    /// including the proportional table, the out-of-range fallback and the
1746    /// u16 saturation.
1747    #[test]
1748    fn text_width_is_the_saturating_fold_of_glyph_advance() {
1749        const BITMAP: [u8; 8] = [0; 8];
1750        const ADVANCES: [u8; 4] = [3, 9, 0, 255];
1751        let proportional = super::BitmapFont {
1752            glyph_w: 8,
1753            glyph_h: 8,
1754            first_char: b'a' as u16,
1755            glyph_count: 4,
1756            bitmap: &BITMAP,
1757            glyph_advances: Some(&ADVANCES),
1758            advance_x: 7,
1759            line_height: 8,
1760            bit_order: super::BitOrder::Lsb,
1761        };
1762        let fixed = super::BitmapFont {
1763            glyph_advances: None,
1764            ..proportional
1765        };
1766
1767        assert_eq!(proportional.glyph_advance('a'), 3);
1768        assert_eq!(proportional.glyph_advance('d'), 255);
1769        // Outside the covered range: falls back to `advance_x`.
1770        assert_eq!(proportional.glyph_advance('z'), 7);
1771        assert_eq!(fixed.glyph_advance('a'), 7);
1772
1773        for font in [&proportional, &fixed] {
1774            for text in ["", "a", "ad", "abcd", "abcdz", "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"] {
1775                let folded = text
1776                    .chars()
1777                    .map(|ch| u16::from(font.glyph_advance(ch)))
1778                    .fold(0u16, u16::saturating_add);
1779                assert_eq!(font.text_width(text), folded, "text_width({text:?})");
1780            }
1781        }
1782        // The long run really does saturate, so the case above is load-bearing.
1783        assert_eq!(
1784            proportional.text_width(&std::string::String::from("d").repeat(258)),
1785            u16::MAX
1786        );
1787    }
1788
1789    #[test]
1790    fn centered_text_is_symmetric_about_the_anchor() {
1791        // A stub renderer keeps the contract test independent of any atlas
1792        // upload, which needs hardware.
1793        struct Fixed(i16);
1794        impl super::TextSink for Fixed {
1795            fn draw(&self, _x: i16, _y: i16, _t: &str, _c: (u8, u8, u8)) {}
1796            fn width(&self, text: &str) -> i16 {
1797                self.0 * text.len() as i16
1798            }
1799            fn line_height(&self) -> i16 {
1800                8
1801            }
1802        }
1803        struct Spy(core::cell::Cell<i16>);
1804        impl super::TextSink for Spy {
1805            fn draw(&self, x: i16, _y: i16, _t: &str, _c: (u8, u8, u8)) {
1806                self.0.set(x);
1807            }
1808            fn width(&self, text: &str) -> i16 {
1809                4 * text.len() as i16
1810            }
1811            fn line_height(&self) -> i16 {
1812                8
1813            }
1814        }
1815        let f = Fixed(4);
1816        assert_eq!(super::TextSink::width(&f, "abcd"), 16);
1817        let spy = Spy(core::cell::Cell::new(-1));
1818        spy.draw_centered(160, 0, "abcd", (0, 0, 0));
1819        // 4 glyphs * 4 px = 16 wide, so centred on 160 starts at 152.
1820        assert_eq!(spy.0.get(), 152);
1821    }
1822
1823    use super::*;
1824
1825    /// Synthetic font: two 8×2 glyphs, LSB-first, for bit-unpacking
1826    /// verification.
1827    const TEST_FONT: BitmapFont = BitmapFont {
1828        glyph_w: 8,
1829        glyph_h: 2,
1830        first_char: b'A' as u16,
1831        glyph_count: 2,
1832        bitmap: &[
1833            // 'A': row 0 = all pixels, row 1 = leftmost only
1834            0xff, 0x01, // 'B': row 0 = alternating, row 1 = rightmost
1835            0x55, 0x80,
1836        ],
1837        glyph_advances: None,
1838        advance_x: 8,
1839        line_height: 2,
1840        bit_order: BitOrder::Lsb,
1841    };
1842
1843    const TEST_PROPORTIONAL_ADVANCES: [u8; 2] = [3, 7];
1844    const TEST_PROPORTIONAL_FONT: BitmapFont = BitmapFont {
1845        glyph_advances: Some(&TEST_PROPORTIONAL_ADVANCES),
1846        ..TEST_FONT
1847    };
1848
1849    const TOO_TALL_FONT: BitmapFont = BitmapFont {
1850        glyph_w: 255,
1851        glyph_h: 255,
1852        glyph_count: 2,
1853        bitmap: &[],
1854        ..TEST_FONT
1855    };
1856
1857    #[test]
1858    fn row_bytes_handles_widths_under_and_over_8() {
1859        let mut f = TEST_FONT;
1860        assert_eq!(f.row_bytes(), 1);
1861        f.glyph_w = 12;
1862        assert_eq!(f.row_bytes(), 2);
1863        f.glyph_w = 16;
1864        assert_eq!(f.row_bytes(), 2);
1865        f.glyph_w = 24;
1866        assert_eq!(f.row_bytes(), 3);
1867    }
1868
1869    #[test]
1870    fn lsb_row_unpacks_as_expected() {
1871        let row_a0 = TEST_FONT.glyph_row_packed(0, 0);
1872        assert_eq!(row_a0, 0xff);
1873        let row_a1 = TEST_FONT.glyph_row_packed(0, 1);
1874        assert_eq!(row_a1, 0x01);
1875        let row_b0 = TEST_FONT.glyph_row_packed(1, 0);
1876        assert_eq!(row_b0, 0x55);
1877        let row_b1 = TEST_FONT.glyph_row_packed(1, 1);
1878        assert_eq!(row_b1, 0x80);
1879    }
1880
1881    #[test]
1882    fn msb_order_mirrors_the_byte() {
1883        let msb_font = BitmapFont {
1884            bit_order: BitOrder::Msb,
1885            ..TEST_FONT
1886        };
1887        // 0xFF mirrors to 0xFF.
1888        assert_eq!(msb_font.glyph_row_packed(0, 0), 0xff);
1889        // 0x01 in MSB-first becomes 0x80 after reversing.
1890        assert_eq!(msb_font.glyph_row_packed(0, 1), 0x80);
1891        // 0x55 (0b01010101) mirrors to 0xAA (0b10101010).
1892        assert_eq!(msb_font.glyph_row_packed(1, 0), 0xaa);
1893    }
1894
1895    #[test]
1896    fn glyph_advances_override_fixed_advance_when_present() {
1897        assert_eq!(TEST_PROPORTIONAL_FONT.glyph_advance('A'), 3);
1898        assert_eq!(TEST_PROPORTIONAL_FONT.glyph_advance('B'), 7);
1899        assert_eq!(TEST_PROPORTIONAL_FONT.glyph_advance('Z'), 8);
1900        assert_eq!(TEST_PROPORTIONAL_FONT.text_width("ABA"), 13);
1901    }
1902
1903    #[test]
1904    fn text_width_with_spacing_inserts_gaps_between_glyphs_only() {
1905        assert_eq!(TEST_PROPORTIONAL_FONT.text_width_with_spacing("", 5), 0);
1906        assert_eq!(TEST_PROPORTIONAL_FONT.text_width_with_spacing("A", 5), 3);
1907        assert_eq!(TEST_PROPORTIONAL_FONT.text_width_with_spacing("ABA", 2), 17);
1908        assert_eq!(TEST_PROPORTIONAL_FONT.text_width_with_spacing("ABA", -2), 9);
1909    }
1910
1911    #[test]
1912    fn q8_scale_helpers_round_to_screen_pixels() {
1913        assert_eq!(scale_q8_i16(8, 256), 8);
1914        assert_eq!(scale_q8_i16(8, 384), 12);
1915        assert_eq!(scale_q8_i16(17, 384), 26);
1916        assert_eq!(round_q8_to_i16(384), 2);
1917        assert_eq!(round_q8_to_i16(-384), -2);
1918    }
1919
1920    #[test]
1921    fn glyph_quad_uvs_saturate_the_rightmost_atlas_column() {
1922        // A 256-texel-wide atlas (16 columns of 16px glyphs) places the last
1923        // column's glyph at u=240, so its far U is 240+16=256, which wraps to 0
1924        // in the u8 UV field and smears the glyph across the quad. It must
1925        // saturate to 255 instead. (This was the "garbled O in MUSIC VOLUME"
1926        // bug: 'O' is the only rightmost-column glyph in uppercase menu text.)
1927        let edge = glyph_quad_uvs(240, 0, 16, 14);
1928        assert_eq!(edge[1].0, 255, "far U must saturate, not wrap to 0");
1929        assert_eq!(edge[3].0, 255);
1930        // Interior columns stay exact (no clamping kicks in).
1931        assert_eq!(
1932            glyph_quad_uvs(224, 0, 16, 14),
1933            [(224, 0), (240, 0), (224, 14), (240, 14)]
1934        );
1935        // V saturates the same way near the bottom edge of a tall atlas.
1936        let tall = glyph_quad_uvs(0, 248, 16, 14);
1937        assert_eq!(tall[2].1, 255);
1938        assert_eq!(tall[3].1, 255);
1939    }
1940
1941    #[test]
1942    fn zen_dots_display_is_native_size_and_fits_the_ps1_upload_budget() {
1943        let font = &crate::fonts::ZEN_DOTS_DISPLAY;
1944        assert_eq!(font.first_char, b'A' as u16);
1945        assert_eq!(font.glyph_count, 26);
1946        assert_eq!(font.glyph_h, 27);
1947        assert_eq!(font.text_width("CORTEX"), 162);
1948
1949        let (_, atlas_w, atlas_h, halfwords_per_row) = font_atlas_dims(font);
1950        assert!(atlas_w <= FontAtlas::MAX_ATLAS_W_TEXELS);
1951        assert!(atlas_h <= u8::MAX as u16);
1952        assert!(
1953            usize::from(halfwords_per_row) * usize::from(atlas_h) <= FontAtlas::MAX_PACK_HALFWORDS
1954        );
1955    }
1956
1957    #[test]
1958    fn drippy_space_is_display_only_and_fits_the_ps1_upload_budget() {
1959        for font in [
1960            &crate::fonts::DRIPPY_SPACE,
1961            &crate::fonts::DRIPPY_SPACE_DISPLAY,
1962        ] {
1963            let expected_first = if font.glyph_count == 26 { b'A' } else { b' ' };
1964            assert_eq!(font.first_char, expected_first as u16);
1965            let (_, atlas_w, atlas_h, halfwords_per_row) = font_atlas_dims(font);
1966            assert!(atlas_w <= FontAtlas::MAX_ATLAS_W_TEXELS);
1967            assert!(atlas_h <= u8::MAX as u16);
1968            assert!(
1969                usize::from(halfwords_per_row) * usize::from(atlas_h)
1970                    <= FontAtlas::MAX_PACK_HALFWORDS
1971            );
1972        }
1973        assert_eq!(crate::fonts::DRIPPY_SPACE.glyph_count, 0x5b - 0x20);
1974        assert_eq!(crate::fonts::DRIPPY_SPACE_DISPLAY.glyph_count, 26);
1975    }
1976
1977    const ARENA_FONTS: &[&BitmapFont] = &[
1978        &crate::fonts::ZEN_DOTS_DISPLAY,
1979        &crate::fonts::ZEN_DOTS,
1980        &crate::fonts::KENNEY_FUTURE_NARROW,
1981        &crate::fonts::KENNEY_PIXEL,
1982        &crate::fonts::KENNEY_FUTURE,
1983        &crate::fonts::BASIC,
1984    ];
1985
1986    #[test]
1987    fn arena_six_font_set_has_a_provably_minimal_two_page_pack() {
1988        let mut placements = [None; MAX_PACKED_FONT_ATLASES];
1989        let metrics = plan_font_pack(ARENA_FONTS, &mut placements).unwrap();
1990        assert_eq!(metrics.pages, 2, "six fonts must share two tpages");
1991        assert_eq!(metrics.upload_rows, 241);
1992        assert_eq!(metrics.scratch_halfwords, 2 * 64 * 241);
1993        assert_eq!(font_pack_metrics(ARENA_FONTS), Some(metrics));
1994
1995        // More than one complete page of rectangle area is occupied, so the
1996        // two-page result is not merely heuristic for this shipping set: it is
1997        // the mathematical minimum without rotating or modifying an atlas.
1998        let occupied_halfwords: usize = ARENA_FONTS
1999            .iter()
2000            .map(|font| {
2001                let (_, _, h, w) = font_atlas_dims(font);
2002                usize::from(h) * usize::from(w)
2003            })
2004            .sum();
2005        assert!(occupied_halfwords > FONT_PAGE_HALFWORDS * 256);
2006        assert!(occupied_halfwords <= 2 * FONT_PAGE_HALFWORDS * 256);
2007
2008        for (a_index, a) in placements[..ARENA_FONTS.len()].iter().enumerate() {
2009            let a = a.unwrap();
2010            let (_, _, a_h, a_w) = font_atlas_dims(ARENA_FONTS[a_index]);
2011            assert!(a.x_halfwords + a_w <= FONT_PAGE_HALFWORDS as u16);
2012            assert!(a.y + a_h <= 256);
2013            for (b_index, b) in placements[..a_index].iter().enumerate() {
2014                let b = b.unwrap();
2015                let (_, _, b_h, b_w) = font_atlas_dims(ARENA_FONTS[b_index]);
2016                assert!(!placements_overlap(a, a_w, a_h, b, b_w, b_h));
2017            }
2018        }
2019    }
2020
2021    #[test]
2022    fn packed_arena_atlases_preserve_every_glyph_and_padding_texel() {
2023        let mut placements = [None; MAX_PACKED_FONT_ATLASES];
2024        let metrics = plan_font_pack(ARENA_FONTS, &mut placements).unwrap();
2025        let mut scratch = std::vec![0xFFFF; metrics.scratch_halfwords];
2026        pack_font_bits(ARENA_FONTS, &placements, metrics, &mut scratch).unwrap();
2027        let stride = usize::from(metrics.pages) * FONT_PAGE_HALFWORDS;
2028
2029        for (font_index, &font) in ARENA_FONTS.iter().enumerate() {
2030            let placement = placements[font_index].unwrap();
2031            let (glyphs_per_row, atlas_w, atlas_h, _) = font_atlas_dims(font);
2032            let cell_w = cell_width(font);
2033            for local_y in 0..atlas_h {
2034                let glyph_row = local_y / u16::from(font.glyph_h);
2035                let glyph_y = (local_y % u16::from(font.glyph_h)) as u8;
2036                for local_x in 0..atlas_w {
2037                    let glyph_col = local_x / cell_w;
2038                    let glyph_x = local_x % cell_w;
2039                    let glyph_index = glyph_row * glyphs_per_row + glyph_col;
2040                    let expected =
2041                        if glyph_index < font.glyph_count && glyph_x < u16::from(font.glyph_w) {
2042                            ((font.glyph_row_packed(glyph_index, glyph_y) >> glyph_x) & 1) as u16
2043                        } else {
2044                            0
2045                        };
2046                    let global_halfword = usize::from(placement.page) * FONT_PAGE_HALFWORDS
2047                        + usize::from(placement.x_halfwords)
2048                        + usize::from(local_x / 4);
2049                    let word =
2050                        scratch[usize::from(placement.y + local_y) * stride + global_halfword];
2051                    let actual = (word >> ((local_x & 3) * 4)) & 0xf;
2052                    assert_eq!(
2053                        actual, expected,
2054                        "font {font_index} texel ({local_x},{local_y})"
2055                    );
2056                }
2057            }
2058        }
2059    }
2060
2061    #[test]
2062    fn packed_origins_feed_exact_rect_and_quad_packet_uvs() {
2063        let fonts = [&TEST_FONT, &TEST_FONT];
2064        let mut placements = [None; MAX_PACKED_FONT_ATLASES];
2065        let metrics = plan_font_pack(&fonts, &mut placements).unwrap();
2066        assert_eq!(metrics.pages, 1);
2067        assert_eq!(placements[0].unwrap().x_halfwords, 0);
2068        assert_eq!(placements[1].unwrap().x_halfwords, 4);
2069
2070        let clut = Clut::new(960, 500);
2071        for (index, &font) in fonts.iter().enumerate() {
2072            let placement = placements[index].unwrap();
2073            let (glyphs_per_row, _, _, _) = font_atlas_dims(font);
2074            let atlas = FontAtlas {
2075                font,
2076                tpage: TexturePage::new(placement.page * 64, 0, TextureDepth::Bit4),
2077                clut_word: clut.uv_word(),
2078                glyphs_per_row,
2079                uv_origin: ((placement.x_halfwords * 4) as u8, placement.y as u8),
2080            };
2081            for glyph_index in 0..font.glyph_count {
2082                let ch = char::from_u32(u32::from(font.first_char + glyph_index)).unwrap();
2083                let (u, v) = atlas.glyph_uv(ch).unwrap();
2084                let expected_u = u16::from(atlas.uv_origin.0)
2085                    + (glyph_index % glyphs_per_row) * cell_width(font);
2086                let expected_v = u16::from(atlas.uv_origin.1)
2087                    + (glyph_index / glyphs_per_row) * u16::from(font.glyph_h);
2088                assert_eq!((u16::from(u), u16::from(v)), (expected_u, expected_v));
2089
2090                // GP0(64h) takes this packed UV/CLUT word. Every quad path
2091                // shares `glyph_uv` and only extends the same top-left corner.
2092                let rect_uv_word = pack_texcoord(u, v, atlas.clut_word);
2093                assert_eq!(rect_uv_word & 0xffff, u32::from(u) | (u32::from(v) << 8));
2094                assert_eq!((rect_uv_word >> 16) as u16, atlas.clut_word);
2095                let quad = glyph_quad_uvs(u, v, font.glyph_w, font.glyph_h);
2096                assert_eq!(quad[0], (u, v));
2097                assert_eq!(quad[3].0, u.saturating_add(font.glyph_w));
2098                assert_eq!(quad[3].1, v.saturating_add(font.glyph_h));
2099            }
2100        }
2101    }
2102
2103    #[test]
2104    fn font_pack_planner_fails_closed_outside_its_bound() {
2105        assert_eq!(font_pack_metrics(&[]), None);
2106        let too_many = [&TEST_FONT; MAX_PACKED_FONT_ATLASES + 1];
2107        assert_eq!(font_pack_metrics(&too_many), None);
2108
2109        assert_eq!(font_pack_metrics(&[&TOO_TALL_FONT]), None);
2110    }
2111
2112    #[test]
2113    fn every_pre_upload_failure_clears_stale_atlas_outputs() {
2114        struct NoAllocationExpected;
2115        impl VramRegionSource for NoAllocationExpected {
2116            fn alloc_page_run(
2117                &mut self,
2118                _count: u16,
2119                _depth: TextureDepth,
2120                _page_y: u16,
2121            ) -> Option<(TexturePage, VramHandle)> {
2122                panic!("preflight failure must not reserve pages")
2123            }
2124
2125            fn alloc_clut(&mut self, _entries: u16) -> Option<(Clut, VramHandle)> {
2126                panic!("preflight failure must not reserve a CLUT")
2127            }
2128        }
2129
2130        let stale = FontAtlas {
2131            font: &TEST_FONT,
2132            tpage: TexturePage::new(0, 0, TextureDepth::Bit4),
2133            clut_word: Clut::new(0, 480).uv_word(),
2134            glyphs_per_row: 2,
2135            uv_origin: (0, 0),
2136        };
2137        let mut alloc = NoAllocationExpected;
2138
2139        let mut out = [Some(stale); 2];
2140        assert!(upload_fonts(&[], &mut alloc, &mut [], &mut out).is_none());
2141        assert!(out.iter().all(Option::is_none));
2142
2143        out.fill(Some(stale));
2144        assert!(upload_fonts(
2145            &[&TEST_FONT, &TEST_FONT, &TEST_FONT],
2146            &mut alloc,
2147            &mut [],
2148            &mut out,
2149        )
2150        .is_none());
2151        assert!(out.iter().all(Option::is_none));
2152
2153        out.fill(Some(stale));
2154        assert!(upload_fonts(&[&TEST_FONT], &mut alloc, &mut [], &mut out).is_none());
2155        assert!(out.iter().all(Option::is_none));
2156    }
2157}
2158
2159#[cfg(test)]
2160mod deferred_packet_tests {
2161    extern crate std;
2162    use super::*;
2163    use std::vec::Vec;
2164
2165    fn atlas() -> FontAtlas {
2166        FontAtlas {
2167            font: &fonts::SPLEEN_5X8,
2168            tpage: TexturePage::new(640, 0, TextureDepth::Bit4),
2169            clut_word: Clut::new(960, 500).uv_word(),
2170            glyphs_per_row: 32,
2171            uv_origin: (0, 16),
2172        }
2173    }
2174
2175    #[test]
2176    fn deferred_text_uses_padded_cells_and_packed_origin() {
2177        let atlas = atlas();
2178        let mut packets = Vec::new();
2179        assert!(atlas.emit_text_packets(-4, 9, "fg", (128, 90, 20), |p| {
2180            packets.push(p.to_vec());
2181            true
2182        }));
2183        assert_eq!(packets.len(), 3);
2184        assert_eq!(packets[0].len(), 2);
2185        assert_eq!(packets[0][0] >> 24, 0xe1);
2186        assert_eq!(packets[0][1], 0xe2000000);
2187        for (i, ch) in ['f', 'g'].into_iter().enumerate() {
2188            let index = ch as u16 - atlas.font.first_char;
2189            let u = (index % 32) * 8; // five texels padded to eight
2190            let v = 16 + (index / 32) * 8;
2191            assert_eq!(
2192                packets[i + 1],
2193                [
2194                    0x64000000 | pack_color(128, 90, 20),
2195                    pack_vertex(-4 + i as i16 * 5, 9),
2196                    pack_texcoord(u as u8, v as u8, atlas.clut_word),
2197                    pack_xy(5, 8),
2198                ]
2199            );
2200        }
2201    }
2202
2203    #[test]
2204    fn deferred_sink_failure_stops_without_emitting_more_packets() {
2205        for capacity in 0..3 {
2206            let mut calls = 0;
2207            assert!(
2208                !atlas().emit_text_packets(0, 0, "abcdef", (128, 128, 128), |_| {
2209                    calls += 1;
2210                    calls <= capacity
2211                })
2212            );
2213            assert_eq!(calls, capacity + 1);
2214        }
2215    }
2216
2217    #[test]
2218    fn missing_glyph_keeps_advance_and_empty_run_only_sets_material() {
2219        let atlas = atlas();
2220        let mut packets = Vec::new();
2221        assert!(
2222            atlas.emit_text_packets(10, 20, "\u{10ffff}f", (128, 128, 128), |p| {
2223                packets.push(p.to_vec());
2224                true
2225            })
2226        );
2227        assert_eq!(packets.len(), 2);
2228        assert_eq!(
2229            packets[1][1],
2230            pack_vertex(10 + atlas.glyph_advance('\u{10ffff}') as i16, 20)
2231        );
2232        let mut calls = 0;
2233        assert!(atlas.emit_text_packets(0, 0, "", (0, 0, 0), |p| {
2234            calls += 1;
2235            assert_eq!(p.len(), 2);
2236            true
2237        }));
2238        assert_eq!(calls, 1);
2239    }
2240}