incular-rendering 0.1.1

Renderer-neutral scene, canvas, display-list, and compositor APIs for Incular
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
use crate::compositor::LayerId;
use crate::effects::{BlendMode, ColorFilter, DropShadowEffect, GaussianBlur};
use crate::geometry::RRect;
use crate::glyphs::GlyphRun;
use crate::gradients::Brush;
use crate::paint::{Border, FillRule, Paint, PaintStyle, Stroke};
use crate::paths::Path;
use incular_core::{Color, Rect, Size, Transform};
use incular_image::ImageHandle;
use std::sync::{
    Arc,
    atomic::{AtomicU64, Ordering},
};

/// Flutter's `BackdropKey`: backdrop filters sharing a key in one frame
/// sample the backdrop once, as it is when the first of them is reached,
/// instead of each sampling what the filters before it drew. A backend may
/// reuse that one capture for all of them.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct BackdropKey(u64);

impl BackdropKey {
    /// A key no other call returns.
    #[must_use]
    pub fn new() -> Self {
        static NEXT: AtomicU64 = AtomicU64::new(1);
        Self(NEXT.fetch_add(1, Ordering::Relaxed))
    }
}

impl Default for BackdropKey {
    fn default() -> Self {
        Self::new()
    }
}

/// Renderer-neutral identity for a detachable composition subtree.
///
/// The retained widget layer maps its generational transient-surface identity
/// onto this value. Renderers treat partition markers as no-ops unless a host
/// explicitly detaches the marked commands for presentation on another
/// surface.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SurfacePartitionId {
    index: u32,
    generation: u32,
}

impl SurfacePartitionId {
    #[must_use]
    pub const fn from_parts(index: u32, generation: u32) -> Self {
        Self { index, generation }
    }

    #[must_use]
    pub const fn index(self) -> u32 {
        self.index
    }

    #[must_use]
    pub const fn generation(self) -> u32 {
        self.generation
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum PaintCommand {
    /// Begins a retained subtree that may be detached to another presentation
    /// surface. The marker itself has no visual effect.
    PushSurfacePartition {
        id: SurfacePartitionId,
    },
    /// Ends the most recent surface partition.
    PopSurfacePartition,
    Rect {
        rect: Rect,
        color: Color,
    },
    RRect {
        rrect: RRect,
        brush: Brush,
    },
    Border {
        rrect: RRect,
        border: Border,
    },
    FillPath {
        path: Arc<Path>,
        brush: Brush,
        fill_rule: FillRule,
    },
    StrokePath {
        path: Arc<Path>,
        brush: Brush,
        stroke: Stroke,
    },
    /// Source is image pixels; destination is local logical geometry.
    Image {
        image: ImageHandle,
        source: Rect,
        destination: Rect,
        sampling: ImageSampling,
    },
    GlyphRun {
        run: Arc<GlyphRun>,
        color: Color,
    },
    PushClip {
        rect: Rect,
    },
    PushClipRRect {
        rrect: RRect,
    },
    PushClipOval {
        rect: Rect,
    },
    PushClipPath {
        path: Arc<Path>,
        fill_rule: FillRule,
    },
    PopClip,
    PushTransform {
        transform: Transform,
    },
    PopTransform,
    /// Begins an isolated retained opacity group. The compositor renders the
    /// enclosed commands into a transparent target and applies `alpha` once
    /// when that target is composited back into its parent.
    PushOpacity {
        layer: LayerId,
        alpha: f32,
        generation: u64,
        bounds: Rect,
    },
    PopOpacity,
    /// Begins an isolated Gaussian-filtered subtree. The generation and
    /// bounds describe source pixels only; sigma is a compositor property.
    PushBlur {
        layer: LayerId,
        blur: GaussianBlur,
        generation: u64,
        bounds: Rect,
    },
    /// Begins an isolated arbitrary-subtree drop shadow. The child source is
    /// emitted once and the compositor draws the blurred alpha behind it.
    PushDropShadow {
        layer: LayerId,
        shadow: DropShadowEffect,
        generation: u64,
        bounds: Rect,
    },
    /// Begins an isolated straight-RGBA color-matrix stage.
    PushColorFilter {
        layer: LayerId,
        filter: ColorFilter,
        generation: u64,
        bounds: Rect,
    },
    /// Begins an isolated blend group. The source is emitted once and the
    /// compositor combines it with the destination in painter order.
    PushBlend {
        layer: LayerId,
        mode: BlendMode,
        generation: u64,
        bounds: Rect,
    },
    /// Begins an isolated shader-mask stage. The shader is evaluated in the
    /// mask's logical coordinate space and blended over the child source.
    PushShaderMask {
        layer: LayerId,
        shader: Brush,
        blend_mode: BlendMode,
        mask_size: Size,
        mask_transform: Transform,
        generation: u64,
        bounds: Rect,
    },
    /// Begins a backdrop stage. The backend samples the already painted
    /// destination in `bounds`, filters it, and then composites the filtered
    /// pixels before the child source is painted.
    PushBackdropFilter {
        layer: LayerId,
        blur: GaussianBlur,
        blend_mode: BlendMode,
        enabled: bool,
        /// Flutter's `ImageFilter.matrix`: when set, the backdrop is
        /// transformed by it, in the stage's coordinates, instead of blurred.
        matrix: Option<Transform>,
        /// The backdrop this stage shares with others, if any.
        backdrop_key: Option<BackdropKey>,
        generation: u64,
        bounds: Rect,
    },
    PopEffect,
}
/// Renderer-neutral raster filtering policy. Ordinary UI images default to
/// linear sampling; pixel art can opt into nearest-neighbour sampling.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ImageSampling {
    #[default]
    Linear,
    Nearest,
}
/// Recorded paint commands. Cloning is a reference-count bump; the command
/// buffer is copied only when a shared list is mutated.
#[derive(Clone, Default)]
pub struct DisplayList {
    commands: Option<std::sync::Arc<Vec<PaintCommand>>>,
}
impl PartialEq for DisplayList {
    fn eq(&self, other: &Self) -> bool {
        self.commands() == other.commands()
    }
}
impl std::fmt::Debug for DisplayList {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DisplayList")
            .field("commands", &self.commands())
            .finish()
    }
}
impl DisplayList {
    #[must_use]
    pub const fn new() -> Self {
        Self { commands: None }
    }
    fn commands_mut(&mut self) -> &mut Vec<PaintCommand> {
        std::sync::Arc::make_mut(
            self.commands
                .get_or_insert_with(|| std::sync::Arc::new(Vec::new())),
        )
    }
    /// Independent copy that shares no storage with `self`.
    pub(crate) fn deep_copy(&self) -> Self {
        Self {
            commands: Some(std::sync::Arc::new(self.commands().to_vec())),
        }
    }
    pub fn push(&mut self, command: PaintCommand) {
        let commands = self.commands_mut();
        if commands.len() == commands.capacity() {
            // Retained pictures usually hold one or two commands. Doubling
            // from one slot avoids Vec's four-command (576-byte) minimum.
            commands.reserve_exact(commands.len().max(1));
        }
        commands.push(command);
    }
    pub fn extend_from(&mut self, other: &Self) {
        if other.is_empty() {
            return;
        }
        self.commands_mut().extend(other.commands().iter().cloned());
    }

    /// Splits selected retained surface partitions out of this display list.
    ///
    /// Commands inside an active selected partition are omitted from `parent`
    /// and returned under that partition's stable identity. Nested selected
    /// partitions are assigned to the deepest selected surface, so a submenu
    /// can be detached independently from its owning menu. Partition markers
    /// never reach either output.
    #[must_use]
    pub fn detach_surface_partitions(
        &self,
        selected: &std::collections::HashSet<SurfacePartitionId>,
    ) -> (Self, std::collections::HashMap<SurfacePartitionId, Self>) {
        let mut parent = Self::new();
        let mut detached = std::collections::HashMap::<SurfacePartitionId, Self>::new();
        let mut stack = Vec::<SurfacePartitionId>::new();
        for command in self.commands() {
            match command {
                PaintCommand::PushSurfacePartition { id } => stack.push(*id),
                PaintCommand::PopSurfacePartition => {
                    let _ = stack.pop();
                }
                command => {
                    let target = stack.iter().rev().copied().find(|id| selected.contains(id));
                    if let Some(id) = target {
                        detached.entry(id).or_default().push(command.clone());
                    } else {
                        parent.push(command.clone());
                    }
                }
            }
        }
        (parent, detached)
    }

    /// Wraps this list in one logical translation without mutating retained
    /// command geometry.
    #[must_use]
    pub fn translated(&self, offset: incular_core::Offset) -> Self {
        if self.is_empty() || offset == incular_core::Offset::ZERO {
            return self.clone();
        }
        let mut output = Self::new();
        output.push(PaintCommand::PushTransform {
            transform: Transform::translation(offset),
        });
        output.extend_from(self);
        output.push(PaintCommand::PopTransform);
        output
    }

    /// Conservatively proves that the first visual operation covers the entire
    /// target with an opaque axis-aligned rectangle.
    ///
    /// This is intentionally stricter than a general coverage analysis. A
    /// backend may use it before presenting through an opaque native surface;
    /// returning `false` means "not proven" and must never be interpreted as
    /// transparency being unnecessary.
    #[must_use]
    pub fn begins_with_opaque_surface_rect(&self, surface_size: Size) -> bool {
        if !surface_size.width.is_finite()
            || !surface_size.height.is_finite()
            || surface_size.width <= 0.0
            || surface_size.height <= 0.0
        {
            return false;
        }
        let mut transforms = vec![Transform::IDENTITY];
        for command in self.commands() {
            match command {
                PaintCommand::PushTransform { transform } => {
                    let next = transforms
                        .last()
                        .copied()
                        .expect("root transform")
                        .then(*transform);
                    if !next.is_translation() {
                        return false;
                    }
                    transforms.push(next);
                }
                PaintCommand::PopTransform => {
                    if transforms.len() <= 1 {
                        return false;
                    }
                    transforms.pop();
                }
                PaintCommand::PushSurfacePartition { .. } | PaintCommand::PopSurfacePartition => {}
                PaintCommand::Rect { rect, color } => {
                    if color.alpha != u8::MAX {
                        return false;
                    }
                    let world = transforms
                        .last()
                        .expect("root transform")
                        .transform_rect_bbox(*rect);
                    const EPSILON: f32 = 0.01;
                    return world.origin.x <= EPSILON
                        && world.origin.y <= EPSILON
                        && world.origin.x + world.size.width >= surface_size.width - EPSILON
                        && world.origin.y + world.size.height >= surface_size.height - EPSILON;
                }
                // Any clip, effect, or visual primitive before a full opaque
                // rectangle makes complete pixel coverage impossible to prove
                // with this intentionally cheap predicate.
                _ => return false,
            }
        }
        false
    }
    #[must_use]
    pub fn commands(&self) -> &[PaintCommand] {
        self.commands.as_deref().map_or(&[], Vec::as_slice)
    }
    #[must_use]
    pub fn len(&self) -> usize {
        self.commands().len()
    }
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.commands().is_empty()
    }
    /// Removes every command, keeping the allocation for the next recording.
    pub fn clear(&mut self) {
        if let Some(commands) = self.commands.as_mut() {
            match std::sync::Arc::get_mut(commands) {
                Some(unique) => unique.clear(),
                None => self.commands = None,
            }
        }
    }
}
#[derive(Default)]
pub struct Canvas {
    list: DisplayList,
    saves: Vec<SaveKind>,
}
#[derive(Clone, Copy)]
enum SaveKind {
    Transform,
    Clip,
}
impl Canvas {
    pub fn rect(&mut self, rect: Rect, color: Color) {
        self.list.push(PaintCommand::Rect { rect, color });
    }
    pub fn rrect(&mut self, rrect: RRect, brush: impl Into<Brush>) {
        self.list.push(PaintCommand::RRect {
            rrect,
            brush: brush.into(),
        });
    }
    pub fn border(&mut self, rrect: RRect, border: Border) {
        self.list.push(PaintCommand::Border { rrect, border });
    }
    pub fn fill_path(&mut self, path: Arc<Path>, brush: impl Into<Brush>, fill_rule: FillRule) {
        self.list.push(PaintCommand::FillPath {
            path,
            brush: brush.into(),
            fill_rule,
        });
    }
    pub fn stroke_path(&mut self, path: Arc<Path>, brush: impl Into<Brush>, stroke: Stroke) {
        self.list.push(PaintCommand::StrokePath {
            path,
            brush: brush.into(),
            stroke,
        });
    }
    /// Lowers a [`Paint`] to the existing renderer-neutral path command.
    ///
    /// Blend and color-filter metadata remain available on the paint for a
    /// compositor/backend that needs them; the retained path geometry itself
    /// is never duplicated into a second command representation.
    pub fn draw_path(&mut self, path: Arc<Path>, paint: &Paint, fill_rule: FillRule) {
        match paint.style_value() {
            PaintStyle::Fill => self.fill_path(path, paint.brush_value().clone(), fill_rule),
            PaintStyle::Stroke => {
                self.stroke_path(path, paint.brush_value().clone(), paint.stroke_value())
            }
        }
    }
    pub fn image(&mut self, image: ImageHandle, source: Rect, destination: Rect) {
        self.image_with_sampling(image, source, destination, ImageSampling::Linear);
    }
    pub fn image_with_sampling(
        &mut self,
        image: ImageHandle,
        source: Rect,
        destination: Rect,
        sampling: ImageSampling,
    ) {
        self.list.push(PaintCommand::Image {
            image,
            source,
            destination,
            sampling,
        });
    }
    pub fn glyph_run(&mut self, run: Arc<GlyphRun>, color: Color) {
        self.list.push(PaintCommand::GlyphRun { run, color });
    }
    pub fn save_transform(&mut self, transform: Transform) {
        self.saves.push(SaveKind::Transform);
        self.list.push(PaintCommand::PushTransform { transform });
    }
    pub fn save_clip(&mut self, rect: Rect) {
        self.saves.push(SaveKind::Clip);
        self.list.push(PaintCommand::PushClip { rect });
    }
    pub fn save_clip_rrect(&mut self, rrect: RRect) {
        self.saves.push(SaveKind::Clip);
        self.list.push(PaintCommand::PushClipRRect { rrect });
    }
    pub fn save_clip_oval(&mut self, rect: Rect) {
        self.saves.push(SaveKind::Clip);
        self.list.push(PaintCommand::PushClipOval { rect });
    }
    pub fn save_clip_path(&mut self, path: Arc<Path>, fill_rule: FillRule) {
        self.saves.push(SaveKind::Clip);
        self.list
            .push(PaintCommand::PushClipPath { path, fill_rule });
    }
    pub fn restore(&mut self) {
        match self.saves.pop().expect("unbalanced canvas restore") {
            SaveKind::Transform => self.list.push(PaintCommand::PopTransform),
            SaveKind::Clip => self.list.push(PaintCommand::PopClip),
        }
    }
    #[must_use]
    pub fn finish(self) -> DisplayList {
        assert!(self.saves.is_empty(), "unbalanced display list");
        self.list
    }
}