Skip to main content

wackasm_opencomputers/
draw.rs

1//! Easy, efficient drawing: draw into a [`Canvas`] in your program's memory,
2//! then [`Canvas::present`] sends only what changed to the GPU, in as few
3//! calls as it can.
4//!
5//! ```no_run
6//! use wackasm_opencomputers::{draw::{Canvas, Rgb, Shapes}, prelude::*};
7//!
8//! let mut canvas = Canvas::new(Gpu::first().ok_or(Error::NoSuchComponent)?)?;
9//! canvas.clear(Rgb::BLACK);
10//! canvas.text(1, 0, "hello", Rgb::WHITE, Rgb::BLACK);
11//!
12//! // Half-block pixels: two square-ish pixels per character cell.
13//! let mut px = canvas.pixels();
14//! px.fill_circle(20, 12, 6, Rgb::hsv(0.12, 1.0, 1.0));
15//! px.line(0, 2, 40, 20, Rgb::new(0x33, 0xCC, 0xFF));
16//!
17//! // Braille dots: 2x4 per cell, one colour per cell.
18//! let mut dots = canvas.dots();
19//! dots.circle(60, 30, 10, Rgb::WHITE);
20//!
21//! let calls = canvas.present()?; // later presents only send changes
22//! # Ok::<(), Error>(())
23//! ```
24//!
25//! # Coordinates
26//!
27//! Everything here counts from **0** at the top left (OpenComputers' own GPU
28//! calls count from 1): cells are `0..width() x 0..height()`, half-block
29//! pixels `0..width() x 0..height() * 2`, and braille dots
30//! `0..width() * 2 x 0..height() * 4`. Drawing outside is clipped.
31//!
32//! # How drawing modes mix
33//!
34//! A cell holds one character with a foreground and a background colour.
35//! Half-block pixels turn a cell into `▀` (top pixel in front, bottom pixel
36//! behind); braille dots turn it into a braille character in one colour,
37//! over the cell's background. Writing one kind of graphics over another
38//! replaces it, keeping the cell's background colour.
39//!
40//! # What `present` sends
41//!
42//! It compares the canvas with what it last sent, and for each row writes
43//! the changed cells as runs: one `gpu.set` per run of cells sharing colours
44//! (a space matches any foreground), plus a colour change only when the
45//! colour differs from the last one set. So redrawing a moving sprite costs a
46//! few calls, not a screen's worth. With [`Canvas::double_buffered`], changes
47//! go to a GPU buffer first and reach the screen in one `bitblt`, which
48//! avoids tearing. If something else draws on the screen, call
49//! [`Canvas::invalidate`] so the next present redraws everything.
50
51#[cfg(feature = "async")]
52use crate::component::Component;
53use crate::{
54    components::Gpu,
55    error::Result,
56    value::Number,
57};
58
59/// A 24-bit colour. The GPU shows the nearest colour its tier supports.
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
61pub struct Rgb(pub u32);
62
63impl Rgb {
64    pub const BLACK: Rgb = Rgb(0x000000);
65    pub const WHITE: Rgb = Rgb(0xFFFFFF);
66    pub const GREY: Rgb = Rgb(0x808080);
67    pub const RED: Rgb = Rgb(0xFF0000);
68    pub const GREEN: Rgb = Rgb(0x00FF00);
69    pub const BLUE: Rgb = Rgb(0x0000FF);
70    pub const YELLOW: Rgb = Rgb(0xFFFF00);
71    pub const CYAN: Rgb = Rgb(0x00FFFF);
72    pub const MAGENTA: Rgb = Rgb(0xFF00FF);
73
74    pub const fn new(r: u8, g: u8, b: u8) -> Rgb {
75        Rgb(((r as u32) << 16) | ((g as u32) << 8) | b as u32)
76    }
77
78    pub const fn r(self) -> u8 {
79        (self.0 >> 16) as u8
80    }
81
82    pub const fn g(self) -> u8 {
83        (self.0 >> 8) as u8
84    }
85
86    pub const fn b(self) -> u8 {
87        self.0 as u8
88    }
89
90    /// From hue (0..1, wrapping), saturation and value (0..1).
91    pub fn hsv(hue: f64, saturation: f64, value: f64) -> Rgb {
92        let h = hue.rem_euclid(1.0) * 6.0;
93        let (s, v) = (saturation.clamp(0.0, 1.0), value.clamp(0.0, 1.0));
94        let c = v * s;
95        let x = c * (1.0 - (h % 2.0 - 1.0).abs());
96        let (r, g, b) = match h as u32 {
97            0 => (c, x, 0.0),
98            1 => (x, c, 0.0),
99            2 => (0.0, c, x),
100            3 => (0.0, x, c),
101            4 => (x, 0.0, c),
102            _ => (c, 0.0, x),
103        };
104        let m = v - c;
105        let byte = |f: f64| ((f + m) * 255.0).round().clamp(0.0, 255.0) as u8;
106        Rgb::new(byte(r), byte(g), byte(b))
107    }
108
109    /// The colour `t` (0..1) of the way from `self` to `other`.
110    pub fn lerp(self, other: Rgb, t: f64) -> Rgb {
111        let t = t.clamp(0.0, 1.0);
112        let mix = |a: u8, b: u8| (a as f64 + (b as f64 - a as f64) * t).round() as u8;
113        Rgb::new(mix(self.r(), other.r()), mix(self.g(), other.g()), mix(self.b(), other.b()))
114    }
115}
116
117impl From<Rgb> for Number {
118    fn from(c: Rgb) -> Number {
119        Number::Int(c.0 as i64)
120    }
121}
122
123const HALF: char = '▀';
124
125#[derive(Clone, Copy, Debug, PartialEq)]
126struct Cell {
127    ch: char,
128    fg: Rgb,
129    bg: Rgb,
130}
131
132/// One GPU call `present` makes.
133#[derive(Clone, Debug, PartialEq)]
134pub(crate) enum Op {
135    Fg(Rgb),
136    Bg(Rgb),
137    /// 1-based, as the GPU wants.
138    Text { x: i64, y: i64, text: String, vertical: bool },
139    Fill { x: i64, y: i64, w: i64, h: i64, ch: char },
140}
141
142struct Run {
143    len: usize,
144    changed: usize,
145    fg: Option<Rgb>,
146}
147
148struct Rect {
149    w: usize,
150    h: usize,
151    changed: usize,
152}
153
154/// A framebuffer for one GPU's screen; see the [module docs](self).
155pub struct Canvas {
156    gpu: Gpu,
157    w: usize,
158    h: usize,
159    cells: Vec<Cell>,
160    /// What the GPU shows (`None`: unknown, so it is sent next time).
161    shown: Vec<Option<Cell>>,
162    gpu_fg: Option<Rgb>,
163    gpu_bg: Option<Rgb>,
164    /// The GPU buffer changes go to first, with `double_buffered`.
165    vram: Option<Number>,
166}
167
168impl Canvas {
169    /// A canvas the size of the GPU's current resolution, at its deepest
170    /// colour depth.
171    pub fn new(gpu: Gpu) -> Result<Canvas> {
172        let (w, h) = gpu.get_resolution()?;
173        if let Ok(depth) = gpu.max_depth() {
174            let _ = gpu.set_depth(depth);
175        }
176        Ok(Canvas::with_size(gpu, w.as_i64().max(1) as usize, h.as_i64().max(1) as usize))
177    }
178
179    /// A canvas of `w` x `h` cells, drawn from the screen's top left corner.
180    /// Makes no GPU calls until [`Canvas::present`].
181    pub fn with_size(gpu: Gpu, w: usize, h: usize) -> Canvas {
182        let blank = Cell { ch: ' ', fg: Rgb::WHITE, bg: Rgb::BLACK };
183        Canvas {
184            gpu,
185            w,
186            h,
187            cells: vec![blank; w * h],
188            shown: vec![None; w * h],
189            gpu_fg: None,
190            gpu_bg: None,
191            vram: None,
192        }
193    }
194
195    /// Width in cells.
196    pub fn width(&self) -> usize {
197        self.w
198    }
199
200    /// Height in cells.
201    pub fn height(&self) -> usize {
202        self.h
203    }
204
205    pub fn gpu(&self) -> &Gpu {
206        &self.gpu
207    }
208
209    /// Composes each present in a GPU buffer and copies it to the screen in
210    /// one `bitblt`, so the screen never shows a half-drawn frame. Returns
211    /// `false` (and keeps drawing directly) if the GPU has no video memory to
212    /// spare. `double_buffered(false)` frees the buffer.
213    pub fn double_buffered(&mut self, on: bool) -> Result<bool> {
214        match (on, self.vram) {
215            (true, Some(_)) => Ok(true),
216            (true, None) => match self.gpu.allocate_buffer(Some(Number::from(self.w)), Some(Number::from(self.h))) {
217                Ok(id) => {
218                    self.vram = Some(id);
219                    // The buffer starts empty: send everything next time.
220                    self.invalidate();
221                    Ok(true)
222                }
223                Err(_) => Ok(false),
224            },
225            (false, Some(id)) => {
226                self.vram = None;
227                self.invalidate();
228                self.gpu.free_buffer(id).map(|_| false)
229            }
230            (false, None) => Ok(false),
231        }
232    }
233
234    /// Forgets what the screen shows, so the next present redraws every
235    /// cell. Call it after anything else draws on the screen.
236    pub fn invalidate(&mut self) {
237        self.shown.fill(None);
238        self.gpu_fg = None;
239        self.gpu_bg = None;
240    }
241
242    fn index(&self, x: i64, y: i64) -> Option<usize> {
243        (x >= 0 && y >= 0 && (x as usize) < self.w && (y as usize) < self.h).then(|| y as usize * self.w + x as usize)
244    }
245
246    /// The character and colours of cell (x, y).
247    pub fn get(&self, x: i64, y: i64) -> Option<(char, Rgb, Rgb)> {
248        self.index(x, y).map(|i| (self.cells[i].ch, self.cells[i].fg, self.cells[i].bg))
249    }
250
251    /// Sets one cell.
252    pub fn set(&mut self, x: i64, y: i64, ch: char, fg: Rgb, bg: Rgb) {
253        if let Some(i) = self.index(x, y) {
254            self.cells[i] = Cell { ch, fg, bg };
255        }
256    }
257
258    /// Every cell blank in `bg`.
259    pub fn clear(&mut self, bg: Rgb) {
260        self.cells.fill(Cell { ch: ' ', fg: Rgb::WHITE, bg });
261    }
262
263    /// Fills a rectangle of cells with `ch`.
264    #[allow(clippy::too_many_arguments)]
265    pub fn fill(&mut self, x: i64, y: i64, w: i64, h: i64, ch: char, fg: Rgb, bg: Rgb) {
266        for yy in y.max(0)..(y + h).min(self.h as i64) {
267            for xx in x.max(0)..(x + w).min(self.w as i64) {
268                self.set(xx, yy, ch, fg, bg);
269            }
270        }
271    }
272
273    /// Writes `text` from cell (x, y) rightwards, clipped at the edge.
274    pub fn text(&mut self, x: i64, y: i64, text: &str, fg: Rgb, bg: Rgb) {
275        for (i, ch) in text.chars().enumerate() {
276            self.set(x + i as i64, y, ch, fg, bg);
277        }
278    }
279
280    /// `text` centred on row `y`.
281    pub fn text_centered(&mut self, y: i64, text: &str, fg: Rgb, bg: Rgb) {
282        let x = (self.w as i64 - text.chars().count() as i64) / 2;
283        self.text(x.max(0), y, text, fg, bg);
284    }
285
286    /// Writes `text` from cell (x, y) downwards.
287    pub fn text_vertical(&mut self, x: i64, y: i64, text: &str, fg: Rgb, bg: Rgb) {
288        for (i, ch) in text.chars().enumerate() {
289            self.set(x, y + i as i64, ch, fg, bg);
290        }
291    }
292
293    /// The canvas as half-block pixels: `width() x height() * 2`.
294    pub fn pixels(&mut self) -> Pixels<'_> {
295        Pixels { canvas: self }
296    }
297
298    /// The canvas as braille dots: `width() * 2 x height() * 4`.
299    pub fn dots(&mut self) -> Dots<'_> {
300        Dots { canvas: self }
301    }
302
303    /// The GPU calls that bring the screen up to date, recording that they
304    /// were made.
305    ///
306    /// Greedy: from each changed cell not yet covered, in reading order, it
307    /// takes whichever covers the most changed cells of a horizontal run, a
308    /// vertical run (one `set` each) or a rectangle of identical cells (one
309    /// `fill`). Runs share a background and, except for spaces, a foreground.
310    pub(crate) fn plan(&mut self) -> Vec<Op> {
311        let (w, h) = (self.w, self.h);
312        let mut done: Vec<bool> = (0..w * h).map(|i| self.shown[i] == Some(self.cells[i])).collect();
313        let mut ops = Vec::new();
314        for y in 0..h {
315            for x in 0..w {
316                if done[y * w + x] {
317                    continue;
318                }
319                let across = self.run(&done, x, y, true);
320                let down = self.run(&done, x, y, false);
321                let rect = self.rect(&done, x, y);
322                let start = self.cells[y * w + x];
323                let (cells, op) = if rect.changed > across.changed.max(down.changed) {
324                    let cells: Vec<usize> =
325                        (y..y + rect.h).flat_map(|yy| (x..x + rect.w).map(move |xx| yy * w + xx)).collect();
326                    let op = Op::Fill { x: x as i64 + 1, y: y as i64 + 1, w: rect.w as i64, h: rect.h as i64, ch: start.ch };
327                    (cells, (op, start.bg, (start.ch != ' ').then_some(start.fg)))
328                } else {
329                    let (run, vertical) = if down.changed > across.changed { (down, true) } else { (across, false) };
330                    let cells: Vec<usize> =
331                        (0..run.len).map(|k| if vertical { (y + k) * w + x } else { y * w + x + k }).collect();
332                    let text: String = cells.iter().map(|&i| self.cells[i].ch).collect();
333                    (cells, (Op::Text { x: x as i64 + 1, y: y as i64 + 1, text, vertical }, start.bg, run.fg))
334                };
335                let (op, bg, fg) = op;
336                if self.gpu_bg != Some(bg) {
337                    ops.push(Op::Bg(bg));
338                    self.gpu_bg = Some(bg);
339                }
340                if let Some(fg) = fg
341                    && self.gpu_fg != Some(fg)
342                {
343                    ops.push(Op::Fg(fg));
344                    self.gpu_fg = Some(fg);
345                }
346                ops.push(op);
347                for i in cells {
348                    done[i] = true;
349                    self.shown[i] = Some(self.cells[i]);
350                }
351            }
352        }
353        ops
354    }
355
356    /// The run from (x, y) across or down: cells sharing the start's
357    /// background and a foreground (spaces match any), up to its last
358    /// changed cell.
359    fn run(&self, done: &[bool], x: usize, y: usize, across: bool) -> Run {
360        let bg = self.cells[y * self.w + x].bg;
361        let mut fg = None;
362        let (mut len, mut changed, mut fg_at_end) = (0, 0, None);
363        let limit = if across { self.w - x } else { self.h - y };
364        let mut seen = 0;
365        for k in 0..limit {
366            let i = if across { y * self.w + x + k } else { (y + k) * self.w + x };
367            let cell = self.cells[i];
368            if cell.bg != bg {
369                break;
370            }
371            if cell.ch != ' ' {
372                if fg.is_some_and(|f| f != cell.fg) {
373                    break;
374                }
375                fg = Some(cell.fg);
376            }
377            if !done[i] {
378                seen += 1;
379                len = k + 1;
380                changed = seen;
381                fg_at_end = fg;
382            }
383        }
384        Run { len, changed, fg: fg_at_end }
385    }
386
387    /// The rectangle from (x, y) of cells identical to (x, y): as wide as the
388    /// row allows, then as tall as every row of that width matches.
389    fn rect(&self, done: &[bool], x: usize, y: usize) -> Rect {
390        let start = self.cells[y * self.w + x];
391        let width = (x..self.w).take_while(|&xx| self.cells[y * self.w + xx] == start).count();
392        let height = (y..self.h)
393            .take_while(|&yy| (x..x + width).all(|xx| self.cells[yy * self.w + xx] == start))
394            .count();
395        let changed = (y..y + height).flat_map(|yy| (x..x + width).map(move |xx| yy * self.w + xx)).filter(|&i| !done[i]).count();
396        Rect { w: width, h: height, changed }
397    }
398
399    /// Sends what changed since the last present to the screen. Returns the
400    /// number of GPU calls it made.
401    pub fn present(&mut self) -> Result<usize> {
402        let ops = self.plan();
403        if ops.is_empty() {
404            return Ok(0);
405        }
406        let result = self.send(&ops);
407        if result.is_err() {
408            self.invalidate(); // the screen is in an unknown state
409        }
410        result
411    }
412
413    fn send(&self, ops: &[Op]) -> Result<usize> {
414        let mut calls = ops.len();
415        if let Some(buffer) = self.vram {
416            self.gpu.set_active_buffer(buffer)?;
417        }
418        for op in ops {
419            match op {
420                Op::Fg(c) => self.gpu.set_foreground(*c, None).map(|_| ())?,
421                Op::Bg(c) => self.gpu.set_background(*c, None).map(|_| ())?,
422                Op::Text { x, y, text, vertical } => {
423                    self.gpu.set(*x, *y, text.as_str(), vertical.then_some(true)).map(|_| ())?
424                }
425                Op::Fill { x, y, w, h, ch } => self.gpu.fill(*x, *y, *w, *h, ch.to_string()).map(|_| ())?,
426            }
427        }
428        if let Some(buffer) = self.vram {
429            self.gpu.set_active_buffer(0)?;
430            self.gpu.bitblt(Some(Number::Int(0)), None, None, None, None, Some(buffer), None, None)?;
431            calls += 3;
432        }
433        Ok(calls)
434    }
435
436    /// [`Canvas::present`] without blocking: every call is queued at once
437    /// (they run in order), and other tasks keep running. Requires the
438    /// `async` feature; see [`crate::task`].
439    #[cfg(feature = "async")]
440    pub async fn present_async(&mut self) -> Result<usize> {
441        let ops = self.plan();
442        if ops.is_empty() {
443            return Ok(0);
444        }
445        let gpu = &self.gpu;
446        let mut calls: Vec<crate::task::Call> = Vec::with_capacity(ops.len() + 3);
447        let (fg, bg) = ("setForeground", "setBackground");
448        if let Some(buffer) = self.vram {
449            calls.push(gpu.invoke_async("setActiveBuffer", vec![buffer.into()]));
450        }
451        for op in &ops {
452            calls.push(match op {
453                Op::Fg(c) => gpu.invoke_async(fg, vec![Number::from(*c).into()]),
454                Op::Bg(c) => gpu.invoke_async(bg, vec![Number::from(*c).into()]),
455                Op::Text { x, y, text, vertical } => {
456                    let mut args = vec![(*x).into(), (*y).into(), text.as_str().into()];
457                    if *vertical {
458                        args.push(true.into());
459                    }
460                    gpu.invoke_async("set", args)
461                }
462                Op::Fill { x, y, w, h, ch } => gpu.invoke_async(
463                    "fill",
464                    vec![(*x).into(), (*y).into(), (*w).into(), (*h).into(), ch.to_string().as_str().into()],
465                ),
466            });
467        }
468        if let Some(buffer) = self.vram {
469            calls.push(gpu.invoke_async("setActiveBuffer", vec![0.into()]));
470            calls.push(gpu.invoke_async("bitblt", vec![0.into(), 1.into(), 1.into(), (self.w as i64).into(), (self.h as i64).into(), buffer.into()]));
471        }
472        let count = calls.len();
473        let results = crate::task::join_all(calls).await;
474        if let Some(Err(e)) = results.into_iter().find(Result::is_err) {
475            self.invalidate();
476            return Err(e);
477        }
478        Ok(count)
479    }
480}
481
482impl Drop for Canvas {
483    fn drop(&mut self) {
484        if let Some(buffer) = self.vram.take() {
485            let _ = self.gpu.free_buffer(buffer);
486        }
487    }
488}
489
490/// Lines, rectangles and circles, for anything that can set a point.
491pub trait Shapes {
492    /// Size in points.
493    fn size(&self) -> (i64, i64);
494    /// Sets one point; outside the surface it does nothing.
495    fn put(&mut self, x: i64, y: i64, colour: Rgb);
496
497    fn line(&mut self, x0: i64, y0: i64, x1: i64, y1: i64, colour: Rgb) {
498        let (dx, dy) = ((x1 - x0).abs(), -(y1 - y0).abs());
499        let (sx, sy) = (if x0 < x1 { 1 } else { -1 }, if y0 < y1 { 1 } else { -1 });
500        let (mut x, mut y, mut err) = (x0, y0, dx + dy);
501        loop {
502            self.put(x, y, colour);
503            if x == x1 && y == y1 {
504                break;
505            }
506            let e2 = 2 * err;
507            if e2 >= dy {
508                err += dy;
509                x += sx;
510            }
511            if e2 <= dx {
512                err += dx;
513                y += sy;
514            }
515        }
516    }
517
518    fn rect(&mut self, x: i64, y: i64, w: i64, h: i64, colour: Rgb) {
519        if w <= 0 || h <= 0 {
520            return;
521        }
522        self.line(x, y, x + w - 1, y, colour);
523        self.line(x, y + h - 1, x + w - 1, y + h - 1, colour);
524        self.line(x, y, x, y + h - 1, colour);
525        self.line(x + w - 1, y, x + w - 1, y + h - 1, colour);
526    }
527
528    fn fill_rect(&mut self, x: i64, y: i64, w: i64, h: i64, colour: Rgb) {
529        let (sw, sh) = self.size();
530        for yy in y.max(0)..(y + h).min(sh) {
531            for xx in x.max(0)..(x + w).min(sw) {
532                self.put(xx, yy, colour);
533            }
534        }
535    }
536
537    fn circle(&mut self, cx: i64, cy: i64, r: i64, colour: Rgb) {
538        let (mut x, mut y, mut err) = (r, 0, 1 - r);
539        while x >= y {
540            for (px, py) in [(x, y), (y, x), (-y, x), (-x, y), (-x, -y), (-y, -x), (y, -x), (x, -y)] {
541                self.put(cx + px, cy + py, colour);
542            }
543            y += 1;
544            if err < 0 {
545                err += 2 * y + 1;
546            } else {
547                x -= 1;
548                err += 2 * (y - x) + 1;
549            }
550        }
551    }
552
553    fn fill_circle(&mut self, cx: i64, cy: i64, r: i64, colour: Rgb) {
554        // Radius r + 1/2 (r^2 + r), so the edges are round rather than
555        // ending in single-pixel points.
556        for dy in -r..=r {
557            let half = ((r * r + r - dy * dy) as f64).sqrt() as i64;
558            for dx in -half..=half {
559                self.put(cx + dx, cy + dy, colour);
560            }
561        }
562    }
563
564    /// `f` from 0 to 1 across the width, with -1 at the bottom and 1 at the
565    /// top, joined so steep parts have no gaps.
566    fn plot(&mut self, f: impl Fn(f64) -> f64, colour: Rgb)
567    where
568        Self: Sized,
569    {
570        let (w, h) = self.size();
571        if w < 1 || h < 1 {
572            return;
573        }
574        let y_at = |x: i64| ((1.0 - f(x as f64 / (w - 1).max(1) as f64)) / 2.0 * (h - 1) as f64).round() as i64;
575        let mut prev = y_at(0);
576        for x in 0..w {
577            let y = y_at(x);
578            for yy in prev.min(y)..=prev.max(y) {
579                self.put(x, yy, colour);
580            }
581            prev = y;
582        }
583    }
584}
585
586/// The canvas as half-block pixels, two per cell (top and bottom); see
587/// [`Canvas::pixels`].
588pub struct Pixels<'a> {
589    canvas: &'a mut Canvas,
590}
591
592impl Pixels<'_> {
593    /// The colour of pixel (x, y).
594    pub fn get(&self, x: i64, y: i64) -> Option<Rgb> {
595        let (ch, fg, bg) = self.canvas.get(x, y.div_euclid(2))?;
596        Some(if ch == HALF && y % 2 == 0 { fg } else { bg })
597    }
598
599    pub fn clear(&mut self, colour: Rgb) {
600        self.canvas.clear(colour);
601    }
602}
603
604impl Shapes for Pixels<'_> {
605    fn size(&self) -> (i64, i64) {
606        (self.canvas.w as i64, self.canvas.h as i64 * 2)
607    }
608
609    fn put(&mut self, x: i64, y: i64, colour: Rgb) {
610        if y < 0 {
611            return;
612        }
613        let cy = y / 2;
614        let Some(i) = self.canvas.index(x, cy) else { return };
615        let cell = self.canvas.cells[i];
616        let (mut top, mut bottom) = if cell.ch == HALF { (cell.fg, cell.bg) } else { (cell.bg, cell.bg) };
617        if y % 2 == 0 {
618            top = colour;
619        } else {
620            bottom = colour;
621        }
622        // Two equal halves are just a background, which merges into runs.
623        self.canvas.cells[i] = if top == bottom {
624            Cell { ch: ' ', fg: cell.fg, bg: top }
625        } else {
626            Cell { ch: HALF, fg: top, bg: bottom }
627        };
628    }
629}
630
631/// The canvas as braille dots, 2x4 per cell; see [`Canvas::dots`]. A cell's
632/// dots share one colour: the last one drawn there.
633pub struct Dots<'a> {
634    canvas: &'a mut Canvas,
635}
636
637/// Braille dot bits by column and row within a cell.
638const BRAILLE: [[u32; 4]; 2] = [[0x01, 0x02, 0x04, 0x40], [0x08, 0x10, 0x20, 0x80]];
639
640impl Dots<'_> {
641    /// Turns dot (x, y) off.
642    pub fn unset(&mut self, x: i64, y: i64) {
643        self.update(x, y, None);
644    }
645
646    /// Whether dot (x, y) is on.
647    pub fn is_set(&self, x: i64, y: i64) -> bool {
648        if x < 0 || y < 0 {
649            return false;
650        }
651        match self.canvas.get(x / 2, y / 4) {
652            Some((ch, _, _)) if ('\u{2800}'..='\u{28FF}').contains(&ch) => {
653                (ch as u32 - 0x2800) & BRAILLE[(x % 2) as usize][(y % 4) as usize] != 0
654            }
655            _ => false,
656        }
657    }
658
659    /// Turns every dot off, keeping cell backgrounds.
660    pub fn clear(&mut self) {
661        for cell in &mut self.canvas.cells {
662            if ('\u{2800}'..='\u{28FF}').contains(&cell.ch) {
663                cell.ch = ' ';
664            }
665        }
666    }
667
668    fn update(&mut self, x: i64, y: i64, colour: Option<Rgb>) {
669        if x < 0 || y < 0 {
670            return;
671        }
672        let Some(i) = self.canvas.index(x / 2, y / 4) else { return };
673        let cell = &mut self.canvas.cells[i];
674        let mut bits = if ('\u{2800}'..='\u{28FF}').contains(&cell.ch) { cell.ch as u32 - 0x2800 } else { 0 };
675        let bit = BRAILLE[(x % 2) as usize][(y % 4) as usize];
676        match colour {
677            Some(c) => {
678                bits |= bit;
679                cell.fg = c;
680            }
681            None => bits &= !bit,
682        }
683        cell.ch = if bits == 0 { ' ' } else { char::from_u32(0x2800 + bits).expect("braille range") };
684    }
685}
686
687impl Shapes for Dots<'_> {
688    fn size(&self) -> (i64, i64) {
689        (self.canvas.w as i64 * 2, self.canvas.h as i64 * 4)
690    }
691
692    fn put(&mut self, x: i64, y: i64, colour: Rgb) {
693        self.update(x, y, Some(colour));
694    }
695}
696
697#[cfg(test)]
698mod tests {
699    use super::*;
700    use crate::component::{Address, Component};
701
702    fn canvas(w: usize, h: usize) -> Canvas {
703        Canvas::with_size(Gpu::from_address(Address("gpu".into())), w, h)
704    }
705
706    fn text(x: i64, y: i64, text: &str) -> Op {
707        Op::Text { x, y, text: text.into(), vertical: false }
708    }
709
710    fn down(x: i64, y: i64, text: &str) -> Op {
711        Op::Text { x, y, text: text.into(), vertical: true }
712    }
713
714    #[test]
715    fn the_first_present_sends_everything_then_only_changes() {
716        let mut c = canvas(4, 2);
717        c.text(0, 0, "ab", Rgb::WHITE, Rgb::BLACK);
718        assert_eq!(c.plan(), [Op::Bg(Rgb::BLACK), Op::Fg(Rgb::WHITE), text(1, 1, "ab  "), text(1, 2, "    ")]);
719        assert_eq!(c.plan(), []);
720        c.set(1, 1, 'x', Rgb::WHITE, Rgb::BLACK);
721        // Colours are already set: one call.
722        assert_eq!(c.plan(), [text(2, 2, "x")]);
723    }
724
725    #[test]
726    fn runs_break_on_colour_and_spaces_match_any_foreground() {
727        let mut c = canvas(5, 1);
728        c.text(0, 0, "a", Rgb::RED, Rgb::BLACK);
729        c.text(2, 0, "b", Rgb::RED, Rgb::BLACK); // the space between joins the run
730        c.text(3, 0, "c", Rgb::BLUE, Rgb::BLACK);
731        assert_eq!(
732            c.plan(),
733            [Op::Bg(Rgb::BLACK), Op::Fg(Rgb::RED), text(1, 1, "a b"), Op::Fg(Rgb::BLUE), text(4, 1, "c ")]
734        );
735    }
736
737    #[test]
738    fn unchanged_cells_inside_a_run_are_resent_rather_than_split() {
739        let mut c = canvas(5, 1);
740        c.plan();
741        c.set(0, 0, 'x', Rgb::WHITE, Rgb::BLACK);
742        c.set(3, 0, 'y', Rgb::WHITE, Rgb::BLACK);
743        assert_eq!(c.plan(), [Op::Fg(Rgb::WHITE), text(1, 1, "x  y")]);
744    }
745
746    #[test]
747    fn columns_of_one_colour_go_down_and_blocks_are_filled() {
748        let mut c = canvas(3, 4);
749        c.plan();
750        // A gradient: each column its own background, so one call per column
751        // (a vertical set; a 1-wide fill would cost the same).
752        for (x, colour) in [Rgb::RED, Rgb::GREEN, Rgb::BLUE].into_iter().enumerate() {
753            c.fill(x as i64, 0, 1, 4, ' ', Rgb::WHITE, colour);
754        }
755        assert_eq!(
756            c.plan(),
757            [
758                Op::Bg(Rgb::RED),
759                down(1, 1, "    "),
760                Op::Bg(Rgb::GREEN),
761                down(2, 1, "    "),
762                Op::Bg(Rgb::BLUE),
763                down(3, 1, "    "),
764            ]
765        );
766        // A clear is one fill.
767        c.clear(Rgb::GREY);
768        assert_eq!(c.plan(), [Op::Bg(Rgb::GREY), Op::Fill { x: 1, y: 1, w: 3, h: 4, ch: ' ' }]);
769        // A vertical bar of mixed characters is one vertical set.
770        c.text_vertical(1, 0, "█▄", Rgb::YELLOW, Rgb::GREY);
771        assert_eq!(c.plan(), [Op::Fg(Rgb::YELLOW), down(2, 1, "█▄")]);
772    }
773
774    #[test]
775    fn half_block_pixels() {
776        let mut c = canvas(2, 1);
777        let mut px = c.pixels();
778        px.put(0, 0, Rgb::RED);
779        px.put(0, 1, Rgb::BLUE);
780        px.put(1, 0, Rgb::GREEN);
781        px.put(1, 1, Rgb::GREEN);
782        assert_eq!(px.get(0, 0), Some(Rgb::RED));
783        assert_eq!(px.get(0, 1), Some(Rgb::BLUE));
784        assert_eq!(c.get(0, 0), Some(('▀', Rgb::RED, Rgb::BLUE)));
785        // Equal halves become a plain background.
786        assert_eq!(c.get(1, 0).map(|(ch, _, bg)| (ch, bg)), Some((' ', Rgb::GREEN)));
787    }
788
789    #[test]
790    fn braille_dots() {
791        let mut c = canvas(1, 1);
792        let mut dots = c.dots();
793        dots.put(0, 0, Rgb::WHITE); // dot 1
794        dots.put(1, 3, Rgb::WHITE); // dot 8
795        assert!(dots.is_set(1, 3) && !dots.is_set(1, 2));
796        assert_eq!(c.get(0, 0).map(|(ch, ..)| ch), Some('\u{2881}'));
797        let mut dots = c.dots();
798        dots.unset(0, 0);
799        dots.unset(1, 3);
800        assert_eq!(c.get(0, 0).map(|(ch, ..)| ch), Some(' '));
801    }
802
803    #[test]
804    fn shapes_are_clipped() {
805        let mut c = canvas(3, 2);
806        let mut px = c.pixels();
807        px.fill_circle(1, 1, 5, Rgb::RED);
808        px.line(-10, -10, 10, 10, Rgb::BLUE);
809        assert_eq!(px.size(), (3, 4));
810        assert_eq!(px.get(2, 3), Some(Rgb::RED));
811        assert_eq!(px.get(1, 1), Some(Rgb::BLUE));
812    }
813
814    #[test]
815    fn hsv_and_lerp() {
816        assert_eq!(Rgb::hsv(0.0, 1.0, 1.0), Rgb::RED);
817        assert_eq!(Rgb::hsv(1.0 / 3.0, 1.0, 1.0), Rgb::GREEN);
818        assert_eq!(Rgb::hsv(0.5, 0.0, 0.5), Rgb::new(128, 128, 128));
819        assert_eq!(Rgb::BLACK.lerp(Rgb::WHITE, 0.5), Rgb::new(128, 128, 128));
820    }
821}