sciart_core/title.rs
1//! Science titles: `Phenomenon · mechanism`, fitted and drawn at the bottom-left of every
2//! scene by [`Stage`](crate::Stage) (SPEC-001 CORE-R71..R75, ADR-0014).
3//!
4//! Everything here works on `&'static str` slices of `Meta.title` and the captions, so
5//! fitting and drawing never allocate (GEN-R11). The HUD (RND-R9) reuses [`Title::width`],
6//! [`Title::chars`] and [`ascii_of`] to write the same forms.
7
8use std::ops::Range;
9
10use unicode_width::UnicodeWidthStr;
11
12use crate::{Canvas, Generator, Glyph, Ink, Meta, Role, Size, ink};
13
14/// Splits a title into phenomenon and mechanism (CORE-R71).
15pub const SEPARATOR: &str = " · ";
16
17/// Rows below which no title is shown: on tiny canvases the art needs every row (CORE-R73).
18const MIN_HEIGHT: u16 = 6;
19/// Ink levels (CORE-R74): the phenomenon reads first, the mechanism recedes.
20const PHENOMENON_LEVEL: f64 = 170.0;
21const MECHANISM_LEVEL: f64 = 110.0;
22/// Ink level of every title-row readout (CORE-R76), and the level the whole title fades to
23/// once the viewer has had time to read it (CORE-R74): the numbers never outshine the
24/// scene's name, even after it has dimmed to stop competing with the art.
25pub const READOUT_LEVEL: u8 = 90;
26const DIM_FROM_S: f64 = 8.0;
27const DIM_OVER_S: f64 = 2.0;
28/// Blank cells between the title's text and a title-row readout's text (CORE-R76): with only
29/// the two pad cells between them, two grey runs read as one sentence.
30const READOUT_GAP: usize = 4;
31
32/// Which part of a title is shown (CORE-R72, CORE-R73).
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum Form {
35 /// The phenomenon alone: the short form.
36 Phenomenon,
37 /// `phenomenon · mechanism` (the phenomenon alone when the mechanism is empty).
38 Full,
39}
40
41/// A scene's live title: `Meta.title` split at [`SEPARATOR`], with the mechanism replaced
42/// by the live caption when there is one (CORE-R71).
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct Title {
45 pub phenomenon: &'static str,
46 /// Empty when the title has no separator and there is no caption.
47 pub mechanism: &'static str,
48}
49
50impl Title {
51 pub fn new(title: &'static str, caption: Option<&'static str>) -> Self {
52 let (phenomenon, mechanism) = title.split_once(SEPARATOR).unwrap_or((title, ""));
53 Self {
54 phenomenon,
55 mechanism: caption.unwrap_or(mechanism),
56 }
57 }
58
59 /// The live title of `g`: its `Meta.title` with its current caption (CORE-R71).
60 pub fn of(g: &(impl Generator + ?Sized)) -> Self {
61 Self::new(g.meta().title, g.caption())
62 }
63
64 /// The pieces of `form` in reading order: phenomenon, separator, mechanism (the last
65 /// two empty for the short form or an empty mechanism).
66 fn parts(&self, form: Form) -> [&'static str; 3] {
67 match form {
68 Form::Full if !self.mechanism.is_empty() => {
69 [self.phenomenon, SEPARATOR, self.mechanism]
70 }
71 _ => [self.phenomenon, "", ""],
72 }
73 }
74
75 /// Display width of `form` in cells (CORE-R72).
76 pub fn width(&self, form: Form) -> usize {
77 self.parts(form).iter().map(|s| s.width()).sum()
78 }
79
80 /// The chars of `form` in reading order, for callers that write it themselves
81 /// (the HUD maps them through [`ascii_of`]).
82 pub fn chars(&self, form: Form) -> impl Iterator<Item = char> + use<> {
83 let [a, b, c] = self.parts(form);
84 a.chars().chain(b.chars()).chain(c.chars())
85 }
86
87 /// The longest form that fits a canvas of `size`, or `None` (CORE-R73). A form fits
88 /// when it plus its gutter and pad cells take at most 3/5 of the width, so the title
89 /// never dominates the art; forms are shown whole, never clipped.
90 pub fn fit(&self, size: Size) -> Option<Form> {
91 if size.height() < MIN_HEIGHT {
92 return None;
93 }
94 let limit = usize::from(size.width()) * 3 / 5;
95 [Form::Full, Form::Phenomenon]
96 .into_iter()
97 .find(|&form| self.width(form) + 2 <= limit)
98 }
99
100 /// The narrowest canvas width from which [`fit`](Self::fit) always picks
101 /// [`Form::Full`] (at a tall enough height): `⌊3w/5⌋ ≥ n` ⇔ `w ≥ ⌈5n/3⌉`, with `n` the
102 /// full form plus its two pad cells (CORE-R73).
103 pub fn full_fits_from(&self) -> usize {
104 (5 * (self.width(Form::Full) + 2)).div_ceil(3)
105 }
106}
107
108/// The title charset and its one-cell ASCII fallback (CORE-R72): printable ASCII maps to
109/// itself, the separator dot and en dash to `-`, and the few accented vowels titles need
110/// to their plain vowel. Anything else is `None`, i.e. not allowed in a title (GEN-R12).
111pub const fn ascii_of(c: char) -> Option<char> {
112 match c {
113 ' '..='~' => Some(c),
114 '·' | '–' => Some('-'),
115 'á' => Some('a'),
116 'é' => Some('e'),
117 'ö' => Some('o'),
118 _ => None,
119 }
120}
121
122/// The row and columns [`draw`] writes for `title` on a canvas of `size` (gutter, text and
123/// pad), or `None` when the title is hidden (CORE-R74). Scenes keep their text out of it
124/// (GEN-R13).
125pub fn span(size: Size, title: &Title) -> Option<(i32, Range<i32>)> {
126 let form = title.fit(size)?;
127 let end = i32::try_from(title.width(form) + 2).unwrap_or(i32::MAX);
128 Some((i32::from(size.height()) - 1, 0..end))
129}
130
131/// The most chars a [`draw::label_right`](crate::draw::label_right) readout on the title
132/// row can hold while keeping [`READOUT_GAP`] blank cells from the title's text (GEN-R13),
133/// and at most half the row, so on narrow canvases the row stays art with a name and a
134/// number rather than one line of text. Scenes drop or shorten parts to fit.
135pub fn readout_room(size: Size, title: &Title) -> usize {
136 let w = usize::from(size.width());
137 // Cells left of the readout's text: the gutter and title text, then the gap; or only
138 // the readout's leading blank when there is no title.
139 let before = span(size, title).map_or(1, |(_, cols)| cols.len() - 1 + READOUT_GAP);
140 // One more for the readout's trailing blank in the last column.
141 w.saturating_sub(before + 1).min(w / 2)
142}
143
144/// The readout room a captioned scene can count on at `size` whatever its caption
145/// (CORE-R83): the least [`readout_room`] over its title with no caption and with each of
146/// `meta.captions`, at this width and every wider one. A readout sized by it therefore
147/// never comes and goes with the beat, and never grows as the terminal narrows (a
148/// narrower terminal can fall back to the shorter phenomenon-only title and free room).
149/// Scenes compute it in `resize`; it does not allocate.
150pub fn stable_readout_room(size: Size, meta: &Meta) -> usize {
151 let titles = || {
152 std::iter::once(None)
153 .chain(meta.captions.iter().copied().map(Some))
154 .map(|c| Title::new(meta.title, c))
155 };
156 // From this width up every title shows its full form, so its span is fixed and each
157 // `readout_room` only grows with the width: the minimum over wider widths is reached
158 // by this one.
159 let settled = titles().map(|t| t.full_fits_from()).max().unwrap_or(0);
160 let settled = u16::try_from(settled).unwrap_or(u16::MAX).max(size.width());
161 (size.width()..=settled)
162 .map(|w| {
163 let at = Size::new(w, size.height());
164 titles().map(|t| readout_room(at, &t)).min().unwrap_or(0)
165 })
166 .min()
167 .unwrap_or(0)
168}
169
170/// Draw the fitted title on the bottom row, laid out like `draw::label(canvas, 0, h − 1, …)`,
171/// dimming with its `age`, the scene seconds it has been on show (CORE-R74). Touches only
172/// the [`span`] cells, so the art keeps the rest of the row.
173pub fn draw(canvas: &mut Canvas, title: &Title, age: f64) {
174 let Some(form) = title.fit(canvas.size()) else {
175 return;
176 };
177 let age = if age.is_finite() { age } else { 0.0 };
178 let fade = ((age - DIM_FROM_S) / DIM_OVER_S).clamp(0.0, 1.0);
179 let dim = f64::from(READOUT_LEVEL);
180 let ink_at = |base: f64| Ink::new(Role::Text, ink::level(base + (dim - base) * fade));
181 let (phenomenon, rest) = (ink_at(PHENOMENON_LEVEL), ink_at(MECHANISM_LEVEL));
182
183 let y = i32::from(canvas.size().height()) - 1;
184 let gap = Glyph::ascii(' ');
185 canvas.put(0, y, gap, Ink::BLANK);
186 let mut x = 1;
187 for (part, ink) in title.parts(form).into_iter().zip([phenomenon, rest, rest]) {
188 for c in part.chars() {
189 // `?` only for chars outside the charset, which GEN-R12 keeps out of titles.
190 canvas.put(x, y, Glyph::new(c, ascii_of(c).unwrap_or('?')), ink);
191 x += 1;
192 }
193 }
194 canvas.put(x, y, gap, Ink::BLANK);
195}