Skip to main content

sciart_core/
raster.rs

1//! Sub-cell rasters layered onto a [`Canvas`] (SPEC-001 CORE-R41, CORE-R42, CORE-R51,
2//! CORE-R55, CORE-R64, CORE-R65, CORE-R85, CORE-R86, CORE-R95, ADR-0010).
3//!
4//! - [`Dots`]: a braille lattice of 2 × 4 dots per cell, one ink per cell. With cells
5//!   ~2:1 tall ([`ASPECT`](crate::geom::ASPECT)) the dots are *square*, so line art,
6//!   particles and random walks are isotropic at 8× the cell resolution.
7//! - [`Pixels`]: two square pixels per cell drawn as half blocks, with the lower pixel
8//!   in the cell's background colour: 2× the vertical resolution with real colour, for
9//!   fields.
10//! - [`Density`]: an `f32` long-exposure buffer at `Dots` resolution, thresholded onto
11//!   a `Dots` lattice.
12//! - [`Glow`]: an `f32` long-exposure buffer at `Pixels` resolution, tone-mapped onto a
13//!   `Pixels` layer.
14//!
15//! All are plain row-major buffers sized in `resize` and allocation-free afterwards
16//! (GEN-R11). A scene draws into one, then `blit`s it onto the canvas; a cell holds a
17//! single glyph, so one region uses one raster.
18
19use crate::{Canvas, Glyph, GlyphMode, Ink, Role, Size, geom, ink};
20
21/// Bit of dot `(dx, dy)` within its braille cell, indexed `[dx][dy]`: standard Unicode
22/// dot numbering 1-2-3-7 down the left column and 4-5-6-8 down the right, dot `n` being
23/// bit `n − 1` (CORE-R41).
24const BRAILLE_BIT: [[u8; 4]; 2] = [[0x01, 0x02, 0x04, 0x40], [0x08, 0x10, 0x20, 0x80]];
25
26/// The braille bit of lattice dot `(x, y)` within its cell (CORE-R41).
27///
28/// With [`braille`], this lets a scene draw a lone dot with [`Canvas::put`] when it must
29/// *replace* a cell rather than merge into it (as a [`Dots`] layer would).
30#[inline]
31pub fn dot_bit(x: i32, y: i32) -> u8 {
32    BRAILLE_BIT[x.rem_euclid(Dots::CELL_W) as usize][y.rem_euclid(Dots::CELL_H) as usize]
33}
34
35/// The braille glyph `U+2800 + mask`, with an ASCII fallback graded by dot count:
36/// 1 ⇒ `.`, 2 ⇒ `:`, 3–4 ⇒ `+`, ≥ 5 ⇒ `#` (and 0 ⇒ ` `) (CORE-R41, GEN-R10).
37#[inline]
38pub fn braille(mask: u8) -> Glyph {
39    let ascii = match mask.count_ones() {
40        0 => ' ',
41        1 => '.',
42        2 => ':',
43        3 | 4 => '+',
44        _ => '#',
45    };
46    // U+2800..=U+28FF are all valid chars; the fallback is unreachable.
47    let ch = char::from_u32(0x2800 + u32::from(mask)).unwrap_or(ascii);
48    Glyph::new(ch, ascii)
49}
50
51/// How strongly an ink stands out, for picking a cell's one ink among its dots
52/// (CORE-R41): its `level`, except for a signed [`Role::Div`] field, whose zero sits at
53/// 128, so a deep negative lobe (low level) must beat a faint positive one, and a
54/// [`Role::Phase`] field, whose level is an angle: all its dots tie, so the last one set
55/// wins (CORE-R78).
56#[inline]
57fn intensity(ink: Ink) -> u8 {
58    match ink.role {
59        Role::Div => ink.level.abs_diff(128),
60        Role::Phase => 0,
61        _ => ink.level,
62    }
63}
64
65/// The more intense of two inks, `a` on a tie, by the measure a [`Dots`] cell uses to
66/// pick its ink (CORE-R87): the one colour to keep when a cell's two pixels must become a
67/// single glyph (a [`Pixels::blit`] ASCII fallback) or a single background
68/// ([`Pixels::cell_bg`]). An empty ink loses to any drawn one.
69#[inline]
70pub fn stronger(a: Ink, b: Ink) -> Ink {
71    match (is_empty(a), is_empty(b)) {
72        (_, true) => a,
73        (true, false) => b,
74        (false, false) if intensity(b) > intensity(a) => b,
75        (false, false) => a,
76    }
77}
78
79/// Whether stipple dot `(x, y)` of layer `salt` is kept at density `p` (CORE-R107): the
80/// dot's fixed uniform `hash01(salt ^ cell_key(x, y))` is below `p`. Each dot's threshold
81/// never changes, so a cloud drawn this way holds still, and a density that changes
82/// smoothly only adds or removes dots where it crosses their thresholds (no shimmer, few
83/// changed cells per frame). `p ≤ 0` or NaN keeps nothing; `p ≥ 1` keeps every dot.
84#[inline]
85pub fn stipple_keep(salt: u64, x: i32, y: i32, p: f64) -> bool {
86    p > 0.0 && crate::rng::hash01(salt ^ crate::rng::cell_key(x, y)) < p
87}
88
89/// The ASCII brightness ramp of [`ascii_ramp_cell`], dimmest first.
90pub const ASCII_RAMP: [char; 9] = ['.', ':', '-', '=', '+', '*', '#', '%', '@'];
91
92/// A [`Pixels::blit`] ASCII fallback for half-block pictures of light (CORE-R91): the
93/// [`stronger`] of the cell's two pixels, drawn as its level on [`ASCII_RAMP`]
94/// (`level · 9 / 256`) in that pixel's ink; `None` (cell untouched) when both are empty.
95/// Lifted out of black_hole, which gravitational_lensing imported it from (M12).
96#[inline]
97pub fn ascii_ramp_cell(top: Ink, bottom: Ink) -> Option<(char, Ink)> {
98    let ink = stronger(top, bottom);
99    if is_empty(ink) {
100        return None;
101    }
102    Some((
103        ASCII_RAMP[usize::from(ink.level) * ASCII_RAMP.len() / 256],
104        ink,
105    ))
106}
107
108/// Share of the square pixel `(x, y)` (spanning `[x, x + 1) × [y, y + 1)`) inside the
109/// circle of radius `r` about `c` (CORE-R95), estimated from the pixel centre's distance
110/// `d` as `clamp(r + ½ − d, 0, 1)`: one `hypot` per pixel, exact for a straight edge
111/// through the centre and symmetric about the circle's centre. NaN input ⇒ 0.
112#[inline]
113pub fn disc_cover(x: i32, y: i32, c: (f64, f64), r: f64) -> f64 {
114    let d = (f64::from(x) + 0.5 - c.0).hypot(f64::from(y) + 0.5 - c.1);
115    // `f64::min` would turn a NaN distance into full cover; compare first.
116    let cover = r + 0.5 - d;
117    if cover > 0.0 { cover.min(1.0) } else { 0.0 }
118}
119
120/// Call `f(x, y, cover)` for every pixel the disc of radius `r` about `c` covers
121/// (`disc_cover > 0`, CORE-R95), row by row, left to right: the one anti-aliased disc
122/// walk for half-block `Pixels` pictures of suns, moons and planets. Pixel coordinates
123/// are unclipped; `f` ignores the ones off its buffer. Non-finite input or `r < 0` visits
124/// nothing.
125pub fn disc_pixels(c: (f64, f64), r: f64, mut f: impl FnMut(i32, i32, f64)) {
126    if !(c.0.is_finite() && c.1.is_finite() && r.is_finite()) || r < 0.0 {
127        return;
128    }
129    let reach = r + 0.5;
130    let (x0, x1) = ((c.0 - reach).floor() as i32, (c.0 + reach).ceil() as i32);
131    let (y0, y1) = ((c.1 - reach).floor() as i32, (c.1 + reach).ceil() as i32);
132    for y in y0..=y1 {
133        for x in x0..=x1 {
134            let cover = disc_cover(x, y, c, r);
135            if cover > 0.0 {
136                f(x, y, cover);
137            }
138        }
139    }
140}
141
142/// Walk the dots of the segment `(x0, y0)–(x1, y1)` on a `lattice`-sized dot grid
143/// (CORE-R51), calling `f` for each; `f` must ignore off-lattice dots.
144///
145/// Endpoints are rounded and joined by [`geom::line`]. When both lie within a margin of
146/// `w + h` around the lattice the walk is the exact unclipped Bresenham segment (the
147/// off-lattice part costs at most `3·(w + h)` steps). Farther endpoints are first
148/// clipped to that margin box (Liang–Barsky), so the walk length is bounded whatever
149/// the input; that only shifts the Bresenham phase of lines that are already wild.
150fn segment(x0: f64, y0: f64, x1: f64, y1: f64, lattice: Size, mut f: impl FnMut(i32, i32)) {
151    if !(x0.is_finite() && y0.is_finite() && x1.is_finite() && y1.is_finite()) {
152        return;
153    }
154    let (w, h) = (i32::from(lattice.width()), i32::from(lattice.height()));
155    let m = f64::from(w + h);
156    let (lo_x, hi_x) = (-m, f64::from(w) + m);
157    let (lo_y, hi_y) = (-m, f64::from(h) + m);
158    let inside = |x: f64, y: f64| (lo_x..=hi_x).contains(&x) && (lo_y..=hi_y).contains(&y);
159
160    let (mut a, mut b) = ((x0.round(), y0.round()), (x1.round(), y1.round()));
161    if !(inside(a.0, a.1) && inside(b.0, b.1)) {
162        // Parametrise p(t) = p0 + t·(p1 − p0)/2 for t ∈ [0, 2]: the halved difference
163        // cannot overflow even for endpoints at ±f64::MAX.
164        let (dx, dy) = (x1 * 0.5 - x0 * 0.5, y1 * 0.5 - y0 * 0.5);
165        let (mut t0, mut t1) = (0.0f64, 2.0f64);
166        for (p, q) in [
167            (-dx, x0 - lo_x),
168            (dx, hi_x - x0),
169            (-dy, y0 - lo_y),
170            (dy, hi_y - y0),
171        ] {
172            if p == 0.0 {
173                if q < 0.0 {
174                    return; // parallel to this edge and outside it
175                }
176            } else if p < 0.0 {
177                t0 = t0.max(q / p);
178            } else {
179                t1 = t1.min(q / p);
180            }
181        }
182        if t0 > t1 {
183            return;
184        }
185        // Clamp away the last ulps of round-off so the casts below stay in range.
186        let at = |t: f64| {
187            (
188                (x0 + t * dx).round().clamp(lo_x, hi_x),
189                (y0 + t * dy).round().clamp(lo_y, hi_y),
190            )
191        };
192        (a, b) = (at(t0), at(t1));
193    }
194    // Both endpoints are within the margin box, so the walk has at most
195    // max(w, h) + 2m + 1 ≤ 4·(w + h) points; the `take` only guards the arithmetic.
196    let cap = 4 * (w as usize + h as usize);
197    for (x, y) in geom::line(a.0 as i32, a.1 as i32, b.0 as i32, b.1 as i32).take(cap) {
198        f(x, y);
199    }
200}
201
202/// `n` cells times `k` sub-cells per cell, saturated to a `u16` axis.
203fn sub_axis(n: u16, k: u32) -> u16 {
204    u16::try_from(u32::from(n) * k).unwrap_or(u16::MAX)
205}
206
207/// A braille dot lattice: `2·w × 4·h` square dots over a `w × h` cell region (CORE-R41).
208///
209/// Each cell stores its dot mask and one ink, that of its most intense lit dot (highest
210/// `level`, or `|level − 128|` for [`Role::Div`]; ties go to the dot set last), since a
211/// terminal cell has one colour.
212/// Masks and inks are separate arrays so `blit` scans a dense byte array, which is
213/// mostly zeros for sparse line art.
214#[derive(Debug, Clone)]
215pub struct Dots {
216    cells: Size,
217    masks: Vec<u8>,
218    inks: Vec<Ink>,
219}
220
221impl Default for Dots {
222    /// A 1×1-cell lattice, the placeholder until a scene's first `resize`.
223    fn default() -> Self {
224        Self::new(Size::new(1, 1))
225    }
226}
227
228impl Dots {
229    /// Dots per cell horizontally.
230    pub const CELL_W: i32 = 2;
231    /// Dots per cell vertically; `CELL_H / CELL_W = ASPECT` makes the dots square.
232    pub const CELL_H: i32 = 4;
233
234    /// An empty lattice over `cells` terminal cells.
235    pub fn new(cells: Size) -> Self {
236        Self {
237            cells,
238            masks: vec![0; cells.area()],
239            inks: vec![Ink::BLANK; cells.area()],
240        }
241    }
242
243    /// Dot coordinates of the continuous cell point `(x, y)`, where cell `i` spans
244    /// `[i, i + 1)` (CORE-R64): dot `j` is centred at cell `(j + ½) / CELL_W` across and
245    /// `(j + ½) / CELL_H` down, so [`plot`](Self::plot) lights the dot whose area holds
246    /// the point, inside the cell that holds it. The one cell → dot convention for every
247    /// scene; a cell *centre* `(cx + ½, cy + ½)` maps to the middle of its 2×4 block.
248    #[inline]
249    pub fn from_cells(x: f64, y: f64) -> (f64, f64) {
250        (
251            x * f64::from(Self::CELL_W) - 0.5,
252            y * f64::from(Self::CELL_H) - 0.5,
253        )
254    }
255
256    /// Lattice dimensions in dots, `2·w × 4·h` (saturated at `u16::MAX` per axis).
257    pub fn dot_size(&self) -> Size {
258        Size::new(
259            sub_axis(self.cells.width(), Self::CELL_W as u32),
260            sub_axis(self.cells.height(), Self::CELL_H as u32),
261        )
262    }
263
264    /// Resize to `cells` and clear. Reuses the buffers unless they must grow.
265    pub fn resize(&mut self, cells: Size) {
266        self.cells = cells;
267        self.masks.clear();
268        self.masks.resize(cells.area(), 0);
269        self.inks.clear();
270        self.inks.resize(cells.area(), Ink::BLANK);
271    }
272
273    /// Unlight every dot.
274    pub fn clear(&mut self) {
275        // A cell's ink is only read when its mask is non-zero, and `set` overwrites
276        // it for the first dot of a cell, so the inks need no reset.
277        self.masks.fill(0);
278    }
279
280    /// Cell index and bit of dot `(x, y)`, or `None` off the lattice.
281    #[inline]
282    fn locate(&self, x: i32, y: i32) -> Option<(usize, u8)> {
283        let w = i32::from(self.cells.width());
284        let h = i32::from(self.cells.height());
285        // `w · 2` and `h · 4` fit easily in i32 for u16 dimensions.
286        let in_x = (0..w * Self::CELL_W).contains(&x);
287        let in_y = (0..h * Self::CELL_H).contains(&y);
288        (in_x && in_y).then(|| {
289            let (cx, cy) = ((x / Self::CELL_W) as usize, (y / Self::CELL_H) as usize);
290            (cy * w as usize + cx, dot_bit(x, y))
291        })
292    }
293
294    /// Light dot `(x, y)` with `ink`; off-lattice dots are ignored.
295    #[inline]
296    pub fn set(&mut self, x: i32, y: i32, ink: Ink) {
297        let Some((i, bit)) = self.locate(x, y) else {
298            return;
299        };
300        if self.masks[i] == 0 || intensity(ink) >= intensity(self.inks[i]) {
301            self.inks[i] = ink;
302        }
303        self.masks[i] |= bit;
304    }
305
306    /// Light the dot nearest to `(x, y)` (dot units); non-finite or off-lattice points
307    /// are ignored, so simulation code never casts NaN to a coordinate.
308    #[inline]
309    pub fn plot(&mut self, x: f64, y: f64, ink: Ink) {
310        if x.is_finite() && y.is_finite() {
311            // Saturating casts: anything huge lands off the lattice.
312            self.set(x.round() as i32, y.round() as i32, ink);
313        }
314    }
315
316    /// Light dot `(x, y)` with `ink` when [`stipple_keep`]`(salt, x, y, p)` (CORE-R107): a
317    /// probability cloud sampled with fixed per-dot thresholds, as electron_orbitals'
318    /// clouds are. Off-lattice dots are ignored.
319    #[inline]
320    pub fn stipple(&mut self, x: i32, y: i32, p: f64, salt: u64, ink: Ink) {
321        if stipple_keep(salt, x, y, p) {
322            self.set(x, y, ink);
323        }
324    }
325
326    /// Light a small Gaussian stipple atom about `(cx, cy)` (dot units, CORE-R108): each dot
327    /// within `3σ` is kept by [`stipple_keep`] at `peak·e^(−r²/2σ²)`, and the dot nearest
328    /// the centre is always lit, so an atom never vanishes. The density only grows with
329    /// `sigma` and `peak`, so a swelling atom only gains dots. A non-finite or non-positive
330    /// `sigma` leaves just the centre dot; `peak ≤ 0` or a non-finite centre lights nothing.
331    pub fn stipple_puff(&mut self, cx: f64, cy: f64, sigma: f64, peak: f64, salt: u64, ink: Ink) {
332        if !(cx.is_finite() && cy.is_finite() && peak > 0.0) {
333            return;
334        }
335        self.plot(cx, cy, ink);
336        if !(sigma.is_finite() && sigma > 0.0) {
337            return;
338        }
339        let size = self.dot_size();
340        let (w, h) = (f64::from(size.width()), f64::from(size.height()));
341        let reach = 3.0 * sigma;
342        // Only the part of the bounding box on the lattice, so a huge σ stays bounded.
343        let x0 = (cx - reach).ceil().max(0.0);
344        let x1 = (cx + reach).floor().min(w - 1.0);
345        let y0 = (cy - reach).ceil().max(0.0);
346        let y1 = (cy + reach).floor().min(h - 1.0);
347        if x0 > x1 || y0 > y1 {
348            return;
349        }
350        let (reach2, k) = (reach * reach, -0.5 / (sigma * sigma));
351        for y in y0 as i32..=y1 as i32 {
352            let dy = f64::from(y) - cy;
353            for x in x0 as i32..=x1 as i32 {
354                let dx = f64::from(x) - cx;
355                let r2 = dx * dx + dy * dy;
356                if r2 <= reach2 {
357                    self.stipple(x, y, peak * (k * r2).exp(), salt, ink);
358                }
359            }
360        }
361    }
362
363    /// Light the Bresenham segment from `(x0, y0)` to `(x1, y1)` (dot units, rounded),
364    /// both endpoints inclusive, clipped to the lattice (CORE-R51). Non-finite endpoints
365    /// draw nothing, and the walk is capped at `4·(dot width + dot height)` steps, so
366    /// wild coordinates stay cheap.
367    pub fn line(&mut self, x0: f64, y0: f64, x1: f64, y1: f64, ink: Ink) {
368        let size = self.dot_size();
369        segment(x0, y0, x1, y1, size, |x, y| self.set(x, y, ink));
370    }
371
372    /// Light the filled disc of radius `r` (dot units, so round on screen) about `(x, y)`:
373    /// every dot whose centre lies within `r`, plus the dot nearest the centre, so a
374    /// radius below ½ is one dot (CORE-R82). Clipped to the lattice; a non-finite centre
375    /// or radius, or `r < 0`, lights nothing. Bobs, suns and grains in line-art scenes.
376    pub fn disc(&mut self, x: f64, y: f64, r: f64, ink: Ink) {
377        if !(x.is_finite() && y.is_finite() && r.is_finite() && r >= 0.0) {
378            return;
379        }
380        let size = self.dot_size();
381        let (w, h) = (f64::from(size.width()), f64::from(size.height()));
382        // Only the part of the bounding box on the lattice, so a huge r stays cheap.
383        let (x0, x1) = ((x - r).ceil().max(0.0), (x + r).floor().min(w - 1.0));
384        let (y0, y1) = ((y - r).ceil().max(0.0), (y + r).floor().min(h - 1.0));
385        let mut dy = y0;
386        while dy <= y1 {
387            let mut dx = x0;
388            while dx <= x1 {
389                if (dx - x).hypot(dy - y) <= r {
390                    self.set(dx as i32, dy as i32, ink);
391                }
392                dx += 1.0;
393            }
394            dy += 1.0;
395        }
396        self.plot(x, y, ink);
397    }
398
399    /// Draw the iso-contour `v = level` of a row-major `w × h` node field, one dot thick,
400    /// by marching squares (CORE-R105). `to_dot(x, y)` maps continuous node coordinates
401    /// (node `(i, j)` at `(i, j)`) to dot coordinates. Too-short fields and `w` or `h`
402    /// below 2 draw nothing; nothing allocates.
403    pub fn contour(
404        &mut self,
405        values: &[f32],
406        w: usize,
407        h: usize,
408        level: f32,
409        to_dot: impl Fn(f64, f64) -> (f64, f64),
410        ink: Ink,
411    ) {
412        self.contour_by(values, w, h, level, to_dot, |_, _| Some(ink));
413    }
414
415    /// [`contour`](Self::contour) with the ink chosen per cell of four nodes: `ink(i, j)`
416    /// is asked only for cells the level crosses (`(i, j)` the top-left node) and `None`
417    /// skips the cell, so a contour can be coloured by sign, age or a sampled variable.
418    pub fn contour_by(
419        &mut self,
420        values: &[f32],
421        w: usize,
422        h: usize,
423        level: f32,
424        to_dot: impl Fn(f64, f64) -> (f64, f64),
425        mut ink: impl FnMut(usize, usize) -> Option<Ink>,
426    ) {
427        if w < 2 || h < 2 || values.len() < w.saturating_mul(h) {
428            return;
429        }
430        for j in 0..h - 1 {
431            let (top, bottom) = (
432                &values[j * w..(j + 1) * w],
433                &values[(j + 1) * w..(j + 2) * w],
434            );
435            for i in 0..w - 1 {
436                let l = [top[i], top[i + 1], bottom[i + 1], bottom[i]];
437                let below = l.map(|v| v < level);
438                if below == [true; 4] || below == [false; 4] {
439                    continue;
440                }
441                if let Some(ink) = ink(i, j) {
442                    self.contour_cell(l, level, (i, j), &to_dot, ink);
443                }
444            }
445        }
446    }
447
448    /// Draw the level set `v = level` inside one cell of four nodes (CORE-R105), for
449    /// scenes that cull cells themselves. `corners` are the values at nodes `(i, j)`,
450    /// `(i+1, j)`, `(i+1, j+1)`, `(i, j+1)` (clockwise on screen); a node is below the level
451    /// when `v < level`. Each straddling edge's crossing is linearly interpolated, and the
452    /// crossings are joined by [`line`](Self::line): two crossings make one piece, four (a
453    /// saddle) two, paired in edge order. Non-finite corners draw nothing.
454    pub fn contour_cell(
455        &mut self,
456        corners: [f32; 4],
457        level: f32,
458        (i, j): (usize, usize),
459        to_dot: impl Fn(f64, f64) -> (f64, f64),
460        ink: Ink,
461    ) {
462        const AT: [(f64, f64); 4] = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)];
463        if !corners.iter().all(|v| v.is_finite()) || !level.is_finite() {
464            return;
465        }
466        let mut pts = [(0.0f64, 0.0f64); 4];
467        let mut n = 0;
468        for a in 0..4 {
469            let b = (a + 1) % 4;
470            let (la, lb) = (corners[a], corners[b]);
471            if (la < level) != (lb < level) {
472                let f = f64::from((level - la) / (lb - la));
473                let (pa, pb) = (AT[a], AT[b]);
474                let (x, y) = (pa.0 + (pb.0 - pa.0) * f, pa.1 + (pb.1 - pa.1) * f);
475                pts[n] = to_dot(i as f64 + x, j as f64 + y);
476                n += 1;
477            }
478        }
479        for p in pts[..n].chunks_exact(2) {
480            self.line(p[0].0, p[0].1, p[1].0, p[1].1, ink);
481        }
482    }
483
484    /// [`contour_cell`](Self::contour_cell) with the cell refined into `k × k` sub-cells
485    /// whose corners are bilinear in the four node values (CORE-R106): where one node
486    /// spans many dots the level set is traced as a smooth curve (the bilinear surface's
487    /// own level set, to within `1/k` of a cell) instead of one straight chord per cell.
488    /// `k ≤ 1` is plain `contour_cell`; `k` is capped at 16. Sub-cells the level does not
489    /// cross are skipped; nothing allocates.
490    pub fn contour_cell_refined(
491        &mut self,
492        corners: [f32; 4],
493        level: f32,
494        (i, j): (usize, usize),
495        k: usize,
496        to_dot: impl Fn(f64, f64) -> (f64, f64),
497        ink: Ink,
498    ) {
499        let k = k.min(16);
500        if k <= 1 {
501            self.contour_cell(corners, level, (i, j), to_dot, ink);
502            return;
503        }
504        let c = corners;
505        let kf = k as f32;
506        // The bilinear value at sub-node (u, v) of the k × k grid.
507        let at = |u: usize, v: usize| {
508            let (a, b) = (u as f32 / kf, v as f32 / kf);
509            let top = c[0] + (c[1] - c[0]) * a;
510            let bottom = c[3] + (c[2] - c[3]) * a;
511            top + (bottom - top) * b
512        };
513        let (x0, y0, kd) = (i as f64, j as f64, k as f64);
514        let map = |x: f64, y: f64| to_dot(x0 + x / kd, y0 + y / kd);
515        for v in 0..k {
516            for u in 0..k {
517                let sub = [at(u, v), at(u + 1, v), at(u + 1, v + 1), at(u, v + 1)];
518                let below = sub.map(|x| x < level);
519                if below == [true; 4] || below == [false; 4] {
520                    continue;
521                }
522                self.contour_cell(sub, level, (u, v), map, ink);
523            }
524        }
525    }
526
527    /// Whether dot `(x, y)` is lit; `false` off the lattice.
528    pub fn is_lit(&self, x: i32, y: i32) -> bool {
529        self.locate(x, y)
530            .is_some_and(|(i, bit)| self.masks[i] & bit != 0)
531    }
532
533    /// The dot mask of cell `(cx, cy)` (bit layout as [`braille`]; 0 = no dot lit), or
534    /// `None` off the region (CORE-R64).
535    #[inline]
536    pub fn cell_mask(&self, cx: i32, cy: i32) -> Option<u8> {
537        let (w, h) = (
538            i32::from(self.cells.width()),
539            i32::from(self.cells.height()),
540        );
541        ((0..w).contains(&cx) && (0..h).contains(&cy))
542            .then(|| self.masks[cy as usize * w as usize + cx as usize])
543    }
544
545    /// Write every cell with at least one lit dot as its braille glyph (or the
546    /// dot-count ASCII fallback) and ink; cells with no lit dots are left untouched, so
547    /// a lattice layers over earlier drawing.
548    pub fn blit(&self, canvas: &mut Canvas) {
549        self.blit_with(canvas, |_, _| Ink::BLANK);
550    }
551
552    /// [`blit`](Self::blit) over a half-block layer (CORE-R84): each written cell gets
553    /// [`Pixels::cell_bg`] of `under` as its background, so a glow drawn as [`Pixels`]
554    /// carries on under a point cloud or a track instead of stopping at the first dotted
555    /// cell. `under` should cover the same cells; outside it the background is blank.
556    /// ASCII mode has no half blocks, so there it is plain `blit`.
557    pub fn blit_over(&self, canvas: &mut Canvas, under: &Pixels) {
558        if canvas.mode() == GlyphMode::Ascii {
559            self.blit(canvas);
560        } else {
561            self.blit_with(canvas, |x, y| under.cell_bg(x, y));
562        }
563    }
564
565    /// Write every lit cell `(x, y)` with `bg(x, y)` behind its dots.
566    fn blit_with(&self, canvas: &mut Canvas, mut bg: impl FnMut(i32, i32) -> Ink) {
567        const BLOCK: usize = 16;
568        let mut blocks = self.masks.chunks_exact(BLOCK);
569        let mut start = 0;
570        for block in &mut blocks {
571            if block != [0; BLOCK] {
572                self.blit_run(canvas, start, block, &mut bg);
573            }
574            start += BLOCK;
575        }
576        self.blit_run(canvas, start, blocks.remainder(), &mut bg);
577    }
578
579    /// Blit the cells `start..start + masks.len()` (row-major indices).
580    fn blit_run(
581        &self,
582        canvas: &mut Canvas,
583        start: usize,
584        masks: &[u8],
585        bg: &mut impl FnMut(i32, i32) -> Ink,
586    ) {
587        let w = usize::from(self.cells.width());
588        for (i, &mask) in (start..).zip(masks) {
589            if mask != 0 {
590                let (x, y) = ((i % w) as i32, (i / w) as i32);
591                canvas.put_bg(x, y, braille(mask), self.inks[i], bg(x, y));
592            }
593        }
594    }
595}
596
597/// A long-exposure `f32` buffer at [`Dots`] resolution (CORE-R55): particles and
598/// strokes [`deposit`](Self::deposit) weight into it, [`decay`](Self::decay) fades it,
599/// and [`to_dots`](Self::to_dots) thresholds it onto a lattice. For trails, attractor
600/// histograms and aurora curtains, where what matters is where things *have been*.
601#[derive(Debug, Clone)]
602pub struct Density {
603    /// Lattice size in dots.
604    dots: Size,
605    /// Row-major, `dots.w × dots.h`.
606    buf: Vec<f32>,
607}
608
609impl Default for Density {
610    /// A 1×1-cell buffer, the placeholder until a scene's first `resize`.
611    fn default() -> Self {
612        Self::new(Size::new(1, 1))
613    }
614}
615
616impl Density {
617    /// A zeroed buffer over `cells` terminal cells (`2·w × 4·h` dots).
618    pub fn new(cells: Size) -> Self {
619        let mut d = Self {
620            dots: Size::new(1, 1),
621            buf: Vec::new(),
622        };
623        d.resize(cells);
624        d
625    }
626
627    /// Buffer dimensions in dots, as [`Dots::dot_size`].
628    pub fn dot_size(&self) -> Size {
629        self.dots
630    }
631
632    /// Resize to `cells` and zero. Reuses the buffer unless it must grow.
633    pub fn resize(&mut self, cells: Size) {
634        self.dots = Size::new(
635            sub_axis(cells.width(), Dots::CELL_W as u32),
636            sub_axis(cells.height(), Dots::CELL_H as u32),
637        );
638        self.buf.clear();
639        self.buf.resize(self.dots.area(), 0.0);
640    }
641
642    /// Zero every dot.
643    pub fn clear(&mut self) {
644        self.buf.fill(0.0);
645    }
646
647    /// Multiply every value by `k`, clamped to `[0, 1]` (NaN leaves the buffer as is):
648    /// an exponential fade, `k = exp(−dt / τ)` per step.
649    pub fn decay(&mut self, k: f32) {
650        fade(&mut self.buf, k);
651    }
652
653    #[inline]
654    fn index(&self, x: i32, y: i32) -> Option<usize> {
655        let (w, h) = (i32::from(self.dots.width()), i32::from(self.dots.height()));
656        ((0..w).contains(&x) && (0..h).contains(&y))
657            .then(|| y as usize * usize::from(self.dots.width()) + x as usize)
658    }
659
660    #[inline]
661    fn add(&mut self, x: i32, y: i32, w: f32) {
662        if let Some(i) = self.index(x, y) {
663            self.buf[i] += w;
664        }
665    }
666
667    /// Add `w` at the dot nearest to `(x, y)` (dot units). Non-finite coordinates or
668    /// weights and off-buffer dots are ignored.
669    #[inline]
670    pub fn deposit(&mut self, x: f64, y: f64, w: f32) {
671        if x.is_finite() && y.is_finite() && w.is_finite() {
672            // Saturating casts: anything huge lands off the buffer.
673            self.add(x.round() as i32, y.round() as i32, w);
674        }
675    }
676
677    /// The value at dot `(x, y)`, or `None` off the buffer.
678    #[inline]
679    pub fn get(&self, x: i32, y: i32) -> Option<f32> {
680        self.index(x, y).map(|i| self.buf[i])
681    }
682
683    /// Light every dot whose value is `≥ threshold` on `dots` with `map(value)`, in one
684    /// row-major pass. `dots` should cover the same cells; dots outside it are skipped,
685    /// and a NaN threshold lights nothing.
686    pub fn to_dots(&self, dots: &mut Dots, threshold: f32, mut map: impl FnMut(f32) -> Ink) {
687        let w = usize::from(self.dots.width());
688        for (y, row) in self.buf.chunks_exact(w).enumerate() {
689            for (x, &v) in row.iter().enumerate() {
690                if v >= threshold {
691                    dots.set(x as i32, y as i32, map(v));
692                }
693            }
694        }
695    }
696}
697
698/// Multiply every value by `k`, clamped to `[0, 1]` (NaN leaves the values as they are):
699/// the shared fade of [`Density::decay`] and [`Glow::decay`].
700fn fade(buf: &mut [f32], k: f32) {
701    if k.is_nan() || k >= 1.0 {
702        return;
703    }
704    let k = k.max(0.0);
705    for v in buf {
706        *v *= k;
707    }
708}
709
710/// A long-exposure `f32` buffer at [`Pixels`] resolution, `w × 2·h` (CORE-R85): points
711/// [`splat`](Self::splat) weight into it by their [`Dots`] position, [`decay`](Self::decay)
712/// fades it, and scenes tone-map it themselves through [`values`](Self::values) and
713/// [`Tone::level`]. A soft glow under a point cloud or an event display, at an eighth of a
714/// [`Density`]'s memory (one value per pixel instead of per dot).
715#[derive(Debug, Clone)]
716pub struct Glow {
717    /// Buffer size in pixels.
718    px: Size,
719    /// Row-major, `px.w × px.h`.
720    buf: Vec<f32>,
721}
722
723impl Default for Glow {
724    /// A 1×1-cell buffer, the placeholder until a scene's first `resize`.
725    fn default() -> Self {
726        Self::new(Size::new(1, 1))
727    }
728}
729
730impl Glow {
731    /// A pixel is this many dots across and down (a cell is 2 × 4 dots and 1 × 2 pixels).
732    const DOTS_PER_PIXEL: i32 = 2;
733
734    /// A zeroed buffer over `cells` terminal cells (`w × 2·h` pixels).
735    pub fn new(cells: Size) -> Self {
736        let mut g = Self {
737            px: Size::new(1, 1),
738            buf: Vec::new(),
739        };
740        g.resize(cells);
741        g
742    }
743
744    /// Buffer dimensions in pixels, as [`Pixels::pixel_size`].
745    pub fn pixel_size(&self) -> Size {
746        self.px
747    }
748
749    /// Resize to `cells` and zero. Reuses the buffer unless it must grow.
750    pub fn resize(&mut self, cells: Size) {
751        self.px = Size::new(cells.width(), sub_axis(cells.height(), 2));
752        self.buf.clear();
753        self.buf.resize(self.px.area(), 0.0);
754    }
755
756    /// Zero every pixel.
757    pub fn clear(&mut self) {
758        self.buf.fill(0.0);
759    }
760
761    /// Multiply every value by `k`, clamped to `[0, 1]` (NaN leaves the buffer as is):
762    /// an exponential fade, `k = exp(−dt / τ)` per step.
763    pub fn decay(&mut self, k: f32) {
764        fade(&mut self.buf, k);
765    }
766
767    /// Add `scale · w` to pixel `(px + dx, py + dy)` for each `(dx, dy, w)` of `kernel`,
768    /// where `(px, py)` is the pixel holding dot `(x, y)` (dot units, rounded to the
769    /// nearest dot; a pixel is 2 × 2 dots). Non-finite coordinates or weights and
770    /// off-buffer pixels are ignored.
771    pub fn splat(&mut self, x: f64, y: f64, kernel: &[(i32, i32, f32)], scale: f32) {
772        if !(x.is_finite() && y.is_finite()) {
773            return;
774        }
775        // Saturating casts: anything huge lands off the buffer.
776        let (px, py) = (
777            (x.round() as i32).div_euclid(Self::DOTS_PER_PIXEL),
778            (y.round() as i32).div_euclid(Self::DOTS_PER_PIXEL),
779        );
780        let (w, h) = (i32::from(self.px.width()), i32::from(self.px.height()));
781        for &(dx, dy, k) in kernel {
782            let (x, y) = (px.saturating_add(dx), py.saturating_add(dy));
783            let add = scale * k;
784            if (0..w).contains(&x) && (0..h).contains(&y) && add.is_finite() {
785                self.buf[y as usize * w as usize + x as usize] += add;
786            }
787        }
788    }
789
790    /// Add `w` at continuous **pixel** position `(x, y)` (integers are pixel centres; the
791    /// centre of the pixel holding dot `(dx, dy)` is `((dx − 0.5)/2, (dy − 0.5)/2)`),
792    /// split bilinearly over the four nearest pixels (CORE-R92). Motion below a pixel stays
793    /// smooth and a moving source leaves no nearest-pixel stair steps; the in-bounds share
794    /// of `w` is conserved. Non-finite input and off-buffer pixels are ignored.
795    #[inline]
796    pub fn splat_bilinear(&mut self, x: f64, y: f64, w: f32) {
797        if !(x.is_finite() && y.is_finite() && w.is_finite()) {
798            return;
799        }
800        let (pw, ph) = (usize::from(self.px.width()), usize::from(self.px.height()));
801        let (x0, y0) = (x.floor(), y.floor());
802        let (fx, fy) = ((x - x0) as f32, (y - y0) as f32);
803        for (dx, dy, k) in [
804            (0.0, 0.0, (1.0 - fx) * (1.0 - fy)),
805            (1.0, 0.0, fx * (1.0 - fy)),
806            (0.0, 1.0, (1.0 - fx) * fy),
807            (1.0, 1.0, fx * fy),
808        ] {
809            let (px, py) = (x0 + dx, y0 + dy);
810            // Saturating casts: anything huge fails the bounds check.
811            if px >= 0.0 && py >= 0.0 && (px as usize) < pw && (py as usize) < ph {
812                self.buf[py as usize * pw + px as usize] += w * k;
813            }
814        }
815    }
816
817    /// Every pixel value, row-major (`pixel_size().width()` per row).
818    #[inline]
819    pub fn values(&self) -> &[f32] {
820        &self.buf
821    }
822
823    /// The value at pixel `(x, y)`, or `None` off the buffer.
824    #[inline]
825    pub fn get(&self, x: i32, y: i32) -> Option<f32> {
826        let (w, h) = (i32::from(self.px.width()), i32::from(self.px.height()));
827        ((0..w).contains(&x) && (0..h).contains(&y))
828            .then(|| self.buf[y as usize * w as usize + x as usize])
829    }
830}
831
832/// An asinh tone curve for long exposures, tabulated so that a lookup costs one `sqrt`
833/// (CORE-R81): linear for faint values, logarithmic for bright ones (Lupton et al. 2004),
834/// so a sparse trail and a dense core both read without clipping. Inline and allocation-
835/// free, so a scene can rebuild it in `resize`.
836#[derive(Debug, Clone)]
837pub struct Tone {
838    /// `1 / white`: a value's position along the table is `√(v / white)`.
839    inv_white: f32,
840    /// Levels at `v = white · (i / (LUT − 1))²`: finest near zero, where asinh is steepest.
841    lut: [u8; Tone::LUT],
842}
843
844impl Default for Tone {
845    /// `Tone::asinh(1, 1)`, the fallback curve.
846    fn default() -> Self {
847        Self::asinh(1.0, 1.0)
848    }
849}
850
851impl Tone {
852    /// Table entries.
853    pub const LUT: usize = 1024;
854
855    /// `255 · asinh(v / knee) / asinh(white / knee)` on `[0, white]`, 255 above. A
856    /// non-finite or non-positive parameter becomes 1, and `knee` is raised to
857    /// `white / 1000`, the steepest stretch the table resolves to 2 levels.
858    pub fn asinh(knee: f32, white: f32) -> Self {
859        let sane = |v: f32| {
860            if v.is_finite() && v > 0.0 {
861                f64::from(v)
862            } else {
863                1.0
864            }
865        };
866        let white = sane(white);
867        let knee = sane(knee).max(white / 1000.0);
868        let norm = (white / knee).asinh();
869        let last = (Self::LUT - 1) as f64;
870        let lut = std::array::from_fn(|i| {
871            let s = i as f64 / last;
872            ink::level(255.0 * (white * s * s / knee).asinh() / norm)
873        });
874        Self {
875            inv_white: (1.0 / white) as f32,
876            lut,
877        }
878    }
879
880    /// The level of value `v`: 0 for `v ≤ 0` or NaN, 255 from `white` up.
881    #[inline]
882    pub fn level(&self, v: f32) -> u8 {
883        // No branches: √ of a negative or NaN is NaN and the saturating cast maps it to
884        // entry 0 (level 0); +∞ saturates to the last entry (255).
885        let pos = (v * self.inv_white).sqrt() * (Self::LUT - 1) as f32;
886        self.lut[(pos.round() as usize).min(Self::LUT - 1)]
887    }
888}
889
890/// Upper half block: the top pixel is the glyph, the bottom one the cell background.
891const UPPER: Glyph = Glyph::new('▀', '#');
892const LOWER: Glyph = Glyph::new('▄', '#');
893
894/// A half-block pixel buffer: `w × 2·h` square pixels over a `w × h` cell region
895/// (CORE-R42). [`Ink::BLANK`] (any [`Role::Background`] ink) is an empty pixel.
896#[derive(Debug, Clone)]
897pub struct Pixels {
898    cells: Size,
899    /// Row-major, `2·h` rows of `w`: pixel rows `2·cy` and `2·cy + 1` form cell row `cy`.
900    px: Vec<Ink>,
901}
902
903impl Default for Pixels {
904    /// A 1×1-cell buffer, the placeholder until a scene's first `resize`.
905    fn default() -> Self {
906        Self::new(Size::new(1, 1))
907    }
908}
909
910/// Empty pixels are left to the terminal background. Every `Background`-role ink counts,
911/// because the renderer paints that role as "no colour" (RND-R3): a half block in it
912/// would show up in the default foreground colour.
913#[inline]
914fn is_empty(ink: Ink) -> bool {
915    ink.role == Role::Background
916}
917
918impl Pixels {
919    /// An empty buffer over `cells` terminal cells.
920    pub fn new(cells: Size) -> Self {
921        Self {
922            cells,
923            px: vec![Ink::BLANK; 2 * cells.area()],
924        }
925    }
926
927    /// Buffer dimensions in pixels, `w × 2·h` (saturated at `u16::MAX`).
928    pub fn pixel_size(&self) -> Size {
929        Size::new(self.cells.width(), sub_axis(self.cells.height(), 2))
930    }
931
932    /// Resize to `cells` and clear. Reuses the buffer unless it must grow.
933    pub fn resize(&mut self, cells: Size) {
934        self.cells = cells;
935        self.px.clear();
936        self.px.resize(2 * cells.area(), Ink::BLANK);
937    }
938
939    /// Set every pixel to `ink`.
940    pub fn fill(&mut self, ink: Ink) {
941        self.px.fill(ink);
942    }
943
944    /// Empty every pixel.
945    pub fn clear(&mut self) {
946        self.fill(Ink::BLANK);
947    }
948
949    #[inline]
950    fn index(&self, x: i32, y: i32) -> Option<usize> {
951        let w = i32::from(self.cells.width());
952        let h = 2 * i32::from(self.cells.height());
953        ((0..w).contains(&x) && (0..h).contains(&y)).then(|| y as usize * w as usize + x as usize)
954    }
955
956    /// Set pixel `(x, y)`; off-buffer pixels are ignored.
957    #[inline]
958    pub fn set(&mut self, x: i32, y: i32, ink: Ink) {
959        if let Some(i) = self.index(x, y) {
960            self.px[i] = ink;
961        }
962    }
963
964    /// Pixel `(x, y)`, or `None` off the buffer.
965    #[inline]
966    pub fn get(&self, x: i32, y: i32) -> Option<Ink> {
967        self.index(x, y).map(|i| self.px[i])
968    }
969
970    /// The one ink that stands for cell `(x, y)`'s two pixels (CORE-R84): the
971    /// [`stronger`] of the two, or [`Ink::BLANK`] when both are empty or the cell is off
972    /// the buffer. [`Dots::blit_over`] puts it behind a cell's dots.
973    #[inline]
974    pub fn cell_bg(&self, x: i32, y: i32) -> Ink {
975        let px = |py: i32| self.get(x, py).unwrap_or(Ink::BLANK);
976        let ink = stronger(px(2 * y), px(2 * y + 1));
977        if is_empty(ink) { Ink::BLANK } else { ink }
978    }
979
980    /// Give every glyph already drawn over this buffer's pixels its cell's
981    /// [`cell_bg`](Self::cell_bg) as background (CORE-R86), so line art, sprites and
982    /// labels drawn after [`blit`](Self::blit) do not punch black boxes into a half-block
983    /// picture. Glyphs and inks are kept; cells that already have a background, half and
984    /// full blocks, and cells over empty pixels are left alone. Unicode only: an ASCII
985    /// canvas has no half blocks to match.
986    pub fn backdrop(&self, canvas: &mut Canvas) {
987        if canvas.mode() != GlyphMode::Unicode {
988            return;
989        }
990        let w = self.cells.width().min(canvas.size().width());
991        let h = self.cells.height().min(canvas.size().height());
992        for y in 0..i32::from(h) {
993            for x in 0..i32::from(w) {
994                let Some(&cell) = canvas.get(x, y) else {
995                    continue;
996                };
997                if cell.bg != Ink::BLANK || matches!(cell.ch, '▀' | '▄' | '█') {
998                    continue;
999                }
1000                let under = self.cell_bg(x, y);
1001                if under != Ink::BLANK {
1002                    canvas.put_bg(x, y, Glyph::ascii(cell.ch), cell.ink, under);
1003                }
1004            }
1005        }
1006    }
1007
1008    /// Set every pixel to `shader(x, y)`, row by row (CORE-R65): the `Pixels` analogue
1009    /// of [`draw::field`](crate::draw::field), for sampling a simulation lattice (e.g.
1010    /// through a [`SampleMap`](crate::SampleMap)) onto the display pixels.
1011    pub fn shade(&mut self, mut shader: impl FnMut(i32, i32) -> Ink) {
1012        let w = usize::from(self.cells.width());
1013        for (y, row) in self.px.chunks_exact_mut(w).enumerate() {
1014            for (x, px) in row.iter_mut().enumerate() {
1015                // Both fit: x < w ≤ u16::MAX, y < 2·h ≤ 2·u16::MAX.
1016                *px = shader(x as i32, y as i32);
1017            }
1018        }
1019    }
1020
1021    /// Fade a glow's faint fringe smoothly into the empty sky (CORE-R89, M14), so it ends
1022    /// in the terminal's black instead of a ramp's tinted floor, with no dither. A pixel of
1023    /// intensity `i` (as for [`stronger`]) below `floor` is emptied when `i < floor / 2`,
1024    /// and in the band `[floor / 2, floor)` its intensity becomes
1025    /// `i·smoothstep((i − floor/2)/(floor/2))` (a `Div` pixel keeps its sign about 128),
1026    /// emptied if that rounds to 0. The fade is a pure function of the pixel's own
1027    /// intensity, continuous and non-decreasing in it, so a uniform field stays uniform: no
1028    /// ordered or noise pattern. Pixels at or above `floor`, and `Phase` pixels (no
1029    /// intensity), are untouched; `floor = 0` changes nothing. Allocation-free.
1030    pub fn dissolve(&mut self, floor: u8) {
1031        let half = f64::from(floor) / 2.0;
1032        for px in &mut self.px {
1033            let i = intensity(*px);
1034            if is_empty(*px) || px.role == Role::Phase || i >= floor {
1035                continue;
1036            }
1037            let u = ((f64::from(i) - half) / half).clamp(0.0, 1.0);
1038            let faded = (f64::from(i) * u * u * (3.0 - 2.0 * u)).round() as u8;
1039            *px = match (faded, px.role) {
1040                (0, _) => Ink::BLANK,
1041                (f, Role::Div) if px.level >= 128 => Ink::new(Role::Div, 128 + f),
1042                (f, Role::Div) => Ink::new(Role::Div, 128 - f),
1043                (f, role) => Ink::new(role, f),
1044            };
1045        }
1046    }
1047
1048    /// Draw the buffer onto `canvas`, one cell per vertical pixel pair.
1049    ///
1050    /// Unicode mode: both pixels empty ⇒ cell untouched; top only ⇒ `▀` in the top ink;
1051    /// bottom only ⇒ `▄` in the bottom ink; both ⇒ `▀` with the top as foreground and
1052    /// the bottom as background. ASCII mode has no half blocks, so every cell goes
1053    /// through the scene's own `ascii(x, y, top, bottom)` fallback, whose `Some((ch,
1054    /// ink))` is written and `None` leaves the cell untouched (GEN-R10, ADR-0010).
1055    pub fn blit<F>(&self, canvas: &mut Canvas, mut ascii: F)
1056    where
1057        F: FnMut(i32, i32, Ink, Ink) -> Option<(char, Ink)>,
1058    {
1059        let w = usize::from(self.cells.width());
1060        let unicode = canvas.mode() == GlyphMode::Unicode;
1061        for (cy, pair) in self.px.chunks_exact(2 * w).enumerate() {
1062            let (tops, bottoms) = pair.split_at(w);
1063            for (cx, (&top, &bottom)) in tops.iter().zip(bottoms).enumerate() {
1064                let (x, y) = (cx as i32, cy as i32);
1065                if !unicode {
1066                    if let Some((ch, ink)) = ascii(x, y, top, bottom) {
1067                        canvas.put(x, y, Glyph::ascii(ch), ink);
1068                    }
1069                    continue;
1070                }
1071                half_block(canvas, x, y, top, bottom);
1072            }
1073        }
1074    }
1075}
1076
1077/// Draw one cell from its two pixels by the Unicode rule of [`Pixels::blit`] (CORE-R42),
1078/// for a scene that composites an overlay over a blitted buffer.
1079#[inline]
1080pub fn half_block(canvas: &mut Canvas, x: i32, y: i32, top: Ink, bottom: Ink) {
1081    match (is_empty(top), is_empty(bottom)) {
1082        (true, true) => {}
1083        (false, true) => canvas.put(x, y, UPPER, top),
1084        (true, false) => canvas.put(x, y, LOWER, bottom),
1085        (false, false) => canvas.put_bg(x, y, UPPER, top, bottom),
1086    }
1087}