psx_loading/lib.rs
1// SPDX-License-Identifier: GPL-2.0-or-later
2//! An animated LOADING indicator for the stretches where a program is blocked
3//! on the disc.
4//!
5//! A load that blocks for seconds (a chain-load, a pack read, a sound bank
6//! streamed to the SPU) leaves the picture frozen, and a frozen picture reads
7//! as a hang. This crate draws the one thing such a picture needs: a label
8//! (`Loading`) with a tail that steps (trailing dots, or a ring of lights)
9//! and an ink that breathes, so the screen visibly moves while the CPU is busy
10//! elsewhere.
11//!
12//! The adoption guide, game by game, is `sdk/docs/LOADING-INDICATOR.md`.
13//!
14//! The look every PSoXide game uses is the **corner widget**: a small black
15//! square in the bottom-right corner of the picture with a little animation in it
16//! and no text ([`Style::in_corner`] with an empty label). The animation is the
17//! game's own: the built-in ring of lights in the game's colours ([`Tail::Spinner`])
18//! or art it draws itself ([`Tail::Art`]). A label with dots is there for
19//! programs that want words.
20//!
21//! # Design
22//!
23//! * **Plain rectangles.** Every glyph is drawn as GP0(60h) monochrome
24//! rectangles from a [`psx_font::BitmapFont`]'s 1-bit source, so the
25//! indicator needs no texture, no CLUT and no atlas, and disturbs no
26//! texture state. That is what lets one implementation serve a chain-load
27//! blob (nothing in VRAM but the picture), a game mid-boot and a menu with
28//! its own atlases. A game picks its look by giving the font, the scale, the
29//! inks, the backing colour and where the box sits ([`Style`]).
30//! * **Polled, never waiting.** [`Indicator::poll`] takes the caller's tick
31//! (one per VBlank) and draws only when the picture would change: at most
32//! once a VBlank, never waiting for one. A blocking loop calls it between
33//! its own steps (after each CD sector, each spin of a seek wait). Nothing
34//! here runs in an interrupt, so a draw never overlaps the caller's own GPU
35//! traffic.
36//! * **No hardware owned.** The indicator builds GP0 packets and hands them to
37//! a [`Sink`]; [`Gp0`] (guest only) is the sink that writes them to the GPU
38//! with the one-wait-per-packet pacing the silicon needs. A host test sink
39//! records them, which is how the layout and the animation are tested.
40//! * **No float, no 64-bit, no heap.** Colours blend in integer steps and the
41//! breathing is a triangle wave over a sixteen-step ramp.
42//!
43//! The caller owns the GPU state the rectangles are drawn under: the drawing
44//! area and offset must cover the box, and the mask bit and draw mode must be
45//! at their defaults (see [`prepare`]).
46//!
47//! ```
48//! use psx_font::fonts::BASIC_8X16;
49//! use psx_loading::{Indicator, Rgb, Sink, Style};
50//!
51//! struct Count(usize);
52//! impl Sink for Count {
53//! fn packet(&mut self, _words: &[u32]) {
54//! self.0 += 1;
55//! }
56//! }
57//!
58//! const STYLE: Style = Style::new(&BASIC_8X16, "Loading", Rgb(200, 120, 20), Rgb(5, 5, 7));
59//! let mut indicator = Indicator::new(STYLE);
60//! let mut sink = Count(0);
61//! // The first poll draws; the same tick again draws nothing.
62//! assert!(indicator.poll(&mut sink, 0));
63//! assert!(!indicator.poll(&mut sink, 0));
64//! ```
65
66#![no_std]
67#![warn(missing_docs)]
68
69use psx_font::BitmapFont;
70
71/// An 8-bit-per-channel colour, as the GP0 rectangle commands take it.
72#[derive(Copy, Clone, Debug, PartialEq, Eq)]
73pub struct Rgb(pub u8, pub u8, pub u8);
74
75impl Rgb {
76 /// The GP0 colour word: `0x00BBGGRR`.
77 pub const fn word(self) -> u32 {
78 self.0 as u32 | (self.1 as u32) << 8 | (self.2 as u32) << 16
79 }
80
81 /// `self` at `level` of [`LEVELS`] of the way to `other`.
82 const fn toward(self, other: Rgb, level: u8) -> Rgb {
83 const fn mix(a: u8, b: u8, level: u8) -> u8 {
84 let a = a as i32;
85 let b = b as i32;
86 (a + (b - a) * level as i32 / LEVELS as i32) as u8
87 }
88 Rgb(
89 mix(self.0, other.0, level),
90 mix(self.1, other.1, level),
91 mix(self.2, other.2, level),
92 )
93 }
94}
95
96/// Where the indicator's GP0 packets go.
97pub trait Sink {
98 /// Take one complete GP0 packet. A real sink waits for the GPU's command
99 /// FIFO once, then writes every word of the packet back to back (see [`Gp0`]).
100 fn packet(&mut self, words: &[u32]);
101}
102
103/// The sink that writes packets to the GPU's command port.
104///
105/// One bounded wait for `GPUSTAT` ready per packet, then every word of the
106/// packet back to back. Pacing every word is as wrong as pacing none: bit 26
107/// drops while the GPU ingests the rest of a multi-word packet, so a per-word
108/// wait spins its whole bound before each vertex word (silicon finding, see
109/// the chain loader's `paint`). The wait is bounded and gives up quietly: a
110/// dead GPU must not hang the screen that is meant to show a live load.
111#[cfg(target_arch = "mips")]
112pub struct Gp0;
113
114#[cfg(target_arch = "mips")]
115impl Sink for Gp0 {
116 fn packet(&mut self, words: &[u32]) {
117 let _ = psx_io::gpu::try_wait_command_ready(GP0_WAIT_SPINS);
118 for &word in words {
119 psx_io::gpu::write_command(word);
120 }
121 }
122}
123
124/// Spin budget for the ready wait before one packet.
125#[cfg(target_arch = "mips")]
126const GP0_WAIT_SPINS: u32 = 1_000_000;
127
128/// Steps of the breathing ramp: the ink is `ink_dim` at level 0 and
129/// `ink_bright` at this level.
130pub const LEVELS: u8 = 16;
131
132/// Lights on the spinner's ring: the edge cells of a 4 x 4 grid, which is a square.
133const RING_CELLS: usize = 12;
134/// The ring's cells (column, row) in order around the square, clockwise from the
135/// top left corner.
136const RING: [(u8, u8); RING_CELLS] = [
137 (0, 0),
138 (1, 0),
139 (2, 0),
140 (3, 0),
141 (3, 1),
142 (3, 2),
143 (3, 3),
144 (2, 3),
145 (1, 3),
146 (0, 3),
147 (0, 2),
148 (0, 1),
149];
150/// Cells along one side of the ring.
151const RING_SIDE_CELLS: i16 = 4;
152/// How brightly the light `n` places behind the head burns, out of 256: the head,
153/// then a tail that fades. Further back a light is only the unlit dot.
154const TRAIL: [u16; 5] = [256, 168, 98, 52, 24];
155/// Default dot size and pitch (cell to cell) of the ring, in unscaled display units
156/// (one unit is one pixel tall; see [`Style::with_display`]).
157const RING_DOT: i16 = 3;
158const RING_PITCH: i16 = 5;
159/// Gap before the spinner when a label comes first, in unscaled pixels.
160const SPINNER_GAP: i16 = 8;
161
162/// What follows the label and moves.
163#[derive(Copy, Clone, Debug)]
164pub enum Tail {
165 /// Nothing: the label alone, breathing if the ink does.
166 None,
167 /// Up to this many dots after the label (`Loading`, `Loading.`,
168 /// `Loading..`, ...). The box has room for all of them, so the label does
169 /// not slide as they step.
170 Dots(u8),
171 /// A ring of twelve lights chasing each other round a square: the head burns
172 /// at `lit`, a tail fades behind it, and every other light shows `unlit`. The
173 /// ring is square on the display, whatever the pixel aspect of the mode (see
174 /// [`Style::with_display`]), and its lights are drawn with the style's
175 /// [`Blend`].
176 Spinner {
177 /// The head light at full strength.
178 lit: Rgb,
179 /// A light with no head near it, dim enough that the ring still reads as a ring.
180 unlit: Rgb,
181 },
182 /// Animation the game draws itself, in a box of `width` x `height` pixels
183 /// (the widget is as big as that plus its padding). `draw(sink, x, y, frame)`
184 /// paints frame `frame` (`0..frames`) with its top-left at `(x, y)`, using
185 /// [`rect`] or any GP0 packet; the box is already filled with the style's ground.
186 Art {
187 /// Width of the art in pixels.
188 width: i16,
189 /// Height of the art in pixels.
190 height: i16,
191 /// Frames before it repeats.
192 frames: u8,
193 /// Draws one frame.
194 draw: fn(&mut dyn Sink, i16, i16, u8),
195 },
196}
197
198impl Tail {
199 /// Distinct steps before the tail repeats.
200 const fn steps(self) -> u32 {
201 match self {
202 Tail::None => 1,
203 Tail::Dots(n) => n as u32 + 1,
204 Tail::Spinner { .. } => RING_CELLS as u32,
205 Tail::Art { frames, .. } => frames as u32,
206 }
207 }
208
209 /// Cells of the font's advance the tail takes (the dots; 0 otherwise).
210 const fn cells(self) -> i32 {
211 match self {
212 Tail::Dots(n) => n as i32,
213 _ => 0,
214 }
215 }
216}
217
218/// How the spinner's lights combine with what is under them (the GPU's
219/// semi-transparency modes, set through the draw-mode word GP0(E1h)).
220#[derive(Copy, Clone, Debug, PartialEq, Eq)]
221#[non_exhaustive]
222pub enum Blend {
223 /// Opaque: a light replaces the pixels under it.
224 Opaque,
225 /// `B/2 + F/2`: half the light and half of what is behind it. A light is
226 /// dimmer than its colour and nothing brightens past it.
227 Average,
228 /// `B + F`: the light's colour is added to what is behind it. A light burns
229 /// at its full colour, a faint one only brightens its neighbourhood, and where
230 /// two lights meet they add up.
231 Additive,
232 /// `B + F/4`: a quarter of the light added, for a faint glow.
233 Glow,
234}
235
236impl Blend {
237 /// The semi-transparency mode field of GP0(E1h), if the lights are blended.
238 const fn mode(self) -> Option<u32> {
239 match self {
240 Blend::Opaque => None,
241 Blend::Average => Some(0),
242 Blend::Additive => Some(1),
243 Blend::Glow => Some(3),
244 }
245 }
246}
247
248/// What the indicator looks like and where it sits.
249///
250/// Build one with [`Style::new`] (a `const fn`, so a `static` or `const` works)
251/// and refine it with the `with_*` methods.
252#[derive(Copy, Clone, Debug)]
253pub struct Style {
254 /// The glyph source. Any [`BitmapFont`] works; the label is laid out with
255 /// the font's advances (per glyph for a proportional font), and the box always
256 /// has room for the whole tail, so it does not change width as the tail steps.
257 pub font: &'static BitmapFont,
258 /// Integer pixel scale: every font pixel becomes a `scale`-square.
259 pub scale: u8,
260 /// The label, ASCII.
261 pub label: &'static str,
262 /// What follows the label.
263 pub tail: Tail,
264 /// The darkest ink of the breathing.
265 pub ink_dim: Rgb,
266 /// The brightest ink of the breathing. Equal to `ink_dim` for a steady ink.
267 pub ink_bright: Rgb,
268 /// The colour the box is filled with before the text, so each redraw
269 /// erases the last one.
270 pub ground: Rgb,
271 /// A one-pixel line along the top edge of the box, if any.
272 pub rule: Option<Rgb>,
273 /// Horizontal space between the box edge and the content.
274 pub pad_x: i16,
275 /// Vertical space between the box edge and the content.
276 pub pad_y: i16,
277 /// Screen x the box is centred on.
278 pub centre_x: i16,
279 /// Screen y of the box's top edge.
280 pub top: i16,
281 /// The smallest the box may be, `(width, height)`: the content is centred in
282 /// it. `(0, 0)` sizes the box to its content plus the padding.
283 pub min_size: (i16, i16),
284 /// VBlanks per tail step.
285 pub step_ticks: u16,
286 /// VBlanks per full breath (dim to bright and back). Even and at least
287 /// twice [`LEVELS`]; a smaller value is raised to that.
288 pub pulse_ticks: u16,
289 /// How the spinner's lights blend with what is under them.
290 pub blend: Blend,
291 /// Pixels across per unit of height on a 4:3 screen, in 1/256ths, from the display
292 /// mode (256 is square pixels). Set by [`Style::with_display`].
293 across_q8: u16,
294 /// Spinner dot size and spacing between dot centres, in unscaled display units.
295 pub ring: (i16, i16),
296}
297
298impl Style {
299 /// A style with sensible defaults: scale 1, three dots a third of a second
300 /// apart at 60 Hz (20 VBlanks), a steady ink, a breath of 64 VBlanks if one
301 /// is asked for, the box centred horizontally on a 320-wide screen near
302 /// the foot of the picture.
303 pub const fn new(
304 font: &'static BitmapFont,
305 label: &'static str,
306 ink: Rgb,
307 ground: Rgb,
308 ) -> Self {
309 Style {
310 font,
311 scale: 1,
312 label,
313 tail: Tail::Dots(3),
314 ink_dim: ink,
315 ink_bright: ink,
316 ground,
317 rule: None,
318 pad_x: 12,
319 pad_y: 4,
320 centre_x: 160,
321 top: 208,
322 min_size: (0, 0),
323 step_ticks: 20,
324 pulse_ticks: 64,
325 blend: Blend::Additive,
326 across_q8: 256,
327 ring: (RING_DOT, RING_PITCH),
328 }
329 }
330
331 /// The same style breathing between `dim` and `bright`.
332 pub const fn with_breath(mut self, dim: Rgb, bright: Rgb) -> Self {
333 self.ink_dim = dim;
334 self.ink_bright = bright;
335 self
336 }
337
338 /// The same style with `tail` after the label.
339 pub const fn with_tail(mut self, tail: Tail) -> Self {
340 self.tail = tail;
341 self
342 }
343
344 /// The same style with its box centred on `centre_x`, top edge at `top`.
345 pub const fn at(mut self, centre_x: i16, top: i16) -> Self {
346 self.centre_x = centre_x;
347 self.top = top;
348 self
349 }
350
351 /// The same style as a square `size` pixels tall in the bottom-right corner of
352 /// a `screen_w` x `screen_h` picture, `margin` pixels in from the bottom edge:
353 /// the corner widget. With an empty label and a [`Tail::Spinner`] it is the small
354 /// black square with a ring of lights in it.
355 ///
356 /// The square is square on the screen. A mode whose pixels are not square (512
357 /// wide at 240 lines on a 4:3 set, say) makes the box wider in pixels by the
358 /// pixel aspect (see [`with_display`](Self::with_display), which this calls), and
359 /// the side margin is stretched the same way so both margins look alike.
360 pub const fn in_corner(mut self, size: i16, screen_w: i16, screen_h: i16, margin: i16) -> Self {
361 self = self.with_display(screen_w, screen_h);
362 let width = self.across(size as i32) as i16;
363 self.min_size = (width, size);
364 self.pad_x = 0;
365 self.pad_y = 0;
366 self.centre_x = screen_w - self.across(margin as i32) as i16 - width / 2;
367 self.top = screen_h - margin - size;
368 self
369 }
370
371 /// The same style told the display mode it is drawn in, `width` x `height`
372 /// pixels. A 4:3 television shows any mode at 4:3, so a pixel is
373 /// `(4 / 3) * height / width` times as wide as it is tall: square at 320 x 240
374 /// and 640 x 480, wide at 256 x 240, narrow at 512 x 240. The spinner and the
375 /// corner box are laid out in units one pixel tall and widened by that factor,
376 /// so they are square on the screen, not in the framebuffer.
377 #[must_use]
378 pub const fn with_display(mut self, width: i16, height: i16) -> Self {
379 let (w, h) = (
380 if width < 1 { 1 } else { width as i32 },
381 if height < 1 { 1 } else { height as i32 },
382 );
383 // 3 * w / (4 * h) in 1/256ths, rounded. A mode this far from 4:3 is not one a
384 // PS1 has; the clamp keeps the factor in a u16 anyway.
385 let q8 = (3 * w * 256 * 2 + 4 * h) / (8 * h);
386 self.across_q8 = if q8 > u16::MAX as i32 {
387 u16::MAX
388 } else {
389 q8 as u16
390 };
391 self
392 }
393
394 /// The same style with spinner dots `dot` units square, `pitch` units between
395 /// the centres of neighbouring dots (units are one pixel tall before
396 /// [`scaled`](Self::scaled); the ring is three pitches and a dot across).
397 #[must_use]
398 pub const fn with_ring(mut self, dot: i16, pitch: i16) -> Self {
399 self.ring = (
400 if dot < 1 { 1 } else { dot },
401 if pitch < 1 { 1 } else { pitch },
402 );
403 self
404 }
405
406 /// The same style with the spinner's lights blended by `blend`.
407 #[must_use]
408 pub const fn with_blend(mut self, blend: Blend) -> Self {
409 self.blend = blend;
410 self
411 }
412
413 /// `units` of height as pixels across, rounded: what makes a square on a 4:3 screen.
414 const fn across(&self, units: i32) -> i32 {
415 (units * self.across_q8 as i32 + 128) >> 8
416 }
417
418 /// Side of the spinner's ring in units of height (before scale).
419 const fn ring_side(&self) -> i32 {
420 (RING_SIDE_CELLS as i32 - 1) * self.ring.1 as i32 + self.ring.0 as i32
421 }
422
423 /// The ring's width and height in pixels.
424 #[must_use]
425 pub const fn ring_size(&self) -> (i16, i16) {
426 let side = self.ring_side() * self.scale as i32;
427 (self.across(side) as i16, side as i16)
428 }
429
430 /// The same style at integer scale `scale` (at least 1).
431 pub const fn scaled(mut self, scale: u8) -> Self {
432 self.scale = if scale == 0 { 1 } else { scale };
433 self
434 }
435
436 /// The same style with `rule` along the box's top edge.
437 pub const fn with_rule(mut self, rule: Rgb) -> Self {
438 self.rule = Some(rule);
439 self
440 }
441
442 /// The same style with `pad_x` and `pad_y` between the content and the box edge.
443 pub const fn padded(mut self, pad_x: i16, pad_y: i16) -> Self {
444 self.pad_x = pad_x;
445 self.pad_y = pad_y;
446 self
447 }
448
449 /// The same style with the tail stepping every `step_ticks` VBlanks (at
450 /// least 1) and a full breath taking `pulse_ticks`.
451 pub const fn timed(mut self, step_ticks: u16, pulse_ticks: u16) -> Self {
452 self.step_ticks = if step_ticks == 0 { 1 } else { step_ticks };
453 self.pulse_ticks = pulse_ticks;
454 self
455 }
456
457 /// The font's advance for ASCII `byte`, unscaled.
458 fn advance(&self, byte: u8) -> u8 {
459 self.font.glyph_advance(byte as char)
460 }
461
462 /// Pixel width of the content: the label, then the tail.
463 fn content_width(&self) -> i32 {
464 let label: i32 = self
465 .label
466 .bytes()
467 .map(|byte| self.advance(byte) as i32)
468 .sum();
469 let dots = self.tail.cells() * self.advance(b'.') as i32;
470 let text = (label + dots) * self.scale as i32;
471 let gap = if self.label.is_empty() {
472 0
473 } else {
474 SPINNER_GAP as i32 * self.scale as i32
475 };
476 match self.tail {
477 Tail::Spinner { .. } => text + gap + self.ring_size().0 as i32,
478 Tail::Art { width, .. } => text + gap + width as i32 * self.scale as i32,
479 _ => text,
480 }
481 }
482
483 /// Pixel height of the content: the label's row, or the spinner alone.
484 fn content_height(&self) -> i32 {
485 match self.tail {
486 Tail::Spinner { .. } if self.label.is_empty() => self.ring_size().1 as i32,
487 Tail::Art { height, .. } if self.label.is_empty() => height as i32 * self.scale as i32,
488 _ => self.font.glyph_h as i32 * self.scale as i32,
489 }
490 }
491
492 /// The box as `(x, y, width, height)` in screen pixels.
493 pub fn bounds(&self) -> (i16, i16, i16, i16) {
494 let width = (self.content_width() + 2 * self.pad_x as i32).max(self.min_size.0 as i32);
495 let height = (self.content_height() + 2 * self.pad_y as i32).max(self.min_size.1 as i32);
496 (
497 (self.centre_x as i32 - width / 2) as i16,
498 self.top,
499 width as i16,
500 height as i16,
501 )
502 }
503
504 /// The breathing period, kept even and at least twice [`LEVELS`].
505 const fn pulse(&self) -> u32 {
506 let ticks = if self.pulse_ticks < 2 * LEVELS as u16 {
507 2 * LEVELS as u16
508 } else {
509 self.pulse_ticks
510 };
511 (ticks & !1) as u32
512 }
513
514 /// The look at `tick` VBlanks after the indicator began.
515 ///
516 /// The tail steps once every `step_ticks` and repeats. The ink follows a
517 /// triangle wave: dim, up to bright at half a breath, back to dim. With a
518 /// steady ink (`ink_dim == ink_bright`) the level is held at 0, so the
519 /// picture only changes when the tail steps.
520 pub const fn look(&self, tick: u32) -> Look {
521 let step = ((tick / self.step_ticks as u32) % self.tail.steps()) as u8;
522 let level = if self.ink_dim.word() == self.ink_bright.word() {
523 0
524 } else {
525 let period = self.pulse();
526 let phase = tick % period;
527 let half = period / 2;
528 let up = if phase < half { phase } else { period - phase };
529 (up * LEVELS as u32 / half) as u8
530 };
531 Look { step, level }
532 }
533
534 /// The ink colour at `level`.
535 pub const fn ink(&self, level: u8) -> Rgb {
536 self.ink_dim.toward(self.ink_bright, level)
537 }
538}
539
540/// What the indicator shows at one tick.
541#[derive(Copy, Clone, Debug, PartialEq, Eq)]
542pub struct Look {
543 /// The tail step: dots lit for [`Tail::Dots`], the spinner frame for
544 /// [`Tail::Spinner`], always 0 for [`Tail::None`].
545 pub step: u8,
546 /// Ink level, `0` (dim) to [`LEVELS`] (bright).
547 pub level: u8,
548}
549
550/// The GP0 words that put the state the indicator's rectangles are drawn under
551/// to its defaults: mask bit off (E6h), plain draw mode (E1h).
552///
553/// Call it once before the first draw if the program's GPU state is unknown.
554/// The drawing area and offset are the caller's: they decide where in VRAM the
555/// box lands, and a program that draws into a back buffer sets them to the
556/// buffer the viewer is looking at.
557pub fn prepare(sink: &mut dyn Sink) {
558 sink.packet(&[0xe600_0000]);
559 sink.packet(&[0xe100_0000]);
560}
561
562/// A running indicator.
563#[derive(Copy, Clone, Debug)]
564pub struct Indicator {
565 style: Style,
566 start: u32,
567 shown: Option<Look>,
568}
569
570impl Indicator {
571 /// An indicator that has not begun.
572 pub const fn new(style: Style) -> Self {
573 Indicator {
574 style,
575 start: 0,
576 shown: None,
577 }
578 }
579
580 /// The style it was made with.
581 pub const fn style(&self) -> &Style {
582 &self.style
583 }
584
585 /// Restart the animation at `tick` and forget what is on screen, so the
586 /// next [`poll`](Self::poll) draws.
587 pub fn begin(&mut self, tick: u32) {
588 self.start = tick;
589 self.shown = None;
590 }
591
592 /// Forget what is on screen (the picture was cleared or replaced), so the
593 /// next [`poll`](Self::poll) draws again at once.
594 pub fn invalidate(&mut self) {
595 self.shown = None;
596 }
597
598 /// Draw if the picture at `tick` differs from what is on screen. Returns
599 /// whether it drew.
600 ///
601 /// The first poll after [`new`](Self::new), [`begin`](Self::begin) or
602 /// [`invalidate`](Self::invalidate) always draws. After that a poll draws
603 /// only when the tail stepped or the ink moved a level, and a poll at the
604 /// tick already shown does nothing. It never waits for a VBlank. Call it as
605 /// often as is convenient between steps of a blocking load, with a tick
606 /// that advances once per VBlank.
607 pub fn poll(&mut self, sink: &mut dyn Sink, tick: u32) -> bool {
608 // `wrapping_sub`: the VBlank counter wraps, the animation just goes on.
609 let look = self.style.look(tick.wrapping_sub(self.start));
610 if self.shown == Some(look) {
611 return false;
612 }
613 self.draw(sink, look);
614 self.shown = Some(look);
615 true
616 }
617
618 /// Draw `look` unconditionally.
619 pub fn draw(&self, sink: &mut dyn Sink, look: Look) {
620 let style = &self.style;
621 let (x, y, w, h) = style.bounds();
622 rect(sink, x, y, w, h, style.ground);
623 if let Some(rule) = style.rule {
624 rect(sink, x, y, w, 1, rule);
625 }
626 let ink = style.ink(look.level);
627 let scale = style.scale as i16;
628 // The content sits centred in the box (which is its size plus the
629 // padding unless `min_size` made it bigger).
630 let text_top = y + (h - style.content_height() as i16) / 2;
631 let mut pen = x + (w - style.content_width() as i16) / 2;
632 for byte in style.label.bytes() {
633 glyph(sink, style, pen, text_top, byte, ink);
634 pen += style.advance(byte) as i16 * scale;
635 }
636 match style.tail {
637 Tail::None => {}
638 Tail::Dots(n) => {
639 let mut dot = 0;
640 while dot < n.min(look.step) {
641 glyph(sink, style, pen, text_top, b'.', ink);
642 pen += style.advance(b'.') as i16 * scale;
643 dot += 1;
644 }
645 }
646 Tail::Spinner { lit, unlit } => {
647 // Centred on the text's height, not sharing its baseline.
648 let rows = style.content_height() as i16;
649 let top = text_top + (rows - style.ring_size().1) / 2;
650 let gap = if style.label.is_empty() {
651 0
652 } else {
653 SPINNER_GAP
654 };
655 ring(sink, style, pen + gap * scale, top, look.step, lit, unlit);
656 }
657 Tail::Art { height, draw, .. } => {
658 let rows = style.content_height() as i16;
659 let top = text_top + (rows - height * scale) / 2;
660 let gap = if style.label.is_empty() {
661 0
662 } else {
663 SPINNER_GAP
664 };
665 draw(sink, pen + gap * scale, top, look.step);
666 }
667 }
668 }
669}
670
671/// One solid rectangle, GP0(60h): the building block for a game's own [`Tail::Art`].
672pub fn rect(sink: &mut dyn Sink, x: i16, y: i16, w: i16, h: i16, colour: Rgb) {
673 if w <= 0 || h <= 0 {
674 return;
675 }
676 sink.packet(&[
677 0x6000_0000 | colour.word(),
678 (y as u16 as u32) << 16 | x as u16 as u32,
679 (h as u16 as u32) << 16 | w as u16 as u32,
680 ]);
681}
682
683/// One solid semi-transparent rectangle, GP0(62h): blended with what is under it
684/// by the mode last set with [`blend_mode`].
685fn rect_blended(sink: &mut dyn Sink, x: i16, y: i16, w: i16, h: i16, colour: Rgb) {
686 if w <= 0 || h <= 0 {
687 return;
688 }
689 sink.packet(&[
690 0x6200_0000 | colour.word(),
691 (y as u16 as u32) << 16 | x as u16 as u32,
692 (h as u16 as u32) << 16 | w as u16 as u32,
693 ]);
694}
695
696/// GP0(E1h) with semi-transparency mode `mode` (0 to 3) and everything else at the
697/// state [`prepare`] leaves.
698fn blend_mode(sink: &mut dyn Sink, mode: Option<u32>) {
699 sink.packet(&[0xe100_0000 | mode.unwrap_or(0) << 5]);
700}
701
702/// `colour` at `level` out of 256 of its strength.
703const fn dimmed(colour: Rgb, level: u16) -> Rgb {
704 const fn channel(value: u8, level: u16) -> u8 {
705 (value as u32 * level as u32 / 256) as u8
706 }
707 Rgb(
708 channel(colour.0, level),
709 channel(colour.1, level),
710 channel(colour.2, level),
711 )
712}
713
714/// The cell `(col, row)` of the ring as a pixel rectangle `(x, y, w, h)` from the
715/// ring's top left corner `(x0, y0)`.
716fn ring_cell(style: &Style, x0: i16, y0: i16, col: u8, row: u8) -> (i16, i16, i16, i16) {
717 let (dot, pitch) = (style.ring.0 as i32, style.ring.1 as i32);
718 let scale = style.scale as i32;
719 let left = style.across((col as i32 * pitch) * scale);
720 let right = style.across((col as i32 * pitch + dot) * scale);
721 let top = row as i32 * pitch * scale;
722 let bottom = (row as i32 * pitch + dot) * scale;
723 (
724 x0 + left as i16,
725 y0 + top as i16,
726 (right - left) as i16,
727 (bottom - top) as i16,
728 )
729}
730
731/// One frame of the ring: every cell as an `unlit` dot, then the head light at cell
732/// `frame` and its fading tail behind it (towards lower cell numbers, that is
733/// counter-clockwise behind a clockwise head), each blended as the style says.
734fn ring(sink: &mut dyn Sink, style: &Style, x: i16, y: i16, frame: u8, lit: Rgb, unlit: Rgb) {
735 for &(col, row) in &RING {
736 let (cx, cy, cw, ch) = ring_cell(style, x, y, col, row);
737 rect(sink, cx, cy, cw, ch, unlit);
738 }
739 let mode = style.blend.mode();
740 if mode.is_some() {
741 blend_mode(sink, mode);
742 }
743 for (behind, &level) in TRAIL.iter().enumerate() {
744 let cell = (frame as usize + RING_CELLS - behind) % RING_CELLS;
745 let (col, row) = RING[cell];
746 let (cx, cy, cw, ch) = ring_cell(style, x, y, col, row);
747 if mode.is_some() {
748 rect_blended(sink, cx, cy, cw, ch, dimmed(lit, level));
749 } else {
750 rect(
751 sink,
752 cx,
753 cy,
754 cw,
755 ch,
756 unlit.toward(lit, (level as u32 * LEVELS as u32 / 256) as u8),
757 );
758 }
759 }
760 if mode.is_some() {
761 blend_mode(sink, None);
762 }
763}
764
765/// One glyph as rectangles: each row's runs of set pixels, rows with the same
766/// bits merged into one taller rectangle.
767fn glyph(sink: &mut dyn Sink, style: &Style, x: i16, y: i16, code: u8, ink: Rgb) {
768 let font = style.font;
769 let Some(index) = font.glyph_index(code as char) else {
770 return;
771 };
772 let scale = style.scale as i16;
773 let width = font.glyph_w as u32;
774 let mut row = 0u8;
775 while row < font.glyph_h {
776 let bits = font.glyph_row_packed(index, row);
777 let mut span = 1u8;
778 while row + span < font.glyph_h && font.glyph_row_packed(index, row + span) == bits {
779 span += 1;
780 }
781 let mut col = 0u32;
782 while col < width {
783 if bits & (1 << col) == 0 {
784 col += 1;
785 continue;
786 }
787 let start = col;
788 while col < width && bits & (1 << col) != 0 {
789 col += 1;
790 }
791 rect(
792 sink,
793 x + start as i16 * scale,
794 y + row as i16 * scale,
795 (col - start) as i16 * scale,
796 span as i16 * scale,
797 ink,
798 );
799 }
800 row += span;
801 }
802}
803
804#[cfg(test)]
805mod tests;