Skip to main content

dfui/render/
primitives.rs

1use std::sync::Arc;
2use std::sync::atomic::{AtomicU32, Ordering};
3
4use crate::anim::Lerp;
5
6/// An sRGB color with straight alpha, each channel in 0..=1. Blending
7/// happens in sRGB, as in browsers.
8#[derive(Clone, Copy, Debug, PartialEq, Default)]
9pub struct Color {
10    /// Red.
11    pub r: f32,
12    /// Green.
13    pub g: f32,
14    /// Blue.
15    pub b: f32,
16    /// Opacity: 0 transparent, 1 opaque.
17    pub a: f32,
18}
19
20impl Color {
21    /// Draws nothing.
22    pub const TRANSPARENT: Color = Color {
23        r: 0.0,
24        g: 0.0,
25        b: 0.0,
26        a: 0.0,
27    };
28    /// Opaque white.
29    pub const WHITE: Color = Color {
30        r: 1.0,
31        g: 1.0,
32        b: 1.0,
33        a: 1.0,
34    };
35    /// Opaque black.
36    pub const BLACK: Color = Color {
37        r: 0.0,
38        g: 0.0,
39        b: 0.0,
40        a: 1.0,
41    };
42
43    /// sRGB `0xRRGGBB`.
44    pub const fn hex(rgb: u32) -> Color {
45        Color {
46            r: ((rgb >> 16) & 0xff) as f32 / 255.0,
47            g: ((rgb >> 8) & 0xff) as f32 / 255.0,
48            b: (rgb & 0xff) as f32 / 255.0,
49            a: 1.0,
50        }
51    }
52
53    /// The same color at opacity `a`, replacing the current one.
54    pub const fn alpha(self, a: f32) -> Color {
55        Color { a, ..self }
56    }
57
58    /// `self` at `t` 0, `to` at `t` 1, blended per channel, alpha included.
59    pub fn mix(self, to: Color, t: f32) -> Color {
60        self.lerp(to, t)
61    }
62
63    /// Moves `t` of the way to white, keeping alpha.
64    pub fn lighten(self, t: f32) -> Color {
65        self.mix(Color::WHITE.alpha(self.a), t)
66    }
67
68    /// Moves `t` of the way to black, keeping alpha.
69    pub fn darken(self, t: f32) -> Color {
70        self.mix(Color::BLACK.alpha(self.a), t)
71    }
72
73    pub(super) fn rgba(self) -> [f32; 4] {
74        [self.r, self.g, self.b, self.a]
75    }
76}
77
78/// An axis-aligned box in logical px, y growing downward.
79#[derive(Clone, Copy, Debug, PartialEq, Default)]
80pub struct Rect {
81    /// Left edge.
82    pub x: f32,
83    /// Top edge.
84    pub y: f32,
85    /// Width.
86    pub w: f32,
87    /// Height.
88    pub h: f32,
89}
90
91impl Rect {
92    /// A box with its top-left corner at `x`, `y`.
93    pub const fn new(x: f32, y: f32, w: f32, h: f32) -> Rect {
94        Rect { x, y, w, h }
95    }
96
97    /// Whether the point is inside: left and top edges count, right and bottom don't.
98    pub fn contains(&self, x: f32, y: f32) -> bool {
99        x >= self.x && y >= self.y && x < self.x + self.w && y < self.y + self.h
100    }
101
102    /// The overlap of both boxes; zero-sized where they don't meet.
103    pub fn intersect(&self, o: &Rect) -> Rect {
104        let x = self.x.max(o.x);
105        let y = self.y.max(o.y);
106        let r = (self.x + self.w).min(o.x + o.w);
107        let b = (self.y + self.h).min(o.y + o.h);
108        Rect::new(x, y, (r - x).max(0.0), (b - y).max(0.0))
109    }
110
111    /// The smallest box containing both.
112    pub fn union(&self, o: &Rect) -> Rect {
113        let x = self.x.min(o.x);
114        let y = self.y.min(o.y);
115        let r = (self.x + self.w).max(o.x + o.w);
116        let b = (self.y + self.h).max(o.y + o.h);
117        Rect::new(x, y, r - x, b - y)
118    }
119}
120
121/// A rendered frame: sRGB RGBA8, row-major.
122#[derive(Clone, Debug, PartialEq)]
123pub struct Pixels {
124    /// Width in pixels.
125    pub width: u32,
126    /// Height in pixels.
127    pub height: u32,
128    /// Four bytes per pixel, `width * height` pixels.
129    pub rgba: Vec<u8>,
130}
131
132#[cfg(test)]
133impl Pixels {
134    pub(super) fn pixel(&self, x: u32, y: u32) -> [u8; 4] {
135        let i = ((y * self.width + x) * 4) as usize;
136        self.rgba[i..i + 4].try_into().unwrap()
137    }
138}
139
140/// Immutable RGBA8 pixels, cheap to clone and safe to build on any thread.
141/// Decoding is up to the app; the GPU copy lives until the last clone drops.
142#[derive(Clone)]
143pub struct Bitmap(pub(super) Arc<BitmapData>);
144
145pub(super) struct BitmapData {
146    pub(super) id: u32,
147    pub(super) width: u32,
148    pub(super) height: u32,
149    /// Premultiplied sRGB; empty for a `texture`.
150    pub(super) rgba: Box<[u8]>,
151    pub(super) texture: Option<View>,
152}
153
154/// Keeps the compiler from re-deriving `Send`/`Sync` through wgpu's internals,
155/// which overflows its recursion limit in every crate that checks a `Bitmap`.
156pub(super) struct View(pub(super) wgpu::TextureView);
157
158// SAFETY: wgpu's handles are Send + Sync except on wasm with atomics.
159#[cfg(not(all(target_arch = "wasm32", target_feature = "atomics")))]
160unsafe impl Send for View {}
161#[cfg(not(all(target_arch = "wasm32", target_feature = "atomics")))]
162unsafe impl Sync for View {}
163
164static NEXT_BITMAP: AtomicU32 = AtomicU32::new(1);
165
166impl Bitmap {
167    /// Straight-alpha sRGB RGBA8, row-major, as image decoders produce it.
168    pub fn from_rgba8(width: u32, height: u32, mut rgba: Vec<u8>) -> Bitmap {
169        assert_eq!(
170            rgba.len() as u64,
171            width as u64 * height as u64 * 4,
172            "rgba size"
173        );
174        for p in rgba.as_chunks_mut::<4>().0 {
175            let a = p[3] as u32;
176            for c in &mut p[..3] {
177                *c = ((*c as u32 * a + 127) / 255) as u8;
178            }
179        }
180        Bitmap(Arc::new(BitmapData {
181            id: NEXT_BITMAP.fetch_add(1, Ordering::Relaxed),
182            width,
183            height,
184            rgba: rgba.into(),
185            texture: None,
186        }))
187    }
188
189    /// Draws `texture`, which the app keeps drawing into: an `Rgba8Unorm` or
190    /// `Rgba16Float` texture with `TEXTURE_BINDING` usage on
191    /// [`gpu()`](crate::gpu)'s device, holding premultiplied sRGB. In
192    /// `Rgba16Float`, values above 1.0 are brighter than SDR white and show so
193    /// when [`hdr()`](crate::hdr) is on, and values below 0 are colors outside
194    /// sRGB's gamut. Each call is a new bitmap, so a frame that shows new
195    /// contents needs a new one.
196    pub fn from_texture(texture: &wgpu::Texture) -> Bitmap {
197        assert!(
198            matches!(
199                texture.format(),
200                wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Rgba16Float
201            ),
202            "texture format {:?}",
203            texture.format()
204        );
205        Bitmap(Arc::new(BitmapData {
206            id: NEXT_BITMAP.fetch_add(1, Ordering::Relaxed),
207            width: texture.width(),
208            height: texture.height(),
209            rgba: Box::default(),
210            texture: Some(View(texture.create_view(&Default::default()))),
211        }))
212    }
213
214    /// Width in pixels.
215    pub fn width(&self) -> u32 {
216        self.0.width
217    }
218
219    /// Height in pixels.
220    pub fn height(&self) -> u32 {
221        self.0.height
222    }
223}
224
225/// A soft shadow: the shape's box moved by `offset`, its edge faded over `blur`.
226#[derive(Clone, Copy, Debug, Default)]
227pub struct Shadow {
228    /// Color at the shadow's darkest, inside the box.
229    pub color: Color,
230    /// Shift from the shape, logical px; positive is right and down.
231    pub offset: (f32, f32),
232    /// Logical px over which the edge fades, on each side of it.
233    pub blur: f32,
234}
235
236#[cfg(test)]
237mod tests {
238    use super::Bitmap;
239
240    #[test]
241    #[should_panic(expected = "rgba size")]
242    fn bitmap_size_check_does_not_overflow() {
243        Bitmap::from_rgba8(65536, 65536, Vec::new());
244    }
245}