Skip to main content

rouge_render/
scene.rs

1use crate::atlas::AtlasRect;
2use crate::image::{ImageData, ImageFormat};
3use crate::{Color, Corners, Edges, Point, Rect, Size};
4use bytemuck::{Pod, Zeroable, cast_slice};
5use slotmap::{SlotMap, new_key_type};
6use std::ops::Range;
7use std::sync::Arc;
8use std::sync::atomic::{AtomicU64, Ordering};
9use wgpu::{VertexAttribute, vertex_attr_array};
10
11const REMOVED_LOG: usize = 4096;
12static NEXT_LIST: AtomicU64 = AtomicU64::new(1);
13
14new_key_type! {
15    pub struct ListKey;
16}
17
18pub struct DrawLists {
19    id: u64,
20    lists: SlotMap<ListKey, DrawList>,
21    removed: Vec<u64>,
22    forgotten: u64,
23}
24
25impl Default for DrawLists {
26    fn default() -> Self {
27        DrawLists {
28            id: NEXT_LIST.fetch_add(1, Ordering::Relaxed),
29            lists: SlotMap::default(),
30            removed: Vec::new(),
31            forgotten: 0,
32        }
33    }
34}
35
36impl DrawLists {
37    pub fn new() -> Self {
38        Self::default()
39    }
40
41    pub fn insert(&mut self, list: DrawList) -> ListKey {
42        self.lists.insert(list)
43    }
44
45    pub fn get(&self, key: ListKey) -> Option<&DrawList> {
46        self.lists.get(key)
47    }
48
49    pub fn get_mut(&mut self, key: ListKey) -> Option<&mut DrawList> {
50        self.lists.get_mut(key)
51    }
52
53    pub fn remove(&mut self, key: ListKey) -> Option<DrawList> {
54        let list = self.lists.remove(key)?;
55        if self.removed.len() == REMOVED_LOG {
56            self.forgotten += REMOVED_LOG as u64;
57            self.removed.clear();
58        }
59        self.removed.push(list.id);
60        Some(list)
61    }
62
63    pub(crate) fn id(&self) -> u64 {
64        self.id
65    }
66
67    pub(crate) fn removed_since(&self, seen: u64) -> (&[u64], u64) {
68        let known = seen.saturating_sub(self.forgotten) as usize;
69        let removed = self.removed.get(known..).unwrap_or_default();
70        (removed, self.forgotten + self.removed.len() as u64)
71    }
72}
73
74#[derive(Clone, Copy, Debug, PartialEq)]
75pub struct Quad {
76    pub bounds: Rect,
77    pub clip: Rect,
78    pub background: Color,
79    pub border_color: Color,
80    pub corner_radii: Corners,
81    pub border_widths: Edges,
82    pub backing: bool,
83}
84
85impl Quad {
86    pub const fn new(bounds: Rect, background: Color) -> Self {
87        Quad {
88            bounds,
89            clip: Rect::EVERYTHING,
90            background,
91            border_color: Color::TRANSPARENT,
92            corner_radii: Corners::ZERO,
93            border_widths: Edges::ZERO,
94            backing: false,
95        }
96    }
97
98    pub const fn backing(bounds: Rect) -> Self {
99        Quad {
100            backing: true,
101            ..Quad::new(bounds, Color::TRANSPARENT)
102        }
103    }
104
105    pub fn line(bounds: Rect, color: Color) -> Self {
106        let Size { width, height } = bounds.size;
107        let border_widths = if height <= width {
108            Edges {
109                top: height,
110                ..Edges::ZERO
111            }
112        } else {
113            Edges {
114                left: width,
115                ..Edges::ZERO
116            }
117        };
118        Quad {
119            border_color: color,
120            border_widths,
121            ..Quad::new(bounds, Color::TRANSPARENT)
122        }
123    }
124}
125
126#[derive(Clone, Copy, Debug, PartialEq)]
127pub struct Shadow {
128    pub bounds: Rect,
129    pub clip: Rect,
130    pub corner_radii: Corners,
131    pub color: Color,
132    pub blur_radius: f32,
133    pub backing: bool,
134}
135
136impl Shadow {
137    pub const fn new(bounds: Rect, color: Color, blur_radius: f32) -> Self {
138        Shadow {
139            bounds,
140            clip: Rect::EVERYTHING,
141            corner_radii: Corners::ZERO,
142            color,
143            blur_radius,
144            backing: false,
145        }
146    }
147}
148
149#[derive(Clone, Copy, Debug, PartialEq)]
150pub struct Glyph {
151    pub origin: Point,
152    pub clip: Rect,
153    pub color: Color,
154    pub mask: AtlasRect,
155}
156
157#[derive(Clone, Debug, PartialEq)]
158pub struct ImageQuad {
159    pub bounds: Rect,
160    pub clip: Rect,
161    pub corner_radii: Corners,
162    pub source: Rect,
163    pub tint: Color,
164    pub image: ImageData,
165}
166
167impl ImageQuad {
168    pub const fn new(bounds: Rect, image: ImageData) -> Self {
169        ImageQuad {
170            bounds,
171            clip: Rect::EVERYTHING,
172            corner_radii: Corners::ZERO,
173            source: Rect::new(0.0, 0.0, 1.0, 1.0),
174            tint: Color::WHITE,
175            image,
176        }
177    }
178}
179
180#[derive(Clone, PartialEq)]
181pub(crate) struct Batch {
182    pub image: Option<ImageData>,
183    pub instances: Range<u32>,
184}
185
186const SHADOW: u32 = 1;
187const GLYPH: u32 = 2;
188const IMAGE: u32 = 3;
189const LAYER_FILL: u32 = 4;
190const LAYER_RADII: u32 = 8;
191const ALPHA_MASK: u32 = 16;
192
193#[repr(C)]
194#[derive(Clone, Copy, Default, Pod, Zeroable)]
195pub(crate) struct Instance {
196    bounds: [f32; 4],
197    clip: [f32; 4],
198    radii: [f32; 4],
199    params: [f32; 4],
200    color: [u16; 4],
201    border_color: [u16; 4],
202    flags: u32,
203}
204
205impl Instance {
206    pub(crate) const ATTRIBUTES: [VertexAttribute; 7] = vertex_attr_array![
207        0 => Float32x4,
208        1 => Float32x4,
209        2 => Float32x4,
210        3 => Float32x4,
211        4 => Unorm16x4,
212        5 => Unorm16x4,
213        6 => Uint32,
214    ];
215    pub(crate) const SIZE: u64 = size_of::<Instance>() as u64;
216}
217
218fn unorm(color: Color) -> [u16; 4] {
219    color
220        .to_array()
221        .map(|channel| (channel.clamp(0.0, 1.0) * f32::from(u16::MAX)).round() as u16)
222}
223
224#[derive(Clone, Default)]
225struct Geometry {
226    instances: Vec<Instance>,
227    batches: Vec<Batch>,
228}
229
230pub struct DrawList {
231    id: u64,
232    geometry: Arc<Geometry>,
233    extent: Option<Rect>,
234    revision: u64,
235}
236
237impl Default for DrawList {
238    fn default() -> Self {
239        DrawList {
240            id: NEXT_LIST.fetch_add(1, Ordering::Relaxed),
241            geometry: Arc::default(),
242            extent: None,
243            revision: 0,
244        }
245    }
246}
247
248impl Clone for DrawList {
249    fn clone(&self) -> Self {
250        Self {
251            id: NEXT_LIST.fetch_add(1, Ordering::Relaxed),
252            geometry: self.geometry.clone(),
253            extent: self.extent,
254            revision: self.revision,
255        }
256    }
257}
258
259impl DrawList {
260    pub fn new() -> Self {
261        Self::default()
262    }
263
264    pub fn clear(&mut self) {
265        if let Some(geometry) = Arc::get_mut(&mut self.geometry) {
266            geometry.instances.clear();
267            geometry.batches.clear();
268        } else {
269            self.geometry = Arc::default();
270        }
271        self.extent = None;
272        self.revision += 1;
273    }
274
275    pub fn replace(&mut self, other: DrawList) {
276        if !Arc::ptr_eq(&self.geometry, &other.geometry) {
277            if self.extent != other.extent
278                || self.batches() != other.batches()
279                || cast_slice::<Instance, u8>(self.instances())
280                    != cast_slice::<Instance, u8>(other.instances())
281            {
282                self.revision += 1;
283            }
284            self.geometry = other.geometry;
285            self.extent = other.extent;
286        }
287    }
288
289    pub(crate) fn id(&self) -> u64 {
290        self.id
291    }
292
293    pub fn extent(&self) -> Option<Rect> {
294        self.extent
295    }
296
297    pub fn revision(&self) -> u64 {
298        self.revision
299    }
300
301    pub fn is_empty(&self) -> bool {
302        self.geometry.instances.is_empty()
303    }
304
305    pub fn len(&self) -> usize {
306        self.geometry.instances.len()
307    }
308
309    pub fn append(&mut self, other: &DrawList, offset: Point) {
310        let Some(extent) = other.extent else {
311            return;
312        };
313        let everything = Rect::EVERYTHING.to_array();
314        let geometry = Arc::make_mut(&mut self.geometry);
315        let base = geometry.instances.len() as u32;
316        if offset == Point::ZERO {
317            geometry.instances.extend_from_slice(other.instances());
318        } else {
319            let moved = other.instances().iter().map(|instance| {
320                let mut instance = *instance;
321                instance.bounds[0] += offset.x;
322                instance.bounds[1] += offset.y;
323                if instance.clip != everything {
324                    instance.clip[0] += offset.x;
325                    instance.clip[1] += offset.y;
326                }
327                instance
328            });
329            geometry.instances.extend(moved);
330        }
331        for batch in other.batches() {
332            let instances = base + batch.instances.start..base + batch.instances.end;
333            match geometry
334                .batches
335                .last_mut()
336                .filter(|last| last.image == batch.image)
337            {
338                Some(last) => last.instances.end = instances.end,
339                None => geometry.batches.push(Batch {
340                    image: batch.image.clone(),
341                    instances,
342                }),
343            }
344        }
345        let extent = extent.translate(offset);
346        self.extent = Some(self.extent.map_or(extent, |known| known.union(&extent)));
347        self.revision += 1;
348    }
349
350    pub fn push_quad(&mut self, quad: Quad) {
351        if quad.bounds.is_empty() || quad.clip.intersect(&quad.bounds).is_empty() {
352            return;
353        }
354        let backing = if quad.backing {
355            LAYER_FILL | LAYER_RADII
356        } else {
357            0
358        };
359        self.push(
360            None,
361            quad.bounds.inflate(1.0).intersect(&quad.clip),
362            Instance {
363                bounds: quad.bounds.to_array(),
364                clip: quad.clip.to_array(),
365                radii: quad.corner_radii.to_array(),
366                params: quad.border_widths.to_array(),
367                color: unorm(quad.background),
368                border_color: unorm(quad.border_color),
369                flags: backing,
370            },
371        );
372    }
373
374    pub fn push_shadow(&mut self, shadow: Shadow) {
375        if shadow.color.a <= 0.0 {
376            return;
377        }
378        let reach = shadow.blur_radius.max(0.0) * 1.5 + 2.0;
379        self.push(
380            None,
381            shadow.bounds.inflate(reach).intersect(&shadow.clip),
382            Instance {
383                bounds: shadow.bounds.to_array(),
384                clip: shadow.clip.to_array(),
385                radii: shadow.corner_radii.to_array(),
386                params: [shadow.blur_radius.max(0.0) * 0.5, 0.0, 0.0, 0.0],
387                color: unorm(shadow.color),
388                flags: SHADOW | if shadow.backing { LAYER_RADII } else { 0 },
389                ..Default::default()
390            },
391        );
392    }
393
394    pub fn push_glyph(&mut self, glyph: Glyph) {
395        if glyph.color.a <= 0.0 {
396            return;
397        }
398        let mask = glyph.mask;
399        let reach = Rect {
400            origin: glyph.origin,
401            size: Size::new(mask.width as f32, mask.height as f32),
402        };
403        self.push(
404            None,
405            reach.inflate(1.0).intersect(&glyph.clip),
406            Instance {
407                bounds: [glyph.origin.x, glyph.origin.y, 0.0, 0.0],
408                clip: glyph.clip.to_array(),
409                params: [
410                    mask.x as f32,
411                    mask.y as f32,
412                    mask.width as f32,
413                    mask.height as f32,
414                ],
415                color: unorm(glyph.color),
416                flags: GLYPH,
417                ..Default::default()
418            },
419        );
420    }
421
422    pub fn push_image(&mut self, image: ImageQuad) {
423        let ImageQuad {
424            bounds,
425            clip,
426            corner_radii,
427            source,
428            tint,
429            image,
430        } = image;
431        if bounds.is_empty() || clip.intersect(&bounds).is_empty() || tint.a <= 0.0 {
432            return;
433        }
434        let mask = if image.format() == ImageFormat::Alpha8 {
435            ALPHA_MASK
436        } else {
437            0
438        };
439        self.push(
440            Some(image),
441            bounds.inflate(1.0).intersect(&clip),
442            Instance {
443                bounds: bounds.to_array(),
444                clip: clip.to_array(),
445                radii: corner_radii.to_array(),
446                params: source.to_array(),
447                color: unorm(tint),
448                flags: IMAGE | mask,
449                ..Default::default()
450            },
451        );
452    }
453
454    fn push(&mut self, image: Option<ImageData>, reach: Rect, instance: Instance) {
455        let geometry = Arc::make_mut(&mut self.geometry);
456        let index = geometry.instances.len() as u32;
457        match geometry
458            .batches
459            .last_mut()
460            .filter(|batch| batch.image == image)
461        {
462            Some(batch) => batch.instances.end = index + 1,
463            None => geometry.batches.push(Batch {
464                image,
465                instances: index..index + 1,
466            }),
467        }
468        geometry.instances.push(instance);
469        self.extent = Some(self.extent.map_or(reach, |extent| extent.union(&reach)));
470        self.revision += 1;
471    }
472
473    pub(crate) fn instances(&self) -> &[Instance] {
474        &self.geometry.instances
475    }
476
477    pub(crate) fn batches(&self) -> &[Batch] {
478        &self.geometry.batches
479    }
480}