Skip to main content

cranpose_render_common/scene_store/
layer_ref.rs

1// One record of a store as its readers see it: the layer a renderer draws,
2// hit testing walks and the inspector shows, under the names a layer of the
3// render graph had.
4
5use cranpose_core::{NodeId, RecordId, RecordRef, SceneUpdate, StoreId};
6use cranpose_ui::{GraphicsLayer, Point, Rect, RenderEffect, Size};
7use cranpose_ui_graphics::{BlendMode, ColorFilter, CompositingStrategy};
8
9#[cfg(feature = "window-damage")]
10use super::{Extent, OwnDrawFacts, Reach};
11use super::{Item, ItemKind, LayerProps, Placement, RecordFlags, RecordKind, SceneStore, ShapeRef};
12use crate::{
13    graph::{
14        CachePolicy, DrawPrimitiveNode, DrawRunNode, HitTestNode, IsolationReasons, PrimitivePhase,
15        ProjectiveTransform, TextPrimitiveNode,
16    },
17    raster_cache::LayerRasterCacheHashes,
18};
19
20/// One record of a [`SceneStore`]: a layer, a wrapper, a draw group or a
21/// leaf drawn in its parent's layer.
22#[derive(Clone, Copy)]
23pub struct LayerRef<'a> {
24    pub(super) store: &'a SceneStore,
25    pub(super) id: RecordId,
26}
27
28/// One item of a record, in draw order.
29#[derive(Clone, Copy)]
30pub enum ItemRef<'a> {
31    /// A child layer: a node's layer, a wrapper or a draw group.
32    Layer(LayerRef<'a>),
33    /// A layout node drawn in this record's layer, placed by a translation.
34    Leaf(LayerRef<'a>),
35    /// A draw primitive with its clip.
36    Draw(&'a DrawPrimitiveNode),
37    /// A text.
38    Text(&'a TextPrimitiveNode),
39    /// A run of one draw command's primitives.
40    Run(&'a DrawRunNode),
41    /// Shapes the store keeps in a chunk it shares among shape items.
42    Shape(ShapeRef<'a>),
43}
44
45/// What a record and its subtree were at their last changes, and where the
46/// record sat in its parent's layer: two values taken of one record agree
47/// where nothing changed in between.
48#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
49pub struct RecordChanges {
50    store: StoreId,
51    record: RecordRef,
52    subtree: SceneUpdate,
53    own: SceneUpdate,
54    // The record's placement in its parent and its parent's content offset,
55    // which together put it in its parent's layer.
56    placed: SceneUpdate,
57    parent_placed: SceneUpdate,
58}
59
60impl RecordChanges {
61    /// The record the changes are of, with the generation of its row.
62    #[inline]
63    pub fn record(self) -> RecordRef {
64        self.record
65    }
66
67    /// Whether nothing in the record's subtree changed between `self` and
68    /// `other`.
69    #[inline]
70    pub fn same_subtree(self, other: Self) -> bool {
71        (self.store, self.record, self.subtree) == (other.store, other.record, other.subtree)
72    }
73
74    /// Whether the record itself, its properties, draws and items, did not
75    /// change between `self` and `other`, whatever changed beneath it.
76    #[inline]
77    pub fn same_own(self, other: Self) -> bool {
78        (self.store, self.record, self.own) == (other.store, other.record, other.own)
79    }
80
81    /// Whether the record sat in one place in its parent's layer between
82    /// `self` and `other`: neither it nor its parent's content moved.
83    #[inline]
84    pub fn same_place(self, other: Self) -> bool {
85        (self.store, self.record, self.placed, self.parent_placed)
86            == (other.store, other.record, other.placed, other.parent_placed)
87    }
88}
89
90impl<'a> LayerRef<'a> {
91    #[inline]
92    pub(crate) fn new(store: &'a SceneStore, id: RecordId) -> Self {
93        Self { store, id }
94    }
95
96    /// The store that holds the record.
97    #[inline]
98    pub fn store(self) -> &'a SceneStore {
99        self.store
100    }
101
102    /// The record's id in its store.
103    #[inline]
104    pub fn id(self) -> RecordId {
105        self.id
106    }
107
108    /// What the record draws for.
109    #[inline]
110    pub fn kind(self) -> RecordKind {
111        self.store.tree[self.id.index()].kind
112    }
113
114    /// The layout node of a node's layer or leaf; `None` for a wrapper, a
115    /// draw group and an overlay.
116    #[inline]
117    pub fn node_id(self) -> Option<NodeId> {
118        match self.kind() {
119            RecordKind::Layer | RecordKind::Leaf => self.owner(),
120            RecordKind::Wrapper | RecordKind::DrawGroup => None,
121        }
122    }
123
124    /// The node whose outer draws a wrapper holds.
125    #[inline]
126    pub fn wraps(self) -> Option<NodeId> {
127        match self.kind() {
128            RecordKind::Wrapper => self.owner(),
129            RecordKind::Layer | RecordKind::Leaf | RecordKind::DrawGroup => None,
130        }
131    }
132
133    /// [`Self::node_id`] and [`Self::wraps`] from one read of the record.
134    #[inline]
135    pub fn identity(self) -> (Option<NodeId>, Option<NodeId>) {
136        let owner = self.owner();
137        match self.kind() {
138            RecordKind::Layer | RecordKind::Leaf => (owner, None),
139            RecordKind::Wrapper => (None, owner),
140            RecordKind::DrawGroup => (None, None),
141        }
142    }
143
144    /// The layout node the record draws for, whatever its kind.
145    #[inline]
146    pub fn owner(self) -> Option<NodeId> {
147        self.store.node(self.id)
148    }
149
150    /// The record that holds this one.
151    #[inline]
152    pub fn parent(self) -> Option<Self> {
153        self.store.tree[self.id.index()]
154            .parent
155            .map(|parent| Self::new(self.store, parent))
156    }
157
158    /// The properties the record keeps beyond its fixed-size parts.
159    #[inline]
160    pub fn props(self) -> Option<&'a LayerProps> {
161        self.store.props(self.id)
162    }
163
164    /// The record's flags.
165    #[inline]
166    pub fn flags(self) -> RecordFlags {
167        self.store.tree[self.id.index()].flags
168    }
169
170    /// The node's rect, `(0, 0, size)`, where its pointer handlers are.
171    #[inline]
172    pub fn node_rect(self) -> Rect {
173        self.store.geo[self.id.index()].node_rect()
174    }
175
176    /// The node's size.
177    #[inline]
178    pub fn size(self) -> Size {
179        let [width, height] = self.store.geo[self.id.index()].size;
180        Size { width, height }
181    }
182
183    #[expect(
184        clippy::inline_always,
185        reason = "the collect walk and the update call it for every record; out of line the gauntlet frame took 2% more instructions"
186    )]
187    /// The bounds of the layer, where its clip cuts, its transforms pivot and
188    /// an offscreen pass draws it.
189    #[inline(always)]
190    pub fn local_bounds(self) -> Rect {
191        if !self.flags().contains(RecordFlags::HAS_LAYER_BOUNDS) {
192            return self.node_rect();
193        }
194        self.props()
195            .and_then(|props| props.layer_bounds)
196            .unwrap_or_else(|| self.node_rect())
197    }
198
199    /// The node's rect when it differs from [`Self::local_bounds`].
200    #[inline]
201    pub fn node_bounds(self) -> Option<Rect> {
202        self.props()
203            .and_then(|props| props.layer_bounds)
204            .map(|_| self.node_rect())
205    }
206
207    /// The record's top left in its parent's layer: its placement and the
208    /// parent's content offset. A leaf's transform moves it there.
209    #[inline]
210    pub fn origin(self) -> Point {
211        self.store.origin(self.id)
212    }
213
214    /// Maps the record's space to its parent's content space, with the
215    /// placement, the graphics layer transform and the parent's content
216    /// offset applied.
217    #[inline]
218    pub fn transform_to_parent(self) -> ProjectiveTransform {
219        self.store.transform_to_parent(self.id)
220    }
221
222    /// Where the record sits in its parent's layer: [`Self::transform_to_parent`]
223    /// without making a transform of a point.
224    #[inline]
225    pub fn placement(self) -> Placement {
226        self.store.placement(self.id)
227    }
228
229    /// Offset of the node's content box from its origin, where its children
230    /// are placed.
231    #[inline]
232    pub fn content_offset(self) -> Point {
233        self.store.content_offset(self.id)
234    }
235
236    /// Where layout placed the record within its parent's content, before
237    /// the parent's content offset.
238    #[inline]
239    pub fn origin_in_parent(self) -> Point {
240        self.store.origin_in_parent(self.id)
241    }
242
243    /// Whether the record lies in a motion context such as an animated
244    /// scroll, where a renderer must not snap its content rigidly to the
245    /// pixel grid.
246    #[inline]
247    pub fn motion_context_animated(self) -> bool {
248        self.flags().contains(RecordFlags::MOTION_ANIMATED)
249    }
250
251    /// Whether the record moves its content as one translated block, so a
252    /// renderer may snap that content to the pixel grid as a whole.
253    #[inline]
254    pub fn translated_content_context(self) -> bool {
255        self.flags().contains(RecordFlags::TRANSLATED_CONTENT)
256    }
257
258    /// Translation of the content in a translated content context.
259    #[inline]
260    pub fn translated_content_offset(self) -> Point {
261        self.props()
262            .map_or_default(|props| props.translated_content_offset)
263    }
264
265    /// The graphics layer properties; defaults when none were set.
266    #[inline]
267    pub fn graphics_layer(self) -> &'a GraphicsLayer {
268        self.store
269            .graphics_layer(self.id)
270            .unwrap_or(&GraphicsLayer::DEFAULT)
271    }
272
273    /// Whether the record cuts its content to its local bounds.
274    #[inline]
275    pub fn clip_to_bounds(self) -> bool {
276        self.flags().contains(RecordFlags::CLIP_TO_BOUNDS)
277    }
278
279    /// Pointer handling of the node.
280    #[inline]
281    pub fn hit_test(self) -> Option<&'a HitTestNode> {
282        self.props().and_then(|props| props.hit_test.as_ref())
283    }
284
285    /// Whether the record or a record beneath it handles pointers.
286    #[inline]
287    pub fn has_hit_targets(self) -> bool {
288        super::facts::has_hit_targets(self)
289    }
290
291    /// Whether the record's subtree publishes live window origins: a text
292    /// field's popup anchor, a scroll container's viewport rect.
293    #[inline]
294    pub fn has_origin_sinks(self) -> bool {
295        super::facts::has_origin_sinks(self)
296    }
297
298    /// Whether the record or a record beneath it is a scene, a mesh surface
299    /// or a 3D transform.
300    #[inline]
301    pub fn has_space(self) -> bool {
302        super::facts::has_space(self)
303    }
304
305    /// What the record's own draws hold that decides how a renderer snaps
306    /// them to the pixel grid.
307    #[cfg(feature = "window-damage")]
308    #[inline]
309    pub fn own_draw_facts(self) -> OwnDrawFacts {
310        super::facts::own_draw_facts(self)
311    }
312
313    /// Where the record's subtree draws, in its own space: what its items
314    /// draw and its children's extents, within its clip. A change beneath
315    /// the record since [`SceneStore::refresh_reach`] leaves it unknown.
316    #[cfg(feature = "window-damage")]
317    pub fn reach(self) -> Reach {
318        if self.flags().contains(RecordFlags::REACH_STALE) {
319            return Reach::Unknown;
320        }
321        self.store.reach(self.id.index())
322    }
323
324    /// Whether the record is a leaf whose last redraw changed only where it
325    /// reached at the [`SceneStore::refresh_reach`] before that redraw. Such
326    /// a leaf redraws within where it drew then, as long as it did not move.
327    #[cfg(feature = "window-damage")]
328    #[inline]
329    pub fn redrawn_within(self) -> bool {
330        self.flags().contains(RecordFlags::REDRAWN_WITHIN)
331    }
332
333    /// Where the record's own draws reach, beside its children's, in its
334    /// own space and within its clip. A change beneath the record since
335    /// [`SceneStore::refresh_reach`] leaves it unknown.
336    #[cfg(feature = "window-damage")]
337    pub fn own_reach(self) -> Reach {
338        if self.flags().contains(RecordFlags::REACH_STALE) {
339            return Reach::Unknown;
340        }
341        let marks = self.store.warm[self.id.index()].own_marks;
342        super::own_marks::reach(self.store.marks.pool.span(marks)).within(self.visual_clip_rect())
343    }
344
345    /// What the record draws in its parent's space.
346    #[cfg(feature = "window-damage")]
347    pub fn extent(self) -> Extent {
348        super::reach::extent(self)
349    }
350
351    /// Whether everything the record's subtree draws lies within its local
352    /// bounds, give or take [`crate::graph::CONTAINED_DRAW_SLACK`].
353    #[cfg(feature = "window-damage")]
354    #[inline]
355    pub fn draws_within_bounds(self) -> bool {
356        super::facts::contained(self)
357    }
358
359    /// The reasons the record is drawn through its own offscreen buffer.
360    #[inline]
361    pub fn isolation(self) -> IsolationReasons {
362        self.props().map_or_default(|props| props.isolation)
363    }
364
365    /// Whether the record's own composition needs its content on a texture
366    /// of its own: a reason to draw offscreen, or a graphics layer that
367    /// composites apart.
368    #[inline]
369    pub fn needs_surface(self) -> bool {
370        // A record with neither properties nor a graphics layer draws in
371        // place.
372        let kept = self
373            .flags()
374            .only(RecordFlags::HAS_PROPS | RecordFlags::HAS_GRAPHICS_LAYER);
375        kept != RecordFlags::default() && self.composes_apart()
376    }
377
378    #[inline(never)]
379    fn composes_apart(self) -> bool {
380        let graphics = self.graphics_layer();
381        let isolation = self.isolation();
382        isolation.explicit_offscreen
383            || isolation.effect
384            || isolation.blend_mode
385            || isolation.group_opacity
386            || graphics.compositing_strategy == CompositingStrategy::Offscreen
387            || crate::layer_composition::layer_requires_isolation(graphics)
388    }
389
390    /// The phase a draw group paints in among its node's own draws; `None`
391    /// for every other kind.
392    pub fn draw_phase(self) -> Option<PrimitivePhase> {
393        (self.kind() == RecordKind::DrawGroup).then(|| {
394            if self.flags().contains(RecordFlags::AFTER_CHILDREN) {
395                PrimitivePhase::AfterChildren
396            } else {
397                PrimitivePhase::BeforeChildren
398            }
399        })
400    }
401
402    /// Whether a renderer may keep the record's pixels between frames.
403    #[inline]
404    pub fn cache_policy(self) -> CachePolicy {
405        self.props().map_or_default(|props| props.cache_policy)
406    }
407
408    #[expect(
409        clippy::inline_always,
410        reason = "the collect walk and the update call it for every record; out of line the gauntlet frame took 2% more instructions"
411    )]
412    /// The rectangle that cuts the content and pointer hits: the local
413    /// bounds when the record clips to them or its graphics layer clips.
414    #[inline(always)]
415    pub fn clip_rect(self) -> Option<Rect> {
416        (self.clip_to_bounds() || self.graphics_layer().clip).then(|| self.local_bounds())
417    }
418
419    /// Where the record's own shadow is cut: its bounds when it clips its
420    /// content to them. A graphics-layer clip leaves the shadow whole.
421    #[inline]
422    pub fn shadow_clip(self) -> Option<Rect> {
423        self.clip_to_bounds().then(|| self.local_bounds())
424    }
425
426    #[expect(
427        clippy::inline_always,
428        reason = "the collect walk and the update call it for every record; out of line the gauntlet frame took 2% more instructions"
429    )]
430    /// Where the record's drawing is cut: its clip or, when it composites
431    /// through an offscreen buffer for its alpha or by request, its bounds.
432    #[inline(always)]
433    pub fn visual_clip_rect(self) -> Option<Rect> {
434        let clip = self.clip_rect();
435        if clip.is_some() {
436            return clip;
437        }
438        self.cut_by_isolation().then(|| self.local_bounds())
439    }
440
441    #[expect(
442        clippy::inline_always,
443        reason = "the collect walk calls it for every record; out of line the gauntlet frame took 2.5 M more instructions"
444    )]
445    /// [`Self::visual_clip_rect`] of the record whose graphics layer
446    /// `graphics` and local bounds `bounds` a reader holds already.
447    #[inline(always)]
448    pub fn visual_clip_of(self, graphics: &GraphicsLayer, bounds: Rect) -> Option<Rect> {
449        (self.clip_to_bounds() || graphics.clip || self.cut_by_isolation()).then_some(bounds)
450    }
451
452    // Whether the record composites through an offscreen buffer for its
453    // alpha or by request, which cuts its drawing to its bounds.
454    #[inline]
455    fn cut_by_isolation(self) -> bool {
456        let isolation = self.isolation();
457        isolation.group_opacity || isolation.explicit_offscreen
458    }
459
460    /// The render effect applied to the record's content.
461    #[inline]
462    pub fn effect(self) -> Option<&'a RenderEffect> {
463        self.graphics_layer().render_effect.as_ref()
464    }
465
466    /// The effect applied to what lies behind the record.
467    #[inline]
468    pub fn backdrop(self) -> Option<&'a RenderEffect> {
469        self.graphics_layer().backdrop_effect.as_ref()
470    }
471
472    /// Alpha of the record from 0.0 (transparent) to 1.0 (opaque).
473    #[inline]
474    pub fn opacity(self) -> f32 {
475        self.graphics_layer().alpha
476    }
477
478    /// How the record composites onto what lies beneath it.
479    #[inline]
480    pub fn blend_mode(self) -> BlendMode {
481        self.graphics_layer().blend_mode
482    }
483
484    /// The color filter applied to the record's content.
485    #[inline]
486    pub fn color_filter(self) -> Option<&'a ColorFilter> {
487        self.graphics_layer().color_filter.as_ref()
488    }
489
490    /// Hash of everything the record draws into its target. Equal hashes
491    /// mean cached pixels are still valid.
492    pub fn target_content_hash(self) -> u64 {
493        self.raster_cache_hashes().target_content
494    }
495
496    /// Hash of the record's content like [`Self::target_content_hash`],
497    /// without the translated content offset, so it stays equal while the
498    /// content only moves.
499    pub fn motion_source_content_hash(self) -> u64 {
500        super::content_hash::motion_source_content_hash(self)
501    }
502
503    /// Hash of the record's render effect, for keying cached effect output.
504    pub fn effect_hash(self) -> u64 {
505        self.raster_cache_hashes().effect
506    }
507
508    fn raster_cache_hashes(self) -> LayerRasterCacheHashes {
509        let index = self.id.index();
510        let subtree_rev = self.store.tree[index].subtree_rev;
511        self.store.hashes.hashes(index, subtree_rev, || {
512            super::content_hash::raster_cache_hashes(self)
513        })
514    }
515
516    /// Whether what the record draws changed in scene update `update` and in
517    /// the one before it, so a raster cache keyed on its content would miss
518    /// again.
519    #[cfg(feature = "window-damage")]
520    pub fn content_churns(self, update: SceneUpdate) -> bool {
521        self.props()
522            .is_some_and(|props| props.content_run.churns(update))
523    }
524
525    /// What the record and its subtree were at their last changes, and
526    /// where it sat in its parent's layer.
527    #[inline]
528    pub fn changes(self) -> RecordChanges {
529        let row = &self.store.tree[self.id.index()];
530        let parent_placed = row.parent.map_or_else(SceneUpdate::default, |parent| {
531            self.store.tree[parent.index()].place_rev
532        });
533        RecordChanges {
534            store: self.store.id(),
535            record: self.store.record_ref(self.id),
536            subtree: row.subtree_rev,
537            own: row.content_rev,
538            placed: row.place_rev,
539            parent_placed,
540        }
541    }
542
543    /// Whether the record itself, its properties, draws and items, changed
544    /// since `held` at most by the offset at which it moves its translated
545    /// content, whatever changed beneath it. A record that draws nothing of
546    /// its own keeps its children through such a change.
547    #[inline]
548    pub fn only_translated_since(self, held: RecordChanges) -> bool {
549        let now = self.changes();
550        now.same_own(held)
551            || self
552                .props()
553                .is_some_and(|props| props.translate_run.covers(held.own, now.own))
554    }
555
556    /// How many items the record holds.
557    #[inline]
558    pub fn item_count(self) -> usize {
559        self.store.items(self.id).len()
560    }
561
562    /// The record's item at `index` in draw order, read without the items
563    /// before it.
564    #[inline]
565    pub fn item(self, index: usize) -> Option<ItemRef<'a>> {
566        let item = *self.store.items(self.id).get(index)?;
567        Some(ItemRef::of(self.store, item))
568    }
569
570    /// The record's items in draw order.
571    #[inline]
572    pub fn items(self) -> impl DoubleEndedIterator<Item = ItemRef<'a>> + ExactSizeIterator + 'a {
573        let store = self.store;
574        store
575            .items(self.id)
576            .iter()
577            .map(move |item| ItemRef::of(store, *item))
578    }
579
580    /// The kinds of the record's items in draw order, read without the
581    /// items themselves.
582    #[inline]
583    pub fn item_kinds(self) -> impl Iterator<Item = ItemKind> + 'a {
584        self.store.items(self.id).iter().map(|item| item.kind())
585    }
586
587    /// The record's own draws in draw order: its items without its children.
588    #[inline]
589    pub fn own_draws(self) -> impl Iterator<Item = ItemRef<'a>> + 'a {
590        let store = self.store;
591        store
592            .items(self.id)
593            .iter()
594            .filter(|item| item.kind() != ItemKind::Child)
595            .map(move |item| ItemRef::of(store, *item))
596    }
597
598    /// The child records among the items, in draw order.
599    #[inline]
600    pub fn children(self) -> impl DoubleEndedIterator<Item = Self> + 'a {
601        let store = self.store;
602        store
603            .items(self.id)
604            .iter()
605            .filter_map(move |item| item.as_child().map(|child| Self::new(store, child)))
606    }
607}
608
609impl<'a> ItemRef<'a> {
610    #[expect(
611        clippy::inline_always,
612        reason = "the collect walk and the update call it for every record; out of line the gauntlet frame took 2% more instructions"
613    )]
614    #[inline(always)]
615    pub(crate) fn of(store: &'a SceneStore, item: Item) -> Self {
616        match item.kind() {
617            ItemKind::Child => {
618                let child = LayerRef::new(
619                    store,
620                    RecordId::from_index(item.index()).expect("a child item names a record row"),
621                );
622                match child.kind() {
623                    RecordKind::Leaf => Self::Leaf(child),
624                    RecordKind::Layer | RecordKind::Wrapper | RecordKind::DrawGroup => {
625                        Self::Layer(child)
626                    }
627                }
628            }
629            ItemKind::Draw => Self::Draw(store.draw(item)),
630            ItemKind::Text => Self::Text(store.text(item)),
631            ItemKind::Run => Self::Run(store.run(item)),
632            ItemKind::Shape => Self::Shape(store.shapes(item)),
633        }
634    }
635}