ombre: Move UI code to `Canvas` backend

fd8e7e26a1d3dde146b9bda793d25d36ea717188
Alexis Sellier committed ago 1 parent 2243b507
.cargo/config.toml +1 -0
1 1
[alias]
2 2
y = "clippy --all-targets --all-features -- -D warnings"
3 +
d = "doc --all-features --no-deps --document-private-items"
ombre/Cargo.toml +10 -2
9 9
10 10
[features]
11 11
default = ["glfw", "color-logging"]
12 12
color-logging = ["termcolor"]
13 13
derive = ["ombre-derive"]
14 -
draw = ["derive"]
15 -
ui = ["draw"]
14 +
paint = ["derive"]
15 +
ui = ["paint", "derive"]
16 16
17 17
[dependencies]
18 18
glfw = { version = "0.58.0", optional = true }
19 19
glow = { version = "0.14.0" }
20 20
log = { version = "0.4.20", features = ["std"] }
25 25
[lints]
26 26
workspace = true
27 27
28 28
[dev-dependencies]
29 29
ombre = { version = "0.6.6", features = ["derive", "ui"], path = "." }
30 +
31 +
[[example]]
32 +
name = "paint-basic"
33 +
path = "examples/paint/basic.rs"
34 +
35 +
[[example]]
36 +
name = "paint-showcase"
37 +
path = "examples/paint/showcase.rs"
ombre/examples/buttons.rs +9 -12
23 23
impl<T: gfx::RenderBackend> Example<T> {
24 24
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
25 25
        let root = zstack((
26 26
            canvas(|data: &Data, bounds, mut p| {
27 27
                p.fill(bounds, Rgba8::BLUE.alpha(0x80));
28 -
                p.write(
29 -
                    format!("{} ({})", data.blue.0, data.blue.1),
30 -
                    Rgba::WHITE,
31 -
                    bounds,
28 +
                p.text(
29 +
                    format!("{} ({})", data.blue.0, data.blue.1).as_str(),
30 +
                    bounds.origin,
32 31
                );
33 32
            })
34 33
            .sized((256., 256.))
35 34
            .on_click(|_, data, _| data.blue.0 += 1)
36 35
            .on_hover(|_, hovered, data, _| data.blue.1 = hovered)
37 36
            .center(),
38 37
            canvas(|data: &Data, bounds, mut p| {
39 38
                p.fill(bounds, Rgba8::RED.alpha(0x80));
40 -
                p.write(
41 -
                    format!("{} ({})", data.red.0, data.red.1),
42 -
                    Rgba::WHITE,
43 -
                    bounds,
39 +
                p.text(
40 +
                    format!("{} ({})", data.red.0, data.red.1).as_str(),
41 +
                    bounds.origin,
44 42
                );
45 43
            })
46 44
            .sized((192., 192.))
47 45
            .on_click(|_, data, _| data.red.0 += 1)
48 46
            .on_hover(|_, hovered, data, _| data.red.1 = hovered)
49 47
            .center(),
50 48
            canvas(|data: &Data, bounds, mut p| {
51 49
                p.fill(bounds, Rgba8::GREEN.alpha(0x80));
52 -
                p.write(
53 -
                    format!("{} ({})", data.green.0, data.green.1),
54 -
                    Rgba::WHITE,
55 -
                    bounds,
50 +
                p.text(
51 +
                    format!("{} ({})", data.green.0, data.green.1).as_str(),
52 +
                    bounds.origin,
56 53
                );
57 54
            })
58 55
            .sized((128., 128.))
59 56
            .on_click(|_, data, _| data.green.0 += 1)
60 57
            .on_hover(|_, hovered, data, _| data.green.1 = hovered)
ombre/examples/canvas.rs +1 -1
20 20
            g.stroke(view, Rgba8::BLUE, 9.);
21 21
            for click in state.iter().copied() {
22 22
                g.fill(Rect::centered(click, Size::from(18.)), Rgba8::GREEN);
23 23
            }
24 24
        })
25 -
        .on_click(|_, state, ctx| state.push(ctx.cursor.convert()));
25 +
        .on_click(|_, state, ctx| state.push(ctx.cursor));
26 26
27 27
        let ui = gui::interface(win, &mut backend).scale(2.0).build(root)?;
28 28
29 29
        Ok(Self {
30 30
            backend,
ombre/examples/checkbox.rs +1 -1
23 23
            .scale(4.0)
24 24
            .cursor(gui::CursorDescriptor {
25 25
                name: "pointer",
26 26
                image: pointer,
27 27
                origin: Point2D::ORIGIN,
28 -
            })?
28 +
            })
29 29
            .build(root)?;
30 30
31 31
        Ok(Self {
32 32
            backend,
33 33
            ui,
ombre/examples/circles.rs +1 -1
1 1
#![deny(clippy::all)]
2 2
#[path = "common/runtime.rs"]
3 3
mod runtime;
4 4
5 -
use ombre::draw::{
5 +
use ombre::paint::{
6 6
    batch::{TextureInfo, VertexBatch},
7 7
    pipeline,
8 8
    pipeline::*,
9 9
    shape::Circle,
10 10
};
ombre/examples/counter.rs +1 -1
23 23
            .on_click(|_, state, _| *state += 1)
24 24
            .center()
25 25
            .boxed();
26 26
27 27
        let ui = gui::interface(win, &mut backend)
28 -
            .font(gui::fonts::uf2::VENICE)?
28 +
            .font(gfx::font::uf2::VENICE)?
29 29
            .scale(4.0)
30 30
            .build(root)?;
31 31
32 32
        Ok(Self {
33 33
            ui,
ombre/examples/cursors.rs +3 -3
35 35
            .scale(2.0)
36 36
            .cursor(CursorDescriptor {
37 37
                name: "pointer",
38 38
                image: pointer,
39 39
                origin: Point2D::ORIGIN,
40 -
            })?
40 +
            })
41 41
            .cursor(CursorDescriptor {
42 42
                name: "grab",
43 43
                image: grab,
44 44
                origin: Point2D::ORIGIN,
45 -
            })?
45 +
            })
46 46
            .cursor(CursorDescriptor {
47 47
                name: "hand",
48 48
                image: hand,
49 49
                origin: Point2D::ORIGIN,
50 -
            })?
50 +
            })
51 51
            .build(root)?;
52 52
53 53
        Ok(Self {
54 54
            ui,
55 55
            state: State::default(),
ombre/examples/fonts.rs +2 -2
13 13
    backend: T,
14 14
}
15 15
16 16
impl<T: gfx::RenderBackend> Example<T> {
17 17
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
18 -
        let venice = gui::fonts::uf2::VENICE;
19 -
        let default = gui::fonts::uf2::DEFAULT;
18 +
        let venice = gfx::font::uf2::VENICE;
19 +
        let default = gfx::font::uf2::DEFAULT;
20 20
        let text = "Sphinx. $%/~_Jq!`,|";
21 21
        let ui = gui::interface(win, &mut backend).font(venice)?.scale(20.0).build(
22 22
            gui::label(text)
23 23
                .align(TextAlign::Center)
24 24
                .font(default.name)
ombre/examples/input.rs +2 -2
3 3
#[path = "common/runtime.rs"]
4 4
mod runtime;
5 5
6 6
use ombre::prelude::*;
7 7
use ombre::ui::widgets::*;
8 -
use ombre::ui::{self as gui, fonts};
8 +
use ombre::ui::{self as gui};
9 9
10 10
pub struct Example<T> {
11 11
    ui: gui::Interface<Box<dyn Widget<String>>, String>,
12 12
    data: String,
13 13
    backend: T,
15 15
16 16
impl<T: gfx::RenderBackend> Example<T> {
17 17
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
18 18
        let ui = gui::interface(win, &mut backend)
19 19
            .scale(10.0)
20 -
            .font(fonts::uf2::VENICE)?
20 +
            .font(gfx::font::uf2::VENICE)?
21 21
            .build(
22 22
                gui::hstack((
23 23
                    gui::input(gui::Label::empty())
24 24
                        .font("Venice")
25 25
                        .padding([2., 2.])
ombre/examples/paint/basic.rs added +89 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
use std::time::Duration;
4 +
5 +
use ombre::paint::{canvas, shape, Canvas, PaintSurface};
6 +
use ombre::platform::Window;
7 +
use ombre::prelude::*;
8 +
use ombre::rng::Rng;
9 +
10 +
pub struct Example<T> {
11 +
    canvas: Canvas,
12 +
    rng: Rng,
13 +
    delta: f64,
14 +
    backend: T,
15 +
}
16 +
17 +
impl<T: gfx::RenderBackend + std::fmt::Debug> Example<T> {
18 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, canvas::Error<T>> {
19 +
        let canvas = ombre::canvas(win.size().into(), &mut backend).build()?;
20 +
        let rng = Rng::default();
21 +
22 +
        Ok(Self {
23 +
            canvas,
24 +
            rng,
25 +
            backend,
26 +
            delta: 0.,
27 +
        })
28 +
    }
29 +
}
30 +
31 +
impl<R: RenderBackend> Application for Example<R> {
32 +
    type Error = R::Error;
33 +
34 +
    fn event(
35 +
        &mut self,
36 +
        event: platform::WindowEvent,
37 +
        _win: &mut platform::Window,
38 +
    ) -> Result<(), R::Error> {
39 +
        if let platform::WindowEvent::Resized(size) = event {
40 +
            self.canvas.resize(size, &mut self.backend)?;
41 +
        }
42 +
        Ok(())
43 +
    }
44 +
45 +
    fn tick(&mut self, delta: Duration, win: &mut Window) -> Result<(), Self::Error> {
46 +
        self.delta += delta.as_secs_f64();
47 +
        let size = win.size();
48 +
        let origin = Point2D::new(
49 +
            (self.rng.fraction() * size.width) as f32,
50 +
            (self.rng.fraction() * size.height) as f32,
51 +
        );
52 +
        let color = Rgba::new(
53 +
            self.rng.fraction() as f32,
54 +
            self.rng.fraction() as f32,
55 +
            self.rng.fraction() as f32,
56 +
            1.0,
57 +
        );
58 +
59 +
        if self.rng.flip() {
60 +
            self.canvas.fill(shape::circle(origin, 32., 8), color);
61 +
        } else {
62 +
            self.canvas.fill(shape::rectangle(origin, Size::new(48., 48.)), color);
63 +
        }
64 +
        win.redraw();
65 +
66 +
        Ok(())
67 +
    }
68 +
69 +
    fn frame(&mut self) -> Result<(), Self::Error> {
70 +
        let mut frame = self.backend.frame();
71 +
        self.canvas.flush(&mut frame)?;
72 +
73 +
        Ok(())
74 +
    }
75 +
}
76 +
77 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
78 +
    logger::init(log::Level::Debug)?;
79 +
80 +
    let (mut win, events) =
81 +
        platform::init("paint/basic", 640, 480, &[], platform::GraphicsContext::Gl)?;
82 +
    let ctx = unsafe { glow::Context::from_loader_function(|p| win.get_proc_address(p)) };
83 +
    let backend = gfx::gl::Context::new(ctx, win.size())?;
84 +
    let app = Example::init(backend, &win)?;
85 +
86 +
    ombre::runtime::default::run(win, events, app)?;
87 +
88 +
    Ok(())
89 +
}
ombre/examples/paint/showcase.rs added +101 -0
1 +
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
3 +
use ombre::gfx::font::uf2::VENICE;
4 +
use ombre::paint::shape::Circle;
5 +
use ombre::paint::{canvas, Canvas, PaintSurface};
6 +
use ombre::prelude::*;
7 +
use ombre::text::Text;
8 +
9 +
pub struct Example<T> {
10 +
    canvas: Canvas,
11 +
    image: Image,
12 +
    backend: T,
13 +
}
14 +
15 +
impl<T: gfx::RenderBackend + std::fmt::Debug> Example<T> {
16 +
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, canvas::Error<T>> {
17 +
        let canvas = ombre::canvas(win.size().into(), &mut backend)
18 +
            .scale(4.0)
19 +
            .font(VENICE)?
20 +
            .build()?;
21 +
        let src = include_bytes!("../common/rx.rgba");
22 +
        let image = gfx::Image::try_from(src.as_slice()).unwrap();
23 +
24 +
        Ok(Self {
25 +
            image,
26 +
            canvas,
27 +
            backend,
28 +
        })
29 +
    }
30 +
}
31 +
32 +
impl<R: RenderBackend> Application for Example<R> {
33 +
    type Error = R::Error;
34 +
35 +
    fn event(
36 +
        &mut self,
37 +
        event: platform::WindowEvent,
38 +
        _win: &mut platform::Window,
39 +
    ) -> Result<(), R::Error> {
40 +
        match event {
41 +
            platform::WindowEvent::Resized(size) => {
42 +
                self.canvas.resize(size, &mut self.backend)?;
43 +
            }
44 +
            platform::WindowEvent::RedrawRequested => {
45 +
                self.frame()?;
46 +
            }
47 +
            _ => {}
48 +
        }
49 +
        Ok(())
50 +
    }
51 +
52 +
    fn frame(&mut self) -> Result<(), Self::Error> {
53 +
        let mut frame = self.backend.frame();
54 +
55 +
        self.canvas.clear();
56 +
        self.canvas.stroke(Rect::new([24., 24.], [256., 128.]), Rgba::RED, 2.);
57 +
        self.canvas
58 +
            .fill(Rect::new([64., 64.], [128., 128.]), Rgba::BLUE.alpha(0.8));
59 +
        self.canvas
60 +
            .stroke(Circle::new([256., 128.], 128., 64), Rgba::GREEN, 1.);
61 +
        self.canvas
62 +
            .fill(Circle::new([256., 256.], 32., 12), Rgba::YELLOW.alpha(0.5));
63 +
        self.canvas.with_transform(Vector2D::new(128.0f32, 256.), |c| {
64 +
            c.with_transform(Vector2D::new(128.0f32, 0.), |c| {
65 +
                c.blit(
66 +
                    self.image.clone(),
67 +
                    self.image.rect(),
68 +
                    Rect::origin([128., 128.]),
69 +
                    Rgba::BLUE.alpha(0.3),
70 +
                    0.8,
71 +
                );
72 +
            })
73 +
        });
74 +
        self.canvas.text(
75 +
            Text::new("A Shadow is Born!").with_font("Venice"),
76 +
            [112., 112.],
77 +
        );
78 +
        self.canvas.flush(&mut frame)?;
79 +
80 +
        Ok(())
81 +
    }
82 +
}
83 +
84 +
fn main() -> Result<(), Box<dyn std::error::Error>> {
85 +
    logger::init(log::Level::Debug)?;
86 +
87 +
    let (mut win, events) = platform::init(
88 +
        "paint/showcase",
89 +
        640,
90 +
        480,
91 +
        &[],
92 +
        platform::GraphicsContext::Gl,
93 +
    )?;
94 +
    let ctx = unsafe { glow::Context::from_loader_function(|p| win.get_proc_address(p)) };
95 +
    let backend = gfx::gl::Context::new(ctx, win.size())?;
96 +
    let app = Example::init(backend, &win)?;
97 +
98 +
    ombre::runtime::default::run(win, events, app)?;
99 +
100 +
    Ok(())
101 +
}
ombre/examples/particles.rs +5 -4
1 1
#![deny(clippy::all)]
2 +
#![allow(clippy::unwrap_used)]
2 3
#[path = "common/runtime.rs"]
3 4
mod runtime;
4 5
5 6
use ombre::math::Vector3D;
6 7
use ombre::prelude::*;
51 52
            .buffer(
52 53
                BufferKind::Vertex,
53 54
                BufferUsage::Immutable,
54 55
                BufferSource::slice(&vertices),
55 56
            )
56 -
            .map_err(gui::Error::Render)?;
57 +
            .unwrap();
57 58
58 59
        // Create instance buffer for particle positions.
59 60
        let instance_buf = backend
60 61
            .buffer(
61 62
                BufferKind::Vertex,
62 63
                BufferUsage::Stream,
63 64
                BufferSource::<Vector3D<f32>>::empty(MAX_PARTICLES),
64 65
            )
65 -
            .map_err(gui::Error::Render)?;
66 +
            .unwrap();
66 67
67 68
        // Create index buffer
68 69
        let ibuf = backend
69 70
            .buffer(
70 71
                BufferKind::Index,
71 72
                BufferUsage::Immutable,
72 73
                BufferSource::slice(&indices),
73 74
            )
74 -
            .map_err(gui::Error::Render)?;
75 +
            .unwrap();
75 76
76 77
        let bindings = gfx::Bindings {
77 78
            vertex: [vbuf, instance_buf],
78 79
            index: Some(ibuf),
79 80
            textures: [],
80 81
        };
81 -
        let pipeline = pipeline(&mut backend).map_err(gui::Error::Render)?;
82 +
        let pipeline = pipeline(&mut backend).unwrap();
82 83
83 84
        Ok(Self {
84 85
            backend,
85 86
            pipeline,
86 87
            bindings,
ombre/examples/sprite.rs +1 -1
53 53
                        i as f32 / rows as f32,
54 54
                        j as f32 / cols as f32,
55 55
                        (f32::sin(freq * elapsed) + 1.0) / 2.0,
56 56
                        0.5,
57 57
                    );
58 -
                    g.blit(state.image.clone(), src, dst, tint);
58 +
                    g.blit(state.image.clone(), src, dst, tint, 1.);
59 59
                }
60 60
            }
61 61
        });
62 62
63 63
        let ui = gui::interface(win, &mut backend).build(root)?;
ombre/examples/text.rs +5 -5
47 47
    backend: T,
48 48
}
49 49
50 50
impl<T: gfx::RenderBackend> Example<T> {
51 51
    pub fn init(mut backend: T, win: &platform::Window) -> Result<Self, gui::Error<T>> {
52 -
        let venice = gui::fonts::uf2::VENICE;
52 +
        let venice = gfx::font::uf2::VENICE;
53 53
        let spans: Vec<TextSpan> = [
54 54
            TextSpan {
55 55
                range: 0..2,
56 56
                font: FontName::new("Venice"),
57 -
                tint: Rgba8::RED,
57 +
                tint: Rgba::RED,
58 58
                style: FontStyle::default(),
59 59
            },
60 60
            TextSpan {
61 61
                range: 2..5,
62 62
                font: FontName::new("Default"),
63 -
                tint: Rgba8::GREEN,
63 +
                tint: Rgba::GREEN,
64 64
                style: FontStyle::default(),
65 65
            },
66 66
            TextSpan {
67 67
                range: 5..8,
68 68
                font: FontName::new("Default"),
69 -
                tint: Rgba8::PINK,
69 +
                tint: Rgba::PINK,
70 70
                style: FontStyle::default(),
71 71
            },
72 72
            TextSpan {
73 73
                range: 8..17,
74 74
                font: FontName::new("Venice"),
75 -
                tint: Rgba8::BLUE,
75 +
                tint: Rgba::BLUE,
76 76
                style: FontStyle::default(),
77 77
            },
78 78
        ]
79 79
        .into_iter()
80 80
        .cycle()
ombre/examples/texture.rs +2 -2
117 117
        )?;
118 118
119 119
        let texture = backend.texture(gfx::Texture {
120 120
            data: PIXELS.as_slice(),
121 121
            size: Size::new(4, 4),
122 -
            min_filter: FilterMode::Nearest,
123 -
            mag_filter: FilterMode::Nearest,
122 +
            min_filter: FilterMode::Linear,
123 +
            mag_filter: FilterMode::Linear,
124 124
            format: TextureFormat::Srgba8,
125 125
            ..gfx::Texture::default()
126 126
        })?;
127 127
128 128
        let bindings = Bindings {
ombre/src/draw.rs deleted +0 -5
1 -
pub mod batch;
2 -
pub mod blit;
3 -
pub mod pipeline;
4 -
pub mod shape;
5 -
pub mod traits;
ombre/src/draw/traits.rs deleted +0 -17
1 -
use crate::gfx::Rgba;
2 -
3 -
/// Defines how a shape should be colored.
4 -
/// Can be either a solid color or a gradient between multiple colors.
5 -
#[derive(Debug, Clone)]
6 -
pub enum Brush {
7 -
    /// A [`Rgba`] color.
8 -
    Color(Rgba<f32>),
9 -
    /// A gradient between a set of colors.
10 -
    LinearGradient([Rgba<f32>; 8]),
11 -
}
12 -
13 -
impl From<Rgba<f32>> for Brush {
14 -
    fn from(src: Rgba<f32>) -> Brush {
15 -
        Brush::Color(src)
16 -
    }
17 -
}
ombre/src/gfx/color.rs +5 -0
247 247
impl<T> Rgba<T> {
248 248
    /// Create a new `Rgba` color.
249 249
    pub const fn new(r: T, g: T, b: T, a: T) -> Self {
250 250
        Self { r, g, b, a }
251 251
    }
252 +
253 +
    /// Return the color with a changed alpha.
254 +
    pub fn alpha(self, a: T) -> Self {
255 +
        Self::new(self.r, self.g, self.b, a)
256 +
    }
252 257
}
253 258
254 259
impl Rgba<f32> {
255 260
    /// Invert the color.
256 261
    pub fn invert(self) -> Self {
ombre/src/gfx/font.rs +82 -0
1 1
//! Bitmap font encodings.
2 2
use std::array::TryFromSliceError;
3 +
use std::collections::HashMap;
3 4
use std::fmt;
4 5
use std::ops::Deref;
6 +
use std::rc::Rc;
5 7
6 8
use crate::gfx::pixels::PixelsMut;
7 9
use crate::gfx::*;
8 10
use crate::math::*;
9 11
use crate::string::Str;
10 12
13 +
/// Default font identifier.
14 +
pub const DEFAULT_FONT: FontName = FontName::new("Default");
15 +
11 16
/// Font error.
12 17
#[derive(Debug, Clone)]
13 18
pub enum FontError {
14 19
    TryFromSlice(TryFromSliceError),
15 20
    TileCount(usize, usize),
224 229
    /// such that there is equal space above and below.
225 230
    pub fn line_height(&self) -> u8 {
226 231
        self.cap_height + self.desc_height * 2
227 232
    }
228 233
}
234 +
235 +
/// Font style.
236 +
#[derive(Clone, Copy, Debug, Default)]
237 +
pub enum FontStyle {
238 +
    /// The default font style.
239 +
    #[default]
240 +
    Normal,
241 +
}
242 +
243 +
/// Map of loaded fonts.
244 +
#[derive(Debug)]
245 +
pub struct Fonts<T> {
246 +
    /// The default font.
247 +
    pub default: Rc<Font<T>>,
248 +
    /// All the other loaded fonts.
249 +
    pub(crate) loaded: HashMap<FontName, Rc<Font<T>>>,
250 +
}
251 +
252 +
impl<T> Deref for Fonts<T> {
253 +
    type Target = HashMap<FontName, Rc<Font<T>>>;
254 +
255 +
    fn deref(&self) -> &Self::Target {
256 +
        &self.loaded
257 +
    }
258 +
}
259 +
260 +
impl<T> Fonts<T> {
261 +
    /// Create a new fonts database with a default font.
262 +
    pub fn new(font: Font<T>) -> Self {
263 +
        Self {
264 +
            default: Rc::new(font),
265 +
            loaded: HashMap::new(),
266 +
        }
267 +
    }
268 +
269 +
    /// Include a loaded font in the fonts map.
270 +
    pub fn with(mut self, name: FontName, font: Rc<Font<T>>) -> Self {
271 +
        self.loaded.insert(name, font);
272 +
        self
273 +
    }
274 +
275 +
    /// Lookup a loaded font, or return the default font if not found.
276 +
    pub fn lookup(&self, name: &FontName) -> &Rc<Font<T>> {
277 +
        self.loaded.get(name).unwrap_or(&self.default)
278 +
    }
279 +
}
280 +
281 +
/// UF2 fonts.
282 +
pub mod uf2 {
283 +
    use super::*;
284 +
285 +
    /// Default font.
286 +
    pub const DEFAULT: FontDescriptor<'static> = FontDescriptor {
287 +
        name: DEFAULT_FONT,
288 +
        format: FontFormat::UF2,
289 +
        data: include_bytes!("fonts/gohu14.uf2"),
290 +
        metrics: FontMetrics {
291 +
            cap_height: 9,
292 +
            desc_height: 3,
293 +
            glyph_height: 14,
294 +
            baseline: 3,
295 +
        },
296 +
    };
297 +
298 +
    /// Venice.
299 +
    pub const VENICE: FontDescriptor<'static> = FontDescriptor {
300 +
        name: FontName::new("Venice"),
301 +
        format: FontFormat::UF2,
302 +
        data: include_bytes!("fonts/venice14.uf2"),
303 +
        metrics: FontMetrics {
304 +
            cap_height: 10,
305 +
            desc_height: 4,
306 +
            glyph_height: 16,
307 +
            baseline: 4,
308 +
        },
309 +
    };
310 +
}
ombre/src/ui/gfx/fonts/chicago12.uf2 → ombre/src/gfx/fonts/chicago12.uf2 renamed +0 -0
ombre/src/ui/gfx/fonts/courier12.uf2 → ombre/src/gfx/fonts/courier12.uf2 renamed +0 -0
ombre/src/ui/gfx/fonts/diamond12.uf2 → ombre/src/gfx/fonts/diamond12.uf2 renamed +0 -0
ombre/src/ui/gfx/fonts/geneva12.uf2 → ombre/src/gfx/fonts/geneva12.uf2 renamed +0 -0
ombre/src/ui/gfx/fonts/gohu14.uf2 → ombre/src/gfx/fonts/gohu14.uf2 renamed +0 -0
ombre/src/ui/gfx/fonts/helvetica12.uf2 → ombre/src/gfx/fonts/helvetica12.uf2 renamed +0 -0
ombre/src/ui/gfx/fonts/losangeles12.uf2 → ombre/src/gfx/fonts/losangeles12.uf2 renamed +0 -0
ombre/src/ui/gfx/fonts/monaco12.uf2 → ombre/src/gfx/fonts/monaco12.uf2 renamed +0 -0
ombre/src/ui/gfx/fonts/msx816.uf2 → ombre/src/gfx/fonts/msx816.uf2 renamed +0 -0
ombre/src/ui/gfx/fonts/newyork12.uf2 → ombre/src/gfx/fonts/newyork12.uf2 renamed +0 -0
ombre/src/ui/gfx/fonts/palatino12.uf2 → ombre/src/gfx/fonts/palatino12.uf2 renamed +0 -0
ombre/src/ui/gfx/fonts/sans10-regular.uf2 → ombre/src/gfx/fonts/sans10-regular.uf2 renamed +0 -0
ombre/src/ui/gfx/fonts/sapphire14.uf2 → ombre/src/gfx/fonts/sapphire14.uf2 renamed +0 -0
ombre/src/ui/gfx/fonts/terminal12.uf2 → ombre/src/gfx/fonts/terminal12.uf2 renamed +0 -0
ombre/src/ui/gfx/fonts/venice14.uf2 → ombre/src/gfx/fonts/venice14.uf2 renamed +0 -0
ombre/src/gfx/gl.rs +3 -2
7 7
use glow::HasContext as _;
8 8
9 9
use super::*;
10 10
use crate::bytes::Packed;
11 11
use crate::collections::IntMap;
12 +
use crate::math::ZDepth;
12 13
use types::ToGl as _;
13 14
14 15
pub use error::Error;
15 16
16 17
/// OpenGL context information.
526 527
        }
527 528
528 529
        Ok(())
529 530
    }
530 531
531 -
    fn clear(&mut self, color: Option<Rgba<f32>>, depth: Option<f32>, stencil: Option<i32>) {
532 +
    fn clear(&mut self, color: Option<Rgba<f32>>, depth: Option<ZDepth>, stencil: Option<i32>) {
532 533
        let mut bits = 0;
533 534
        if let Some(color) = color {
534 535
            bits |= glow::COLOR_BUFFER_BIT;
535 536
            unsafe {
536 537
                self.ctx.gl.clear_color(color.r, color.g, color.b, color.a);
538 539
        }
539 540
540 541
        if let Some(v) = depth {
541 542
            bits |= glow::DEPTH_BUFFER_BIT;
542 543
            unsafe {
543 -
                self.ctx.gl.clear_depth_f32(v);
544 +
                self.ctx.gl.clear_depth_f32(*v);
544 545
            }
545 546
        }
546 547
547 548
        if let Some(v) = stencil {
548 549
            bits |= glow::STENCIL_BUFFER_BIT;
ombre/src/gfx/image.rs +2 -2
3 3
use std::sync::Arc;
4 4
5 5
use super::{pixels, Color as _, Point2D, Rect, Rgba8, Size};
6 6
use crate::{
7 7
    bytes::encoding::{Decode, Encode},
8 -
    math::Zero,
8 +
    math::{Local, Zero},
9 9
};
10 10
11 11
/// File extension for RGBA images.
12 12
pub const FILE_EXTENSION: &str = "rgba";
13 13
/// File header magic.
87 87
            pixels: scaled.into(),
88 88
        }
89 89
    }
90 90
91 91
    /// Get the image area rectangle.
92 -
    pub fn rect(&self) -> Rect<u32> {
92 +
    pub fn rect(&self) -> Rect<f32, Local> {
93 93
        Rect::origin(self.size)
94 94
    }
95 95
96 96
    /// Create a blank image of the given size.
97 97
    pub fn blank(size: impl Into<Size<u32>>) -> Self {
ombre/src/gfx/pass.rs +4 -3
1 1
use super::*;
2 +
use crate::math::ZDepth;
2 3
3 4
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
4 5
pub struct PassId(id::Id);
5 6
6 7
impl std::fmt::Display for PassId {
19 20
#[derive(Debug, Clone)]
20 21
pub enum PassAction {
21 22
    Nothing,
22 23
    Clear {
23 24
        color: Option<color::Rgba<f32>>,
24 -
        depth: Option<f32>,
25 +
        depth: Option<ZDepth>,
25 26
        stencil: Option<i32>,
26 27
    },
27 28
}
28 29
29 30
impl PassAction {
30 31
    pub fn clear(color: impl Into<Rgba<f32>>) -> PassAction {
31 32
        PassAction::Clear {
32 33
            color: Some(color.into()),
33 -
            depth: Some(1.),
34 +
            depth: Some(ZDepth::from(1.)),
34 35
            stencil: None,
35 36
        }
36 37
    }
37 38
}
38 39
39 40
impl Default for PassAction {
40 41
    fn default() -> PassAction {
41 42
        PassAction::Clear {
42 43
            color: Some(Rgba::TRANSPARENT),
43 -
            depth: Some(1.),
44 +
            depth: Some(ZDepth::from(1.)),
44 45
            stencil: None,
45 46
        }
46 47
    }
47 48
}
48 49
ombre/src/gfx/sdf/fragment.glsl +1 -1
19 19
// Center position of shape in NDC space.
20 20
uniform vec2 position;
21 21
22 22
// Circle SDF.
23 23
float circle(vec2 p, float radius) {
24 -
    return length(p) - radius;
24 +
    return abs(length(p) - radius);
25 25
}
26 26
27 27
// Box SDF.
28 28
// `p` is the point to test, `h` is the half-width and half-height.
29 29
float box(vec2 p, vec2 h) {
ombre/src/gfx/traits.rs +2 -1
1 1
//! Graphics rendering traits, implemented by backends.
2 2
use crate::bytes::Packed;
3 3
use crate::collections::IntMap;
4 +
use crate::math::ZDepth;
4 5
5 6
use super::*;
6 7
7 8
/// Graphics rendering backend.
8 9
/// This trait is implemented by compatible backends, eg. OpenGL, Vulkan etc.
149 150
        bindings: &Bindings<V, N>,
150 151
    ) -> Result<(), Self::Error>;
151 152
    /// Apply shader uniforms.
152 153
    fn apply_uniforms<T: AsBytes>(&mut self, uniforms: &T) -> Result<(), Self::Error>;
153 154
    /// Clear the view.
154 -
    fn clear(&mut self, color: Option<Rgba<f32>>, depth: Option<f32>, stencil: Option<i32>);
155 +
    fn clear(&mut self, color: Option<Rgba<f32>>, depth: Option<ZDepth>, stencil: Option<i32>);
155 156
    /// Update a buffer. Same as [`RenderBackend::buffer_update`].
156 157
    fn buffer_update<T: Packed>(
157 158
        &mut self,
158 159
        buffer: BufferId,
159 160
        kind: BufferKind,
ombre/src/lib.rs +7 -3
3 3
#![allow(clippy::single_match)]
4 4
#![allow(clippy::collapsible_match)]
5 5
#![allow(clippy::identity_op)]
6 6
#![warn(clippy::unwrap_used)]
7 7
8 -
#[cfg(feature = "draw")]
8 +
#[cfg(feature = "paint")]
9 9
extern crate self as ombre;
10 10
11 11
pub mod array;
12 12
pub mod bench;
13 13
pub mod bytes;
14 14
pub mod collections;
15 -
#[cfg(feature = "draw")]
16 -
pub mod draw;
17 15
pub mod gfx;
18 16
pub mod lenses;
19 17
pub mod lisp;
20 18
pub mod logger;
21 19
pub mod math;
22 20
pub mod platform;
23 21
pub mod rng;
24 22
pub mod runtime;
25 23
pub mod string;
24 +
pub mod text;
26 25
#[cfg(feature = "ui")]
27 26
pub mod ui;
28 27
29 28
#[cfg(feature = "derive")]
30 29
pub mod derive;
31 30
#[cfg(feature = "derive")]
32 31
pub use derive::*;
33 32
33 +
#[cfg(feature = "paint")]
34 +
pub mod paint;
35 +
#[cfg(feature = "paint")]
36 +
pub use paint::{canvas, Canvas};
37 +
34 38
pub use gfx::color;
35 39
pub use glow;
36 40
37 41
/// Crate prelude.
38 42
pub mod prelude {
ombre/src/math/rect.rs +14 -0
59 59
        Rect {
60 60
            origin: Point2D::new(f(self.origin.x), f(self.origin.y)),
61 61
            size: Size::new(f(self.size.w), f(self.size.h)),
62 62
        }
63 63
    }
64 +
65 +
    /// Convert coordinate system.
66 +
    pub fn convert<V>(self) -> Rect<T, V> {
67 +
        Rect {
68 +
            origin: self.origin.convert(),
69 +
            size: self.size,
70 +
        }
71 +
    }
64 72
}
65 73
66 74
impl<T: Copy + std::fmt::Display + Sub<Output = T> + Add<Output = T> + Neg<Output = T>, U>
67 75
    Rect<T, U>
68 76
{
419 427
    fn sub_assign(&mut self, vec: Vector2D<T>) {
420 428
        self.origin = self.origin - vec;
421 429
    }
422 430
}
423 431
432 +
impl<T: Copy + Sub<Output = T>, U> From<Box2D<T, U>> for Rect<T, U> {
433 +
    fn from(b: Box2D<T, U>) -> Self {
434 +
        Rect::new(b.min, b.max - b.min)
435 +
    }
436 +
}
437 +
424 438
/// A 2D box. Like a rectangle, but has a minimum and maximum point instead of an origin and size.
425 439
#[derive(Debug, Clone, PartialEq, Eq)]
426 440
pub struct Box2D<T, U = ()> {
427 441
    /// Minimum point.
428 442
    pub min: Point2D<T, U>,
ombre/src/math/size.rs +6 -0
1 1
use std::fmt;
2 2
use std::ops::{Div, Mul, Sub};
3 3
4 +
use super::Bounded;
4 5
use super::{traits::FloatExt as _, Vector2D, Zero};
5 6
6 7
/// Size.
7 8
#[derive(Debug, Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Default)]
8 9
pub struct Size<T = f32> {
189 190
    fn from(size: Size<T>) -> Self {
190 191
        [size.w, size.h]
191 192
    }
192 193
}
193 194
195 +
impl<T: Bounded> Bounded for Size<T> {
196 +
    const MIN: Self = Size::new(T::MIN, T::MIN);
197 +
    const MAX: Self = Size::new(T::MAX, T::MAX);
198 +
}
199 +
194 200
impl<T: fmt::Display> fmt::Display for Size<T> {
195 201
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 202
        write!(f, "({} x {})", self.w, self.h)
197 203
    }
198 204
}
ombre/src/math/traits.rs +10 -0
205 205
impl Bounded for i64 {
206 206
    const MIN: Self = i64::MIN;
207 207
    const MAX: Self = i64::MAX;
208 208
}
209 209
210 +
impl Bounded for f64 {
211 +
    const MIN: Self = f64::MIN;
212 +
    const MAX: Self = f64::MAX;
213 +
}
214 +
215 +
impl Bounded for f32 {
216 +
    const MIN: Self = f32::MIN;
217 +
    const MAX: Self = f32::MAX;
218 +
}
219 +
210 220
impl Bounded for usize {
211 221
    const MIN: Self = usize::MIN;
212 222
    const MAX: Self = usize::MAX;
213 223
}
214 224
ombre/src/math/transform.rs +13 -0
176 176
            unit: PhantomData,
177 177
        }
178 178
    }
179 179
}
180 180
181 +
impl<Src: Copy, Dst: Copy> Default for Transform2D<Src, Dst> {
182 +
    fn default() -> Self {
183 +
        Transform2D::identity()
184 +
    }
185 +
}
186 +
187 +
impl<Src: Copy, Dst: Copy> From<Vector2D<f32, Src>> for Transform2D<Src, Dst> {
188 +
    #[inline]
189 +
    fn from(other: Vector2D<f32, Src>) -> Self {
190 +
        Transform2D::translate(other)
191 +
    }
192 +
}
193 +
181 194
impl<Src: Copy, Dst: Copy> Mul<Transform2D<Src, Dst>> for Transform2D<Src, Dst> {
182 195
    type Output = Transform2D<Src, Dst>;
183 196
184 197
    /// Multiply without changing the original coordinate system.
185 198
    fn mul(self, mat: Transform2D<Src, Dst>) -> Transform2D<Src, Dst> {
ombre/src/paint.rs added +13 -0
1 +
//! 2D drawing.
2 +
pub mod batch;
3 +
pub mod blit;
4 +
pub mod canvas;
5 +
pub mod pipeline;
6 +
pub mod shape;
7 +
pub mod text;
8 +
pub mod traits;
9 +
10 +
pub use blit::Blit;
11 +
pub use canvas::{canvas, Canvas};
12 +
pub use shape::{Circle, Geometry, Line, Rectangle, Shape};
13 +
pub use traits::{Brush, PaintOp, PaintSurface};
ombre/src/draw/batch.rs → ombre/src/paint/batch.rs renamed +13 -3
1 -
use crate::draw::{blit::Blit, pipeline::Vertex, shape::Shape};
2 1
use crate::gfx::TextureId;
3 2
use crate::math::*;
4 3
5 4
use super::traits::Brush;
5 +
use super::{blit::Blit, pipeline::Vertex, shape::Geometry};
6 6
7 7
/// Information about a texture used in a render batch.
8 8
///
9 9
/// Contains the metadata needed to properly render a texture.
10 10
/// This information is shared across all sprites in a batch that use
38 38
            vertices: Vec::new(),
39 39
            texture,
40 40
        }
41 41
    }
42 42
43 +
    /// Clear all vertices from this batch.
44 +
    pub fn clear(&mut self) {
45 +
        self.vertices.clear();
46 +
    }
47 +
43 48
    /// Fill a shape into the batch.
44 -
    pub fn fill(&mut self, shape: impl Shape, brush: impl Into<Brush>) -> &mut Self {
49 +
    pub fn fill(&mut self, shape: impl Geometry, brush: impl Into<Brush>) -> &mut Self {
45 50
        self.vertices.extend(shape.fill(brush));
46 51
        self
47 52
    }
48 53
49 54
    /// Stroke a shape into the batch.
50 -
    pub fn stroke(&mut self, shape: impl Shape, brush: impl Into<Brush>, width: f32) -> &mut Self {
55 +
    pub fn stroke(
56 +
        &mut self,
57 +
        shape: impl Geometry,
58 +
        brush: impl Into<Brush>,
59 +
        width: f32,
60 +
    ) -> &mut Self {
51 61
        self.vertices.extend(shape.stroke(brush, width));
52 62
        self
53 63
    }
54 64
55 65
    /// Add a sprite blit to the batch.
ombre/src/draw/blit.rs → ombre/src/paint/blit.rs renamed +2 -2
35 35
/// Controls source/destination rectangles, color tinting, opacity and other
36 36
/// rendering parameters.
37 37
#[derive(Clone, Debug, PartialEq)]
38 38
pub struct Blit<U> {
39 39
    /// Source (texture) rectangle.
40 -
    pub src: Rect<f32, Screen>,
40 +
    pub src: Rect<f32, Local>,
41 41
    /// Destination rectangle.
42 42
    pub dst: Rect<f32, U>,
43 43
    /// Z-depth to render at.
44 44
    pub zdepth: ZDepth,
45 45
    /// Tint color.
52 52
    pub repeat: Repeat,
53 53
}
54 54
55 55
impl<U: Default> Blit<U> {
56 56
    /// Create a new blit.
57 -
    pub fn new(src: Rect<f32, Screen>, dst: Rect<f32, U>) -> Self {
57 +
    pub fn new(src: Rect<f32, Local>, dst: Rect<f32, U>) -> Self {
58 58
        Self {
59 59
            src,
60 60
            dst,
61 61
            opacity: 1.,
62 62
            zdepth: ZDepth::default(),
ombre/src/paint/canvas.rs added +628 -0
1 +
//! Canvas rendering system for 2D graphics.
2 +
#![warn(missing_docs)]
3 +
4 +
use std::collections::{HashMap, VecDeque};
5 +
use std::rc::Rc;
6 +
7 +
use crate::math::ZDepth;
8 +
use crate::prelude::*;
9 +
use crate::text::Text;
10 +
use crate::ui::gfx::{font, present};
11 +
12 +
use super::traits::{Brush, Paint, PaintSurface};
13 +
use super::{batch::TextureInfo, batch::VertexBatch, blit::Blit, pipeline, shape::ToGeometry};
14 +
15 +
/// Default number of vertices in the interface VBO.
16 +
/// Roughly 16MB of VRAM. This number has to be divisible by 3,
17 +
/// given that we are drawing triangles.
18 +
pub const DEFAULT_MAX_VERTICES: usize = 2usize.pow(18) - 1;
19 +
/// Default number of texture layers used by the rendering pipeline.
20 +
/// This is the maximum number of distinct texture objects available for rendering.
21 +
pub const DEFAULT_MAX_TEXTURE_LAYERS: usize = 16;
22 +
23 +
/// Errors that can occur during canvas operations.
24 +
pub enum Error<T: RenderBackend> {
25 +
    /// Render backend error.
26 +
    Render(T::Error),
27 +
    /// Font error.
28 +
    Font(font::FontError),
29 +
    /// Config error.
30 +
    Config(&'static str),
31 +
}
32 +
33 +
impl<T: RenderBackend> std::fmt::Debug for Error<T> {
34 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35 +
        write!(f, "{self}")
36 +
    }
37 +
}
38 +
39 +
impl<T: RenderBackend> std::fmt::Display for Error<T> {
40 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 +
        match self {
42 +
            Self::Render(e) => e.fmt(f),
43 +
            Self::Font(e) => e.fmt(f),
44 +
            Self::Config(e) => write!(f, "config: {e}"),
45 +
        }
46 +
    }
47 +
}
48 +
49 +
impl<T: RenderBackend + std::fmt::Debug> std::error::Error for Error<T> {}
50 +
51 +
impl<T: RenderBackend> From<font::FontError> for Error<T> {
52 +
    fn from(e: font::FontError) -> Self {
53 +
        Self::Font(e)
54 +
    }
55 +
}
56 +
57 +
/// Graphics pipeline and its bindings.
58 +
///
59 +
/// Type parameters:
60 +
/// - `N`: Number of vertex buffers
61 +
/// - `M`: Number of texture bindings
62 +
struct Pipeline<const N: usize, const M: usize> {
63 +
    /// The GPU pipeline identifier.
64 +
    pipeline: PipelineId,
65 +
    /// Vertex and texture bindings for this pipeline.
66 +
    bindings: Bindings<N, M>,
67 +
}
68 +
69 +
/// Represents a layer in a 2D texture array, tracking both the source image and its index.
70 +
#[derive(Copy, Clone, PartialEq, Debug)]
71 +
struct TextureLayer {
72 +
    /// The source image ID if this layer contains an image, or `None` if the texture was generated
73 +
    /// programatically, eg. the blank texture used for shape rendering.
74 +
    image: Option<ImageId>,
75 +
    /// The GPU texture layer index where this texture is stored.
76 +
    index: u8,
77 +
}
78 +
79 +
/// Internal rendering operations that need to be processed during the next frame.
80 +
enum Op {
81 +
    /// Upload an image to a specific texture layer.
82 +
    UploadImage {
83 +
        /// The image data to upload.
84 +
        image: Image,
85 +
        /// The target texture layer index.
86 +
        layer: u8,
87 +
    },
88 +
}
89 +
90 +
/// Manages the state for a batched rendering system with a fixed number of texture layers.
91 +
///
92 +
/// RenderState tracks texture allocation, paint operations, and vertex batching for efficient
93 +
/// GPU rendering. It uses a fixed-size array of texture layers.
94 +
///
95 +
/// The system auto-allocates texture layers as needed when blitting images, up to the maximum
96 +
/// supported by the GPU (constant `N`). Each layer maintains its original size information, for
97 +
/// proper UV coordinate calculation in the shaders.
98 +
struct RenderState<const N: usize> {
99 +
    /// Array of texture layers
100 +
    /// The first slot is reserved for the blank texture used in shape rendering.
101 +
    textures: [Option<TextureLayer>; N],
102 +
    /// Parallel array to `textures` storing the dimensions of each image.
103 +
    /// Used for UV coordinate calculations.
104 +
    sizes: [Size<u32>; N],
105 +
    /// Accumulates vertices for all paint operations in the current batch.
106 +
    /// Used to minimize draw calls by batching compatible operations together.
107 +
    batch: VertexBatch,
108 +
    /// Queue of pending render operations to execute in the next frame.
109 +
    queue: VecDeque<Op>,
110 +
}
111 +
112 +
impl<const N: usize> RenderState<N> {
113 +
    fn new(texture: TextureInfo) -> Self {
114 +
        let mut textures = [None; N];
115 +
        let sizes = [texture.size; N];
116 +
117 +
        // The first layer contains a blank texture used for rendering shapes.
118 +
        textures[0] = Some(TextureLayer {
119 +
            image: None,
120 +
            index: 0,
121 +
        });
122 +
123 +
        Self {
124 +
            textures,
125 +
            sizes,
126 +
            batch: VertexBatch::new(texture),
127 +
            queue: VecDeque::new(),
128 +
        }
129 +
    }
130 +
131 +
    // Helper function to find or create texture layer.
132 +
    fn get_or_create_layer(&mut self, image: Image) -> Option<TextureLayer> {
133 +
        // First try to find an existing layer with the given image.
134 +
        if let Some(&layer) = self.textures.iter().flatten().find(|l| l.image == Some(image.id())) {
135 +
            return Some(layer);
136 +
        }
137 +
        // Then try to create new layer.
138 +
        let index = self.textures.iter().position(Option::is_none)?;
139 +
        let layer = TextureLayer {
140 +
            image: Some(image.id()),
141 +
            index: index as u8,
142 +
        };
143 +
        self.textures[index] = Some(layer);
144 +
        self.sizes[index] = image.size;
145 +
        self.queue.push_back(Op::UploadImage {
146 +
            image,
147 +
            layer: layer.index,
148 +
        });
149 +
        Some(layer)
150 +
    }
151 +
}
152 +
153 +
/// Configuration options for the canvas rendering system.
154 +
pub struct Config {
155 +
    /// Maximum number of vertices that can be allocated by the renderer.
156 +
    /// Defaults to [`DEFAULT_MAX_VERTICES`].
157 +
    pub max_vertices: usize,
158 +
}
159 +
160 +
impl Default for Config {
161 +
    fn default() -> Self {
162 +
        Self {
163 +
            max_vertices: DEFAULT_MAX_VERTICES,
164 +
        }
165 +
    }
166 +
}
167 +
168 +
/// Builder for configuring and creating a new [`Canvas`] instance.
169 +
pub struct CanvasBuilder<'r, R: RenderBackend> {
170 +
    scale: f32,
171 +
    size: Size<f32>,
172 +
    debug: bool,
173 +
    fonts: HashMap<FontName, Rc<Font<Image>>>,
174 +
    config: Config,
175 +
    backend: &'r mut R,
176 +
}
177 +
178 +
impl<'r, R: RenderBackend> CanvasBuilder<'r, R> {
179 +
    /// Creates a new canvas builder with the given maximum canvas size and rendering backend.
180 +
    pub fn new(size: Size<f32>, backend: &'r mut R) -> Self {
181 +
        Self {
182 +
            debug: false,
183 +
            size,
184 +
            scale: 1.,
185 +
            fonts: HashMap::default(),
186 +
            config: Config::default(),
187 +
            backend,
188 +
        }
189 +
    }
190 +
}
191 +
192 +
/// Creates a new canvas builder with the specified size and rendering backend.
193 +
pub fn canvas<R: RenderBackend>(size: Size<f32>, backend: &mut R) -> CanvasBuilder<'_, R> {
194 +
    CanvasBuilder::new(size, backend)
195 +
}
196 +
197 +
impl<R: RenderBackend> CanvasBuilder<'_, R> {
198 +
    /// Load a font.
199 +
    pub fn font(mut self, desc: FontDescriptor<'_>) -> Result<Self, Error<R>> {
200 +
        let name = desc.name;
201 +
        let font = self._font(desc)?;
202 +
203 +
        self.fonts.insert(name, font);
204 +
205 +
        Ok(self)
206 +
    }
207 +
208 +
    /// Set the interface scale.
209 +
    pub fn scale(mut self, scale: f32) -> Self {
210 +
        self.scale = scale;
211 +
        self
212 +
    }
213 +
214 +
    /// Set the interface configuration.
215 +
    pub fn config(mut self, config: Config) -> Self {
216 +
        self.config = config;
217 +
        self
218 +
    }
219 +
220 +
    /// Set debug mode.
221 +
    pub fn debug(mut self, debug: bool) -> Self {
222 +
        self.debug = debug;
223 +
        self
224 +
    }
225 +
226 +
    /// Build the interface by giving it the root of the widget tree.
227 +
    pub fn build(mut self) -> Result<Canvas, Error<R>> {
228 +
        let default = self._font(font::uf2::DEFAULT)?;
229 +
        // Adjust max vertices to fit complete triangles.
230 +
        self.config.max_vertices -= self.config.max_vertices % pipeline::VERTEX_STRIDE;
231 +
        self._build(default).map_err(Error::Render)
232 +
    }
233 +
234 +
    /// Inner build function.
235 +
    fn _build(self, default: Rc<Font<Image>>) -> Result<Canvas, R::Error> {
236 +
        // Ensure the renderable viewport is a multiple of the scale.
237 +
        let size = Size::new(
238 +
            self.size.w - self.size.w % self.scale,
239 +
            self.size.h - self.size.h % self.scale,
240 +
        );
241 +
        let size_scaled = size / self.scale;
242 +
        let size_max = self.size;
243 +
        let offscreen_depth = self.backend.texture(gfx::Texture {
244 +
            data: gfx::Empty,
245 +
            access: gfx::TextureAccess::RenderTarget,
246 +
            size: size_scaled.map(|n| n as u32),
247 +
            format: gfx::TextureFormat::Depth,
248 +
            ..Default::default()
249 +
        })?;
250 +
        let offscreen_color = self.backend.texture(gfx::Texture {
251 +
            data: gfx::Empty,
252 +
            target: TextureKind::default(),
253 +
            size: size_scaled.map(|n| n as u32),
254 +
            access: gfx::TextureAccess::RenderTarget,
255 +
            wrap: gfx::TextureWrap::Clamp,
256 +
            format: gfx::TextureFormat::Rgba8,
257 +
            min_filter: FilterMode::Nearest,
258 +
            mag_filter: FilterMode::Nearest,
259 +
        })?;
260 +
        let offscreen = self.backend.pass(gfx::PassDescriptor {
261 +
            color_attachments: &[offscreen_color],
262 +
            depth_attachment: Some(offscreen_depth),
263 +
        })?;
264 +
265 +
        let layers = self.backend.texture(Texture {
266 +
            data: gfx::Empty,
267 +
            size: Size::new(256, 256),
268 +
            access: TextureAccess::Static,
269 +
            target: TextureKind::Texture2DArray { arity: 16 },
270 +
            format: TextureFormat::Srgba8,
271 +
            wrap: TextureWrap::Repeat,
272 +
            min_filter: FilterMode::Nearest,
273 +
            mag_filter: FilterMode::Nearest,
274 +
        })?;
275 +
        self.backend.texture_update_layer(
276 +
            layers,
277 +
            0,
278 +
            Rect::origin([256, 256]),
279 +
            &[Rgba8::WHITE; 256 * 256],
280 +
        )?;
281 +
        let vbo = self.backend.buffer(
282 +
            gfx::BufferKind::Vertex,
283 +
            gfx::BufferUsage::Stream,
284 +
            gfx::BufferSource::<pipeline::Vertex>::empty(self.config.max_vertices),
285 +
        )?;
286 +
        let shade = Pipeline {
287 +
            pipeline: pipeline::create::<_, DEFAULT_MAX_TEXTURE_LAYERS>(self.backend)?,
288 +
            bindings: gfx::Bindings {
289 +
                vertex: [vbo],
290 +
                index: None,
291 +
                textures: [layers],
292 +
            },
293 +
        };
294 +
        let present = Pipeline {
295 +
            pipeline: present::pipeline(self.backend)?,
296 +
            bindings: gfx::Bindings {
297 +
                vertex: [],
298 +
                index: None,
299 +
                textures: [offscreen_color],
300 +
            },
301 +
        };
302 +
        let layers = TextureInfo {
303 +
            id: layers,
304 +
            size: Size::new(256, 256),
305 +
        };
306 +
        let render = RenderState::new(layers);
307 +
        let fonts = Fonts {
308 +
            default,
309 +
            loaded: self.fonts,
310 +
        };
311 +
312 +
        Ok(Canvas {
313 +
            offscreen,
314 +
            debug: DebugState::default(),
315 +
            action: Some(PassAction::default()),
316 +
            stack: Vec::with_capacity(16),
317 +
            shade,
318 +
            present,
319 +
            size,
320 +
            size_scaled,
321 +
            size_viewport: size_max,
322 +
            scale: self.scale,
323 +
            transform: Transform2D::identity(),
324 +
            render,
325 +
            fonts,
326 +
            config: self.config,
327 +
        })
328 +
    }
329 +
330 +
    fn _font(&mut self, desc: FontDescriptor<'_>) -> Result<Rc<Font<Image>>, Error<R>> {
331 +
        let Font {
332 +
            widths,
333 +
            image,
334 +
            format,
335 +
            metrics,
336 +
        } = desc.decode()?;
337 +
338 +
        Ok(Rc::new(Font {
339 +
            widths,
340 +
            image,
341 +
            format,
342 +
            metrics,
343 +
        }))
344 +
    }
345 +
}
346 +
347 +
/// Holds debug render state.
348 +
#[derive(Default)]
349 +
struct DebugState {
350 +
    /// Whether debug overlays should be rendered.
351 +
    visible: bool,
352 +
}
353 +
354 +
/// A 2D drawing canvas that provides batched rendering capabilities.
355 +
///
356 +
/// The Canvas manages texture allocation, vertex batching, and provides a high-level
357 +
/// drawing API for shapes, images and text. It uses a fixed number of texture layers
358 +
/// specified by the type parameter `N`.
359 +
pub struct Canvas<const N: usize = DEFAULT_MAX_TEXTURE_LAYERS> {
360 +
    /// Size of the canvas. This is the usable area of the viewport.
361 +
    /// It might be smaller than the full viewport if the viewport is not a
362 +
    /// multiple of the scaling factor. This avoids stretching pixels.
363 +
    size: Size<f32>,
364 +
    /// Size of renderable viewport. This is the size available to render the canvas.
365 +
    size_viewport: Size<f32>,
366 +
    /// Size of the canvas, scaled (divided) by the `scale` factor.
367 +
    size_scaled: Size<f32>,
368 +
    /// Transform stack. Used by [`Canvas::save`] and [`Canvas::restore`].
369 +
    stack: Vec<Transform2D<Local, Screen>>,
370 +
    /// Current transform.
371 +
    transform: Transform2D<Local, Screen>,
372 +
    /// UI scale.
373 +
    scale: f32,
374 +
    /// Offscreen pass ID.
375 +
    offscreen: PassId,
376 +
    /// Shading stage pipeline.
377 +
    shade: Pipeline<1, 1>,
378 +
    /// Present to screen pipeline.
379 +
    present: Pipeline<0, 1>,
380 +
    /// Render state.
381 +
    render: RenderState<N>,
382 +
    /// Debug state.
383 +
    debug: DebugState,
384 +
    /// Next pass action.
385 +
    action: Option<PassAction>,
386 +
    /// Loaded fonts.
387 +
    fonts: Fonts<Image>,
388 +
    /// Canvas configuration.
389 +
    config: Config,
390 +
}
391 +
392 +
impl<const N: usize> Canvas<N> {
393 +
    /// Returns the current size of the drawable area in logical pixels.
394 +
    pub fn size(&self) -> Size<f32> {
395 +
        self.size
396 +
    }
397 +
398 +
    /// Returns a reference to the font library used by this canvas.
399 +
    pub fn fonts(&self) -> &Fonts<Image> {
400 +
        &self.fonts
401 +
    }
402 +
403 +
    /// Returns the current scaling factor applied to the canvas.
404 +
    pub fn scale(&self) -> f32 {
405 +
        self.scale
406 +
    }
407 +
408 +
    /// Set the debug overlay visibility.
409 +
    /// When enabled, additional debug information will be rendered on top of the canvas.
410 +
    pub fn debug(&mut self, visible: bool) {
411 +
        self.debug.visible = visible;
412 +
    }
413 +
414 +
    /// Resize the canvas to the specified size.
415 +
    pub fn resize<R: RenderBackend>(
416 +
        &mut self,
417 +
        size: platform::LogicalSize,
418 +
        backend: &mut R,
419 +
    ) -> Result<(), R::Error> {
420 +
        // When the canvas is resized, we want to keep pixels aligned to the pixel grid,
421 +
        // even when UI scaling is used. To do this, we render to a subarea of the canvas's
422 +
        // framebuffer: the largest area with a size that is a multiple of the `scale`
423 +
        // value.
424 +
        let bounds = Size::new(size.width as f32, size.height as f32);
425 +
        let bounds_aligned = {
426 +
            // Snap to the nearest multiple of the UI `scale`.
427 +
            let w = bounds.w - bounds.w % self.scale;
428 +
            let h = bounds.h - bounds.h % self.scale;
429 +
430 +
            // Ensure minimum size.
431 +
            let w = w.max(self.scale);
432 +
            let h = h.max(self.scale);
433 +
434 +
            Size::new(w, h)
435 +
        };
436 +
437 +
        self.size = bounds_aligned;
438 +
        self.size_viewport = bounds;
439 +
        self.size_scaled = bounds_aligned / self.scale;
440 +
441 +
        log::debug!(
442 +
            target: "ui",
443 +
            "canvas resized to {}, aligned to {}, scaled by {} from {}",
444 +
            self.size_viewport,
445 +
            self.size,
446 +
            self.scale,
447 +
            self.size_scaled,
448 +
        );
449 +
        backend.pass_resize_attachments(self.offscreen, self.size_scaled.map(|n| n as u32))?;
450 +
451 +
        Ok(())
452 +
    }
453 +
454 +
    /// Renders the current batch of vertices using the shading pipeline.
455 +
    ///
456 +
    /// This handles splitting large batches into multiple draw calls if they exceed
457 +
    /// the maximum vertex buffer size.
458 +
    fn draw_render_state<'f, F: RenderFrame<'f>>(
459 +
        &mut self,
460 +
        viewport: Size<f32>,
461 +
        frame: &mut F,
462 +
    ) -> Result<(), F::Error> {
463 +
        let batch = self.render.batch.vertices();
464 +
        let length = batch.len();
465 +
        let chunk = self.config.max_vertices.min(length);
466 +
        let bindings = &self.shade.bindings;
467 +
468 +
        frame.apply_pipeline(&self.shade.pipeline)?;
469 +
        frame.apply_uniforms(&pipeline::Uniforms::new(
470 +
            viewport,
471 +
            Transform3D::identity(),
472 +
            self.render.sizes,
473 +
        ))?;
474 +
475 +
        if !batch.is_empty() {
476 +
            if length > self.config.max_vertices {
477 +
                log::debug!(
478 +
                    target: "ui",
479 +
                    "vertex buffer capacity ({}) exceeded, \
480 +
                    splitting batch render of {length} vertices into {} draw calls..",
481 +
                    self.config.max_vertices,
482 +
                    length.div_ceil(chunk)
483 +
                );
484 +
            }
485 +
            for chunk in batch.chunks(chunk) {
486 +
                frame.buffer_update(bindings.vertex[0], BufferKind::Vertex, 0, chunk)?;
487 +
                frame.apply_bindings(bindings)?;
488 +
                frame.draw(0, chunk.len(), 1)?;
489 +
            }
490 +
        }
491 +
        Ok(())
492 +
    }
493 +
}
494 +
495 +
impl<const N: usize> PaintSurface for Canvas<N> {
496 +
    fn clear(&mut self) {
497 +
        self.render.batch.clear();
498 +
        self.action = Some(PassAction::Clear {
499 +
            color: Some(Rgba::TRANSPARENT),
500 +
            depth: Some(ZDepth::from(1.)),
501 +
            stencil: None,
502 +
        });
503 +
    }
504 +
505 +
    fn fill(&mut self, shape: impl ToGeometry, brush: impl Into<Brush>) {
506 +
        self.render.batch.fill(shape.transform(self.transform), brush);
507 +
    }
508 +
509 +
    fn stroke(&mut self, shape: impl ToGeometry, brush: impl Into<Brush>, width: f32) {
510 +
        self.render
511 +
            .batch
512 +
            .stroke(shape.transform(self.transform), brush, width);
513 +
    }
514 +
515 +
    fn mask(&mut self, _shape: impl ToGeometry) {
516 +
        todo!()
517 +
    }
518 +
519 +
    fn save(&mut self) {
520 +
        self.stack.push(self.transform);
521 +
    }
522 +
523 +
    fn restore(&mut self) {
524 +
        self.transform = self.stack.pop().unwrap_or_default();
525 +
    }
526 +
527 +
    fn transform(&mut self, transform: impl Into<Transform2D<Local, Screen>>) {
528 +
        self.transform = transform.into() * self.transform;
529 +
    }
530 +
531 +
    fn blit(
532 +
        &mut self,
533 +
        image: Image,
534 +
        src: impl Into<Rect<f32, Local>>,
535 +
        dst: impl Into<Rect<f32, Local>>,
536 +
        tint: impl Into<Rgba<f32>>,
537 +
        opacity: f32,
538 +
    ) {
539 +
        let Some(layer) = self.render.get_or_create_layer(image) else {
540 +
            log::error!(
541 +
                target: "ui",
542 +
                "texture limit exceeded: renderer only supports {N} concurrent texture(s)"
543 +
            );
544 +
            return;
545 +
        };
546 +
        let src = src.into();
547 +
        let dst = dst.into();
548 +
549 +
        self.render.batch.blit(
550 +
            Blit::new(src, dst.transform(self.transform))
551 +
                .tint(tint)
552 +
                .opacity(opacity),
553 +
            layer.index,
554 +
        );
555 +
    }
556 +
557 +
    fn text<'a>(&mut self, text: impl Into<Text<'a>>, dst: impl Into<Point2D<f32, Local>>) {
558 +
        let offset = Vector2D::from(dst.into());
559 +
        let text = text.into();
560 +
        let layout = text.build(&self.fonts);
561 +
562 +
        self.with_transform(offset, |c| {
563 +
            layout.paint(c);
564 +
        });
565 +
    }
566 +
567 +
    fn read(&mut self, _src: impl Into<Rect<f32>>) -> Result<Image, super::traits::Error> {
568 +
        todo!()
569 +
    }
570 +
571 +
    fn status(&mut self) -> Result<(), super::traits::Error> {
572 +
        Ok(())
573 +
    }
574 +
575 +
    fn flush<'f, F: RenderFrame<'f>>(&mut self, frame: &mut F) -> Result<(), F::Error> {
576 +
        self.transform = Transform2D::identity();
577 +
        self.stack.clear();
578 +
579 +
        for op in self.render.queue.drain(..) {
580 +
            match op {
581 +
                Op::UploadImage { image, layer } => {
582 +
                    // Update backend texture layer with image data.
583 +
                    if let Err(e) = frame.backend_mut().texture_update_layer(
584 +
                        self.render.batch.texture.id,
585 +
                        layer,
586 +
                        Rect::origin(image.size),
587 +
                        &image.pixels,
588 +
                    ) {
589 +
                        log::error!(target: "ui", "texture layer update error: {e}");
590 +
                    }
591 +
                }
592 +
            }
593 +
        }
594 +
595 +
        // Begin offscreen pass.
596 +
        frame.begin_pass(
597 +
            self.offscreen,
598 +
            self.action.take().unwrap_or(PassAction::Nothing),
599 +
        );
600 +
        self.draw_render_state(self.size_scaled, frame)?;
601 +
        frame.end_pass();
602 +
603 +
        // Begin onscreen pass.
604 +
        //
605 +
        // The size of the pass is the full backbuffer size, so we clear to that size. But
606 +
        // we're only going to be drawing to a viewport that is the size of the aligned
607 +
        // window size.
608 +
        frame.begin_default_pass(PassAction::default(), self.size_viewport.map(|n| n as u32));
609 +
        frame.apply_viewport(Rect::new(
610 +
            [0, self.size_viewport.h as i32 - self.size.h as i32],
611 +
            self.size.map(|n| n as i32),
612 +
        ))?;
613 +
        frame.apply_pipeline(&self.present.pipeline)?;
614 +
        frame.apply_uniforms(&())?;
615 +
        frame.apply_bindings(&self.present.bindings)?;
616 +
        // Draw the screen quad which consists in two triangles. The vertex data is in a static
617 +
        // variable in the shader, so there is no need to bind any buffer here.
618 +
        frame.draw(0, 6, 1)?;
619 +
620 +
        if self.debug.visible {
621 +
            // TODO: Add debug information here.
622 +
            self.draw_render_state(self.size_viewport, frame)?;
623 +
        }
624 +
        frame.end_pass();
625 +
626 +
        Ok(())
627 +
    }
628 +
}
ombre/src/draw/pipeline.rs → ombre/src/paint/pipeline.rs renamed +3 -0
10 10
use crate::derive::VertexAttributes;
11 11
use crate::gfx;
12 12
use crate::gfx::*;
13 13
use crate::math::{Origin, Size, Transform3D};
14 14
15 +
/// Number of vertices per primitive.
16 +
pub const VERTEX_STRIDE: usize = 3;
17 +
15 18
/// A vertex in the rendering pipeline.
16 19
/// Contains all the attributes needed for rendering sprites and shapes.
17 20
#[repr(C)]
18 21
#[derive(Copy, Clone, Debug, VertexAttributes)]
19 22
pub struct Vertex {
ombre/src/draw/shaders/fragment.glsl → ombre/src/paint/shaders/fragment.glsl renamed +0 -0
ombre/src/draw/shaders/vertex.glsl → ombre/src/paint/shaders/vertex.glsl renamed +0 -0
ombre/src/draw/shape.rs → ombre/src/paint/shape.rs renamed +151 -37
1 1
//! Shape rendering.
2 2
use std::f32;
3 3
use std::fmt;
4 +
use std::ops::Deref;
4 5
5 6
use crate::gfx::Rgba;
6 7
use crate::math::rect::{Box2D, Rect};
7 8
use crate::math::*;
8 9
76 77
    }
77 78
}
78 79
79 80
/// A rectangular shape that can be rendered.
80 81
#[derive(Debug, Clone)]
81 -
pub struct Rectangle {
82 +
pub struct Rectangle<U = Local> {
82 83
    /// Position and size in screen space.
83 -
    rect: Rect<f32, Screen>,
84 +
    rect: Rect<f32, U>,
84 85
    /// Z-depth for controlling render order.
85 86
    zdepth: ZDepth,
86 87
    /// Rotation around a point.
87 88
    rotation: Rotation,
88 89
}
89 90
90 -
impl From<Rect<f32, Screen>> for Rectangle {
91 +
impl<U> From<Rect<f32, U>> for Rectangle<U> {
91 92
    /// Creates a rectangle from a screen-space rect.
92 -
    fn from(rect: Rect<f32, Screen>) -> Self {
93 +
    fn from(rect: Rect<f32, U>) -> Self {
93 94
        Self::new(rect.origin, rect.size)
94 95
    }
95 96
}
96 97
97 -
impl Rectangle {
98 +
impl Deref for Rectangle {
99 +
    type Target = Rect<f32, Local>;
100 +
101 +
    fn deref(&self) -> &Self::Target {
102 +
        &self.rect
103 +
    }
104 +
}
105 +
106 +
impl<U> Rectangle<U> {
98 107
    /// Create a new rectangle.
99 -
    pub fn new(origin: impl Into<Point2D<f32, Screen>>, size: impl Into<Size>) -> Self {
108 +
    pub fn new(origin: impl Into<Point2D<f32, U>>, size: impl Into<Size>) -> Self {
100 109
        Self {
101 110
            rect: Rect::new(origin, size),
102 111
            zdepth: ZDepth::default(),
103 112
            rotation: Rotation::default(),
104 113
        }
105 114
    }
106 115
116 +
    /// Create a new rectangle at the origin.
117 +
    pub fn origin(size: impl Into<Size>) -> Self {
118 +
        Self::new(Point2D::<f32, U>::ORIGIN, size)
119 +
    }
120 +
107 121
    /// Set the z-depth.
108 122
    pub fn zdepth(self, zdepth: impl Into<ZDepth>) -> Self {
109 123
        Self {
110 124
            zdepth: zdepth.into(),
111 125
            ..self
118 132
        let rotation = Rotation::new(angle, center);
119 133
        Self { rotation, ..self }
120 134
    }
121 135
}
122 136
123 -
/// A shape is any object that can be converted into renderable vertices.
137 +
#[derive(Debug, Clone)]
138 +
pub enum Shape<U> {
139 +
    Rectangle(Rectangle<U>),
140 +
    Circle(Circle<U>),
141 +
    Line(Line<U>),
142 +
}
143 +
144 +
impl Shape<Local> {
145 +
    pub fn transform(self, t: Transform2D<Local, Screen>) -> Shape<Screen> {
146 +
        match self {
147 +
            Self::Rectangle(s) => s.transform(t).into(),
148 +
            Self::Circle(s) => s.transform(t).into(),
149 +
            Self::Line(s) => s.transform(t).into(),
150 +
        }
151 +
    }
152 +
}
153 +
154 +
impl<U> From<Line<U>> for Shape<U> {
155 +
    fn from(value: Line<U>) -> Self {
156 +
        Self::Line(value)
157 +
    }
158 +
}
159 +
160 +
impl<U> From<Rectangle<U>> for Shape<U> {
161 +
    fn from(value: Rectangle<U>) -> Self {
162 +
        Self::Rectangle(value)
163 +
    }
164 +
}
165 +
166 +
impl<U> From<Circle<U>> for Shape<U> {
167 +
    fn from(value: Circle<U>) -> Self {
168 +
        Self::Circle(value)
169 +
    }
170 +
}
171 +
172 +
impl<U> From<Rect<f32, U>> for Shape<U> {
173 +
    fn from(rect: Rect<f32, U>) -> Self {
174 +
        Shape::Rectangle(Rectangle::from(rect))
175 +
    }
176 +
}
177 +
178 +
/// Geometry can be converted into renderable vertices.
124 179
///
125 180
/// This trait allows different geometric shapes to be rendered by converting
126 181
/// them into a sequence of vertices that define their visual representation.
127 182
/// Implementations should generate the appropriate vertex data for the shape,
128 183
/// including position, color, texture coordinates and other attributes needed
129 184
/// for rendering.
130 -
pub trait Shape: fmt::Debug {
185 +
pub trait Geometry: fmt::Debug {
131 186
    /// Return the vertices for this shape's fill.
132 -
    fn fill<'a>(&self, brush: impl Into<Brush>) -> impl Iterator<Item = Vertex> + 'a;
187 +
    fn fill<'a>(self, brush: impl Into<Brush>) -> impl Iterator<Item = Vertex> + 'a;
133 188
    /// Return the vertices for this shape's stroke.
134 -
    fn stroke<'a>(&self, brush: impl Into<Brush>, width: f32) -> impl Iterator<Item = Vertex> + 'a;
189 +
    fn stroke<'a>(self, brush: impl Into<Brush>, width: f32) -> impl Iterator<Item = Vertex> + 'a;
135 190
}
136 191
137 -
impl Shape for Rectangle {
138 -
    fn fill<'a>(&self, brush: impl Into<Brush>) -> impl Iterator<Item = Vertex> + 'a {
192 +
pub trait ToGeometry: fmt::Debug {
193 +
    type Transformed: Geometry;
194 +
195 +
    /// Transform this shape according to the given transformation.
196 +
    fn transform(self, t: Transform2D<Local, Screen>) -> Self::Transformed;
197 +
}
198 +
199 +
impl ToGeometry for Rect<f32, Local> {
200 +
    type Transformed = Rect<f32, Screen>;
201 +
202 +
    fn transform(self, t: Transform2D<Local, Screen>) -> Self::Transformed {
203 +
        self.transform(t)
204 +
    }
205 +
}
206 +
207 +
impl Geometry for Rect<f32, Screen> {
208 +
    fn fill<'a>(self, brush: impl Into<Brush>) -> impl Iterator<Item = Vertex> + 'a {
209 +
        Rectangle::from(self).fill(brush)
210 +
    }
211 +
212 +
    fn stroke<'a>(self, brush: impl Into<Brush>, width: f32) -> impl Iterator<Item = Vertex> + 'a {
213 +
        Rectangle::from(self).stroke(brush, width)
214 +
    }
215 +
}
216 +
217 +
impl ToGeometry for Rectangle<Local> {
218 +
    type Transformed = Rectangle<Screen>;
219 +
220 +
    fn transform(self, t: Transform2D<Local, Screen>) -> Self::Transformed {
221 +
        Rectangle {
222 +
            rect: self.rect.transform(t),
223 +
            zdepth: self.zdepth,
224 +
            rotation: self.rotation,
225 +
        }
226 +
    }
227 +
}
228 +
229 +
impl Geometry for Rectangle<Screen> {
230 +
    fn fill<'a>(self, brush: impl Into<Brush>) -> impl Iterator<Item = Vertex> + 'a {
139 231
        let outer = Box2D::from(self.rect);
140 232
        let z = *self.zdepth;
141 233
        let Rotation { angle, center } = self.rotation;
142 234
143 235
        match brush.into() {
154 246
155 247
            Brush::LinearGradient(_) => unimplemented!(),
156 248
        }
157 249
    }
158 250
159 -
    fn stroke<'a>(&self, brush: impl Into<Brush>, width: f32) -> impl Iterator<Item = Vertex> + 'a {
251 +
    fn stroke<'a>(self, brush: impl Into<Brush>, width: f32) -> impl Iterator<Item = Vertex> + 'a {
160 252
        let outer = Box2D::from(self.rect);
161 253
        let inner = Box2D::<_, Screen>::new(
162 254
            Point2D::new(outer.min.x + width, outer.min.y + width),
163 255
            Point2D::new(outer.max.x - width, outer.max.y - width),
164 256
        );
204 296
    }
205 297
}
206 298
207 299
/// A circular shape that can be rendered.
208 300
#[derive(Clone, Debug)]
209 -
pub struct Circle {
301 +
pub struct Circle<U = Local> {
210 302
    /// Origin point (center).
211 -
    origin: Point2D,
303 +
    origin: Point2D<f32, U>,
212 304
    /// Radius.
213 305
    radius: f32,
214 306
    /// Number of sides (for approximating the circle).
215 307
    sides: u32,
216 308
    /// Z-depth for controlling render order.
217 309
    zdepth: ZDepth,
218 310
}
219 311
220 -
impl Circle {
312 +
impl<U> Circle<U> {
221 313
    /// Create a circle.
222 -
    pub fn new(origin: impl Into<Point2D>, radius: f32, sides: u32) -> Self {
314 +
    pub fn new(origin: impl Into<Point2D<f32, U>>, radius: f32, sides: u32) -> Self {
223 315
        let origin = origin.into();
224 316
225 317
        Self {
226 318
            origin,
227 319
            radius,
229 321
            zdepth: ZDepth::default(),
230 322
        }
231 323
    }
232 324
}
233 325
234 -
impl Shape for Circle {
235 -
    fn fill<'a>(&self, brush: impl Into<Brush>) -> impl Iterator<Item = Vertex> + 'a {
326 +
impl ToGeometry for Circle<Local> {
327 +
    type Transformed = Circle<Screen>;
328 +
329 +
    fn transform(self, t: Transform2D<Local, Screen>) -> Self::Transformed {
330 +
        Self::Transformed {
331 +
            radius: self.radius,
332 +
            sides: self.sides,
333 +
            origin: self.origin.transform(t),
334 +
            zdepth: self.zdepth,
335 +
        }
336 +
    }
337 +
}
338 +
339 +
impl Geometry for Circle<Screen> {
340 +
    fn fill<'a>(self, brush: impl Into<Brush>) -> impl Iterator<Item = Vertex> + 'a {
236 341
        let brush = brush.into();
237 342
        let z = *self.zdepth;
238 343
        let sides = self.sides as usize;
239 344
240 345
        match brush {
265 370
            }
266 371
            Brush::LinearGradient(_) => unimplemented!(),
267 372
        }
268 373
    }
269 374
270 -
    fn stroke<'a>(&self, brush: impl Into<Brush>, width: f32) -> impl Iterator<Item = Vertex> + 'a {
375 +
    fn stroke<'a>(self, brush: impl Into<Brush>, width: f32) -> impl Iterator<Item = Vertex> + 'a {
271 376
        let z = *self.zdepth;
272 377
        let sides = self.sides as usize;
273 378
274 379
        match brush.into() {
275 380
            Brush::Color(color) => {
315 420
    }
316 421
}
317 422
318 423
/// A line segment that can be rendered.
319 424
#[derive(Clone, Debug)]
320 -
pub struct Line {
425 +
pub struct Line<U = Local> {
321 426
    /// Start point in screen space.
322 -
    from: Point2D<f32, Screen>,
427 +
    from: Point2D<f32, U>,
323 428
    /// End point in screen space.
324 -
    to: Point2D<f32, Screen>,
429 +
    to: Point2D<f32, U>,
325 430
    /// Z-depth for controlling render order.
326 431
    zdepth: ZDepth,
327 432
    /// Rotation.
328 433
    rotation: Rotation,
329 434
}
330 435
331 -
impl Line {
436 +
impl<U: Copy> Line<U> {
332 437
    /// Creates a new line between two points in screen space.
333 438
    /// The line can be styled with color and width.
334 -
    pub fn new<P: Into<Point2D<f32, Screen>>>(from: P, to: P) -> Self {
439 +
    pub fn new<P: Into<Point2D<f32, U>>, Q: Into<Point2D<f32, U>>>(from: P, to: Q) -> Self {
335 440
        Self {
336 441
            from: from.into(),
337 442
            to: to.into(),
338 443
            zdepth: ZDepth::default(),
339 444
            rotation: Rotation::default(),
340 445
        }
341 446
    }
342 447
343 448
    /// Transform a line.
344 -
    pub fn transform(self, m: impl Into<Transform2D<Screen, Screen>>) -> Self {
345 -
        let t = m.into();
449 +
    pub fn transform(self, t: impl Into<Transform2D<U, Screen>>) -> Line<Screen> {
450 +
        let t = t.into();
346 451
347 -
        Self {
452 +
        Line {
348 453
            from: t * self.from,
349 454
            to: t * self.to,
350 -
            ..self
455 +
            zdepth: self.zdepth,
456 +
            rotation: self.rotation,
351 457
        }
352 458
    }
353 459
}
354 460
355 -
impl Shape for Line {
356 -
    fn fill<'a>(&self, brush: impl Into<Brush>) -> impl Iterator<Item = Vertex> + 'a {
461 +
impl ToGeometry for Line<Local> {
462 +
    type Transformed = Line<Screen>;
463 +
464 +
    fn transform(self, t: Transform2D<Local, Screen>) -> Line<Screen> {
465 +
        Line::transform(self, t)
466 +
    }
467 +
}
468 +
469 +
impl Geometry for Line<Screen> {
470 +
    fn fill<'a>(self, brush: impl Into<Brush>) -> impl Iterator<Item = Vertex> + 'a {
357 471
        self.stroke(brush, 1.0)
358 472
    }
359 473
360 -
    fn stroke<'a>(&self, brush: impl Into<Brush>, width: f32) -> impl Iterator<Item = Vertex> + 'a {
474 +
    fn stroke<'a>(self, brush: impl Into<Brush>, width: f32) -> impl Iterator<Item = Vertex> + 'a {
361 475
        let (from, to) = (self.from, self.to);
362 476
        let z = *self.zdepth;
363 477
        let Rotation { angle, center } = self.rotation;
364 478
        let v = (to - from).normalize();
365 479
        let wx = width / 2. * v.y;
391 505
            ..self
392 506
        }
393 507
    }
394 508
}
395 509
396 -
impl std::ops::Add<Vector2D<f32, Screen>> for Line {
510 +
impl<U: Copy> std::ops::Add<Vector2D<f32, U>> for Line<U> {
397 511
    type Output = Self;
398 512
399 -
    fn add(self, vec: Vector2D<f32, Screen>) -> Self {
513 +
    fn add(self, vec: Vector2D<f32, U>) -> Self {
400 514
        Self {
401 515
            from: self.from + vec,
402 516
            to: self.to + vec,
403 517
            ..self
404 518
        }
405 519
    }
406 520
}
407 521
408 522
/// Create a line.
409 -
pub fn line<P: Into<Point2D<f32, Screen>>>(from: P, to: P) -> Line {
523 +
pub fn line<U: Copy, P: Into<Point2D<f32, U>>>(from: P, to: P) -> Line<U> {
410 524
    Line::new(from, to)
411 525
}
412 526
413 527
/// Create a rectangle.
414 -
pub fn rectangle(origin: impl Into<Point2D<f32, Screen>>, size: impl Into<Size>) -> Rectangle {
528 +
pub fn rectangle(origin: impl Into<Point2D<f32, Local>>, size: impl Into<Size>) -> Rectangle {
415 529
    Rectangle::new(origin, size)
416 530
}
417 531
418 532
/// Create a circle.
419 -
pub fn circle(origin: impl Into<Point2D>, radius: f32, sides: u32) -> Circle {
533 +
pub fn circle(origin: impl Into<Point2D<f32, Local>>, radius: f32, sides: u32) -> Circle {
420 534
    Circle::new(origin, radius, sides)
421 535
}
ombre/src/paint/text.rs added +78 -0
1 +
use crate::gfx::Transform2D;
2 +
use crate::math::Rect;
3 +
use crate::{text::rich::TextSpanLayout, text::RichTextLayout, text::TextLayout};
4 +
5 +
use super::traits::Paint;
6 +
use super::PaintOp;
7 +
8 +
struct TextSpanLayoutIter {
9 +
    layout: TextSpanLayout,
10 +
    ix: usize,
11 +
}
12 +
13 +
impl From<TextSpanLayout> for TextSpanLayoutIter {
14 +
    fn from(layout: TextSpanLayout) -> Self {
15 +
        Self { layout, ix: 0 }
16 +
    }
17 +
}
18 +
19 +
impl Iterator for TextSpanLayoutIter {
20 +
    type Item = PaintOp;
21 +
22 +
    fn next(&mut self) -> Option<Self::Item> {
23 +
        if self.ix >= self.layout.glyphs.len() {
24 +
            return None;
25 +
        }
26 +
        let g = &self.layout.glyphs[self.ix];
27 +
        self.ix += 1;
28 +
29 +
        let size = self.layout.font.tile_size();
30 +
        let stride = self.layout.font.image.size.w / size.w as u32;
31 +
        if stride == 0 {
32 +
            panic!("TextSpanLayoutIter::next: texture stride must not be zero");
33 +
        }
34 +
        let i = g.character as u32;
35 +
        let x = (i % stride) as f32 * size.w;
36 +
        let y = (i / stride) as f32 * size.h;
37 +
38 +
        Some(PaintOp::Blit {
39 +
            image: self.layout.font.image.clone(),
40 +
            src: Rect::new([x, y], g.bounds.size),
41 +
            dst: g.bounds,
42 +
            tint: self.layout.tint.into(),
43 +
            opacity: 1.0,
44 +
            transform: Transform2D::identity(),
45 +
        })
46 +
    }
47 +
}
48 +
49 +
impl Paint for TextSpanLayout {
50 +
    fn ops(&self) -> impl Iterator<Item = super::PaintOp> + '_ {
51 +
        TextSpanLayoutIter::from(self.clone())
52 +
    }
53 +
}
54 +
55 +
impl Paint for RichTextLayout {
56 +
    fn ops(&self) -> impl Iterator<Item = PaintOp> + '_ {
57 +
        self.lines
58 +
            .iter()
59 +
            .flat_map(|line| &line.spans)
60 +
            .flat_map(|span| span.ops())
61 +
    }
62 +
}
63 +
64 +
impl Paint for TextLayout {
65 +
    fn ops(&self) -> impl Iterator<Item = PaintOp> + '_ {
66 +
        TextSpanLayoutIter::from(TextSpanLayout {
67 +
            font: self.font.clone(),
68 +
            tint: self.color.into(),
69 +
            glyphs: self.glyphs.clone(),
70 +
        })
71 +
    }
72 +
}
73 +
74 +
impl<T: Paint> Paint for &T {
75 +
    fn ops(&self) -> impl Iterator<Item = PaintOp> + '_ {
76 +
        T::ops(self)
77 +
    }
78 +
}
ombre/src/paint/traits.rs added +324 -0
1 +
//! Traits relating to 2D drawing.
2 +
// (c) 2019 the Piet Authors, the traits and docs here are heavily drawn from `piet`.
3 +
#![warn(missing_docs)]
4 +
5 +
use crate::gfx::RenderFrame;
6 +
use crate::gfx::{Image, Point2D, Rect, Rgba, Rgba8, Transform2D};
7 +
use crate::math::{Local, Screen};
8 +
use crate::text::Text;
9 +
10 +
use super::shape::{Shape, ToGeometry};
11 +
12 +
/// Errors that can occur during paint operations.
13 +
#[derive(Debug)]
14 +
pub enum Error {}
15 +
16 +
impl std::error::Error for Error {}
17 +
18 +
impl std::fmt::Display for Error {
19 +
    fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20 +
        Ok(())
21 +
    }
22 +
}
23 +
24 +
/// Objects that can be painted to the screen using a [`PaintSurface`] can implement
25 +
/// this trait.
26 +
pub trait Paint {
27 +
    /// Paint the object using a [`PaintSurface`].
28 +
    fn paint(&self, surface: &mut impl PaintSurface) {
29 +
        for op in self.ops() {
30 +
            surface.op(op);
31 +
        }
32 +
    }
33 +
    /// Return the operations required to paint this object.
34 +
    fn ops(&self) -> impl Iterator<Item = PaintOp> + '_;
35 +
}
36 +
37 +
/// Provides an API for drawing 2D graphics to a surface or recording context.
38 +
/// Implementations can target different rendering backends while providing
39 +
/// a consistent interface for drawing operations.
40 +
pub trait PaintSurface {
41 +
    /// Reports any internal errors that occurred during rendering.
42 +
    ///
43 +
    /// Drawing operations may cause internal errors, which may also occur
44 +
    /// asynchronously after the drawing command was issued. This method reports
45 +
    /// any such error that has been detected.
46 +
    fn status(&mut self) -> Result<(), Error>;
47 +
48 +
    /// Clear the canvas.
49 +
    ///
50 +
    /// Clears the surface of anything that was drawn. Also clears any
51 +
    /// pending drawing operations.
52 +
    fn clear(&mut self);
53 +
54 +
    /// Stroke a [`Shape`].
55 +
    fn stroke(&mut self, shape: impl ToGeometry, brush: impl Into<Brush>, width: f32);
56 +
57 +
    /// Fill a [`Shape`].
58 +
    fn fill(&mut self, shape: impl ToGeometry, brush: impl Into<Brush>);
59 +
60 +
    /// Draw an [`Image`] area into the provided [`Rect`].
61 +
    ///
62 +
    /// The `src` area of `image` is scaled to the provided `dst` rect.
63 +
    /// It will be squashed if the aspect ratios don't match.
64 +
    fn blit(
65 +
        &mut self,
66 +
        image: Image,
67 +
        src: impl Into<Rect<f32, Local>>,
68 +
        dst: impl Into<Rect<f32, Local>>,
69 +
        tint: impl Into<Rgba<f32>>,
70 +
        opacity: f32,
71 +
    );
72 +
73 +
    /// Draw text at the given point.
74 +
    fn text<'a>(&mut self, text: impl Into<Text<'a>>, dst: impl Into<Point2D<f32, Local>>);
75 +
76 +
    /// Mask using a [`Shape`].
77 +
    ///
78 +
    /// All subsequent drawing operations up to the next [`Self::restore`]
79 +
    /// are clipped by the shape.
80 +
    fn mask(&mut self, shape: impl ToGeometry);
81 +
82 +
    /// Save the context state.
83 +
    ///
84 +
    /// Pushes the current context state onto a stack, to be popped by
85 +
    /// [`Self::restore`].
86 +
    ///
87 +
    /// Prefer [`Self::with_transform`] if possible, as that statically
88 +
    /// enforces balance of save/restore pairs.
89 +
    ///
90 +
    /// The context state currently consists of a clip region and an affine
91 +
    /// transform, but is expected to grow in the near future.
92 +
    fn save(&mut self);
93 +
94 +
    /// Restore the context state.
95 +
    ///
96 +
    /// Pop a context state that was pushed by [`Self::save`]. See that method for details.
97 +
    /// Returns an error if there is no state to pop.
98 +
    fn restore(&mut self);
99 +
100 +
    /// Flush pending draw operations to the display. This should generally be called once
101 +
    /// per frame.
102 +
    fn flush<'f, F: RenderFrame<'f>>(&mut self, frame: &mut F) -> Result<(), F::Error>;
103 +
104 +
    /// Apply a transform.
105 +
    ///
106 +
    /// Apply a 2D transformation. The transformation remains in effect
107 +
    /// until a [`Self::restore`] operation.
108 +
    fn transform(&mut self, transform: impl Into<Transform2D<Local, Screen>>);
109 +
110 +
    /// Do graphics operations with the context state saved and then restored.
111 +
    ///
112 +
    /// Equivalent to [`Self::save`], calling `f`, then
113 +
    /// [`Self::restore`]. See those methods for more details.
114 +
    fn with_transform(
115 +
        &mut self,
116 +
        t: impl Into<Transform2D<Local, Screen>>,
117 +
        f: impl FnOnce(&mut Self),
118 +
    ) {
119 +
        self.save();
120 +
        self.transform(t);
121 +
        f(self);
122 +
        self.restore();
123 +
    }
124 +
125 +
    /// Create an [`Image`] of the specified region of the context.
126 +
    /// Do graphics operations with the context state saved and then restored.
127 +
    ///
128 +
    /// Equivalent to [`Self::save`], calling `f`, then
129 +
    /// [`Self::restore`]. See those methods for more details. fn with_transform( &mut self, t: impl Into<Transform2D<Local, Screen>>, f: impl FnOnce(&mut Self),) { self.save(); self.transform(t); f(self); self.restore(); } Create an [`Image`] of the specified region of the context.
130 +
    ///
131 +
    /// The `src` area of the current render context will be captured
132 +
    /// as a copy and returned.
133 +
    fn read(&mut self, src: impl Into<Rect<f32>>) -> Result<Image, Error>;
134 +
135 +
    /// Execute a recorded paint operation.
136 +
    ///
137 +
    /// This method takes a [`PaintOp`] and dispatches it to the appropriate
138 +
    /// method on the [`PaintSurface`].
139 +
    fn op(&mut self, op: PaintOp) {
140 +
        match op {
141 +
            PaintOp::Clear => self.clear(),
142 +
            PaintOp::Stroke {
143 +
                shape,
144 +
                brush,
145 +
                width,
146 +
                transform,
147 +
            } => self.with_transform(transform, |p| match shape {
148 +
                Shape::Rectangle(s) => p.stroke(s, brush, width),
149 +
                Shape::Circle(s) => p.stroke(s, brush, width),
150 +
                Shape::Line(s) => p.stroke(s, brush, width),
151 +
            }),
152 +
            PaintOp::Fill {
153 +
                shape,
154 +
                brush,
155 +
                transform,
156 +
            } => self.with_transform(transform, |p| match shape {
157 +
                Shape::Rectangle(s) => p.fill(s, brush),
158 +
                Shape::Circle(s) => p.fill(s, brush),
159 +
                Shape::Line(s) => p.fill(s, brush),
160 +
            }),
161 +
            PaintOp::Blit {
162 +
                image,
163 +
                src,
164 +
                dst,
165 +
                tint,
166 +
                opacity,
167 +
                transform,
168 +
            } => self.with_transform(transform, |p| p.blit(image, src, dst, tint, opacity)),
169 +
            PaintOp::Text {
170 +
                text,
171 +
                dst,
172 +
                transform,
173 +
            } => self.with_transform(transform, |p| p.text(text, dst)),
174 +
            PaintOp::Mask { shape } => match shape {
175 +
                Shape::Rectangle(s) => self.mask(s),
176 +
                Shape::Circle(s) => self.mask(s),
177 +
                Shape::Line(s) => self.mask(s),
178 +
            },
179 +
        }
180 +
    }
181 +
182 +
    /// Execute a series of recording paint operations.
183 +
    /// Execute multiple paint operations in sequence.
184 +
    ///
185 +
    /// This is a convenience method that takes an iterator of paint operations
186 +
    /// and executes them in order using the surface's `op` method.
187 +
    fn ops(&mut self, ops: impl IntoIterator<Item = PaintOp>) {
188 +
        for op in ops.into_iter() {
189 +
            self.op(op);
190 +
        }
191 +
    }
192 +
}
193 +
194 +
/// Represents a recorded paint operation.
195 +
#[derive(Debug, Clone)]
196 +
pub enum PaintOp {
197 +
    /// Clear the surface.
198 +
    Clear,
199 +
    /// Stroke a shape.
200 +
    Stroke {
201 +
        /// The shape to stroke.
202 +
        shape: Shape<Local>,
203 +
        /// The brush defining the stroke color/pattern.
204 +
        brush: Brush,
205 +
        /// Width of the stroke in pixels.
206 +
        width: f32,
207 +
        /// Transform to apply before stroking.
208 +
        transform: Transform2D<Local, Screen>,
209 +
    },
210 +
    /// Fill a shape.
211 +
    Fill {
212 +
        /// The shape to fill.
213 +
        shape: Shape<Local>,
214 +
        /// The brush defining the fill color/pattern.
215 +
        brush: Brush,
216 +
        /// Transform to apply before filling.
217 +
        transform: Transform2D<Local, Screen>,
218 +
    },
219 +
    /// Draw an image.
220 +
    Blit {
221 +
        /// Source image to draw.
222 +
        image: Image,
223 +
        /// Source rectangle in image coordinates.
224 +
        src: Rect<f32, Local>,
225 +
        /// Destination rectangle in screen coordinates.
226 +
        dst: Rect<f32, Local>,
227 +
        /// Color tint to apply.
228 +
        tint: Rgba<f32>,
229 +
        /// Opacity multiplier (0-1).
230 +
        opacity: f32,
231 +
        /// Transform to apply before drawing.
232 +
        transform: Transform2D<Local, Screen>,
233 +
    },
234 +
    /// Draw text.
235 +
    Text {
236 +
        /// Text to render.
237 +
        text: Text<'static>,
238 +
        /// Baseline position for the text.
239 +
        dst: Point2D<f32, Local>,
240 +
        /// Transform to apply before rendering.
241 +
        transform: Transform2D<Local, Screen>,
242 +
    },
243 +
    /// Apply a mask.
244 +
    Mask {
245 +
        /// Shape to use as a clipping mask.
246 +
        shape: Shape<Local>,
247 +
    },
248 +
}
249 +
250 +
impl PaintOp {
251 +
    /// Transform the paint operation.
252 +
    pub fn transform(self, t: Transform2D<Local, Screen>) -> Self {
253 +
        match self {
254 +
            PaintOp::Clear => PaintOp::Clear,
255 +
            PaintOp::Mask { shape } => PaintOp::Mask { shape },
256 +
            PaintOp::Blit {
257 +
                image,
258 +
                src,
259 +
                dst,
260 +
                tint,
261 +
                opacity,
262 +
                transform,
263 +
            } => PaintOp::Blit {
264 +
                image,
265 +
                src,
266 +
                dst,
267 +
                tint,
268 +
                opacity,
269 +
                transform: t * transform,
270 +
            },
271 +
            PaintOp::Fill {
272 +
                shape,
273 +
                brush,
274 +
                transform,
275 +
            } => PaintOp::Fill {
276 +
                shape,
277 +
                brush,
278 +
                transform: t * transform,
279 +
            },
280 +
            PaintOp::Stroke {
281 +
                shape,
282 +
                brush,
283 +
                width,
284 +
                transform,
285 +
            } => PaintOp::Stroke {
286 +
                shape,
287 +
                brush,
288 +
                width,
289 +
                transform: t * transform,
290 +
            },
291 +
            PaintOp::Text {
292 +
                text,
293 +
                dst,
294 +
                transform,
295 +
            } => PaintOp::Text {
296 +
                text,
297 +
                dst,
298 +
                transform: t * transform,
299 +
            },
300 +
        }
301 +
    }
302 +
}
303 +
304 +
/// Defines how a shape should be colored.
305 +
/// Can be either a solid color or a gradient between multiple colors.
306 +
#[derive(Debug, Clone)]
307 +
pub enum Brush {
308 +
    /// A [`Rgba`] color.
309 +
    Color(Rgba<f32>),
310 +
    /// A gradient between a set of colors.
311 +
    LinearGradient([Rgba<f32>; 8]),
312 +
}
313 +
314 +
impl From<Rgba<f32>> for Brush {
315 +
    fn from(src: Rgba<f32>) -> Brush {
316 +
        Brush::Color(src)
317 +
    }
318 +
}
319 +
320 +
impl From<Rgba8> for Brush {
321 +
    fn from(src: Rgba8) -> Brush {
322 +
        Brush::Color(src.into())
323 +
    }
324 +
}
ombre/src/platform/glfw.rs +1 -0
52 52
53 53
    let (mut window, events) = glfw
54 54
        .create_window(w, h, title, glfw::WindowMode::Windowed)
55 55
        .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "glfw: error creating window"))?;
56 56
57 +
    window.set_size_limits(Some(1), Some(1), None, None);
57 58
    window.make_current();
58 59
    window.set_all_polling(true);
59 60
60 61
    glfw.set_swap_interval(glfw::SwapInterval::None);
61 62
ombre/src/rng.rs +18 -4
1 -
//! Copyright (c) Simon Heath, some quality nuggets from their `oorandom` crate
2 -
//! Copyright (c) Wang Yi, WyRand algorithm
3 -
//! Copyright (c) The `fastrand` authors, various tidbits
1 +
//! Random number generator.
2 +
// (c) Simon Heath, some quality nuggets from their `oorandom` crate
3 +
// (c) Wang Yi, WyRand algorithm
4 +
// (c) The `fastrand` authors, various tidbits
5 +
#![warn(missing_docs)]
6 +
4 7
use std::collections::hash_map::DefaultHasher;
5 8
use std::hash::{Hash, Hasher};
6 9
use std::ops::{Add, Bound, RangeBounds, Sub};
7 10
use std::time::Instant;
8 11
use std::{fmt, thread};
10 13
use crate::math::traits::Integer;
11 14
use crate::math::{Bounded, One};
12 15
13 16
/// Trait for sources of entropy.
14 17
pub trait Entropy {
18 +
    /// Generate a random [`u64`].
15 19
    fn gen_u64(&mut self) -> u64;
16 20
21 +
    /// Generate a random [`u32`].
17 22
    #[inline]
18 23
    fn gen_u32(&mut self) -> u32 {
19 24
        self.gen_u64() as u32
20 25
    }
21 26
}
78 83
    pub fn with_seed(seed: u64) -> Self {
79 84
        Self { state: seed }
80 85
    }
81 86
82 87
    /// Generates a random float in the range `[0.0, 1.0)` with 53 bits of precision.
88 +
    ///
89 +
    /// This provides high-quality uniformly distributed floating point numbers suitable
90 +
    /// for most applications requiring random real numbers.
83 91
    pub fn fraction(&mut self) -> f64 {
84 92
        const PRECISION: u32 = f64::MANTISSA_DIGITS + 1;
85 93
        const MANTISSA_SCALE: f64 = 1.0 / ((1u64 << PRECISION) as f64);
86 94
87 95
        let mut r = self.gen_u64();
178 186
        let t = u128::from(self.state) * u128::from(self.state ^ 0x8bb8_4b93_962e_acc9);
179 187
        (t as u64) ^ (t >> 64) as u64
180 188
    }
181 189
}
182 190
183 -
/// Uniform distribution over a range
191 +
/// Uniform distribution over a range.
184 192
#[derive(Debug, Clone, Copy)]
185 193
pub struct Uniform<T> {
186 194
    low: T,
187 195
    high: T,
188 196
}
189 197
190 198
impl<T> Uniform<T> {
199 +
    /// Creates a new uniform distribution over the range `[low, high]`.
191 200
    #[inline]
192 201
    pub const fn new(low: T, high: T) -> Self {
193 202
        Self { low, high }
194 203
    }
195 204
}
196 205
197 206
impl<T: Bounded> Uniform<T> {
207 +
    /// Creates a uniform distribution over the full range of the type `T`.
208 +
    ///
209 +
    /// This distribution will generate values across the entire range of valid values
210 +
    /// for the bounded type `T`, from `T::MIN` to `T::MAX` inclusive.
198 211
    #[inline]
199 212
    pub const fn full() -> Self {
200 213
        Self::new(T::MIN, T::MAX)
201 214
    }
202 215
216 +
    /// Like [`Self::full`], but with a specified range.
203 217
    #[inline]
204 218
    pub fn from_range<R: RangeBounds<T>>(range: R) -> Self
205 219
    where
206 220
        T: Copy + PartialOrd + Add<Output = T> + Sub<Output = T> + fmt::Debug + One,
207 221
    {
ombre/src/text.rs added +247 -0
1 +
pub mod plain;
2 +
pub mod rich;
3 +
4 +
use std::borrow::{Borrow, Cow};
5 +
use std::ops::Range;
6 +
use std::rc::Rc;
7 +
8 +
use crate::gfx::{
9 +
    Font, FontMetrics, FontName, FontStyle, Fonts, Image, Rect, Rgba, Size, DEFAULT_FONT,
10 +
};
11 +
use crate::math::{Bounded as _, FloatExt as _, Local};
12 +
13 +
pub use plain::TextLayout;
14 +
pub use rich::{RichTextLayout, RichTextStorage};
15 +
16 +
/// Text alignment.
17 +
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
18 +
pub enum TextAlign {
19 +
    /// Left-align.
20 +
    #[default]
21 +
    Left,
22 +
    /// Center-align.
23 +
    Center,
24 +
    /// Right-align.
25 +
    Right,
26 +
}
27 +
28 +
/// Text layout options.
29 +
#[derive(Copy, Clone, Debug, Default)]
30 +
pub struct TextLayoutOptions {
31 +
    /// Line height. Defaults to the font tile height if `None`.
32 +
    pub line_height: Option<f32>,
33 +
    /// Text alignment (default: left).
34 +
    pub align: TextAlign,
35 +
}
36 +
37 +
impl TextLayoutOptions {
38 +
    /// Centered text.
39 +
    pub fn centered(self) -> Self {
40 +
        self.align(TextAlign::Center)
41 +
    }
42 +
43 +
    /// Set text alignment.
44 +
    pub fn align(mut self, align: impl Into<TextAlign>) -> Self {
45 +
        self.align = align.into();
46 +
        self
47 +
    }
48 +
}
49 +
50 +
/// A single layed out character.
51 +
#[derive(Clone, Debug)]
52 +
pub struct GlyphLayout {
53 +
    /// Character index into the texture.
54 +
    pub character: u8,
55 +
    /// Position of the glyph within the text area.
56 +
    pub bounds: Rect<f32, Local>,
57 +
}
58 +
59 +
/// A span of text contains text with a set style.
60 +
#[derive(Clone, Debug)]
61 +
pub struct TextSpan {
62 +
    /// The range of characters represented by this span,
63 +
    /// within the text.
64 +
    pub range: Range<usize>,
65 +
    /// The font.
66 +
    pub font: FontName,
67 +
    /// The font style.
68 +
    pub style: FontStyle,
69 +
    /// Text color.
70 +
    pub tint: Rgba<f32>,
71 +
}
72 +
73 +
impl TextSpan {
74 +
    /// Resolve a [`TextSpan`] to a [`LoadedTextSpan`].
75 +
    pub(crate) fn load(&self, fonts: &Fonts<Image>) -> LoadedTextSpan {
76 +
        LoadedTextSpan {
77 +
            span: self.clone(),
78 +
            font: fonts.lookup(&self.font).clone(),
79 +
        }
80 +
    }
81 +
}
82 +
83 +
/// A [`TextSpan`] with a loaded font.
84 +
#[derive(Debug)]
85 +
pub struct LoadedTextSpan {
86 +
    pub span: TextSpan,
87 +
    pub font: Rc<Font<Image>>,
88 +
}
89 +
90 +
#[derive(Debug, Clone)]
91 +
pub struct Text<'a> {
92 +
    body: Cow<'a, str>,
93 +
    spans: Vec<TextSpan>,
94 +
    area: Size<f32>,
95 +
    opts: TextLayoutOptions,
96 +
}
97 +
98 +
impl std::fmt::Display for Text<'_> {
99 +
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100 +
        write!(f, "{}", self.body)
101 +
    }
102 +
}
103 +
104 +
impl<'a> Text<'a> {
105 +
    pub fn new(body: impl Into<Cow<'a, str>>) -> Self {
106 +
        Self {
107 +
            body: body.into(),
108 +
            spans: Vec::new(),
109 +
            area: Size::MAX,
110 +
            opts: TextLayoutOptions::default(),
111 +
        }
112 +
    }
113 +
114 +
    /// Convert to a 'static text.
115 +
    pub fn into_owned(self) -> Text<'static> {
116 +
        Text {
117 +
            body: Cow::Owned(self.body.into_owned()),
118 +
            ..self
119 +
        }
120 +
    }
121 +
122 +
    pub fn with_span(
123 +
        mut self,
124 +
        range: Range<usize>,
125 +
        font: FontName,
126 +
        style: FontStyle,
127 +
        tint: Rgba<f32>,
128 +
    ) -> Self {
129 +
        self.span(range, font, style, tint);
130 +
        self
131 +
    }
132 +
133 +
    pub fn span(&mut self, range: Range<usize>, font: FontName, style: FontStyle, tint: Rgba<f32>) {
134 +
        self.spans.push(TextSpan {
135 +
            range,
136 +
            font,
137 +
            style,
138 +
            tint,
139 +
        });
140 +
    }
141 +
142 +
    pub fn with_area(mut self, rect: Size<f32>) -> Self {
143 +
        self.area = rect;
144 +
        self
145 +
    }
146 +
147 +
    pub fn with_align(mut self, align: TextAlign) -> Self {
148 +
        self.opts.align = align;
149 +
        self
150 +
    }
151 +
152 +
    pub fn with_font(mut self, font: impl Into<FontName>) -> Self {
153 +
        self.spans.push(TextSpan {
154 +
            range: 0..self.body.len(),
155 +
            font: font.into(),
156 +
            style: FontStyle::default(),
157 +
            tint: Rgba::default(),
158 +
        });
159 +
        self
160 +
    }
161 +
162 +
    pub fn build(self, fonts: &Fonts<Image>) -> RichTextLayout {
163 +
        let spans = if self.spans.is_empty() {
164 +
            vec![TextSpan {
165 +
                range: 0..self.body.len(),
166 +
                font: DEFAULT_FONT,
167 +
                style: FontStyle::default(),
168 +
                tint: Rgba::default(),
169 +
            }
170 +
            .load(fonts)]
171 +
        } else {
172 +
            self.spans.iter().map(|s| s.load(fonts)).collect::<Vec<_>>()
173 +
        };
174 +
        RichTextLayout::build(self.body.borrow(), spans.as_slice(), self.opts, self.area)
175 +
    }
176 +
}
177 +
178 +
impl<'a> From<&'a str> for Text<'a> {
179 +
    fn from(value: &'a str) -> Self {
180 +
        Text::new(value)
181 +
    }
182 +
}
183 +
184 +
pub(crate) mod align {
185 +
    use super::*;
186 +
187 +
    pub(super) fn horizontal<'a>(
188 +
        glyphs: impl Iterator<Item = &'a mut GlyphLayout>,
189 +
        width: f32,
190 +
        align: TextAlign,
191 +
        bounds: Size<f32>,
192 +
    ) {
193 +
        if width >= bounds.w {
194 +
            return;
195 +
        }
196 +
        let offset = match align {
197 +
            TextAlign::Left => return,
198 +
            TextAlign::Center => (bounds.w - width) / 2.,
199 +
            TextAlign::Right => bounds.w - width,
200 +
        };
201 +
        for glyph in glyphs {
202 +
            glyph.bounds.origin.x += offset;
203 +
        }
204 +
    }
205 +
206 +
    //   ┌─────────────────────────────────┐__ Glyph height (14) (total)
207 +
    //  d│                                 │
208 +
    //  c│_________________________________│__ Cap height (9) (from baseline)
209 +
    //  b│ @@@@                            │
210 +
    //  a│@    @        ___________________│__ X-height (6) (from baseline)
211 +
    //  9│@       @ @@@                    │
212 +
    //  8│@       @@   @                   │
213 +
    //  7│ @@@@   @    @                   │
214 +
    //  6│     @  @    @                   │
215 +
    //  5│     @  @    @                   │
216 +
    //  4│@    @  @@   @                   │
217 +
    //  3│ @@@@   @ @@@ ___________________│__ Baseline (3)
218 +
    //  2│        @                        │
219 +
    //  1│        @                        │
220 +
    //  0│        @ _______________________│__ Descender height (3) (until baseline)
221 +
    //   │                                 │
222 +
    //   │                                 │
223 +
    //   └─────────────────────────────────┘
224 +
    //
225 +
    // The goal is to place the glyph such that `char_height` is vertically centered within
226 +
    // `line_height`, keeping in mind that `char_height` is offset by `baseline`.
227 +
    //
228 +
    pub(super) fn vertical<'a>(
229 +
        glyphs: impl Iterator<Item = &'a mut GlyphLayout>,
230 +
        line_height: f32, // Usually "cap height" + 2 * "descender height", unless line is taller.
231 +
        char_height: f32, // Usually "cap height".
232 +
        metrics: FontMetrics,
233 +
    ) {
234 +
        let glyph_height = metrics.glyph_height as f32;
235 +
        // The baseline as taken from the top of the glyph, instead of the bottom.
236 +
        let baseline = glyph_height - metrics.baseline as f32;
237 +
        let diff = line_height - char_height;
238 +
        // How much space we want above and below the centered piece.
239 +
        let padding = diff / 2.;
240 +
        let offset = (padding - baseline) + char_height;
241 +
        let offset = offset.truncate();
242 +
243 +
        for glyph in glyphs {
244 +
            glyph.bounds.origin.y += offset;
245 +
        }
246 +
    }
247 +
}
ombre/src/ui/gfx/text/plain.rs → ombre/src/text/plain.rs renamed +37 -107
1 1
//! Plain text layout.
2 -
use std::cell::OnceCell;
3 -
use std::rc::Rc;
4 -
use std::sync::Arc;
5 -
6 2
use super::*;
7 -
8 -
/// Text object with layout, style and data.
9 -
#[derive(Debug)]
10 -
pub struct PlainText<T> {
11 -
    pub(crate) font: FontName,
12 -
    pub(crate) value: TextValue<T>,
13 -
    pub(crate) opts: TextLayoutOptions,
14 -
    pub(crate) layout: Option<TextLayout>,
15 -
    pub(crate) bounds: Size<f32>,
16 -
17 -
    /// Loaded font.
18 -
    lfont: OnceCell<Rc<Font<Image>>>,
19 -
    /// Cached text value for comparisons.
20 -
    old: Arc<str>,
21 -
}
22 -
23 -
impl<T> From<String> for PlainText<T> {
24 -
    fn from(data: String) -> Self {
25 -
        Self::new(DEFAULT_FONT, TextLayoutOptions::default(), data)
26 -
    }
27 -
}
28 -
29 -
impl<T> PlainText<T> {
30 -
    /// Create a new text object.
31 -
    pub fn new(font: FontName, opts: TextLayoutOptions, data: impl Into<TextValue<T>>) -> Self {
32 -
        Self {
33 -
            font,
34 -
            lfont: OnceCell::default(),
35 -
            old: String::new().into(),
36 -
            value: data.into(),
37 -
            opts,
38 -
            layout: None,
39 -
            bounds: Size::ZERO,
40 -
        }
41 -
    }
42 -
43 -
    /// Set the value of the text.
44 -
    pub fn set(&mut self, data: impl ToString) {
45 -
        self.value = data.to_string().into();
46 -
        self.layout = None;
47 -
    }
48 -
49 -
    /// Get the font.
50 -
    pub fn font(&self) -> Option<&Font<Image>> {
51 -
        self.lfont.get().map(|lf| lf.as_ref())
52 -
    }
53 -
54 -
    /// Layout the text.
55 -
    pub fn layout(
56 -
        &mut self,
57 -
        data: &T,
58 -
        bounds: Size<f32>,
59 -
        fonts: &Fonts<Image>,
60 -
    ) -> (&TextLayout, &Font<Image>) {
61 -
        let text = self.value.resolve(data);
62 -
63 -
        if bounds != self.bounds || text != self.old {
64 -
            self.layout = None;
65 -
        }
66 -
        let font = self.lfont.get_or_init(|| fonts.lookup(&self.font).clone());
67 -
        let layout =
68 -
            self.layout
69 -
                .get_or_insert(TextLayout::new(text.as_ref(), font, self.opts, bounds));
70 -
71 -
        self.bounds = bounds;
72 -
        self.old = text;
73 -
74 -
        (layout, font)
75 -
    }
76 -
77 -
    /// Force re-layout of text.
78 -
    pub fn clear(&mut self) {
79 -
        self.layout = None;
80 -
    }
81 -
}
3 +
use crate::gfx::font::FontMetrics;
4 +
use crate::math::traits::Zero as _;
5 +
use crate::math::Point2D;
82 6
83 7
/// Text that has been layed out.
84 8
#[derive(Clone, Debug)]
85 9
pub struct TextLayout {
86 10
    /// Area used for the text layout.
87 11
    pub(crate) size: Size<f32>,
88 12
    /// Area bounds.
89 13
    pub(crate) bounds: Size<f32>,
90 -
    /// Font tile size.
91 -
    pub(crate) tile: Size<f32>,
92 14
    /// Font metrics.
93 15
    pub(crate) metrics: FontMetrics,
94 16
    /// Layed out text.
95 -
    glyphs: Vec<GlyphLayout>,
17 +
    pub(crate) glyphs: Vec<GlyphLayout>,
18 +
    /// Text color.
19 +
    #[cfg_attr(not(feature = "ui"), allow(dead_code))]
20 +
    pub(crate) color: Rgba<f32>,
21 +
    /// Loaded font.
22 +
    #[cfg_attr(not(feature = "ui"), allow(dead_code))]
23 +
    pub(crate) font: Rc<Font<Image>>,
96 24
    /// Did we overflow the given bounds?
97 25
    overflow: bool,
98 26
}
99 27
100 28
impl TextLayout {
101 29
    /// Lay out the given text and return a [`TextLayout`] object.
102 -
    pub fn new<I>(text: &str, font: &Font<I>, opts: TextLayoutOptions, bounds: Size<f32>) -> Self {
103 -
        let tile = font.tile_size();
30 +
    pub fn new(
31 +
        text: &str,
32 +
        font: Rc<Font<Image>>,
33 +
        color: Rgba<f32>,
34 +
        opts: TextLayoutOptions,
35 +
        bounds: Size<f32>,
36 +
    ) -> Self {
104 37
        let metrics = font.metrics;
105 38
        let mut overflow = false;
106 39
        let mut dst = Point2D::ZERO;
107 40
        let mut glyphs = Vec::new();
108 41
        let mut width = 0.;
146 79
        if size.h > bounds.h {
147 80
            log::warn!(target: "ui", "Text height ({}) overflows bounds ({})", size.h, bounds.h);
148 81
        }
149 82
150 83
        Self {
151 -
            tile,
84 +
            font,
85 +
            color,
152 86
            metrics,
153 87
            size,
154 88
            bounds,
155 89
            glyphs,
156 90
            overflow,
170 104
    /// Get the layed out characters and with their positions.
171 105
    pub fn chars(&self) -> impl Iterator<Item = &Rect<f32, Local>> {
172 106
        self.glyphs.iter().map(|g| &g.bounds)
173 107
    }
174 108
175 -
    /// Render the layed out text as [`Blit`] objects, using the font texture information.
176 -
    pub fn render(&self, texture: Size<u32>, tint: Rgba8) -> Vec<Blit<Local>> {
177 -
        RawLabel {
178 -
            tile: self.tile,
179 -
            glyphs: self.glyphs.as_slice(),
180 -
            tint,
181 -
        }
182 -
        .render(texture)
183 -
    }
184 -
185 109
    /// Final size of the text area, after layout.
186 110
    pub fn size(&self) -> Size<f32> {
187 111
        self.size
188 112
    }
189 113
195 119
196 120
#[cfg(test)]
197 121
#[allow(clippy::unwrap_used)]
198 122
mod tests {
199 123
    use super::*;
200 -
    use crate::ui::fonts;
124 +
    use crate::gfx::font;
125 +
    use crate::gfx::Color as _;
201 126
202 127
    #[test]
203 128
    fn test_text_layout_basic() {
204 129
        let input = "Sphinx";
205 -
        let font = fonts::uf2::DEFAULT.decode().unwrap();
130 +
        let font = Rc::new(font::uf2::DEFAULT.decode().unwrap());
206 131
        let opts = TextLayoutOptions::default();
207 132
        let bounds = Size::new(256., 256.);
208 -
        let layout = TextLayout::new(input, &font, opts, bounds);
133 +
        let tint = Rgba::RED;
134 +
        let layout = TextLayout::new(input, font.clone(), tint, opts, bounds);
209 135
210 136
        assert_eq!(
211 137
            layout.size,
212 138
            Size::new(font.text_width(input), font.metrics.line_height() as f32)
213 139
        );
217 143
    }
218 144
219 145
    #[test]
220 146
    fn test_text_layout_overflow() {
221 147
        let input = "Sphinx";
222 -
        let font = fonts::uf2::DEFAULT.decode().unwrap();
148 +
        let font = Rc::new(font::uf2::DEFAULT.decode().unwrap());
223 149
        let opts = TextLayoutOptions::default();
224 -
        let layout = TextLayout::new(input, &font, opts, Size::new(48.0, 15.0));
150 +
        let tint = Rgba::RED;
151 +
        let layout = TextLayout::new(input, font.clone(), tint, opts, Size::new(48.0, 15.0));
225 152
        assert!(!layout.is_overflow());
226 153
227 -
        let layout = TextLayout::new(input, &font, opts, Size::new(48.0, 14.0));
154 +
        let layout = TextLayout::new(input, font.clone(), tint, opts, Size::new(48.0, 14.0));
228 155
        assert!(!layout.is_overflow()); // Vertical overflow is ignored.
229 156
230 -
        let layout = TextLayout::new(input, &font, opts, Size::new(47.0, 15.0));
157 +
        let layout = TextLayout::new(input, font, tint, opts, Size::new(47.0, 15.0));
231 158
        assert!(layout.is_overflow());
232 159
        assert!(layout.glyphs.len() < input.len()); // Should not contain all characters.
233 160
    }
234 161
235 162
    #[test]
236 163
    fn test_text_layout_alignment() {
237 164
        let input = "Sphinx";
238 -
        let f_default = fonts::uf2::DEFAULT.decode().unwrap();
239 -
        let f_venice = fonts::uf2::VENICE.decode().unwrap();
165 +
        let tint = Rgba::RED;
166 +
        let f_default = Rc::new(font::uf2::DEFAULT.decode().unwrap());
167 +
        let f_venice = Rc::new(font::uf2::VENICE.decode().unwrap());
240 168
        let cases = [
241 169
            // Default font.
242 170
            (&f_default, Size::new(60., 19.), 19., Point2D::new(6., 3.)), // Even vertical fit.
243 171
            (&f_default, Size::new(60., 18.), 18., Point2D::new(6., 2.)), // Uneven vertical fit.
244 172
            (&f_default, Size::new(60., 15.), 15., Point2D::new(6., 1.)), // Tight vertical fit.
253 181
        assert_eq!(f_venice.metrics.line_height(), 18);
254 182
255 183
        for (i, (font, bounds, line_height, expected)) in cases.iter().enumerate() {
256 184
            let layout = TextLayout::new(
257 185
                input,
258 -
                font,
186 +
                Rc::clone(font),
187 +
                tint,
259 188
                TextLayoutOptions {
260 189
                    line_height: Some(*line_height),
261 190
                    align: TextAlign::Center,
262 191
                },
263 192
                *bounds,
268 197
        }
269 198
    }
270 199
271 200
    #[test]
272 201
    fn test_text_layout_empty_string() {
273 -
        let font = fonts::uf2::DEFAULT.decode().unwrap();
202 +
        let font = Rc::new(font::uf2::DEFAULT.decode().unwrap());
203 +
        let tint = Rgba::RED;
274 204
        let opts = TextLayoutOptions::default();
275 -
        let layout = TextLayout::new("", &font, opts, Size::new(48.0, 15.0));
205 +
        let layout = TextLayout::new("", font.clone(), tint, opts, Size::new(48.0, 15.0));
276 206
277 207
        assert_eq!(
278 208
            layout.size,
279 209
            Size::new(0.0, font.metrics.line_height() as f32)
280 210
        );
ombre/src/ui/gfx/text/rich.rs → ombre/src/text/rich.rs renamed +31 -89
7 7
//     TextSpanLayout* (one per style of text)
8 8
//       GlyphLayout*  (one per character)
9 9
//
10 10
// TODO: Hyphenation
11 11
use std::mem;
12 -
use std::ops::Range;
13 12
use std::rc::Rc;
14 13
15 -
use crate::ui::gfx::{Blit, FontFormat};
14 +
use crate::gfx::FontFormat;
15 +
use crate::gfx::Rgba8;
16 +
use crate::math::*;
17 +
use crate::text::align;
18 +
use crate::text::{LoadedTextSpan, TextSpan};
16 19
17 -
use crate::ui::math::*;
18 -
19 -
use super::{
20 -
    align, Font, FontName, Fonts, GlyphLayout, Image, RawLabel, Rgba8, TextAlign, TextLayoutOptions,
21 -
};
20 +
use super::{Font, GlyphLayout, Image, TextAlign, TextLayoutOptions};
22 21
23 22
/// Storage for rich text. A type that can represent rich text.
24 23
pub trait RichTextStorage: AsRef<str> {
25 24
    /// Return the text spans that contain the styling information
26 25
    /// of the text returned by [`RichTextStorage::as_str`].
27 26
    fn spans(&self) -> impl Iterator<Item = &TextSpan>;
27 +
28 28
    /// Get a reference to the plain string.
29 29
    fn as_str(&self) -> &str {
30 30
        self.as_ref()
31 31
    }
32 +
32 33
    /// Get the string length.
33 34
    fn len(&self) -> usize {
34 35
        self.as_str().len()
35 36
    }
37 +
36 38
    /// Check if the string is empty.
37 39
    fn is_empty(&self) -> bool {
38 40
        self.len() == 0
39 41
    }
40 42
}
41 43
42 -
/// Font style.
43 -
#[derive(Clone, Copy, Debug, Default)]
44 -
pub enum FontStyle {
45 -
    /// The default font style.
46 -
    #[default]
47 -
    Normal,
48 -
}
49 -
50 -
/// A span of text contains text with a set style.
51 -
#[derive(Clone, Debug)]
52 -
pub struct TextSpan {
53 -
    /// The range of characters represented by this span,
54 -
    /// within the text.
55 -
    pub range: Range<usize>,
56 -
    /// The font.
57 -
    pub font: FontName,
58 -
    /// The font style.
59 -
    pub style: FontStyle,
60 -
    /// Text color.
61 -
    pub tint: Rgba8,
62 -
}
63 -
64 -
impl TextSpan {
65 -
    /// Resolve a [`TextSpan`] to a [`LoadedTextSpan`].
66 -
    pub(crate) fn load(&self, fonts: &Fonts<Image>) -> LoadedTextSpan {
67 -
        LoadedTextSpan {
68 -
            span: self.clone(),
69 -
            font: fonts.lookup(&self.font).clone(),
70 -
        }
71 -
    }
72 -
}
73 -
74 -
/// A [`TextSpan`] with a loaded font.
75 -
#[derive(Debug)]
76 -
pub struct LoadedTextSpan {
77 -
    span: TextSpan,
78 -
    font: Rc<Font<Image>>,
79 -
}
80 -
81 44
/// A span of text that was layed out with the layout engine.
82 45
#[derive(Clone, Debug)]
83 -
struct TextSpanLayout {
46 +
pub struct TextSpanLayout {
84 47
    /// The font used for this span.
85 -
    font: Rc<Font<Image>>,
48 +
    pub(crate) font: Rc<Font<Image>>,
86 49
    /// Text color.
87 -
    tint: Rgba8,
50 +
    #[cfg_attr(not(feature = "ui"), allow(dead_code))]
51 +
    pub(crate) tint: Rgba8,
88 52
    /// The layed out glyphs.
89 -
    glyphs: Vec<GlyphLayout>,
90 -
}
91 -
92 -
impl TextSpanLayout {
93 -
    fn to_raw_label(&self) -> RawLabel<'_> {
94 -
        RawLabel {
95 -
            tile: self.font.tile_size(),
96 -
            glyphs: self.glyphs.as_slice(),
97 -
            tint: self.tint,
98 -
        }
99 -
    }
53 +
    pub(crate) glyphs: Vec<GlyphLayout>,
100 54
}
101 55
102 56
/// A row of text.
103 57
#[derive(Debug)]
104 -
struct TextRowLayout {
58 +
pub struct TextRowLayout {
105 59
    /// Total text width for this row.
106 -
    width: f32,
60 +
    pub(crate) width: f32,
107 61
    /// Glyphs, with their local screen position.
108 -
    spans: Vec<TextSpanLayout>,
62 +
    pub(crate) spans: Vec<TextSpanLayout>,
109 63
}
110 64
111 65
/// Rich text that has been layed out.
112 66
#[derive(Debug)]
113 67
pub struct RichTextLayout {
114 68
    /// Area used for the text layout.
115 -
    size: Size<f32>,
69 +
    pub size: Size<f32>,
116 70
    /// Lines of text.
117 -
    lines: Vec<TextRowLayout>,
71 +
    pub lines: Vec<TextRowLayout>,
118 72
}
119 73
120 74
impl RichTextLayout {
121 75
    /// Build a new rich text layout from the given inputs.
122 76
    pub fn build(
125 79
        opts: TextLayoutOptions,
126 80
        area: Size<f32>,
127 81
    ) -> Self {
128 82
        RichTextLayoutBuilder::new().build(text, spans, opts, area)
129 83
    }
84 +
85 +
    /// Final size of the text area, after layout.
86 +
    pub fn size(&self) -> Size<f32> {
87 +
        self.size
88 +
    }
130 89
}
131 90
132 91
/// Build a rich text layout.
133 92
#[derive(Debug)]
134 93
struct RichTextLayoutBuilder {
190 149
        } in spans
191 150
        {
192 151
            for word in text[range.start..range.end].split_inclusive(' ') {
193 152
                // Wrap text if the last glyph would overflow the area width.
194 153
                if self.dst.x + font.text_width(word) > area.w {
195 -
                    self.wrap_line(line_height, *tint, font.clone());
154 +
                    self.wrap_line(line_height, (*tint).into(), font.clone());
196 155
                    // Stop layout if we've overflowed the area height.
197 156
                    if self.dst.y > area.h {
198 157
                        break 'outer;
199 158
                    }
200 159
                }
201 160
                self.push_word(word, font);
202 161
            }
203 -
            self.push_span(*tint, font.clone());
162 +
            self.push_span((*tint).into(), font.clone());
204 163
        }
205 164
        self.push_line();
206 165
        self.finalize_layout(line_height, opts, area)
207 166
    }
208 167
302 261
            size,
303 262
        }
304 263
    }
305 264
}
306 265
307 -
impl RichTextLayout {
308 -
    /// Render the layed out text as [`Blit`] objects.
309 -
    pub fn render(&self) -> impl Iterator<Item = (Image, Blit<Local>)> + '_ {
310 -
        self.lines.iter().flat_map(|line| &line.spans).flat_map(|span| {
311 -
            let image = span.font.image.clone();
312 -
            span.to_raw_label()
313 -
                .render(image.size)
314 -
                .into_iter()
315 -
                .map(move |instance| (image.clone(), instance))
316 -
        })
317 -
    }
318 -
319 -
    /// Final size of the text area, after layout.
320 -
    pub fn size(&self) -> Size<f32> {
321 -
        self.size
322 -
    }
323 -
}
324 -
325 266
#[cfg(test)]
326 267
#[allow(clippy::unwrap_used)]
327 268
mod tests {
328 269
    use std::rc::Rc;
329 270
330 271
    use super::*;
331 -
    use crate::ui::fonts;
272 +
    use crate::gfx::font;
273 +
    use crate::gfx::font::Fonts;
332 274
333 275
    #[allow(dead_code)]
334 276
    fn fonts() -> Fonts<Image> {
335 -
        let font_default = fonts::uf2::DEFAULT.decode().unwrap();
336 -
        let font_venice = fonts::uf2::VENICE.decode().unwrap();
277 +
        let font_default = font::uf2::DEFAULT.decode().unwrap();
278 +
        let font_venice = font::uf2::VENICE.decode().unwrap();
337 279
338 -
        Fonts::new(font_default.clone()).with(fonts::uf2::VENICE.name, Rc::new(font_venice))
280 +
        Fonts::new(font_default.clone()).with(font::uf2::VENICE.name, Rc::new(font_venice))
339 281
    }
340 282
}
ombre/src/ui.rs +0 -2
20 20
pub use crate::platform;
21 21
22 22
pub use context::*;
23 23
pub use gfx::common::{Align, Align2D, Repaint};
24 24
pub use gfx::cursors::CursorDescriptor;
25 -
pub use gfx::fonts;
26 -
pub use gfx::fonts::FontDescriptor;
27 25
pub use gfx::text::{PlainText, RichTextStorage, TextAlign};
28 26
pub use interface::{interface, Error, Interface};
29 27
pub use lazy::Lazy;
30 28
pub use widgets::*;
31 29
pub use widgets::{Widget, WidgetEvent, WidgetExt};
ombre/src/ui/context.rs +64 -98
1 1
//! Widget context.
2 2
use std::collections::HashMap;
3 3
use std::ops::Deref;
4 -
use std::rc::Rc;
5 -
6 -
use crate::ui::gfx::font::Font;
7 4
5 +
use crate::paint::traits::Paint;
6 +
use crate::paint::PaintOp;
7 +
use crate::paint::{Brush, Shape};
8 +
use crate::text::Text;
8 9
use crate::ui::gfx::*;
9 10
use crate::ui::math::*;
10 11
11 -
/// Map of loaded fonts.
12 -
#[derive(Debug)]
13 -
pub struct Fonts<T> {
14 -
    /// The default font.
15 -
    pub default: Rc<Font<T>>,
16 -
    /// All the other loaded fonts.
17 -
    pub(crate) loaded: HashMap<FontName, Rc<Font<T>>>,
18 -
}
19 -
20 -
impl<T> Deref for Fonts<T> {
21 -
    type Target = HashMap<FontName, Rc<Font<T>>>;
22 -
23 -
    fn deref(&self) -> &Self::Target {
24 -
        &self.loaded
25 -
    }
26 -
}
27 -
28 -
impl<T> Fonts<T> {
29 -
    /// Create a new fonts database with a default font.
30 -
    pub fn new(font: Font<T>) -> Self {
31 -
        Self {
32 -
            default: Rc::new(font),
33 -
            loaded: HashMap::new(),
34 -
        }
35 -
    }
36 -
37 -
    /// Include a loaded font in the fonts map.
38 -
    pub fn with(mut self, name: FontName, font: Rc<Font<T>>) -> Self {
39 -
        self.loaded.insert(name, font);
40 -
        self
41 -
    }
42 -
43 -
    /// Lookup a loaded font, or return the default font if not found.
44 -
    pub fn lookup(&self, name: &FontName) -> &Rc<Font<T>> {
45 -
        self.loaded.get(name).unwrap_or(&self.default)
46 -
    }
47 -
}
48 -
49 12
/// Map of loaded cursors.
50 13
pub type Cursors = HashMap<&'static str, platform::Cursor>;
51 14
52 15
/// Global window state that can be modified by widgets.
53 16
#[derive(Debug, Clone)]
54 17
pub struct WindowCtx {
55 -
    /// The window title.
18 +
    /// The window title. Set this to set the window title.
56 19
    pub title: String,
57 -
    /// The cursor icon currently set.
20 +
    /// The cursor icon currently set. Set this to change the appearance
21 +
    /// of the pointer.
58 22
    pub cursor: Option<&'static str>,
59 -
    /// Window (inner) size.
60 -
    pub size: Size<u32>,
61 23
}
62 24
63 25
/// Widget context.
64 26
#[derive(Debug, Copy, Clone)]
65 27
pub struct Context {
75 37
}
76 38
77 39
impl Context {
78 40
    /// Create a new context.
79 41
    pub fn new(cursor: impl Into<Point2D<f32, Local>>, size: impl Into<Size<f32>>) -> Self {
42 +
        let size = size.into();
43 +
80 44
        Self {
81 45
            transform: Transform2D::identity(),
82 46
            cursor: cursor.into(),
83 -
            size: size.into(),
47 +
            size,
84 48
            active: false,
85 49
        }
86 50
    }
87 51
88 52
    /// Offset this context.
89 53
    pub fn offset(self, offset: impl Into<Vector2D<f32, Local>>) -> Self {
90 54
        let t = Transform2D::translate(offset.into());
91 -
        let transform = self.transform * t;
55 +
        let transform = t * self.transform;
92 56
        let cursor = self.cursor.transform(t.inverse().convert());
93 57
94 58
        Self {
95 59
            transform,
96 60
            cursor,
142 106
            ctx: self,
143 107
        }
144 108
    }
145 109
146 110
    /// Derive a paint context.
147 -
    pub(crate) fn as_paint<'a>(
148 -
        self,
149 -
        fonts: &'a Fonts<Image>,
150 -
        ops: &'a mut Vec<PaintOp>,
151 -
    ) -> PaintCtx<'a> {
152 -
        PaintCtx {
153 -
            fonts,
154 -
            ops,
155 -
            ctx: self,
156 -
        }
111 +
    pub(crate) fn as_paint(self, ops: &mut Vec<PaintOp>) -> PaintCtx<'_> {
112 +
        PaintCtx { ops, ctx: self }
157 113
    }
158 114
}
159 115
160 116
/// Layout function context.
161 117
#[derive(Clone)]
196 152
197 153
/// Paint function context.
198 154
pub struct PaintCtx<'a> {
199 155
    /// The parent context.
200 156
    pub ctx: Context,
201 -
    /// The set of loaded fonts.
202 -
    pub fonts: &'a Fonts<Image>,
203 -
    /// Paint operations.
204 -
    pub ops: &'a mut Vec<PaintOp>,
157 +
    /// Paint surface.
158 +
    pub(crate) ops: &'a mut Vec<PaintOp>,
205 159
}
206 160
207 161
impl Deref for PaintCtx<'_> {
208 162
    type Target = Context;
209 163
212 166
    }
213 167
}
214 168
215 169
impl PaintCtx<'_> {
216 170
    /// Blit an image.
217 -
    pub fn blit(&mut self, image: Image, blit: Blit<Local>) {
171 +
    pub fn blit(
172 +
        &mut self,
173 +
        image: Image,
174 +
        src: impl Into<Rect<f32, Local>>,
175 +
        dst: impl Into<Rect<f32, Local>>,
176 +
        tint: impl Into<Rgba<f32>>,
177 +
        opacity: f32,
178 +
    ) {
218 179
        self.ops.push(PaintOp::Blit {
219 180
            image,
220 -
            blit: blit.transform(self.transform),
181 +
            src: src.into(),
182 +
            dst: dst.into(),
183 +
            tint: tint.into(),
184 +
            opacity,
185 +
            transform: self.transform,
186 +
        });
187 +
    }
188 +
189 +
    /// Stroke a [`Shape`].
190 +
    pub fn stroke(&mut self, shape: impl Into<Shape<Local>>, brush: impl Into<Brush>, width: f32) {
191 +
        self.ops.push(PaintOp::Stroke {
192 +
            shape: shape.into(),
193 +
            brush: brush.into(),
194 +
            width,
195 +
            transform: self.transform,
221 196
        });
222 197
    }
223 198
224 -
    /// Fill a rectangle.
225 -
    pub fn fill(&mut self, rect: Rect<f32, Local>, color: Rgba<f32>, zdepth: ZDepth) {
199 +
    /// Fill a [`Shape`].
200 +
    pub fn fill(&mut self, shape: impl Into<Shape<Local>>, brush: impl Into<Brush>) {
226 201
        self.ops.push(PaintOp::Fill {
227 -
            rect: rect.transform(self.transform),
228 -
            color,
229 -
            zdepth,
202 +
            shape: shape.into(),
203 +
            brush: brush.into(),
204 +
            transform: self.transform,
230 205
        });
231 206
    }
232 207
233 -
    /// Stroke a rectangle.
234 -
    pub fn stroke(&mut self, rect: Rect<f32, Local>, color: Rgba<f32>, width: f32) {
235 -
        self.ops.push(PaintOp::Stroke {
236 -
            rect: rect.transform(self.transform),
237 -
            color,
238 -
            width,
208 +
    /// Draw text.
209 +
    pub fn text<'a>(&mut self, text: impl Into<Text<'a>>, dst: impl Into<Point2D<f32, Local>>) {
210 +
        self.ops.push(PaintOp::Text {
211 +
            text: text.into().into_owned(),
212 +
            dst: dst.into(),
213 +
            transform: self.transform,
239 214
        });
240 215
    }
241 216
242 217
    /// Draw a line.
243 218
    pub fn line(
244 219
        &mut self,
245 -
        from: Point2D<f32, Local>,
246 -
        to: Point2D<f32, Local>,
220 +
        from: impl Into<Point2D<f32, Local>>,
221 +
        to: impl Into<Point2D<f32, Local>>,
247 222
        width: f32,
248 223
        color: Rgba<f32>,
249 224
    ) {
250 -
        self.ops.push(PaintOp::Line {
251 -
            from: from.transform(self.transform),
252 -
            to: to.transform(self.transform),
225 +
        self.ops.push(PaintOp::Stroke {
226 +
            shape: Line::new(from, to).into(),
227 +
            brush: color.into(),
253 228
            width,
254 -
            color,
229 +
            transform: self.transform,
255 230
        });
256 231
    }
257 232
233 +
    /// Draw an object that implements [`Paint`].
234 +
    pub fn paint<P: Paint>(&mut self, object: P) {
235 +
        let view = self.transform;
236 +
        self.ops.extend(object.ops().map(|op| op.transform(view)));
237 +
    }
238 +
258 239
    /// Offset this context.
259 240
    pub fn offset(self, offset: impl Into<Vector2D<f32, Local>>) -> Self {
260 241
        let ctx = self.ctx.offset(offset);
261 242
262 -
        Self {
263 -
            ctx,
264 -
            ops: self.ops,
265 -
            fonts: self.fonts,
266 -
        }
243 +
        Self { ctx, ..self }
267 244
    }
268 245
269 246
    /// Inset this context.
270 247
    pub fn inset(self, inset: Size<f32>) -> Self {
271 248
        let ctx = self.ctx.inset(inset);
272 249
273 -
        Self {
274 -
            ctx,
275 -
            ops: self.ops,
276 -
            fonts: self.fonts,
277 -
        }
250 +
        Self { ctx, ..self }
278 251
    }
279 252
280 253
    /// Resize this context.
281 254
    pub fn resize(self, size: impl Into<Size<f32>>) -> Self {
282 255
        Self {
287 260
288 261
    /// Set the "active" flag for this context.
289 262
    pub fn active(self, active: bool) -> Self {
290 263
        Self {
291 264
            ctx: self.ctx.active(active),
292 -
            ops: self.ops,
293 -
            fonts: self.fonts,
265 +
            ..self
294 266
        }
295 267
    }
296 268
297 269
    /// Get the paint area bounds.
298 270
    pub fn rect(&self) -> Rect<f32, Local> {
332 304
            ctx: self.ctx.resize(size),
333 305
            ..self
334 306
        }
335 307
    }
336 308
}
337 -
338 -
/// Graphics pipeline and its bindings.
339 -
pub(crate) struct Pipeline<const N: usize, const M: usize> {
340 -
    pub pipeline: PipelineId,
341 -
    pub bindings: Bindings<N, M>,
342 -
}
ombre/src/ui/gfx.rs +6 -51
1 1
//! Nuit graphics module.
2 -
pub mod fonts;
3 -
4 2
pub(crate) mod common;
5 3
pub(crate) mod cursors;
6 4
pub(crate) mod present;
7 5
pub(crate) mod text;
8 6
9 -
pub use crate::draw::blit::Blit;
10 -
pub use crate::draw::pipeline::{Uniforms, Vertex};
11 -
pub use crate::draw::shape::{circle, line, rectangle, Circle, Line, Rectangle, Rotation};
12 -
pub use crate::draw::{batch, batch::VertexBatch, pipeline, shape};
7 +
pub use crate::gfx::font::FontDescriptor;
13 8
pub use crate::gfx::*;
9 +
pub use crate::paint::blit::Blit;
10 +
pub use crate::paint::pipeline::{Uniforms, Vertex};
11 +
pub use crate::paint::shape::{circle, line, rectangle, Circle, Line, Rectangle, Rotation};
12 +
pub use crate::paint::{batch, batch::VertexBatch, pipeline, shape, PaintOp};
13 +
pub use crate::text::{RichTextLayout, TextAlign, TextLayoutOptions, TextSpan};
14 14
15 15
pub use common::*;
16 16
pub use cursors::CursorDescriptor;
17 -
pub use fonts::FontDescriptor;
18 -
pub use text::{FontStyle, PlainText, RichTextLayout, TextAlign, TextLayoutOptions, TextSpan};
19 -
20 -
use crate::ui::math::{Screen, ZDepth};
21 -
22 -
/// A paint operation.
23 -
#[derive(Debug, Clone, PartialEq)]
24 -
pub enum PaintOp {
25 -
    /// Blit an image onto the screen.
26 -
    Blit {
27 -
        /// Image to blit.
28 -
        image: Image,
29 -
        /// Blit instance for this image.
30 -
        blit: Blit<Screen>,
31 -
    },
32 -
    /// Fill a color.
33 -
    Fill {
34 -
        /// Rectangle to fill.
35 -
        rect: Rect<f32, Screen>,
36 -
        /// Fill color.
37 -
        color: Rgba<f32>,
38 -
        /// Fill depth.
39 -
        zdepth: ZDepth,
40 -
    },
41 -
    /// Draw a line,
42 -
    Line {
43 -
        /// Start point.
44 -
        from: Point2D<f32, Screen>,
45 -
        /// End point.
46 -
        to: Point2D<f32, Screen>,
47 -
        /// Stroke color.
48 -
        color: Rgba<f32>,
49 -
        /// Stroke width.
50 -
        width: f32,
51 -
    },
52 -
    /// Stroke a color.
53 -
    Stroke {
54 -
        /// Rectangle to stroke.
55 -
        rect: Rect<f32, Screen>,
56 -
        /// Stroke color.
57 -
        color: Rgba<f32>,
58 -
        /// Stroke width.
59 -
        width: f32,
60 -
    },
61 -
}
ombre/src/ui/gfx/fonts.rs +0 -38
1 -
//! Font definitions.
2 -
3 -
// Re-exports.
4 -
pub use crate::ui::gfx::{Font, FontDescriptor, FontFormat, FontMetrics, FontName};
5 -
6 -
/// Default font identifier.
7 -
pub const DEFAULT_FONT: FontName = FontName::new("Default");
8 -
9 -
/// UF2 fonts.
10 -
pub mod uf2 {
11 -
    use super::*;
12 -
13 -
    /// Default font.
14 -
    pub const DEFAULT: FontDescriptor<'static> = FontDescriptor {
15 -
        name: DEFAULT_FONT,
16 -
        format: FontFormat::UF2,
17 -
        data: include_bytes!("fonts/gohu14.uf2"),
18 -
        metrics: FontMetrics {
19 -
            cap_height: 9,
20 -
            desc_height: 3,
21 -
            glyph_height: 14,
22 -
            baseline: 3,
23 -
        },
24 -
    };
25 -
26 -
    /// Venice.
27 -
    pub const VENICE: FontDescriptor<'static> = FontDescriptor {
28 -
        name: FontName::new("Venice"),
29 -
        format: FontFormat::UF2,
30 -
        data: include_bytes!("fonts/venice14.uf2"),
31 -
        metrics: FontMetrics {
32 -
            cap_height: 10,
33 -
            desc_height: 4,
34 -
            glyph_height: 16,
35 -
            baseline: 4,
36 -
        },
37 -
    };
38 -
}
ombre/src/ui/gfx/text.rs +66 -137
1 1
//! Text rendering.
2 -
mod plain;
3 -
mod rich;
4 -
5 2
use std::sync::Arc;
6 3
7 -
use crate::ui::context::Fonts;
8 -
use crate::ui::gfx::{Blit, FontMetrics, Image, Rgba8, Size};
9 -
use crate::ui::math::rect::Rect;
10 -
use crate::ui::math::*;
11 -
12 -
use super::fonts::DEFAULT_FONT;
4 +
use crate::gfx::font::{FontName, Fonts, DEFAULT_FONT};
5 +
use crate::gfx::{Image, Rgba, Size};
6 +
use crate::math::Zero as _;
13 7
14 -
pub use crate::ui::gfx::font::{Font, FontName};
15 -
pub use plain::PlainText;
16 -
pub use rich::{FontStyle, LoadedTextSpan, RichTextLayout, RichTextStorage, TextSpan};
8 +
pub use crate::text::*;
17 9
18 10
/// Text value. Either static or dynamic.
19 11
pub enum TextValue<T> {
20 12
    /// For static text that never changes.
21 13
    Static(Arc<str>),
62 54
        let f = Arc::new(move |state: &T| resolve(state).into());
63 55
        TextValue::Dynamic(f)
64 56
    }
65 57
}
66 58
67 -
/// Text alignment.
68 -
#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
69 -
pub enum TextAlign {
70 -
    /// Left-align.
71 -
    #[default]
72 -
    Left,
73 -
    /// Center-align.
74 -
    Center,
75 -
    /// Right-align.
76 -
    Right,
77 -
}
78 -
79 -
/// Text layout options.
80 -
#[derive(Copy, Clone, Debug, Default)]
81 -
pub struct TextLayoutOptions {
82 -
    /// Line height. Defaults to the font tile height if `None`.
83 -
    pub line_height: Option<f32>,
84 -
    /// Text alignment (default: left).
85 -
    pub align: TextAlign,
86 -
}
87 -
88 -
impl TextLayoutOptions {
89 -
    /// Centered text.
90 -
    pub fn centered(self) -> Self {
91 -
        self.align(TextAlign::Center)
92 -
    }
93 -
94 -
    /// Set text alignment.
95 -
    pub fn align(mut self, align: impl Into<TextAlign>) -> Self {
96 -
        self.align = align.into();
97 -
        self
98 -
    }
99 -
}
100 -
101 -
/// A single layed out character.
102 -
#[derive(Clone, Debug)]
103 -
struct GlyphLayout {
104 -
    /// Character index into the texture.
105 -
    character: u8,
106 -
    /// Position of the glyph within the text area.
107 -
    bounds: Rect<f32, Local>,
108 -
}
109 -
110 59
/// An object that can store text.
111 60
/// Used by text input widgets to store the input value.
112 61
pub trait TextStorage {
113 62
    /// Clear the text value.
114 63
    fn clear(&mut self) {
145 94
    fn insert(&mut self, idx: usize, ch: char) {
146 95
        String::insert(self, idx, ch)
147 96
    }
148 97
}
149 98
150 -
pub struct RawLabel<'a> {
151 -
    tile: Size<f32>,
152 -
    glyphs: &'a [GlyphLayout],
153 -
    tint: Rgba8,
99 +
/// Text object with layout, style and data.
100 +
#[derive(Debug)]
101 +
pub struct PlainText<T> {
102 +
    pub(crate) font: FontName,
103 +
    pub(crate) value: TextValue<T>,
104 +
    pub(crate) opts: TextLayoutOptions,
105 +
    pub(crate) color: Rgba<f32>,
106 +
    pub(crate) layout: Option<TextLayout>,
107 +
    pub(crate) bounds: Size<f32>,
108 +
109 +
    /// Cached text value for comparisons.
110 +
    old: Arc<str>,
154 111
}
155 112
156 -
impl RawLabel<'_> {
157 -
    /// Render the glyphs as [`Blit`] objects, using the font texture information.
158 -
    pub fn render(&self, texture: Size<u32>) -> Vec<Blit<Local>> {
159 -
        let size = self.tile;
160 -
        let stride = texture.w / size.w as u32;
161 -
        let mut batch = Vec::new();
162 -
163 -
        if stride == 0 {
164 -
            panic!("RawLabel::render: texture stride must not be zero");
165 -
        }
166 -
        for g in self.glyphs {
167 -
            let i = g.character as u32;
168 -
            let x = (i % stride) as f32 * size.w;
169 -
            let y = (i / stride) as f32 * size.h;
170 -
171 -
            batch.push(
172 -
                Blit::<Local>::new(Rect::new([x, y], g.bounds.size), g.bounds).tint(self.tint),
173 -
            );
174 -
        }
175 -
        batch
113 +
impl<T> From<String> for PlainText<T> {
114 +
    fn from(data: String) -> Self {
115 +
        Self::new(
116 +
            DEFAULT_FONT,
117 +
            TextLayoutOptions::default(),
118 +
            Rgba::default(),
119 +
            data,
120 +
        )
176 121
    }
177 122
}
178 123
179 -
pub(crate) mod align {
180 -
    use super::*;
181 -
182 -
    pub(super) fn horizontal<'a>(
183 -
        glyphs: impl Iterator<Item = &'a mut GlyphLayout>,
184 -
        width: f32,
185 -
        align: TextAlign,
186 -
        bounds: Size<f32>,
187 -
    ) {
188 -
        if width >= bounds.w {
189 -
            return;
190 -
        }
191 -
        let offset = match align {
192 -
            TextAlign::Left => return,
193 -
            TextAlign::Center => (bounds.w - width) / 2.,
194 -
            TextAlign::Right => bounds.w - width,
195 -
        };
196 -
        for glyph in glyphs {
197 -
            glyph.bounds.origin.x += offset;
124 +
impl<T> PlainText<T> {
125 +
    /// Create a new text object.
126 +
    pub fn new(
127 +
        font: FontName,
128 +
        opts: TextLayoutOptions,
129 +
        color: Rgba<f32>,
130 +
        data: impl Into<TextValue<T>>,
131 +
    ) -> Self {
132 +
        Self {
133 +
            font,
134 +
            old: String::new().into(),
135 +
            value: data.into(),
136 +
            color,
137 +
            opts,
138 +
            layout: None,
139 +
            bounds: Size::ZERO,
198 140
        }
199 141
    }
200 142
201 -
    //   ┌─────────────────────────────────┐__ Glyph height (14) (total)
202 -
    //  d│                                 │
203 -
    //  c│_________________________________│__ Cap height (9) (from baseline)
204 -
    //  b│ @@@@                            │
205 -
    //  a│@    @        ___________________│__ X-height (6) (from baseline)
206 -
    //  9│@       @ @@@                    │
207 -
    //  8│@       @@   @                   │
208 -
    //  7│ @@@@   @    @                   │
209 -
    //  6│     @  @    @                   │
210 -
    //  5│     @  @    @                   │
211 -
    //  4│@    @  @@   @                   │
212 -
    //  3│ @@@@   @ @@@ ___________________│__ Baseline (3)
213 -
    //  2│        @                        │
214 -
    //  1│        @                        │
215 -
    //  0│        @ _______________________│__ Descender height (3) (until baseline)
216 -
    //   │                                 │
217 -
    //   │                                 │
218 -
    //   └─────────────────────────────────┘
219 -
    //
220 -
    // The goal is to place the glyph such that `char_height` is vertically centered within
221 -
    // `line_height`, keeping in mind that `char_height` is offset by `baseline`.
222 -
    //
223 -
    pub(super) fn vertical<'a>(
224 -
        glyphs: impl Iterator<Item = &'a mut GlyphLayout>,
225 -
        line_height: f32, // Usually "cap height" + 2 * "descender height", unless line is taller.
226 -
        char_height: f32, // Usually "cap height".
227 -
        metrics: FontMetrics,
228 -
    ) {
229 -
        let glyph_height = metrics.glyph_height as f32;
230 -
        // The baseline as taken from the top of the glyph, instead of the bottom.
231 -
        let baseline = glyph_height - metrics.baseline as f32;
232 -
        let diff = line_height - char_height;
233 -
        // How much space we want above and below the centered piece.
234 -
        let padding = diff / 2.;
235 -
        let offset = (padding - baseline) + char_height;
236 -
        let offset = offset.truncate();
237 -
238 -
        for glyph in glyphs {
239 -
            glyph.bounds.origin.y += offset;
143 +
    /// Set the value of the text.
144 +
    pub fn set(&mut self, data: impl ToString) {
145 +
        self.value = data.to_string().into();
146 +
        self.layout = None;
147 +
    }
148 +
149 +
    /// Layout the text.
150 +
    pub fn layout(&mut self, data: &T, bounds: Size<f32>, fonts: &Fonts<Image>) -> &TextLayout {
151 +
        let text = self.value.resolve(data);
152 +
153 +
        if bounds != self.bounds || text != self.old {
154 +
            self.layout = None;
240 155
        }
156 +
        let layout = self.layout.get_or_insert_with(|| {
157 +
            let font = fonts.lookup(&self.font).clone();
158 +
            TextLayout::new(text.as_ref(), font, self.color, self.opts, bounds)
159 +
        });
160 +
161 +
        self.bounds = bounds;
162 +
        self.old = text;
163 +
164 +
        layout
165 +
    }
166 +
167 +
    /// Force re-layout of text.
168 +
    pub fn clear(&mut self) {
169 +
        self.layout = None;
241 170
    }
242 171
}
ombre/src/ui/interface.rs +75 -467
1 1
//! User interface types.
2 2
use std::collections::HashMap;
3 3
use std::marker::PhantomData;
4 -
use std::mem;
5 4
use std::ops::{Deref, DerefMut};
6 -
use std::rc::Rc;
7 5
8 -
use crate::draw::traits::Brush;
6 +
use crate::canvas;
7 +
use crate::canvas::CanvasBuilder;
8 +
use crate::paint::{Canvas, PaintSurface};
9 9
use crate::prelude::*;
10 -
use crate::ui::gfx::pipeline::Vertex;
11 -
use crate::ui::gfx::{batch::TextureInfo, pipeline, present, shape, PaintOp, VertexBatch};
12 10
use crate::ui::math::Zero;
13 11
use crate::ui::platform::WindowEvent;
14 12
use crate::ui::widgets;
13 +
use crate::ui::Pod;
15 14
use crate::ui::WindowCtx;
16 -
use crate::ui::{
17 -
    context::{Cursors, Fonts, Pipeline},
18 -
    Context, CursorDescriptor, FontDescriptor, Widget, WidgetEvent,
19 -
};
20 -
use crate::ui::{fonts, Pod};
21 -
22 -
/// Default number of vertices in the interface VBO.
23 -
/// Roughly 16MB of VRAM. This number has to be divisible by 3,
24 -
/// given that we are drawing triangles.
25 -
pub const DEFAULT_MAX_VERTICES: usize = 2usize.pow(18) - 1;
26 -
/// Default number of texture layers used by the rendering pipeline.
27 -
/// This is the maximum number of distinct texture objects available for rendering.
28 -
pub const DEFAULT_MAX_TEXTURE_LAYERS: usize = 16;
15 +
use crate::ui::{context::Cursors, Context, CursorDescriptor, Widget, WidgetEvent};
29 16
30 17
/// Interface error.
31 18
#[derive(Debug)]
32 19
pub enum Error<T: RenderBackend> {
33 -
    /// Render backend error.
34 -
    Render(T::Error),
35 -
    /// Font error.
36 -
    Font(font::FontError),
20 +
    /// Canvas error.
21 +
    Canvas(canvas::Error<T>),
37 22
    /// Config error.
38 23
    Config(&'static str),
24 +
    /// Render error.
25 +
    Render(T::Error), // TODO: Remove variant and fix example runtime.
39 26
}
40 27
41 28
impl<T: RenderBackend> std::fmt::Display for Error<T> {
42 29
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 30
        match self {
44 -
            Self::Render(e) => e.fmt(f),
45 -
            Self::Font(e) => e.fmt(f),
31 +
            Self::Canvas(e) => e.fmt(f),
46 32
            Self::Config(e) => write!(f, "config: {e}"),
33 +
            Self::Render(e) => e.fmt(f),
47 34
        }
48 35
    }
49 36
}
50 37
51 38
impl<T: RenderBackend + std::fmt::Debug> std::error::Error for Error<T> {}
52 39
53 -
impl<T: RenderBackend> From<font::FontError> for Error<T> {
54 -
    fn from(e: font::FontError) -> Self {
55 -
        Self::Font(e)
56 -
    }
57 -
}
58 -
59 -
/// Represents a layer in a 2D texture array, tracking both the source image and its index.
60 -
#[derive(Copy, Clone, PartialEq, Debug)]
61 -
struct TextureLayer {
62 -
    /// The source image ID if this layer contains an image, or `None` if the texture was generated
63 -
    /// programatically, eg. the blank texture used for shape rendering.
64 -
    image: Option<ImageId>,
65 -
    /// The GPU texture layer index where this texture is stored.
66 -
    index: u8,
67 -
}
68 -
69 -
/// Manages the state for a batched rendering system with a fixed number of texture layers.
70 -
///
71 -
/// RenderState tracks texture allocation, paint operations, and vertex batching for efficient
72 -
/// GPU rendering. It uses a fixed-size array of texture layers.
73 -
///
74 -
/// The system auto-allocates texture layers as needed when blitting images, up to the maximum
75 -
/// supported by the GPU (constant `N`). Each layer maintains its original size information, for
76 -
/// proper UV coordinate calculation in the shaders.
77 -
struct RenderState<const N: usize> {
78 -
    /// Array of texture layers
79 -
    /// The first slot is reserved for the blank texture used in shape rendering.
80 -
    textures: [Option<TextureLayer>; N],
81 -
    /// Parallel array to `textures` storing the dimensions of each image.
82 -
    /// Used for UV coordinate calculations.
83 -
    sizes: [Size<u32>; N],
84 -
    /// Queue of painting operations to be processed in the next batch.
85 -
    /// Operations are consumed and converted to vertices during batching.
86 -
    ops: Vec<PaintOp>,
87 -
    /// Accumulates vertices for all paint operations in the current batch.
88 -
    /// Used to minimize draw calls by batching compatible operations together.
89 -
    batch: VertexBatch,
90 -
}
91 -
92 -
impl<const N: usize> RenderState<N> {
93 -
    fn new(texture: TextureInfo) -> Self {
94 -
        let mut textures = [None; N];
95 -
        let sizes = [texture.size; N];
96 -
97 -
        // The first layer contains a blank texture used for rendering shapes.
98 -
        textures[0] = Some(TextureLayer {
99 -
            image: None,
100 -
            index: 0,
101 -
        });
102 -
103 -
        Self {
104 -
            textures,
105 -
            sizes,
106 -
            ops: Vec::with_capacity(256),
107 -
            batch: VertexBatch::new(texture),
108 -
        }
109 -
    }
110 -
111 -
    fn texture(&self) -> &TextureInfo {
112 -
        &self.batch.texture
113 -
    }
114 -
115 -
    // Helper function to find or create texture layer.
116 -
    fn get_or_create_layer<'f, F: RenderFrame<'f>>(
117 -
        &mut self,
118 -
        frame: &mut F,
119 -
        image: &Image,
120 -
    ) -> Option<TextureLayer> {
121 -
        // First try to find an existing layer with the given image.
122 -
        if let Some(&layer) = self.textures.iter().flatten().find(|l| l.image == Some(image.id())) {
123 -
            return Some(layer);
124 -
        }
125 -
        // Then try to create new layer.
126 -
        let index = self.textures.iter().position(Option::is_none)?;
127 -
        let layer = TextureLayer {
128 -
            image: Some(image.id()),
129 -
            index: index as u8,
130 -
        };
131 -
        self.textures[index] = Some(layer);
132 -
        self.sizes[index] = image.size;
133 -
134 -
        // Update backend texture layer with image data.
135 -
        if let Err(e) = frame.backend_mut().texture_update_layer(
136 -
            self.batch.texture.id,
137 -
            layer.index,
138 -
            Rect::origin(image.size),
139 -
            &image.pixels,
140 -
        ) {
141 -
            log::error!(target: "ui", "texture layer update error: {e}");
142 -
            return None;
143 -
        }
144 -
        Some(layer)
145 -
    }
146 -
147 -
    fn batch<'f, F: RenderFrame<'f>>(&mut self, frame: &mut F) -> Box<[Vertex]> {
148 -
        for op in mem::take(&mut self.ops) {
149 -
            match op {
150 -
                PaintOp::Blit { image, blit } => {
151 -
                    let Some(layer) = self.get_or_create_layer(frame, &image) else {
152 -
                        log::error!(
153 -
                            target: "ui",
154 -
                            "texture limit exceeded: renderer only supports {N} concurrent texture(s)"
155 -
                        );
156 -
                        continue;
157 -
                    };
158 -
                    self.batch.blit(blit, layer.index);
159 -
                }
160 -
                PaintOp::Fill {
161 -
                    rect,
162 -
                    color,
163 -
                    zdepth,
164 -
                } => {
165 -
                    self.batch.fill(
166 -
                        shape::Rectangle::from(rect).zdepth(zdepth),
167 -
                        Brush::Color(color),
168 -
                    );
169 -
                }
170 -
                PaintOp::Line {
171 -
                    from,
172 -
                    to,
173 -
                    color,
174 -
                    width,
175 -
                } => {
176 -
                    self.batch
177 -
                        .stroke(shape::Line::new(from, to), Brush::Color(color), width);
178 -
                }
179 -
                PaintOp::Stroke { rect, color, width } => {
180 -
                    self.batch
181 -
                        .stroke(shape::Rectangle::from(rect), Brush::Color(color), width);
182 -
                }
183 -
            }
184 -
        }
185 -
        self.batch.vertices()
186 -
    }
187 -
}
188 -
189 -
/// Holds debug render state.
190 -
struct DebugState {
191 -
    visible: bool,
192 -
    render: RenderState<8>,
193 -
    widget: widgets::Grid<()>,
194 -
}
195 -
196 40
/// Interface configuration.
197 41
pub struct Config {
198 42
    /// Maximum number of vertices that can be allocated by the renderer.
199 -
    /// Defaults to [`DEFAULT_MAX_VERTICES`].
43 +
    /// Defaults to [`canvas::DEFAULT_MAX_VERTICES`].
200 44
    pub max_vertices: usize,
201 45
}
202 46
203 47
impl Default for Config {
204 48
    fn default() -> Self {
205 49
        Self {
206 -
            max_vertices: DEFAULT_MAX_VERTICES,
50 +
            max_vertices: canvas::DEFAULT_MAX_VERTICES,
207 51
        }
208 52
    }
209 53
}
210 54
211 55
/// User interface state. Wraps the root widget with additional state
212 56
/// required to render the interface.
213 -
pub struct Interface<W, T, const N: usize = DEFAULT_MAX_TEXTURE_LAYERS> {
57 +
pub struct Interface<W, T, const N: usize = { canvas::DEFAULT_MAX_TEXTURE_LAYERS }> {
214 58
    /// Root of the widget tree.
215 59
    root: widgets::Pod<W, T>,
216 -
    /// Interface bounds in pixels.
217 -
    bounds: Size<f32>,
218 -
    /// UI scale.
219 -
    scale: f32,
220 -
    /// Offscreen pass ID.
221 -
    offscreen: PassId,
222 -
    /// Shading stage pipeline.
223 -
    shade: Pipeline<1, 1>,
224 -
    /// Present to screen pipeline.
225 -
    present: Pipeline<0, 1>,
226 -
    /// Render state.
227 -
    render: RenderState<N>,
228 -
    /// Debug state.
229 -
    debug: DebugState,
60 +
    /// Paint surface.
61 +
    canvas: Canvas,
230 62
    /// Cursor position.
231 63
    cursor: Point2D<f32, Screen>,
232 64
    /// Current window state.
233 65
    window: WindowCtx,
234 -
    /// Size of presentation backbuffer, ie. the window's framebuffer.
235 -
    backbuffer: Size<f32>,
236 -
    /// Loaded fonts.
237 -
    fonts: Fonts<Image>,
238 66
    /// Loaded cursors.
239 67
    cursors: Cursors,
240 -
    /// Interface configuration.
241 -
    config: Config,
242 -
    /// Are there changes to render?
243 -
    dirty: bool,
68 +
    /// Enable debug overlay.
69 +
    debug: bool,
244 70
    /// Widget data type witness.
245 71
    data: PhantomData<T>,
246 72
}
247 73
248 74
impl<W, T> Deref for Interface<W, T> {
273 99
        backend: &mut R,
274 100
        window: &mut platform::Window,
275 101
    ) -> Result<(), R::Error> {
276 102
        let wevent = match event {
277 103
            WindowEvent::CursorMoved { position } => {
278 -
                self.cursor = Point2D::new(position.x as f32, position.y as f32) / self.scale;
104 +
                self.cursor =
105 +
                    Point2D::new(position.x as f32, position.y as f32) / self.canvas.scale();
279 106
                WidgetEvent::MouseMove(self.cursor)
280 107
            }
281 108
            WindowEvent::Resized(size) => {
282 -
                // When the window is resized, we want to keep pixels aligned to the pixel grid,
283 -
                // even when UI scaling is used. To do this, we render to a subarea of the window's
284 -
                // framebuffer: the largest area with a size that is a multiple of the `scale`
285 -
                // value.
286 -
                // TODO: Use `window.set_size_limit`.
287 -
                let win_size = Size::new(size.width, size.height);
288 -
                let win_size_aligned = {
289 -
                    // Snap to the nearest multiple of the UI `scale`.
290 -
                    let w = (win_size.w as u32 / self.scale as u32) * self.scale as u32;
291 -
                    let h = (win_size.h as u32 / self.scale as u32) * self.scale as u32;
292 -
293 -
                    // Ensure minimum size.
294 -
                    let w = w.max(self.scale as u32);
295 -
                    let h = h.max(self.scale as u32);
296 -
297 -
                    Size::new(w, h)
298 -
                };
299 -
                let win_size_scaled = win_size_aligned.map(|n| n as f32) / self.scale;
300 -
301 -
                // The backbuffer is the size of the window without any scaling.
302 -
                self.backbuffer = win_size.map(|n| n as f32);
303 -
                // Window size after it is aligned to the pixel grid.
304 -
                self.window.size = win_size_aligned;
305 -
                // Interface bounds is the "virtual" size that is then scaled to the window size.
306 -
                self.bounds = win_size_scaled;
307 -
308 -
                log::debug!(
309 -
                    target: "ui",
310 -
                    "window resized to {}, aligned to {}, scaled by {} from {}",
311 -
                    win_size,
312 -
                    win_size_aligned,
313 -
                    self.scale,
314 -
                    win_size_scaled,
315 -
                );
316 -
                self.root.layout(data, self.context().as_layout(&self.fonts));
317 -
318 -
                backend.pass_resize_attachments(self.offscreen, self.bounds.map(|n| n as u32))?;
109 +
                self.canvas.resize(size, backend)?;
110 +
                self.root.layout(data, self.context().as_layout(self.canvas.fonts()));
319 111
320 112
                return Ok(());
321 113
            }
322 114
            WindowEvent::RedrawRequested => {
323 -
                self.root.layout(data, self.context().as_layout(&self.fonts));
115 +
                self.root.layout(data, self.context().as_layout(self.canvas.fonts()));
324 116
325 117
                return Ok(());
326 118
            }
327 119
            WindowEvent::MouseInput { state, button, .. } => match state {
328 120
                platform::InputState::Pressed => WidgetEvent::MouseDown(button),
330 122
                platform::InputState::Repeated => {
331 123
                    return Ok(());
332 124
                }
333 125
            },
334 126
            WindowEvent::KeyboardInput(i) if i.is_pressed() && i.key == Some(platform::Key::F9) => {
335 -
                self.debug.visible = !self.debug.visible;
127 +
                self.debug = !self.debug;
128 +
                self.canvas.debug(self.debug);
336 129
337 130
                return Ok(());
338 131
            }
339 132
            WindowEvent::KeyboardInput(i) if i.is_pressed() && i.key == Some(platform::Key::F8) => {
340 133
                self.root.debug().print(&mut std::io::stdout()).ok();
360 153
        };
361 154
        let mut win = self.window.clone();
362 155
        let ctx = self.context();
363 156
364 157
        // Process the event and re-run layout in case it was affected.
365 -
        self.root.event(&wevent, data, ctx.as_event(&self.fonts), &mut win);
366 -
        self.root.layout(data, ctx.as_layout(&self.fonts));
367 -
        self.dirty = true;
158 +
        self.root
159 +
            .event(&wevent, data, ctx.as_event(self.canvas.fonts()), &mut win);
160 +
        self.root.layout(data, ctx.as_layout(self.canvas.fonts()));
368 161
369 162
        // A widget has modified the window cursor.
370 163
        if win.cursor != self.window.cursor {
371 164
            let cursor = win.cursor.and_then(|name| self.cursors.remove(name));
372 165
            if let Some(old) = window.set_cursor(cursor) {
385 178
386 179
        Ok(())
387 180
    }
388 181
389 182
    /// UI frame. Call this on every frame.
390 -
    pub fn frame<'a, 'f, F>(&mut self, data: &T, frame: &'a mut F) -> Result<(), F::Error>
391 -
    where
392 -
        F: RenderFrame<'f> + 'f,
393 -
    {
183 +
    pub fn frame<'f, F: RenderFrame<'f>>(
184 +
        &mut self,
185 +
        data: &T,
186 +
        frame: &mut F,
187 +
    ) -> Result<(), F::Error> {
394 188
        let ctx = self.context();
189 +
        let mut ops = Vec::new(); // TODO: Used fixed size array.
395 190
396 -
        self.dirty = false;
397 -
        self.root.layout(data, ctx.as_layout(&self.fonts));
398 -
        self.root.paint(data, ctx.as_paint(&self.fonts, &mut self.render.ops));
399 -
400 -
        // Begin offscreen pass.
401 -
        frame.begin_pass(self.offscreen, PassAction::default());
402 -
        frame.apply_pipeline(&self.shade.pipeline)?;
403 -
        frame.apply_uniforms(&pipeline::Uniforms::new(
404 -
            self.bounds,
405 -
            Transform3D::identity(),
406 -
            self.render.sizes,
407 -
        ))?;
408 -
409 -
        let texture = self.render.texture().id;
410 -
        let batch = self.render.batch(frame);
411 -
        let length = batch.len();
412 -
        let chunk = self.config.max_vertices.min(length);
413 -
        let bindings = gfx::Bindings {
414 -
            vertex: self.shade.bindings.vertex,
415 -
            index: self.shade.bindings.index,
416 -
            textures: [texture],
417 -
        };
418 -
        if !batch.is_empty() {
419 -
            if log::log_enabled!(log::Level::Debug) && length > self.config.max_vertices {
420 -
                log::debug!(
421 -
                    target: "ui",
422 -
                    "vertex buffer capacity ({}) exceeded, \
423 -
                    splitting batch render of {length} vertices into {} draw calls..",
424 -
                    self.config.max_vertices,
425 -
                    length.div_ceil(chunk)
426 -
                );
427 -
            }
428 -
            for chunk in batch.chunks(chunk) {
429 -
                frame.buffer_update(bindings.vertex[0], BufferKind::Vertex, 0, chunk)?;
430 -
                frame.apply_bindings(&bindings)?;
431 -
                frame.draw(0, chunk.len(), 1)?;
432 -
            }
433 -
        }
434 -
        frame.end_pass();
435 -
436 -
        // Begin onscreen pass.
437 -
        //
438 -
        // The size of the pass is the full backbuffer size, so we clear to that size. But
439 -
        // we're only going to be drawing to a viewport that is the size of the aligned
440 -
        // window size.
441 -
        frame.begin_default_pass(PassAction::default(), self.backbuffer.map(|n| n as u32));
442 -
        frame.apply_viewport(Rect::new(
443 -
            [0, self.backbuffer.h as i32 - self.window.size.h as i32],
444 -
            self.window.size.map(|n| n as i32),
445 -
        ))?;
446 -
        frame.apply_pipeline(&self.present.pipeline)?;
447 -
        frame.apply_uniforms(&())?;
448 -
        frame.apply_bindings(&self.present.bindings)?;
449 -
        frame.draw(0, 6, 1)?;
450 -
451 -
        if self.debug.visible {
452 -
            let ctx = Context::new(self.cursor.convert(), self.window.size);
453 -
454 -
            self.debug.widget.layout(&(), ctx.as_layout(&self.fonts));
455 -
            self.debug
456 -
                .widget
457 -
                .paint(&(), ctx.as_paint(&self.fonts, &mut self.debug.render.ops));
458 -
459 -
            frame.apply_pipeline(&self.shade.pipeline)?;
460 -
            frame.apply_uniforms(&pipeline::Uniforms::new(
461 -
                [self.window.size.w as f32, self.window.size.h as f32],
462 -
                Transform3D::identity(),
463 -
                self.render.sizes,
464 -
            ))?;
465 -
466 -
            let texture = self.debug.render.texture().id;
467 -
            let batch = self.debug.render.batch(frame);
468 -
            let bindings = gfx::Bindings {
469 -
                vertex: self.shade.bindings.vertex,
470 -
                index: self.shade.bindings.index,
471 -
                textures: [texture],
472 -
            };
473 -
            frame.buffer_update(bindings.vertex[0], BufferKind::Vertex, 0, &batch)?;
474 -
            frame.apply_bindings(&bindings)?;
475 -
            frame.draw(0, batch.len(), 1)?;
476 -
        }
477 -
        frame.end_pass();
191 +
        self.root.layout(data, ctx.as_layout(self.canvas.fonts()));
192 +
        self.root.paint(data, ctx.as_paint(&mut ops));
193 +
        self.canvas.ops(ops.drain(..));
194 +
        self.canvas.flush(frame)?;
195 +
        self.canvas.clear();
478 196
479 197
        Ok(())
480 198
    }
481 199
482 200
    /// Create a context object.
483 201
    fn context(&self) -> Context {
484 -
        debug_assert_ne!(self.bounds, Size::ZERO);
485 -
        Context::new(self.cursor.convert::<Local>(), self.bounds)
202 +
        debug_assert_ne!(self.canvas.size(), Size::ZERO);
203 +
        Context::new(
204 +
            self.cursor.convert::<Local>(),
205 +
            self.canvas.size() / self.canvas.scale(),
206 +
        )
486 207
    }
487 208
}
488 209
489 210
/// Interface builder used to produce an [`Interface`].
490 211
pub struct InterfaceBuilder<'r, 'w, R: RenderBackend> {
491 -
    scale: f32,
492 -
    debug: bool,
493 -
    fonts: HashMap<FontName, Rc<Font<Image>>>,
212 +
    canvas: CanvasBuilder<'r, R>,
494 213
    config: Config,
495 -
    cursors: Cursors,
496 -
    backend: &'r mut R,
214 +
    cursors: HashMap<&'static str, CursorDescriptor>,
497 215
    window: &'w platform::Window,
216 +
    scale: f32,
217 +
    debug: bool,
498 218
}
499 219
500 220
/// Build a new interface.
501 221
pub fn interface<'r, 'w, R: RenderBackend>(
502 222
    window: &'w platform::Window,
503 223
    backend: &'r mut R,
504 224
) -> InterfaceBuilder<'r, 'w, R> {
505 225
    InterfaceBuilder {
506 226
        debug: false,
227 +
        canvas: CanvasBuilder::new(window.size().into(), backend),
507 228
        scale: 1.,
508 -
        fonts: HashMap::default(),
509 -
        cursors: Cursors::default(),
229 +
        cursors: HashMap::default(),
510 230
        config: Config::default(),
511 -
        backend,
512 231
        window,
513 232
    }
514 233
}
515 234
516 235
impl<R: RenderBackend> InterfaceBuilder<'_, '_, R> {
517 236
    /// Load a font.
518 237
    pub fn font(mut self, desc: FontDescriptor<'_>) -> Result<Self, Error<R>> {
519 -
        let name = desc.name;
520 -
        let font = self._font(desc)?;
521 -
522 -
        self.fonts.insert(name, font);
238 +
        self.canvas = self.canvas.font(desc).map_err(Error::Canvas)?;
523 239
524 240
        Ok(self)
525 241
    }
526 242
527 243
    /// Load a custom cursor image.
528 -
    pub fn cursor(mut self, desc: CursorDescriptor) -> Result<Self, Error<R>> {
529 -
        let scaled = desc.image.scaled(self.scale as u32);
530 -
        let cursor = platform::Cursor::create(
531 -
            scaled.as_u32_slice(),
532 -
            scaled.size,
533 -
            desc.origin * self.scale as u32,
534 -
        );
535 -
        self.cursors.insert(desc.name, cursor);
536 -
537 -
        Ok(self)
244 +
    pub fn cursor(mut self, desc: CursorDescriptor) -> Self {
245 +
        self.cursors.insert(desc.name, desc);
246 +
        self
538 247
    }
539 248
540 249
    /// Set the interface scale.
541 250
    pub fn scale(mut self, scale: f32) -> Self {
542 251
        self.scale = scale;
554 263
        self.debug = debug;
555 264
        self
556 265
    }
557 266
558 267
    /// Build the interface by giving it the root of the widget tree.
559 -
    pub fn build<T, W: Widget<T>>(mut self, root: W) -> Result<Interface<W, T>, Error<R>> {
560 -
        let default = self._font(fonts::uf2::DEFAULT)?;
561 -
        if self.config.max_vertices % 3 != 0 {
562 -
            return Err(Error::Config("`max_vertices` must be divisible by three"));
563 -
        }
564 -
        self._build(root, default).map_err(Error::Render)
565 -
    }
566 -
567 -
    /// Inner build function.
568 -
    fn _build<T, W: Widget<T>>(
569 -
        self,
570 -
        root: W,
571 -
        default: Rc<Font<Image>>,
572 -
    ) -> Result<Interface<W, T>, R::Error> {
573 -
        // TODO: Keep track of the fact these are scaled pixels, not real.
574 -
        let size: Size<f32> = self.window.size().into();
575 -
        // Snap this texture to the correct size!
576 -
        let size = (size / self.scale).map(|s| s.round() as u32);
577 -
        let offscreen_depth = self.backend.texture(gfx::Texture {
578 -
            data: gfx::Empty,
579 -
            access: gfx::TextureAccess::RenderTarget,
580 -
            size,
581 -
            format: gfx::TextureFormat::Depth,
582 -
            ..Default::default()
583 -
        })?;
584 -
        let offscreen_color = self.backend.texture(gfx::Texture {
585 -
            data: gfx::Empty,
586 -
            target: TextureKind::default(),
587 -
            size,
588 -
            access: gfx::TextureAccess::RenderTarget,
589 -
            wrap: gfx::TextureWrap::Clamp,
590 -
            format: gfx::TextureFormat::Rgba8,
591 -
            min_filter: FilterMode::Nearest,
592 -
            mag_filter: FilterMode::Nearest,
593 -
        })?;
594 -
        let offscreen = self.backend.pass(gfx::PassDescriptor {
595 -
            color_attachments: &[offscreen_color],
596 -
            depth_attachment: Some(offscreen_depth),
597 -
        })?;
598 -
599 -
        let layers = self.backend.texture(Texture {
600 -
            data: gfx::Empty,
601 -
            size: Size::new(256, 256),
602 -
            access: TextureAccess::Static,
603 -
            target: TextureKind::Texture2DArray { arity: 16 },
604 -
            format: TextureFormat::Srgba8,
605 -
            wrap: TextureWrap::Repeat,
606 -
            min_filter: FilterMode::Nearest,
607 -
            mag_filter: FilterMode::Nearest,
608 -
        })?;
609 -
        self.backend.texture_update_layer(
610 -
            layers,
611 -
            0,
612 -
            Rect::origin([256, 256]),
613 -
            &[Rgba8::WHITE; 256 * 256],
614 -
        )?;
615 -
        let vbo = self.backend.buffer(
616 -
            gfx::BufferKind::Vertex,
617 -
            gfx::BufferUsage::Stream,
618 -
            gfx::BufferSource::<pipeline::Vertex>::empty(self.config.max_vertices),
619 -
        )?;
620 -
        let shade = Pipeline {
621 -
            pipeline: pipeline::create::<_, DEFAULT_MAX_TEXTURE_LAYERS>(self.backend)?,
622 -
            bindings: gfx::Bindings {
623 -
                vertex: [vbo],
624 -
                index: None,
625 -
                textures: [layers],
626 -
            },
627 -
        };
628 -
        let present = Pipeline {
629 -
            pipeline: present::pipeline(self.backend)?,
630 -
            bindings: gfx::Bindings {
631 -
                vertex: [],
632 -
                index: None,
633 -
                textures: [offscreen_color],
634 -
            },
635 -
        };
636 -
        let layers = TextureInfo {
637 -
            id: layers,
638 -
            size: Size::new(256, 256),
639 -
        };
640 -
        let debug = DebugState {
641 -
            visible: self.debug,
642 -
            render: RenderState::new(layers.clone()),
643 -
            widget: widgets::grid().spacing(self.scale).color(Rgba::BLUE),
644 -
        };
645 -
        let render = RenderState::new(layers);
268 +
    pub fn build<T, W: Widget<T>>(self, root: W) -> Result<Interface<W, T>, Error<R>> {
269 +
        let canvas = self
270 +
            .canvas
271 +
            .scale(self.scale)
272 +
            .config(canvas::Config {
273 +
                max_vertices: self.config.max_vertices,
274 +
            })
275 +
            .build()
276 +
            .map_err(Error::Canvas)?;
646 277
        let window = WindowCtx {
647 278
            title: self.window.get_title().to_owned(),
648 279
            cursor: None,
649 -
            size,
650 -
        };
651 -
        let fonts = Fonts {
652 -
            default,
653 -
            loaded: self.fonts,
654 280
        };
281 +
        let cursors = Cursors::from_iter(self.cursors.into_iter().map(|(name, desc)| {
282 +
            let scaled = desc.image.scaled(self.scale as u32);
283 +
            let cursor = platform::Cursor::create(
284 +
                scaled.as_u32_slice(),
285 +
                scaled.size,
286 +
                desc.origin * self.scale as u32,
287 +
            );
288 +
            (name, cursor)
289 +
        }));
655 290
656 291
        Ok(Interface {
657 292
            root: Pod::new(root),
658 -
            shade,
659 -
            present,
660 -
            offscreen,
661 -
            debug,
293 +
            canvas,
662 294
            cursor: Point2D::ZERO,
663 295
            window,
664 -
            bounds: size.into(),
665 -
            backbuffer: self.window.size().into(),
666 -
            scale: self.scale,
667 -
            render,
668 -
            fonts,
669 -
            config: self.config,
670 -
            cursors: self.cursors,
671 -
            dirty: true,
296 +
            cursors,
297 +
            debug: false,
672 298
            data: PhantomData,
673 299
        })
674 300
    }
675 -
676 -
    fn _font(&mut self, desc: FontDescriptor<'_>) -> Result<Rc<Font<Image>>, Error<R>> {
677 -
        let Font {
678 -
            widths,
679 -
            image,
680 -
            format,
681 -
            metrics,
682 -
        } = desc.decode()?;
683 -
684 -
        eprintln!("font {:?} image:{}", desc.name, image.id());
685 -
686 -
        Ok(Rc::new(Font {
687 -
            widths,
688 -
            image,
689 -
            format,
690 -
            metrics,
691 -
        }))
692 -
    }
693 301
}
ombre/src/ui/test.rs +6 -11
1 1
//! Utilities for testing UIs.
2 2
use std::mem;
3 3
4 -
use crate::ui::fonts::*;
5 -
use crate::ui::gfx::PaintOp;
4 +
use crate::gfx::font::*;
5 +
use crate::paint::PaintOp;
6 6
use crate::ui::math::*;
7 7
use crate::ui::*;
8 8
9 9
/// Test interface environment.
10 10
pub struct TestInterface<T> {
22 22
        let font = dummy::font();
23 23
        let fonts = Fonts::new(font);
24 24
        let ctx = Context::new(Point2D::ZERO, size);
25 25
        let win = WindowCtx {
26 26
            title: String::from("test"),
27 -
            size,
28 27
            cursor: None,
29 28
        };
30 29
        Self {
31 30
            ctx,
32 31
            win,
43 42
    }
44 43
45 44
    /// Clear the recorded paint operations.
46 45
    #[allow(dead_code)]
47 46
    pub fn clear(&mut self) {
48 -
        self.surface.operations.clear();
47 +
        self.surface.ops.push(PaintOp::Clear);
49 48
    }
50 49
51 50
    /// Layout a widget.
52 51
    pub fn layout<W: Widget<T>>(&mut self, widget: &mut W) -> Size<f32> {
53 52
        // TODO: How to make sure this happens in the real interface?
55 54
        self.ctx.size
56 55
    }
57 56
58 57
    /// Paint a widget.
59 58
    pub fn paint<W: Widget<T>>(&mut self, widget: &mut W) {
60 -
        self.surface.operations.clear();
61 -
        widget.paint(
62 -
            &self.data,
63 -
            self.ctx.as_paint(&self.fonts, &mut self.surface.operations),
64 -
        );
59 +
        self.surface.ops.clear();
60 +
        widget.paint(&self.data, self.ctx.as_paint(&mut self.surface.ops));
65 61
    }
66 62
67 63
    /// Send an event to the UI.
68 64
    pub fn event<W: Widget<T>>(&mut self, root: &mut W, event: &WidgetEvent) -> bool {
69 65
        root.event(
111 107
}
112 108
113 109
/// A paint surface for testing that records paint operations.
114 110
#[derive(Default)]
115 111
pub struct TestSurface {
116 -
    pub operations: Vec<PaintOp>,
112 +
    pub ops: Vec<PaintOp>,
117 113
}
118 114
119 115
/// A widget that checks the received parent widget bounds.
120 116
pub struct AssertBounds {
121 117
    pub expected: Size<f32>,
149 145
150 146
    /// Dummy window context.
151 147
    #[allow(dead_code)]
152 148
    pub const WINDOW: WindowCtx = WindowCtx {
153 149
        title: String::new(),
154 -
        size: Size::new(640, 480),
155 150
        cursor: None,
156 151
    };
157 152
158 153
    /// Dummy font that is unusable.
159 154
    pub fn font() -> Font<gfx::Image> {
ombre/src/ui/widgets.rs +1 -1
371 371
    }
372 372
}
373 373
374 374
impl<T> Widget<T> for crate::ui::gfx::Rgba<f32> {
375 375
    fn paint(&mut self, _data: &T, mut ctx: PaintCtx<'_>) {
376 -
        ctx.fill(ctx.rect(), *self, ZDepth::ZERO);
376 +
        ctx.fill(ctx.rect().convert(), *self);
377 377
    }
378 378
379 379
    fn debug(&self) -> DebugInfo {
380 380
        DebugInfo::new("Rgba").extra(crate::ui::gfx::Rgba8::from(*self))
381 381
    }
ombre/src/ui/widgets/canvas.rs +4 -79
1 1
//! [`Canvas`] widget.
2 -
use crate::ui::gfx::Rgba;
3 -
4 2
use super::*;
5 -
use crate::ui::gfx::Blit;
6 -
use crate::ui::{gfx::color::Rgba8, gfx::Image, gfx::PlainText};
7 3
8 4
/// A surface that can be painted on.
5 +
/// Gives direct access to the underlying [`ombre::paint::PaintSurface`].
9 6
pub struct Canvas<T> {
10 -
    func: Box<dyn Fn(&T, Rect<f32, Local>, Painter<'_, T>) + 'static>,
7 +
    func: Box<dyn Fn(&T, Rect<f32, Local>, PaintCtx<'_>) + 'static>,
11 8
}
12 9
13 10
impl<T> Widget<T> for Canvas<T> {
14 11
    fn event(
15 12
        &mut self,
20 17
    ) -> bool {
21 18
        false
22 19
    }
23 20
24 21
    fn paint(&mut self, data: &T, ctx: PaintCtx<'_>) {
25 -
        (self.func)(
26 -
            data,
27 -
            ctx.rect(),
28 -
            Painter {
29 -
                data,
30 -
                fonts: ctx.fonts,
31 -
                ctx,
32 -
                zdepth: ZDepth::default(),
33 -
            },
34 -
        );
22 +
        (self.func)(data, ctx.rect(), ctx);
35 23
    }
36 24
37 25
    fn debug(&self) -> DebugInfo {
38 26
        DebugInfo::new("Canvas")
39 27
    }
40 28
}
41 29
42 30
/// Create a new [`Canvas`] with the provided paint function.
43 31
pub fn canvas<T, F>(func: F) -> Canvas<T>
44 32
where
45 -
    F: Fn(&T, Rect<f32, Local>, Painter<'_, T>) + 'static,
33 +
    F: Fn(&T, Rect<f32, Local>, PaintCtx<'_>) + 'static,
46 34
{
47 35
    Canvas {
48 36
        func: Box::new(func),
49 37
    }
50 38
}
51 -
52 -
/// Passed to the canvas function for painting.
53 -
pub struct Painter<'a, T> {
54 -
    data: &'a T,
55 -
    fonts: &'a Fonts<Image>,
56 -
    ctx: PaintCtx<'a>,
57 -
    zdepth: ZDepth,
58 -
}
59 -
60 -
impl<T> Painter<'_, T> {
61 -
    /// See [`PaintCtx::blit`].
62 -
    pub fn blit(
63 -
        &mut self,
64 -
        image: Image,
65 -
        src: Rect<f32, Screen>,
66 -
        dst: Rect<f32, Local>,
67 -
        tint: Rgba<f32>,
68 -
    ) {
69 -
        self.ctx.blit(image, Blit::new(src, dst).tint(tint));
70 -
    }
71 -
72 -
    /// See [`PaintCtx::fill`].
73 -
    pub fn fill(&mut self, rect: impl Into<Rect<f32, Local>>, color: impl Into<Rgba<f32>>) {
74 -
        self.ctx.fill(rect.into(), color.into(), self.zdepth)
75 -
    }
76 -
77 -
    /// See [`PaintCtx::line`].
78 -
    pub fn line(
79 -
        &mut self,
80 -
        from: impl Into<Point2D<f32, Local>>,
81 -
        to: impl Into<Point2D<f32, Local>>,
82 -
        width: f32,
83 -
        color: impl Into<Rgba<f32>>,
84 -
    ) {
85 -
        self.ctx.line(from.into(), to.into(), width, color.into())
86 -
    }
87 -
88 -
    /// Write text onto the canvas.
89 -
    pub fn write(
90 -
        &mut self,
91 -
        text: impl Into<PlainText<T>>,
92 -
        color: impl Into<Rgba8>,
93 -
        bounds: impl Into<Rect<f32, Local>>,
94 -
    ) {
95 -
        let bounds = bounds.into();
96 -
        let mut text = text.into();
97 -
        let (layout, font) = text.layout(self.data, bounds.size, self.fonts);
98 -
99 -
        for blit in layout.render(font.image.size, color.into()) {
100 -
            self.ctx.blit(font.image.clone(), blit);
101 -
        }
102 -
    }
103 -
104 -
    /// See [`PaintCtx::stroke`].
105 -
    pub fn stroke(
106 -
        &mut self,
107 -
        rect: impl Into<Rect<f32, Local>>,
108 -
        color: impl Into<Rgba<f32>>,
109 -
        width: f32,
110 -
    ) {
111 -
        self.ctx.stroke(rect.into(), color.into(), width)
112 -
    }
113 -
}
ombre/src/ui/widgets/grid.rs +3 -10
11 11
    color: Rgba<f32>,
12 12
    /// Line width.
13 13
    width: f32,
14 14
    /// Line spacing.
15 15
    spacing: f32,
16 +
    /// Type witness.
16 17
    data: PhantomData<T>,
17 18
}
18 19
19 20
impl<T> std::fmt::Debug for Grid<T> {
20 21
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 48
        // The grid lines sit on pixel boundaries.
48 49
        let mut x = -self.width / 2.;
49 50
        let mut y = -self.width / 2.;
50 51
51 52
        while x <= ctx.size.w {
52 -
            ctx.fill(
53 -
                Rect::new([x, 0.], [self.width, ctx.size.h]),
54 -
                self.color,
55 -
                ZDepth::default(),
56 -
            );
53 +
            ctx.fill(Rect::new([x, 0.], [self.width, ctx.size.h]), self.color);
57 54
            x += self.spacing;
58 55
        }
59 56
60 57
        while y <= ctx.size.h {
61 -
            ctx.fill(
62 -
                Rect::new([0., y], [ctx.size.w, self.width]),
63 -
                self.color,
64 -
                ZDepth::default(),
65 -
            );
58 +
            ctx.fill(Rect::new([0., y], [ctx.size.w, self.width]), self.color);
66 59
            y += self.spacing;
67 60
        }
68 61
    }
69 62
70 63
    fn debug(&self) -> DebugInfo {
ombre/src/ui/widgets/hstack.rs +58 -37
176 176
}
177 177
178 178
#[cfg(test)]
179 179
mod tests {
180 180
    use super::*;
181 -
    use crate::ui::gfx::{Color, PaintOp, Rgba8};
181 +
    use crate::paint::{Brush, PaintOp, Shape};
182 +
    use crate::ui::gfx::{Color, Rgba8};
182 183
    use crate::ui::test::TestInterface;
183 184
    use crate::ui::widgets;
184 185
185 186
    #[test]
186 187
    fn test_hstack() {
221 222
        let mut ui = TestInterface::new(size);
222 223
223 224
        ui.layout(&mut widget);
224 225
        ui.paint(&mut widget);
225 226
226 -
        let ops = ui.surface.operations.as_slice();
227 +
        let ops = ui.surface.ops.as_slice();
227 228
        assert_eq!(ops.len(), 3); // One fill operation for each child
228 229
229 230
        if let [PaintOp::Fill {
230 -
            rect: r1,
231 -
            color: c1,
231 +
            shape: Shape::Rectangle(r1),
232 +
            brush: Brush::Color(c1),
233 +
            transform: t1,
232 234
            ..
233 235
        }, PaintOp::Fill {
234 -
            rect: r2,
235 -
            color: c2,
236 +
            shape: Shape::Rectangle(r2),
237 +
            brush: Brush::Color(c2),
238 +
            transform: t2,
236 239
            ..
237 240
        }, PaintOp::Fill {
238 -
            rect: r3,
239 -
            color: c3,
241 +
            shape: Shape::Rectangle(r3),
242 +
            brush: Brush::Color(c3),
243 +
            transform: t3,
240 244
            ..
241 245
        }] = ops
242 246
        {
243 -
            assert_eq!(r1.origin, Point2D::new(0., 0.));
247 +
            assert_eq!(r1.origin, Point2D::ZERO);
248 +
            assert_eq!(t1.translation(), Vector2D::new(0., 0.));
244 249
            assert_eq!(r1.size, Size::new(3., 3.));
245 250
            assert_eq!(c1, &Rgba::RED);
246 251
247 -
            assert_eq!(r2.origin, Point2D::new(4., 0.));
252 +
            assert_eq!(r2.origin, Point2D::ZERO);
248 253
            assert_eq!(r2.size, Size::new(3., 3.));
249 254
            assert_eq!(c2, &Rgba::GREEN);
255 +
            assert_eq!(t2.translation(), Vector2D::new(4., 0.));
250 256
251 -
            assert_eq!(r3.origin, Point2D::new(8., 0.));
257 +
            assert_eq!(r3.origin, Point2D::ZERO);
258 +
            assert_eq!(t3.translation(), Vector2D::new(8., 0.));
252 259
            assert_eq!(r3.size, Size::new(3., 3.));
253 260
            assert_eq!(c3, &Rgba::BLUE);
254 261
        } else {
255 262
            panic!("Unexpected paint operations {ops:#?}");
256 263
        }
271 278
        let layout_size = ui.layout(&mut widget);
272 279
        assert_eq!(layout_size, Size::new(7., 7.)); // Two rows of height 3 with a 1-pixel gap between them
273 280
274 281
        ui.paint(&mut widget);
275 282
276 -
        let ops = ui.surface.operations.as_slice();
283 +
        let ops = ui.surface.ops.as_slice();
277 284
        assert_eq!(ops.len(), 4); // One fill operation for each child
278 285
279 286
        if let [PaintOp::Fill {
280 -
            rect: r1,
281 -
            color: c1,
287 +
            shape: Shape::Rectangle(r1),
288 +
            brush: Brush::Color(c1),
289 +
            transform: t1,
282 290
            ..
283 291
        }, PaintOp::Fill {
284 -
            rect: r2,
285 -
            color: c2,
292 +
            shape: Shape::Rectangle(r2),
293 +
            brush: Brush::Color(c2),
294 +
            transform: t2,
286 295
            ..
287 296
        }, PaintOp::Fill {
288 -
            rect: r3,
289 -
            color: c3,
297 +
            shape: Shape::Rectangle(r3),
298 +
            brush: Brush::Color(c3),
299 +
            transform: t3,
290 300
            ..
291 301
        }, PaintOp::Fill {
292 -
            rect: r4,
293 -
            color: c4,
302 +
            shape: Shape::Rectangle(r4),
303 +
            brush: Brush::Color(c4),
304 +
            transform: t4,
294 305
            ..
295 306
        }] = ops
296 307
        {
297 308
            // First row
298 -
            assert_eq!(r1.origin, Point2D::new(0., 0.));
309 +
            assert_eq!(r1.origin.transform(*t1), Point2D::new(0., 0.));
299 310
            assert_eq!(r1.size, Size::new(3., 3.));
300 311
            assert_eq!(c1, &Rgba::RED);
301 312
302 -
            assert_eq!(r2.origin, Point2D::new(4., 0.)); // 3 + 1 gap
313 +
            assert_eq!(r2.origin.transform(*t2), Point2D::new(4., 0.)); // 3 + 1 gap
303 314
            assert_eq!(r2.size, Size::new(3., 3.));
304 315
            assert_eq!(c2, &Rgba::GREEN);
305 316
306 317
            // Second row (wrapped)
307 -
            assert_eq!(r3.origin, Point2D::new(0., 4.)); // 3 + 1 vertical gap
318 +
            assert_eq!(r3.origin.transform(*t3), Point2D::new(0., 4.)); // 3 + 1 vertical gap
308 319
            assert_eq!(r3.size, Size::new(3., 3.));
309 320
            assert_eq!(c3, &Rgba::BLUE);
310 321
311 -
            assert_eq!(r4.origin, Point2D::new(4., 4.)); // 3 + 1 horizontal gap, 3 + 1 vertical gap
322 +
            assert_eq!(r4.origin.transform(*t4), Point2D::new(4., 4.)); // 3 + 1 horizontal gap, 3 + 1 vertical gap
312 323
            assert_eq!(r4.size, Size::new(3., 3.));
313 324
            assert_eq!(c4, &Rgba::YELLOW);
314 325
        } else {
315 326
            panic!("Unexpected paint operations {ops:#?}");
316 327
        }
326 337
        let mut ui = TestInterface::new(size);
327 338
328 339
        ui.layout(&mut widget);
329 340
        ui.paint(&mut widget);
330 341
331 -
        let ops = ui.surface.operations.as_slice();
342 +
        let ops = ui.surface.ops.as_slice();
332 343
        assert_eq!(ops.len(), 3); // One fill operation for each child
333 344
334 345
        if let [PaintOp::Fill {
335 -
            rect: r1,
336 -
            color: c1,
346 +
            shape: Shape::Rectangle(r1),
347 +
            brush: Brush::Color(c1),
348 +
            transform: t1,
337 349
            ..
338 350
        }, PaintOp::Fill {
339 -
            rect: r2,
340 -
            color: c2,
351 +
            shape: Shape::Rectangle(r2),
352 +
            brush: Brush::Color(c2),
353 +
            transform: t2,
341 354
            ..
342 355
        }, PaintOp::Fill {
343 -
            rect: r3,
344 -
            color: c3,
356 +
            shape: Shape::Rectangle(r3),
357 +
            brush: Brush::Color(c3),
358 +
            transform: t3,
345 359
            ..
346 360
        }] = ops
347 361
        {
348 -
            assert_eq!(r1.origin, Point2D::new(0., 2.));
362 +
            assert_eq!(r1.origin, Point2D::ZERO);
363 +
            assert_eq!(t1.translation(), Vector2D::new(0., 2.));
349 364
            assert_eq!(r1.size, Size::new(2., 2.));
350 365
            assert_eq!(c1, &Rgba::RED);
351 366
352 -
            assert_eq!(r2.origin, Point2D::new(2., 1.));
367 +
            assert_eq!(r2.origin, Point2D::ZERO);
368 +
            assert_eq!(t2.translation(), Vector2D::new(2., 1.));
353 369
            assert_eq!(r2.size, Size::new(3., 4.));
354 370
            assert_eq!(c2, &Rgba::GREEN);
355 371
356 -
            assert_eq!(r3.origin, Point2D::new(5., 0.));
372 +
            assert_eq!(r3.origin, Point2D::ZERO);
373 +
            assert_eq!(t3.translation(), Vector2D::new(5., 0.));
357 374
            assert_eq!(r3.size, Size::new(1., 6.));
358 375
            assert_eq!(c3, &Rgba::BLUE);
359 376
        } else {
360 377
            panic!("Unexpected paint operations {ops:#?}");
361 378
        }
390 407
                "For container {container}, expected {expected}, got {actual}",
391 408
            );
392 409
393 410
            // Ensure no child extends beyond the layout width.
394 411
            ui.paint(&mut widget);
395 -
            for op in &ui.surface.operations {
396 -
                if let PaintOp::Fill { rect, .. } = op {
412 +
            for op in &ui.surface.ops {
413 +
                if let PaintOp::Fill {
414 +
                    shape: Shape::Rectangle(r),
415 +
                    ..
416 +
                } = op
417 +
                {
397 418
                    assert!(
398 -
                        rect.max().x <= expected.w,
419 +
                        r.max().x <= expected.w,
399 420
                        "Child extends beyond container {container}",
400 421
                    );
401 422
                }
402 423
            }
403 424
        }
ombre/src/ui/widgets/image.rs +4 -2
1 1
//! [`Image`] widget.
2 2
use crate::ui::gfx::color::Rgba;
3 -
use crate::ui::gfx::Blit;
4 3
use crate::ui::gfx::Color;
5 4
6 5
use crate::ui::gfx;
7 6
use crate::ui::widgets::*;
8 7
20 19
21 20
impl<T> Widget<T> for Image {
22 21
    fn paint(&mut self, _data: &T, mut ctx: PaintCtx<'_>) {
23 22
        ctx.blit(
24 23
            self.src.clone(),
25 -
            Blit::new(Rect::origin(self.src.size), ctx.rect()).tint(self.tint),
24 +
            Rect::origin(self.src.size),
25 +
            ctx.rect(),
26 +
            self.tint,
27 +
            1.0,
26 28
        );
27 29
    }
28 30
}
29 31
30 32
/// Create a new [`Image`] widget.
ombre/src/ui/widgets/input.rs +4 -18
1 1
//! [`Input`] widget.
2 2
use std::marker::PhantomData;
3 3
4 -
use crate::ui::gfx::{Color as _, Rgba8};
5 -
6 4
use super::*;
7 -
use crate::bail;
8 -
use crate::ui::fonts::{FontName, DEFAULT_FONT};
5 +
use crate::gfx::font::{FontName, DEFAULT_FONT};
9 6
use crate::ui::gfx::text::{PlainText, TextStorage};
7 +
use crate::ui::gfx::Color as _;
10 8
use crate::ui::gfx::TextLayoutOptions;
11 9
use crate::ui::widgets::Label;
12 10
13 11
/// A text input field.
14 12
#[derive(Debug)]
15 13
pub struct Input<T> {
16 14
    text: PlainText<T>,
17 -
    color: Rgba8,
18 15
    cursor: usize,
19 16
    size: Size<f32>,
20 17
    placeholder: Label<String>,
21 18
    padding: Size<f32>,
22 19
    active: bool,
26 23
impl<T: TextStorage> Widget<T> for Input<T> {
27 24
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
28 25
        debug_assert_ne!(ctx.bounds, Size::ZERO);
29 26
30 27
        self.text.layout(data, ctx.bounds - self.padding * 2., ctx.fonts);
31 -
32 28
        self.size = ctx.bounds;
33 29
        self.size
34 30
    }
35 31
36 32
    fn event(
90 86
        self.active
91 87
    }
92 88
93 89
    fn paint(&mut self, _data: &T, ctx: PaintCtx<'_>) {
94 90
        let mut ctx = ctx.inset(self.padding);
95 -
        let Some(font) = self.text.font() else {
96 -
            bail!("Font {:?} was not initialized", self.text.font)
97 -
        };
98 91
        let Some(layout) = &self.text.layout else {
99 92
            log::error!(target: "ui", "Cannot compute character offset: text layout not found");
100 93
            return;
101 94
        };
102 95
        // Text offset.
120 113
121 114
            if let Some(cursor) = position {
122 115
                ctx.fill(
123 116
                    Rect::new([cursor.x, cursor.y], [1., layout.line_height()]),
124 117
                    Rgba::RED,
125 -
                    ZDepth::ZERO,
126 118
                );
127 119
            }
128 120
        }
129 -
        for blit in layout.render(font.image.size, self.color) {
130 -
            ctx.blit(
131 -
                font.image.clone(),
132 -
                blit.transform(Transform2D::translate(offset)),
133 -
            );
134 -
        }
121 +
        ctx.paint(layout);
135 122
    }
136 123
137 124
    fn debug(&self) -> DebugInfo {
138 125
        DebugInfo::new("Input").children([&self.placeholder])
139 126
    }
156 143
/// Create a new [`Input`] with the provided placeholder.
157 144
pub fn input<T>(placeholder: Label<String>) -> Input<T> {
158 145
    let style = TextLayoutOptions::default();
159 146
160 147
    Input {
161 -
        color: Rgba8::WHITE,
162 148
        size: Size::default(),
163 -
        text: PlainText::new(DEFAULT_FONT, style, ""),
149 +
        text: PlainText::new(DEFAULT_FONT, style, Rgba::default(), ""),
164 150
        cursor: 0,
165 151
        active: false,
166 152
        placeholder,
167 153
        witness: PhantomData,
168 154
        padding: Size::default(),
ombre/src/ui/widgets/label.rs +8 -22
1 1
//! [`Label`] widget.
2 -
use crate::ui::gfx::Color;
3 -
4 2
use super::*;
5 3
use crate::bail;
6 -
use crate::ui::{
7 -
    fonts::{FontName, DEFAULT_FONT},
8 -
    gfx::{
9 -
        text::{PlainText, TextAlign, TextLayoutOptions, TextValue},
10 -
        Rgba8,
11 -
    },
12 -
};
4 +
use crate::gfx::font::{FontName, DEFAULT_FONT};
5 +
use crate::ui::gfx::text::{PlainText, TextAlign, TextLayoutOptions, TextValue};
13 6
14 7
/// A text label with wrapping.
15 8
#[derive(Debug)]
16 9
pub struct Label<T> {
17 10
    text: PlainText<T>,
18 -
    tint: Rgba8,
19 11
    size: Size<f32>,
20 12
}
21 13
22 14
impl<T> Widget<T> for Label<T> {
23 15
    fn layout(&mut self, data: &T, ctx: LayoutCtx<'_>) -> Size<f32> {
24 16
        debug_assert_ne!(ctx.bounds, Size::ZERO);
25 17
26 -
        let (layout, _) = self.text.layout(data, ctx.bounds, ctx.fonts);
18 +
        let layout = self.text.layout(data, ctx.bounds, ctx.fonts);
27 19
28 20
        self.size = layout.size;
29 21
        self.size
30 22
    }
31 23
32 24
    fn paint(&mut self, _data: &T, mut ctx: PaintCtx<'_>) {
33 -
        let Some(font) = self.text.font() else {
34 -
            bail!("Font {:?} was not initialized", self.text.font)
35 -
        };
36 25
        let Some(layout) = self.text.layout.as_ref() else {
37 -
            bail!("Widget layout was not run")
26 +
            bail!("Label::paint: widget layout was not run");
38 27
        };
39 -
        for blit in layout.render(font.image.size, self.tint) {
40 -
            ctx.blit(font.image.clone(), blit);
41 -
        }
28 +
        ctx.paint(layout);
42 29
    }
43 30
44 31
    fn debug(&self) -> DebugInfo {
45 32
        DebugInfo::new("Label").size(self.size)
46 33
    }
57 44
        self.text.font = font.into();
58 45
        self
59 46
    }
60 47
61 48
    /// Set the label tint.
62 -
    pub fn tint(mut self, color: impl Into<Rgba8>) -> Self {
63 -
        self.tint = color.into();
49 +
    pub fn tint(mut self, color: impl Into<Rgba<f32>>) -> Self {
50 +
        self.text.color = color.into();
64 51
        self
65 52
    }
66 53
67 54
    /// Set the label text alignment.
68 55
    pub fn align(mut self, align: impl Into<TextAlign>) -> Self {
75 62
pub fn label<T>(text: impl Into<TextValue<T>>) -> Label<T> {
76 63
    let font = DEFAULT_FONT;
77 64
    let text = text.into();
78 65
79 66
    Label {
80 -
        text: PlainText::new(font, TextLayoutOptions::default(), text),
67 +
        text: PlainText::new(font, TextLayoutOptions::default(), Rgba::default(), text),
81 68
        size: Size::default(),
82 -
        tint: Rgba8::WHITE,
83 69
    }
84 70
}
ombre/src/ui/widgets/style.rs +1 -1
120 120
                ..ctx
121 121
            },
122 122
        );
123 123
124 124
        if self.fill != Rgba::TRANSPARENT {
125 -
            ctx.fill(rect, self.fill, ZDepth::ZERO);
125 +
            ctx.fill(rect, self.fill);
126 126
        }
127 127
        if self.stroke != Stroke::NONE {
128 128
            ctx.stroke(rect, self.stroke.color, self.stroke.width);
129 129
        }
130 130
    }
ombre/src/ui/widgets/text.rs +2 -6
1 1
//! [`RichText`] widget.
2 2
use super::{DebugInfo, LayoutCtx, PaintCtx, Size, Widget};
3 3
use crate::bail;
4 -
use crate::ui::gfx::text::{
5 -
    LoadedTextSpan, RichTextLayout, RichTextStorage, TextAlign, TextLayoutOptions,
6 -
};
4 +
use crate::text::{LoadedTextSpan, RichTextLayout, RichTextStorage, TextAlign, TextLayoutOptions};
7 5
use crate::ui::math::Zero;
8 6
9 7
/// A rich text block.
10 8
#[derive(Debug)]
11 9
pub struct RichText {
47 45
48 46
    fn paint(&mut self, _data: &T, mut ctx: PaintCtx<'_>) {
49 47
        let Some(layout) = &self.layout else {
50 48
            bail!("RichText::paint: widget layout was not run!");
51 49
        };
52 -
        for (img, blit) in layout.render() {
53 -
            ctx.blit(img, blit);
54 -
        }
50 +
        ctx.paint(layout);
55 51
    }
56 52
57 53
    fn debug(&self) -> DebugInfo {
58 54
        DebugInfo::new("RichText").size(self.size)
59 55
    }
ombre/src/ui/widgets/vstack.rs +22 -14
132 132
}
133 133
134 134
#[cfg(test)]
135 135
mod tests {
136 136
    use super::*;
137 -
    use crate::ui::gfx::{Color, PaintOp, Rgba8};
137 +
    use crate::paint::{Brush, PaintOp, Shape};
138 +
    use crate::ui::gfx::{Color, Rgba8};
138 139
    use crate::ui::test::TestInterface;
139 140
    use crate::ui::widgets;
140 141
141 142
    #[test]
142 143
    fn test_vstack() {
174 175
        let mut ui = TestInterface::new(size);
175 176
176 177
        ui.layout(&mut widget);
177 178
        ui.paint(&mut widget);
178 179
179 -
        let ops = ui.surface.operations.as_slice();
180 +
        let ops = ui.surface.ops.as_slice();
180 181
        assert_eq!(ops.len(), 3); // One fill operation for each child
181 182
182 183
        if let [PaintOp::Fill {
183 -
            rect: r1,
184 -
            color: c1,
184 +
            shape: Shape::Rectangle(r1),
185 +
            brush: Brush::Color(c1),
186 +
            transform: t1,
185 187
            ..
186 188
        }, PaintOp::Fill {
187 -
            rect: r2,
188 -
            color: c2,
189 +
            shape: Shape::Rectangle(r2),
190 +
            brush: Brush::Color(c2),
191 +
            transform: t2,
189 192
            ..
190 193
        }, PaintOp::Fill {
191 -
            rect: r3,
192 -
            color: c3,
194 +
            shape: Shape::Rectangle(r3),
195 +
            brush: Brush::Color(c3),
196 +
            transform: t3,
193 197
            ..
194 198
        }] = ops
195 199
        {
196 -
            assert_eq!(r1.origin, Point2D::new(0., 0.));
200 +
            assert_eq!(r1.origin.transform(*t1), Point2D::new(0., 0.));
197 201
            assert_eq!(r1.size, Size::new(3., 3.));
198 202
            assert_eq!(c1, &Rgba::RED);
199 203
200 -
            assert_eq!(r2.origin, Point2D::new(0., 4.));
204 +
            assert_eq!(r2.origin.transform(*t2), Point2D::new(0., 4.));
201 205
            assert_eq!(r2.size, Size::new(3., 3.));
202 206
            assert_eq!(c2, &Rgba::GREEN);
203 207
204 -
            assert_eq!(r3.origin, Point2D::new(0., 8.));
208 +
            assert_eq!(r3.origin.transform(*t3), Point2D::new(0., 8.));
205 209
            assert_eq!(r3.size, Size::new(3., 3.));
206 210
            assert_eq!(c3, &Rgba::BLUE);
207 211
        } else {
208 212
            panic!("Unexpected paint operations {ops:#?}");
209 213
        }
235 239
                actual, expected,
236 240
                "For container {container}, expected {expected}, got {actual}",
237 241
            );
238 242
            // Ensure no child extends beyond the layout height.
239 243
            ui.paint(&mut widget);
240 -
            for op in &ui.surface.operations {
241 -
                if let PaintOp::Fill { rect, .. } = op {
244 +
            for op in &ui.surface.ops {
245 +
                if let PaintOp::Fill {
246 +
                    shape: Shape::Rectangle(r),
247 +
                    ..
248 +
                } = op
249 +
                {
242 250
                    assert!(
243 -
                        rect.max().y <= expected.h,
251 +
                        r.max().y <= expected.h,
244 252
                        "Child extends beyond container {container}",
245 253
                    );
246 254
                }
247 255
            }
248 256
        }