grafo 0.16.1

A GPU-accelerated rendering library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
use std::sync::Arc;

use ahash::{HashMap, HashMapExt};

use crate::effect::{self, LoadedEffect};
use crate::shape::{CachedShapeDrawData, DrawShapeCommand};
use crate::texture_manager::TextureManager;
use crate::util::GradientCache;
use crate::vertex::InstanceTransform;

use super::traversal::TraversalScratch;

// TODO: probably some parts of it also can be cached, so we don't need to copy it all the time.
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub(super) enum DrawCommand {
    CachedShape(CachedShapeDrawData),
    ClipRect(ClipRectDrawData),
}

#[derive(Debug)]
pub(super) struct ClipRectDrawData {
    pub(super) rect_bounds: [(f32, f32); 2],
    pub(super) transform: Option<InstanceTransform>,
    pub(super) is_leaf: bool,
    pub(super) clips_children: bool,
}

impl ClipRectDrawData {
    pub(super) fn new(
        rect_bounds: [(f32, f32); 2],
        transform: Option<InstanceTransform>,
        clips_children: bool,
    ) -> Self {
        Self {
            rect_bounds,
            transform,
            clips_children,
            is_leaf: true,
        }
    }
}

impl DrawCommand {
    /// Whether this node is a leaf (has no children in the draw tree).
    /// Starts as `true`; set to `false` when a child is added.
    pub(super) fn is_leaf(&self) -> bool {
        match self {
            DrawCommand::CachedShape(s) => s.is_leaf,
            DrawCommand::ClipRect(clip_rect) => clip_rect.is_leaf,
        }
    }

    pub(super) fn set_not_leaf(&mut self) {
        match self {
            DrawCommand::CachedShape(s) => s.is_leaf = false,
            DrawCommand::ClipRect(clip_rect) => clip_rect.is_leaf = false,
        }
    }

    pub(super) fn is_clip_rect(&self) -> bool {
        matches!(self, DrawCommand::ClipRect(_))
    }
}

impl DrawCommand {
    pub(super) fn transform(&self) -> Option<InstanceTransform> {
        match self {
            DrawCommand::CachedShape(cached_shape) => cached_shape.transform(),
            DrawCommand::ClipRect(clip_rect) => clip_rect.transform,
        }
    }

    pub(super) fn texture_id(&self, layer: usize) -> Option<u64> {
        match self {
            DrawCommand::CachedShape(cached_shape) => cached_shape.texture_id(layer),
            DrawCommand::ClipRect(_) => None,
        }
    }

    pub(super) fn local_bounds(&self) -> [(f32, f32); 2] {
        match self {
            DrawCommand::CachedShape(cached_shape) => cached_shape.local_bounds(),
            DrawCommand::ClipRect(clip_rect) => clip_rect.rect_bounds,
        }
    }

    pub(super) fn instance_color_override(&self) -> Option<[f32; 4]> {
        match self {
            DrawCommand::CachedShape(cached_shape) => cached_shape.instance_color_override(),
            DrawCommand::ClipRect(_) => None,
        }
    }

    pub(super) fn has_gradient_fill(&self) -> bool {
        match self {
            DrawCommand::CachedShape(cached_shape) => cached_shape.has_gradient_fill(),
            DrawCommand::ClipRect(_) => false,
        }
    }

    pub(super) fn gradient_bind_group(&self) -> Option<&std::sync::Arc<wgpu::BindGroup>> {
        match self {
            DrawCommand::CachedShape(cached_shape) => cached_shape.gradient_bind_group(),
            DrawCommand::ClipRect(_) => None,
        }
    }

    pub(super) fn refresh_gradient_bind_group(
        &mut self,
        gradient_cache: &mut GradientCache,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        layout: &wgpu::BindGroupLayout,
        sampler: &wgpu::Sampler,
        layout_epoch: u64,
    ) {
        match self {
            DrawCommand::ClipRect(_) => {}
            DrawCommand::CachedShape(cached_shape) => cached_shape.refresh_gradient_bind_group(
                gradient_cache,
                device,
                queue,
                layout,
                sampler,
                layout_epoch,
            ),
        }
    }

    pub(super) fn clips_children(&self) -> bool {
        match self {
            DrawCommand::CachedShape(cached_shape) => cached_shape.clips_children(),
            DrawCommand::ClipRect(clip_rect) => clip_rect.clips_children,
        }
    }

    pub(super) fn is_rect(&self) -> bool {
        match self {
            DrawCommand::CachedShape(cached_shape) => cached_shape.is_rect(),
            DrawCommand::ClipRect(_) => true,
        }
    }

    pub(super) fn rect_bounds(&self) -> Option<[(f32, f32); 2]> {
        match self {
            DrawCommand::CachedShape(cached_shape) => cached_shape.rect_bounds(),
            DrawCommand::ClipRect(clip_rect) => Some(clip_rect.rect_bounds),
        }
    }

    pub(super) fn clear_frame_state(&mut self) {
        match self {
            DrawCommand::CachedShape(cached_shape) => {
                // Geometry ranges are stable across frames until the draw queue is rebuilt.
                // Clearing them here makes the next frame silently skip the shape.
                cached_shape.stencil_ref = None;
            }
            DrawCommand::ClipRect(_) => {}
        }
    }
}

#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum DrawCommandError {
    #[error("Shape with id {0} doesn't exist in the draw tree.")]
    InvalidShapeId(usize),
    #[error("Shape with id {0} has not been loaded yet")]
    ShapeNotLoaded(u64),
    #[error("Texture layer {0} is invalid; expected 0 or 1.")]
    InvalidTextureLayer(usize),
    #[error("Clip rect node only supports axis-aligned transforms.")]
    UnsupportedClipRectTransform,
    #[error("Clip rect node {0} does not support {1}.")]
    UnsupportedClipRectOperation(usize, &'static str),
}

#[derive(Debug)]
pub(super) enum TraversalEvent {
    Pre(usize),
    Post(usize),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Pipeline {
    None,
    StencilIncrement,
    StencilIncrementGradient,
    StencilDecrement,
    LeafDraw,
    LeafDrawGradient,
}

/// Records which clipping strategy was used by each non-leaf parent during
/// `Pre` traversal so the `Post` path can tear down state without
/// re-evaluating the scissor eligibility check.
#[derive(Clone, Copy)]
pub(super) enum ClipKind {
    /// Parent does not clip children — a dummy stencil entry was pushed.
    NonClipping,
    /// Parent clips children via hardware scissor rect.
    Scissor,
    /// Parent clips children via stencil increment/decrement.
    Stencil,
}

/// Wraps [`Pipeline`] tracking with optional per-frame switch counters.
///
/// When the `render_metrics` feature is enabled the tracker also counts
/// every GPU `set_pipeline` call and every scissor-clip substitution so
/// the numbers can be queried after the frame.
pub(super) struct PipelineTracker {
    pub(super) current: Pipeline,
    #[cfg(feature = "render_metrics")]
    pub(super) counts: super::metrics::PipelineSwitchCounts,
}

impl PipelineTracker {
    pub(super) fn new() -> Self {
        Self {
            current: Pipeline::None,
            #[cfg(feature = "render_metrics")]
            counts: super::metrics::PipelineSwitchCounts::default(),
        }
    }

    /// Record a real GPU pipeline switch (only when the pipeline actually changes).
    pub(super) fn switch_to(&mut self, pipeline: Pipeline) {
        if self.current == pipeline {
            return;
        }
        self.current = pipeline;
        #[cfg(feature = "render_metrics")]
        {
            self.counts.total_switches += 1;
            match pipeline {
                Pipeline::StencilIncrement | Pipeline::StencilIncrementGradient => {
                    self.counts.to_stencil_increment += 1
                }
                Pipeline::StencilDecrement => self.counts.to_stencil_decrement += 1,
                Pipeline::LeafDraw | Pipeline::LeafDrawGradient => self.counts.to_leaf_draw += 1,
                Pipeline::None => self.counts.to_composite += 1,
            }
        }
    }

    /// Record that a scissor clip was used instead of stencil increment/decrement.
    #[cfg(feature = "render_metrics")]
    pub(super) fn record_scissor_clip(&mut self) {
        self.counts.scissor_clips += 1;
    }

    /// Record one draw pass that modifies the stencil buffer.
    #[cfg(feature = "render_metrics")]
    pub(super) fn record_stencil_pass(&mut self) {
        self.counts.stencil_passes += 1;
    }
}

/// Tracks the currently-bound texture bind groups to skip redundant `set_bind_group` calls.
///
/// Each layer stores the texture ID that is currently bound (`Some(id)` for a real texture,
/// `None` for the default white texture). The outer `Option` distinguishes "unknown / first
/// use" (`None`) from a known state (`Some(..)`).
#[derive(Debug, Clone, Copy, Default)]
pub(super) struct BoundTextureState {
    layers: [Option<Option<u64>>; 2],
}

impl BoundTextureState {
    /// Reset both layers to "unknown" — forces the next bind call to actually issue
    /// `set_bind_group`. Call this whenever a pipeline switch resets bind group state.
    pub(super) fn invalidate(&mut self) {
        self.layers = [None, None];
    }

    /// Returns `true` when the given texture id (or `None` for the default) is not
    /// already bound on `layer`, and updates the tracked state.
    pub(super) fn needs_rebind(&mut self, layer: usize, texture_id: Option<u64>) -> bool {
        let current = self.layers[layer];
        if current == Some(texture_id) {
            return false;
        }
        self.layers[layer] = Some(texture_id);
        true
    }

    /// Update the tracked state for `layer` without returning whether a rebind is
    /// needed. Use this when you know the bind group was just set (e.g. after a
    /// pipeline switch that binds default textures).
    pub(super) fn mark_bound(&mut self, layer: usize, texture_id: Option<u64>) {
        self.layers[layer] = Some(texture_id);
    }
}

pub(super) struct Buffers<'a> {
    pub(super) aggregated_vertex_buffer: Option<&'a wgpu::Buffer>,
    pub(super) aggregated_index_buffer: Option<&'a wgpu::Buffer>,
    pub(super) identity_instance_transform_buffer: &'a wgpu::Buffer,
    pub(super) identity_instance_color_buffer: &'a wgpu::Buffer,
    pub(super) identity_instance_metadata_buffer: &'a wgpu::Buffer,
    pub(super) aggregated_instance_transform_buffer: Option<&'a wgpu::Buffer>,
    pub(super) aggregated_instance_color_buffer: Option<&'a wgpu::Buffer>,
    pub(super) aggregated_instance_metadata_buffer: Option<&'a wgpu::Buffer>,
}

pub(super) struct Pipelines<'a> {
    pub(super) and_pipeline: &'a wgpu::RenderPipeline,
    pub(super) and_gradient_pipeline: &'a wgpu::RenderPipeline,
    pub(super) and_bind_group: &'a wgpu::BindGroup,
    pub(super) decrementing_pipeline: &'a wgpu::RenderPipeline,
    pub(super) decrementing_bind_group: &'a wgpu::BindGroup,
    pub(super) leaf_draw_pipeline: &'a wgpu::RenderPipeline,
    pub(super) leaf_draw_gradient_pipeline: &'a wgpu::RenderPipeline,
    pub(super) shape_texture_bind_group_layout_background: &'a wgpu::BindGroupLayout,
    pub(super) shape_texture_bind_group_layout_foreground: &'a wgpu::BindGroupLayout,
    pub(super) default_shape_texture_bind_groups: &'a [Arc<wgpu::BindGroup>; 2],
    pub(super) shape_texture_layout_epoch: u64,
    pub(super) texture_manager: &'a TextureManager,
}

/// Backdrop-specific rendering resources. Only needed when backdrop effects exist.
/// General resources (pipelines, buffers, textures) are passed separately.
pub(super) struct BackdropContext<'a> {
    pub(super) loaded_effects: &'a HashMap<u64, LoadedEffect>,
    pub(super) composite_bgl: &'a wgpu::BindGroupLayout,
    pub(super) effect_sampler: &'a wgpu::Sampler,
    pub(super) gradient_ramp_sampler: &'a wgpu::Sampler,
    pub(super) texture_blit_pipeline: &'a wgpu::RenderPipeline,
    pub(super) stencil_only_pipeline: &'a wgpu::RenderPipeline,
    pub(super) backdrop_color_pipeline: &'a wgpu::RenderPipeline,
    pub(super) backdrop_color_gradient_pipeline: &'a wgpu::RenderPipeline,
    pub(super) device: &'a wgpu::Device,
    pub(super) queue: &'a wgpu::Queue,
    pub(super) config_format: wgpu::TextureFormat,
    pub(super) max_texture_dimension_2d: u32,
    pub(super) backdrop_texture_bind_group_layout: &'a wgpu::BindGroupLayout,
    pub(super) default_backdrop_texture_bind_group: &'a wgpu::BindGroup,
    pub(super) backdrop_gradient_bind_group_layout: &'a wgpu::BindGroupLayout,
}

const MAX_EFFECT_RESULTS_CAPACITY: usize = 4_096;
const MAX_EFFECT_NODE_IDS_CAPACITY: usize = 4_096;
const MAX_TEXTURE_RECYCLE_CAPACITY: usize = 1_024;
const MAX_EFFECT_OUTPUT_TEXTURES_CAPACITY: usize = 2_048;
const MAX_STENCIL_STACK_CAPACITY: usize = 16_384;
const MAX_SKIPPED_STACK_CAPACITY: usize = 16_384;
const MAX_SCISSOR_STACK_CAPACITY: usize = 16_384;
const MAX_READBACK_BYTES_CAPACITY: usize = 64 * 1024 * 1024;

pub(super) struct RendererScratch {
    pub(super) effect_results: HashMap<usize, wgpu::BindGroup>,
    pub(super) effect_node_ids: Vec<(usize, usize)>,
    pub(super) textures_to_recycle: Vec<effect::PooledTexture>,
    pub(super) effect_output_textures: Vec<effect::PooledTexture>,
    pub(super) stencil_stack: Vec<u32>,
    pub(super) skipped_stack: Vec<usize>,
    /// Stack of intersected scissor rects (x, y, width, height) in physical pixels.
    /// Used to replace stencil clipping for axis-aligned rect parents.
    pub(super) scissor_stack: Vec<(u32, u32, u32, u32)>,
    /// Parallel stack to `stencil_stack`: records which clipping strategy each
    /// non-leaf parent used so the `Post` path avoids re-evaluating eligibility.
    pub(super) clip_kind_stack: Vec<ClipKind>,
    pub(super) backdrop_work_textures: Vec<effect::PooledTexture>,
    /// Reused across readback calls; intentionally not cleared on `begin_frame`
    /// because readback may run after render submission and reuse prior capacity.
    pub(super) readback_bytes: Vec<u8>,
    pub(super) traversal_scratch: TraversalScratch,
}

impl RendererScratch {
    pub(super) fn new() -> Self {
        Self {
            effect_results: HashMap::new(),
            effect_node_ids: Vec::new(),
            textures_to_recycle: Vec::new(),
            effect_output_textures: Vec::new(),
            stencil_stack: Vec::new(),
            skipped_stack: Vec::new(),
            scissor_stack: Vec::new(),
            clip_kind_stack: Vec::new(),
            backdrop_work_textures: Vec::new(),
            readback_bytes: Vec::new(),
            traversal_scratch: TraversalScratch::new(),
        }
    }

    pub(super) fn begin_frame(&mut self) {
        self.effect_results.clear();
        self.effect_node_ids.clear();
        self.textures_to_recycle.clear();
        self.effect_output_textures.clear();
        self.stencil_stack.clear();
        self.skipped_stack.clear();
        self.scissor_stack.clear();
        self.clip_kind_stack.clear();
        self.backdrop_work_textures.clear();
        self.traversal_scratch.begin();
        // Keep readback bytes length/capacity untouched to preserve reuse across
        // `render_to_buffer`/`render_to_argb32` calls that are not tied to frame start.
    }

    pub(super) fn trim_to_policy(&mut self) {
        trim_hash_map_if_needed(&mut self.effect_results, MAX_EFFECT_RESULTS_CAPACITY);
        trim_vector_if_needed(&mut self.effect_node_ids, MAX_EFFECT_NODE_IDS_CAPACITY);
        trim_vector_if_needed(&mut self.textures_to_recycle, MAX_TEXTURE_RECYCLE_CAPACITY);
        trim_vector_if_needed(
            &mut self.effect_output_textures,
            MAX_EFFECT_OUTPUT_TEXTURES_CAPACITY,
        );
        trim_vector_if_needed(&mut self.stencil_stack, MAX_STENCIL_STACK_CAPACITY);
        trim_vector_if_needed(&mut self.skipped_stack, MAX_SKIPPED_STACK_CAPACITY);
        trim_vector_if_needed(&mut self.scissor_stack, MAX_SCISSOR_STACK_CAPACITY);
        trim_vector_if_needed(&mut self.clip_kind_stack, MAX_SCISSOR_STACK_CAPACITY);
        trim_vector_if_needed(
            &mut self.backdrop_work_textures,
            MAX_EFFECT_OUTPUT_TEXTURES_CAPACITY,
        );
        if self.readback_bytes.len() > MAX_READBACK_BYTES_CAPACITY {
            self.readback_bytes.truncate(MAX_READBACK_BYTES_CAPACITY);
        }
        trim_vector_if_needed(&mut self.readback_bytes, MAX_READBACK_BYTES_CAPACITY);
        self.traversal_scratch.trim_to_policy();
    }
}

pub(super) fn trim_vector_if_needed<T>(values: &mut Vec<T>, max_capacity: usize) {
    if values.capacity() > max_capacity {
        values.shrink_to(max_capacity);
    }
}

pub(super) fn trim_hash_map_if_needed<K, V>(values: &mut HashMap<K, V>, max_capacity: usize)
where
    K: Eq + std::hash::Hash,
{
    if values.capacity() > max_capacity {
        values.shrink_to(max_capacity);
    }
}

#[derive(Debug, Clone, Copy)]
pub(super) struct BufferSizingDecision {
    pub(super) should_reallocate: bool,
}

pub(super) fn decide_buffer_sizing(
    existing_size: Option<u64>,
    required_size: usize,
) -> BufferSizingDecision {
    let required_size = required_size as u64;
    let should_reallocate = existing_size
        .map(|size| size < required_size)
        .unwrap_or(true);

    BufferSizingDecision { should_reallocate }
}

#[cfg(test)]
mod tests {
    use super::{decide_buffer_sizing, RendererScratch};

    #[test]
    fn decide_buffer_sizing_reallocates_when_missing() {
        let decision = decide_buffer_sizing(None, 128);
        assert!(decision.should_reallocate);
    }

    #[test]
    fn decide_buffer_sizing_reallocates_when_too_small() {
        let decision = decide_buffer_sizing(Some(64), 128);
        assert!(decision.should_reallocate);
    }

    #[test]
    fn decide_buffer_sizing_keeps_buffer_when_large_enough() {
        let decision = decide_buffer_sizing(Some(512), 128);
        assert!(!decision.should_reallocate);
    }

    #[test]
    fn renderer_scratch_begin_frame_clears_lengths() {
        let mut scratch = RendererScratch::new();
        scratch.effect_node_ids.extend([(1, 1), (2, 2)]);
        scratch.readback_bytes.extend([1, 2, 3, 4]);
        scratch.begin_frame();

        assert!(scratch.effect_node_ids.is_empty());
        assert_eq!(scratch.readback_bytes.len(), 4);
    }

    #[test]
    fn renderer_scratch_trims_large_capacities() {
        let mut scratch = RendererScratch::new();
        scratch
            .effect_node_ids
            .resize(super::MAX_EFFECT_NODE_IDS_CAPACITY + 2_048, (0, 0));
        scratch.effect_node_ids.clear();

        scratch.trim_to_policy();
        assert!(scratch.effect_node_ids.capacity() <= super::MAX_EFFECT_NODE_IDS_CAPACITY);
    }

    #[test]
    fn renderer_scratch_trims_readback_bytes_length_before_shrinking() {
        let mut scratch = RendererScratch::new();
        scratch
            .readback_bytes
            .resize(super::MAX_READBACK_BYTES_CAPACITY + 1_024, 0);

        scratch.trim_to_policy();

        assert!(scratch.readback_bytes.len() <= super::MAX_READBACK_BYTES_CAPACITY);
    }
}