Skip to main content

cranpose_render_common/scene_store/
store.rs

1// The records a renderer draws: a tree of layout nodes' layers, wrappers,
2// draw groups and leaves, each a row of fixed-size records with its items in
3// one span, its other properties and its draws in side arenas.
4
5use std::{
6    rc::Rc,
7    sync::atomic::{AtomicU16, Ordering},
8};
9
10use cranpose_core::{NodeId, RecordId, RecordRef, SceneUpdate, StoreId};
11use cranpose_ui::{GraphicsLayer, Rect};
12use cranpose_ui_graphics::CommandRecording;
13
14use super::{
15    ChildOrder, Facts, GeoRecord, HashCache, Item, ItemKind, ItemLists, Journal, JournalEntry,
16    JournalRead, LayerProps, LayerRef, NodeRecords, Reach, RecordEvent, RecordEvents, RecordFlags,
17    RecordKind, RecordNode, ShapeChunks, ShapeRun, Slab, Span, SpanPool, TreeRecord, WarmRecord,
18    recordings::Recordings,
19};
20#[cfg(feature = "window-damage")]
21use super::{ReachState, own_marks};
22#[cfg(feature = "layer-tree")]
23use crate::graph::LayerNode;
24use crate::graph::{
25    DrawCommandId, DrawPrimitiveNode, DrawRunNode, ProjectiveTransform, TextPrimitiveNode,
26};
27
28/// The scene a renderer draws and the hit targets come from.
29pub struct SceneStore {
30    // The store's identity among the renderers' stores.
31    id: StoreId,
32    pub(super) tree: Vec<TreeRecord>,
33    pub(super) geo: Vec<GeoRecord>,
34    pub(super) warm: Vec<WarmRecord>,
35    pub(super) generations: Vec<u32>,
36    // The generation a new row starts at: past every one a cleared store
37    // or a cut row gave out.
38    pub(super) generation_floor: u32,
39    pub(super) free_rows: Vec<u32>,
40    pub(super) items: SpanPool<Item>,
41    #[cfg(feature = "window-damage")]
42    pub(super) marks: own_marks::Marks,
43    pub(super) props: Slab<LayerProps>,
44    pub(super) graphics_layers: Slab<GraphicsLayer>,
45    pub(super) transforms: Slab<ProjectiveTransform>,
46    pub(super) draws: Slab<DrawPrimitiveNode>,
47    pub(super) texts: Slab<TextPrimitiveNode>,
48    pub(super) runs: Slab<DrawRunNode>,
49    pub(super) shape_runs: Slab<ShapeRun>,
50    pub(super) shape_chunks: ShapeChunks,
51    pub(super) hashes: HashCache,
52    pub(super) facts: Facts,
53    pub(super) node_records: NodeRecords,
54    pub(crate) lists: ItemLists,
55    root: Option<RecordId>,
56    update: SceneUpdate,
57    pub(super) journal: Journal,
58    pub(super) order: ChildOrder,
59    pub(crate) recordings: Recordings,
60}
61
62/// One state of one store: what it held after one of its updates.
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64pub struct SceneVersion {
65    store: StoreId,
66    update: SceneUpdate,
67}
68
69impl SceneVersion {
70    /// The update the store had made.
71    pub fn update(self) -> SceneUpdate {
72        self.update
73    }
74}
75
76/// What a new record starts as.
77#[derive(Clone, Copy, Debug)]
78pub struct RecordSeed {
79    /// What the record draws for.
80    pub kind: RecordKind,
81    /// The layout node the record draws for, `None` for an overlay that
82    /// draws for none.
83    pub node: Option<NodeId>,
84    /// The record that holds it, `None` for the root.
85    pub parent: Option<RecordId>,
86}
87
88fn next_store_id() -> StoreId {
89    static NEXT: AtomicU16 = AtomicU16::new(1);
90    loop {
91        if let Some(id) = StoreId::new(NEXT.fetch_add(1, Ordering::Relaxed)) {
92            return id;
93        }
94    }
95}
96
97impl Default for SceneStore {
98    fn default() -> Self {
99        Self::new()
100    }
101}
102
103impl SceneStore {
104    /// An empty store.
105    pub fn new() -> Self {
106        Self {
107            id: next_store_id(),
108            tree: Vec::new(),
109            geo: Vec::new(),
110            warm: Vec::new(),
111            generations: Vec::new(),
112            generation_floor: 0,
113            free_rows: Vec::new(),
114            items: SpanPool::default(),
115            #[cfg(feature = "window-damage")]
116            marks: own_marks::Marks::default(),
117            props: Slab::default(),
118            graphics_layers: Slab::default(),
119            transforms: Slab::default(),
120            draws: Slab::default(),
121            texts: Slab::default(),
122            runs: Slab::default(),
123            shape_runs: Slab::default(),
124            shape_chunks: ShapeChunks::default(),
125            hashes: HashCache::default(),
126            facts: Facts::default(),
127            node_records: NodeRecords::default(),
128            lists: ItemLists::default(),
129            root: None,
130            update: SceneUpdate::default(),
131            journal: Journal::default(),
132            order: ChildOrder::default(),
133            recordings: Recordings::default(),
134        }
135    }
136
137    /// The store's identity among the renderers' stores.
138    #[inline]
139    pub fn id(&self) -> StoreId {
140        self.id
141    }
142
143    /// The store's identity and latest update.
144    pub fn version(&self) -> SceneVersion {
145        SceneVersion {
146            store: self.id,
147            update: self.update,
148        }
149    }
150
151    /// The root record, `None` before the first build.
152    pub fn root(&self) -> Option<RecordId> {
153        self.root
154    }
155
156    /// The latest scene update.
157    pub fn update(&self) -> SceneUpdate {
158        self.update
159    }
160
161    /// Starts a scene update and returns its number.
162    pub fn begin_update(&mut self) -> SceneUpdate {
163        self.recordings.begin_update();
164        self.update = self.update.next();
165        self.journal.begin(self.update, self.tree.len());
166        self.update
167    }
168
169    /// Whether `id` changed itself or moved in the latest `updates` updates.
170    #[inline]
171    pub fn changed_within(&self, id: RecordId, updates: u32) -> bool {
172        let row = &self.tree[id.index()];
173        self.update.since(row.content_rev) < updates || self.update.since(row.place_rev) < updates
174    }
175
176    // Lists the record at `index` among those the update changed, unless a
177    // stamp of the update shows it listed.
178    #[inline]
179    fn touch(&mut self, index: usize) {
180        let tree = &self.tree[index];
181        if self.journal.follows_stamps()
182            && tree.content_rev != self.update
183            && tree.place_rev != self.update
184        {
185            self.journal.stamp(RecordRef {
186                id: RecordId::from_index(index).expect("a row is a record"),
187                generation: self.generations[index],
188            });
189        }
190    }
191
192    /// Keeps the changes of the kinds in `events` for the store's readers
193    /// from the next update on, in place of those it kept.
194    pub fn follow(&mut self, events: RecordEvents) {
195        if self.journal.followed() != events {
196            self.journal.follow(events);
197            self.mark_for_redraws();
198        }
199    }
200
201    // Whether a reader follows where the update in progress redraws.
202    #[cfg(feature = "window-damage")]
203    #[inline]
204    pub(super) fn follows_redrawn_reach(&self) -> bool {
205        self.journal.wants_redrawn_reach(self.update)
206    }
207
208    // Works out the marks that wait once a reader follows where records
209    // redraw, so it compares the next redraws with the store as it is now.
210    #[cfg(feature = "window-damage")]
211    fn mark_for_redraws(&mut self) {
212        if self.follows_redrawn_reach() {
213            own_marks::refresh_lost(self);
214        }
215    }
216
217    #[cfg(not(feature = "window-damage"))]
218    #[inline]
219    fn mark_for_redraws(&mut self) {}
220
221    /// The changes of the store's records in the updates after `read`, the
222    /// version of the store a reader read last. Lost for no version, a
223    /// version of another store or one older than the store keeps.
224    pub fn changes_since(&self, read: Option<SceneVersion>) -> JournalRead<'_> {
225        match read {
226            Some(read) if read.store == self.id => self.journal.since(read.update, self.update),
227            _ => JournalRead::Lost,
228        }
229    }
230
231    /// The records the updates after `read` made, changed or moved, while
232    /// the store follows [`RecordEvents::STAMPS`]; a record may come more
233    /// than once. `None` for no version, a version of another store or one
234    /// older than the store keeps, or when an update stamped more records
235    /// than the store keeps.
236    pub fn stamps_since(&self, read: Option<SceneVersion>) -> Option<&[RecordRef]> {
237        let read = read.filter(|read| read.store == self.id)?;
238        self.journal.stamps_since(read.update, self.update)
239    }
240
241    /// Whether an update after `read`, the version of the store a reader
242    /// read last, changed a record. True for no version, a version of
243    /// another store or one the store was cleared after.
244    pub fn changed_since(&self, read: Option<SceneVersion>) -> bool {
245        match read {
246            Some(read) if read.store == self.id => self.journal.changed_since(read.update),
247            _ => true,
248        }
249    }
250
251    // Notes the change of `event` for `id` and logs it as the record is
252    // now, when a reader follows it.
253    #[inline]
254    pub(super) fn log(&mut self, event: RecordEvent, id: RecordId) {
255        self.journal.note_change(self.update);
256        if self.journal.wants(event, self.update) {
257            self.log_entry(event, id);
258        }
259    }
260
261    fn log_entry(&mut self, event: RecordEvent, id: RecordId) {
262        let index = id.index();
263        self.journal.log(JournalEntry {
264            update: self.update,
265            event,
266            record: RecordRef {
267                id,
268                generation: self.generations[index],
269            },
270            parent: self.tree[index].parent.map(|parent| RecordRef {
271                id: parent,
272                generation: self.generations[parent.index()],
273            }),
274            node: self.warm[index].node.map(RecordNode::id),
275        });
276    }
277
278    /// Ends the update in progress: logs the records whose children it put
279    /// in another order and the own draws it redrew. Readers read the store
280    /// after it.
281    pub fn finish_update(&mut self) {
282        super::child_order::settle(self);
283        #[cfg(feature = "window-damage")]
284        own_marks::settle(self);
285    }
286
287    /// Gives back the room the store's arrays hold past their records and
288    /// draws: the room a burst took, such as a first build's or a long
289    /// list's. The store's owner calls it at rest, when no frame waits, as
290    /// a frame would take the room again. Returns whether most rows stay
291    /// free past records made after them, room that only a store cleared
292    /// and built anew gives back.
293    pub fn trim(&mut self) -> bool {
294        super::growth_slack::trim(self)
295    }
296
297    // Leaves the own draws of the record at `index` to be compared with what
298    // they were at the end of the update. While no reader follows where
299    // records redraw, the record's marks wait at once.
300    #[expect(
301        clippy::inline_always,
302        reason = "the collect walk and the update call it for every record; out of line the gauntlet frame took 2% more instructions"
303    )]
304    #[inline(always)]
305    #[cfg(feature = "window-damage")]
306    pub(super) fn redraw_pending(&mut self, index: usize) {
307        if !self.follows_redrawn_reach() {
308            own_marks::lose(self, index);
309            return;
310        }
311        let flags = &mut self.tree[index].flags;
312        if !flags.contains(RecordFlags::REDRAW_PENDING) {
313            *flags = flags.with(RecordFlags::REDRAW_PENDING);
314            self.marks.redrawn.push(RecordRef {
315                id: RecordId::from_index(index).expect("a row is a record"),
316                generation: self.generations[index],
317            });
318        }
319    }
320
321    // Without window damage a record keeps no marks, and logs each redraw
322    // without its reach.
323    #[cfg(not(feature = "window-damage"))]
324    #[inline]
325    pub(super) fn redraw_pending(&mut self, index: usize) {
326        self.log(
327            RecordEvent::Redrawn(Reach::Unknown),
328            RecordId::from_index(index).expect("a row is a record"),
329        );
330    }
331
332    #[cfg(feature = "window-damage")]
333    pub(super) fn reach(&self, index: usize) -> Reach {
334        match self.tree[index].reach_state {
335            ReachState::Empty => Reach::Empty,
336            ReachState::Finite => Reach::Finite(self.geo[index].reach),
337            ReachState::Unknown => Reach::Unknown,
338        }
339    }
340
341    #[cfg(feature = "window-damage")]
342    pub(super) fn set_reach(&mut self, index: usize, reach: Reach) {
343        let (state, rect) = match reach {
344            Reach::Empty => (ReachState::Empty, Rect::default()),
345            Reach::Finite(rect) => (ReachState::Finite, rect),
346            Reach::Unknown => (ReachState::Unknown, Rect::default()),
347        };
348        self.tree[index].reach_state = state;
349        self.geo[index].reach = rect;
350    }
351
352    // Leaves the containment and the reach of the record at `index` and of
353    // the ancestors that follow from them to be worked out again. Most often
354    // an earlier change in the update left the record so already.
355    #[cfg(feature = "window-damage")]
356    #[inline]
357    pub(super) fn stale(&mut self, index: usize) {
358        if !self.tree[index].flags.contains(RecordFlags::REACH_STALE)
359            || super::facts::keeps_contained(self, index)
360        {
361            self.stale_climb(index);
362        }
363    }
364
365    // Without window damage no reader asks for reach or containment.
366    #[cfg(not(feature = "window-damage"))]
367    #[inline]
368    pub(super) fn stale(&mut self, _index: usize) {}
369
370    #[cfg(feature = "window-damage")]
371    #[inline(never)]
372    fn stale_climb(&mut self, index: usize) {
373        super::facts::forget_contained(self, index);
374        self.reach_stale(index);
375    }
376
377    // Leaves the reach of the record at `index` and of its ancestors to be
378    // worked out again, stopping at the first that waits for it already.
379    #[cfg(feature = "window-damage")]
380    fn reach_stale(&mut self, index: usize) {
381        let mut current = Some(index);
382        while let Some(index) = current {
383            let flags = &mut self.tree[index].flags;
384            if flags.contains(RecordFlags::REACH_STALE) {
385                break;
386            }
387            *flags = flags.with(RecordFlags::REACH_STALE);
388            current = self.tree[index].parent.map(RecordId::index);
389        }
390    }
391
392    /// Works out the reach of every record whose reach a change beneath it
393    /// left to be worked out again, as [`LayerRef::reach`] reads it.
394    #[cfg(feature = "window-damage")]
395    pub fn refresh_reach(&mut self) {
396        own_marks::refresh_lost(self);
397        if let Some(root) = self.root {
398            super::reach::refresh(self, root);
399        }
400    }
401
402    // Leaves the containment of the record at `index` and of its parent,
403    // which reads what the record draws, to be worked out again.
404    #[inline]
405    pub(super) fn stale_with_parent(&mut self, index: usize) {
406        self.stale(index);
407        if let Some(parent) = self.tree[index].parent {
408            self.stale(parent.index());
409        }
410    }
411
412    /// A store that holds `root` and the tree beneath it as records.
413    #[cfg(feature = "layer-tree")]
414    pub fn from_layer(root: &LayerNode) -> Self {
415        let mut store = Self::new();
416        store.describe(root);
417        store
418    }
419
420    /// Writes `root` and the tree beneath it as records in place of what the
421    /// store held, in a new update. Records of the same kind and node at the
422    /// same place stay, so the update changes only what differs.
423    #[cfg(feature = "layer-tree")]
424    pub fn describe(&mut self, root: &LayerNode) {
425        self.begin_update();
426        super::spec::write_root(self, root);
427        self.finish_update();
428    }
429
430    /// The record `id` as its readers see it.
431    #[inline]
432    pub fn layer(&self, id: RecordId) -> LayerRef<'_> {
433        LayerRef::new(self, id)
434    }
435
436    /// The root record as its readers see it.
437    pub fn root_layer(&self) -> Option<LayerRef<'_>> {
438        self.root.map(|root| self.layer(root))
439    }
440
441    /// Estimated heap memory the store holds, in bytes, for memory reports.
442    pub fn heap_bytes(&self) -> usize {
443        super::heap_bytes::store_heap_bytes(self)
444    }
445
446    /// How many records and draws the store holds: each record counts once,
447    /// each primitive of a draw run on its own.
448    pub fn node_count(&self) -> usize {
449        self.record_count()
450            + self.draws.values().count()
451            + self.texts.values().count()
452            + self.runs.values().map(DrawRunNode::len).sum::<usize>()
453            + self.shape_item_count()
454    }
455
456    /// How many records the store holds.
457    pub fn record_count(&self) -> usize {
458        self.tree.len() - self.free_rows.len()
459    }
460
461    /// Removes every record.
462    pub fn clear(&mut self) {
463        self.tree.clear();
464        self.geo.clear();
465        self.warm.clear();
466        // A record made after the clear takes a generation past every one
467        // given out before, so no handle taken before names it. The floor
468        // already counts the rows an update cut from the end.
469        if let Some(&last) = self.generations.iter().max() {
470            self.generation_floor = self.generation_floor.max(last.wrapping_add(1));
471        }
472        self.generations.clear();
473        self.free_rows = Vec::new();
474        self.items.clear();
475        #[cfg(feature = "window-damage")]
476        self.marks.clear();
477        self.props.clear();
478        self.graphics_layers.clear();
479        self.transforms.clear();
480        self.draws.clear();
481        self.texts.clear();
482        self.runs.clear();
483        self.clear_shapes();
484        self.hashes.clear();
485        self.facts.clear();
486        self.node_records.clear();
487        self.root = None;
488        // The store takes an update of its own, which no reader read: a
489        // reader of an earlier version finds its changes lost.
490        self.update = self.update.next();
491        self.journal.clear(self.update);
492    }
493
494    // Makes room for `records` records past the rows free to take, so a
495    // build that makes them moves none of the record arrays to a larger
496    // block on the way.
497    pub(crate) fn reserve_records(&mut self, records: usize) {
498        let more = records.saturating_sub(self.free_rows.len());
499        self.tree.reserve_exact(more);
500        self.geo.reserve_exact(more);
501        self.warm.reserve_exact(more);
502        self.generations.reserve_exact(more);
503        self.facts.reserve_rows(self.tree.len() + more);
504        self.node_records.reserve(more);
505    }
506
507    /// Makes a record from `seed`, changed in the update in progress, with no
508    /// items, at the origin of its parent and of zero size. Its ancestors
509    /// take the update as their subtree's; the caller adds it to its
510    /// parent's items.
511    pub fn insert(&mut self, seed: RecordSeed) -> RecordId {
512        let update = self.update;
513        let tree = TreeRecord {
514            parent: seed.parent,
515            items: Span::default(),
516            kind: seed.kind,
517            #[cfg(feature = "window-damage")]
518            reach_state: ReachState::Empty,
519            flags: RecordFlags::default(),
520            content_rev: update,
521            place_rev: update,
522            subtree_rev: update,
523            transform: None,
524        };
525        let warm = WarmRecord {
526            node: seed.node.map(RecordNode::of),
527            props: None,
528            graphics_layer: None,
529            content_offset: [0.0; 2],
530            #[cfg(feature = "window-damage")]
531            own_marks: Span::default(),
532        };
533        let id = match self.free_rows.pop() {
534            Some(row) => {
535                let index = row as usize;
536                self.tree[index] = tree;
537                self.geo[index] = GeoRecord::default();
538                self.warm[index] = warm;
539                RecordId::from_index(index).expect("a freed row was a record")
540            }
541            None => {
542                self.tree.push(tree);
543                self.geo.push(GeoRecord::default());
544                self.warm.push(warm);
545                self.generations.push(self.generation_floor);
546                RecordId::from_index(self.tree.len() - 1).expect("fewer than 2^32 records")
547            }
548        };
549        self.facts.open_row(id.index());
550        self.node_records.claim(id, seed.kind, seed.node);
551        match seed.parent {
552            Some(parent) => self.note_subtree_change(Some(parent)),
553            None => self.root = Some(id),
554        }
555        self.stale_with_parent(id.index());
556        #[cfg(feature = "window-damage")]
557        own_marks::pend_inserted(self, id.index());
558        self.log(RecordEvent::Inserted, id);
559        if self.journal.follows_stamps() {
560            self.journal.stamp(self.record_ref(id));
561        }
562        id
563    }
564
565    // Out of line: inlined into `remove_item`, a removal most updates never
566    // make takes room in the code that drops each replaced draw.
567    /// Removes `id`, its draws, its properties and every record beneath it.
568    #[inline(never)]
569    pub fn remove_subtree(&mut self, id: RecordId) {
570        self.log(RecordEvent::Removed, id);
571        let index = id.index();
572        self.node_records
573            .release(id, self.tree[index].kind, self.node(id));
574        if let Some(parent) = self.tree[index].parent {
575            self.stale(parent.index());
576        }
577        let span = self.tree[index].items;
578        for position in 0..span.len() {
579            let item = self.items.span(span)[position];
580            self.remove_item(item);
581        }
582        // A free row names no span, so a trim packs the live spans alone.
583        self.items.free_span(span);
584        self.tree[index].items = Span::default();
585        #[cfg(feature = "window-damage")]
586        self.marks
587            .pool
588            .free_span(std::mem::take(&mut self.warm[index].own_marks));
589        self.hashes.remove(index);
590        self.drop_props(index);
591        if let Some(transform) = self.tree[index].transform.take() {
592            self.transforms.remove(transform.index());
593        }
594        self.generations[index] = self.generations[index].wrapping_add(1);
595        self.free_rows
596            .push(u32::try_from(index).expect("fewer than 2^32 records"));
597        if self.root == Some(id) {
598            self.root = None;
599        }
600    }
601
602    /// Removes what `item` holds: a child record's subtree or a draw.
603    pub fn remove_item(&mut self, item: Item) {
604        match item.kind() {
605            ItemKind::Child => {
606                if let Some(child) = item.as_child() {
607                    self.remove_subtree(child);
608                }
609            }
610            ItemKind::Draw => {
611                self.draws.remove(item.index());
612            }
613            ItemKind::Text => {
614                self.texts.remove(item.index());
615            }
616            ItemKind::Run => {
617                if let Some(run) = self.runs.take(item.index()) {
618                    self.keep_released(run.command, &run.recording);
619                }
620            }
621            ItemKind::Shape => self.remove_shapes(item.index()),
622        }
623    }
624
625    /// A handle to `id` that tells a later holder whether the row went to
626    /// another record since.
627    #[inline]
628    pub fn record_ref(&self, id: RecordId) -> RecordRef {
629        RecordRef {
630            id,
631            generation: self.generations[id.index()],
632        }
633    }
634
635    /// The record `held` names, while its row still holds that record.
636    #[inline]
637    pub fn resolve(&self, held: RecordRef) -> Option<RecordId> {
638        (self.generations.get(held.id.index()) == Some(&held.generation)).then_some(held.id)
639    }
640
641    /// The items of `id` in draw order.
642    #[inline]
643    pub fn items(&self, id: RecordId) -> &[Item] {
644        self.items.span(self.tree[id.index()].items)
645    }
646
647    // Writes the items of `id` for the scene builder, which notes the
648    // change itself.
649    pub(crate) fn write_items(&mut self, id: RecordId, items: &[Item]) {
650        self.replace_items(id, items);
651        self.stale(id.index());
652    }
653
654    // Replaces the items of `id` with `items` and logs the change, leaving
655    // its containment and reach to the caller. Returns whether the items
656    // differ from the ones it held.
657    pub(super) fn replace_items(&mut self, id: RecordId, items: &[Item]) -> bool {
658        let index = id.index();
659        let old = self.items.span(self.tree[index].items);
660        // Draws written in place of removed ones of the same kinds take
661        // their handles: the items read as before.
662        if old == items {
663            return false;
664        }
665        if !super::facts::same_children(old, items) {
666            super::facts::forget_children(self, index);
667        }
668        super::facts::forget_own(self, index);
669        let noted = self.journal.follows(RecordEvent::Changed);
670        if noted {
671            let record = self.record_ref(id);
672            self.order.note(record, old);
673        }
674        self.tree[index].items = self.items.write(self.tree[index].items, items);
675        self.touch(index);
676        // A reader that follows these changes learns them when the update
677        // ends, from the order of the children and the redrawn own draws.
678        // Any other write of items is a change of its own.
679        if !noted {
680            self.journal.note_change(self.update);
681        }
682        true
683    }
684
685    /// Adds a draw primitive for an item.
686    pub fn add_draw(&mut self, draw: DrawPrimitiveNode) -> Item {
687        Item::new(ItemKind::Draw, self.draws.insert(draw))
688    }
689
690    /// Adds a text for an item.
691    pub fn add_text(&mut self, text: TextPrimitiveNode) -> Item {
692        Item::new(ItemKind::Text, self.texts.insert(text))
693    }
694
695    /// Adds a draw run for an item.
696    pub fn add_run(&mut self, run: DrawRunNode) -> Item {
697        Item::new(ItemKind::Run, self.runs.insert(run))
698    }
699
700    /// The draw primitive of a draw item.
701    #[inline]
702    pub fn draw(&self, item: Item) -> &DrawPrimitiveNode {
703        &self.draws[item.index()]
704    }
705
706    /// The text of a text item.
707    #[inline]
708    pub fn text(&self, item: Item) -> &TextPrimitiveNode {
709        &self.texts[item.index()]
710    }
711
712    // The text of a text item, to change in place by the scene builder,
713    // which notes the change of the record that holds it.
714    pub(crate) fn text_mut(&mut self, item: Item) -> &mut TextPrimitiveNode {
715        &mut self.texts[item.index()]
716    }
717
718    /// The draw run of a run item.
719    #[inline]
720    pub fn run(&self, item: Item) -> &DrawRunNode {
721        &self.runs[item.index()]
722    }
723
724    // The draw run of a run item, to draw again in place.
725    #[inline]
726    pub(crate) fn run_mut(&mut self, item: Item) -> &mut DrawRunNode {
727        &mut self.runs[item.index()]
728    }
729
730    // Puts `recording` in place of the recording of the run `item`.
731    pub(crate) fn swap_run_recording(&mut self, item: Item, recording: Rc<CommandRecording>) {
732        let run = &mut self.runs[item.index()];
733        // A run handed the recording it draws lets go of nothing.
734        if Rc::ptr_eq(&run.recording, &recording) {
735            return;
736        }
737        let command = run.command;
738        let old = std::mem::replace(&mut run.recording, recording);
739        self.keep_released(command, &old);
740    }
741
742    // Keeps `recording`, which `command` recorded and which the store lets
743    // go of, for the command's next recording once no reader holds it.
744    fn keep_released(&mut self, command: Option<DrawCommandId>, recording: &Rc<CommandRecording>) {
745        if let Some(id) = command {
746            self.recordings.keep(id, recording);
747        }
748    }
749
750    /// What `id` draws for.
751    #[inline]
752    pub fn kind(&self, id: RecordId) -> RecordKind {
753        self.tree[id.index()].kind
754    }
755
756    /// The layout node `id` draws for.
757    #[inline]
758    pub fn node(&self, id: RecordId) -> Option<NodeId> {
759        self.warm[id.index()].node.map(RecordNode::id)
760    }
761
762    /// The record that holds `id`.
763    #[inline]
764    pub fn parent(&self, id: RecordId) -> Option<RecordId> {
765        self.tree[id.index()].parent
766    }
767
768    // The record `node` draws through: its layer or its leaf.
769    pub(crate) fn record_of(&self, node: NodeId) -> Option<RecordId> {
770        self.node_records.get(node)
771    }
772
773    // The node whose record holds the records of `node`: the one to draw
774    // again for the records of `node` to leave. `None` when no record draws
775    // for `node` or its record is the root.
776    pub(crate) fn drawn_parent(&self, node: NodeId) -> Option<NodeId> {
777        let mut record = self.record_of(node)?;
778        loop {
779            record = self.parent(record)?;
780            if let Some(parent) = self.node(record)
781                && parent != node
782            {
783                return Some(parent);
784            }
785        }
786    }
787
788    /// The flags of `id`.
789    #[inline]
790    pub fn flags(&self, id: RecordId) -> RecordFlags {
791        self.tree[id.index()].flags
792    }
793
794    // Writes the flags of `id` for the scene builder, which notes the
795    // change itself; `false` when they stay.
796    pub(crate) fn write_flags(&mut self, id: RecordId, flags: RecordFlags) -> bool {
797        let changed = self.write_flag_row(id.index(), flags);
798        if changed {
799            self.stale_with_parent(id.index());
800        }
801        changed
802    }
803
804    /// The size of the node rect of `id`.
805    #[inline]
806    pub fn node_rect(&self, id: RecordId) -> Rect {
807        self.geo[id.index()].node_rect()
808    }
809
810    // Writes the node rect size of `id` for the scene builder, which notes
811    // the change itself; `false` when it stays.
812    #[inline]
813    pub(crate) fn write_size(&mut self, id: RecordId, width: f32, height: f32) -> bool {
814        let index = id.index();
815        let size = [width, height];
816        if super::records::same_pair(self.geo[index].size, size) {
817            return false;
818        }
819        self.geo[index].size = size;
820        self.stale_with_parent(index);
821        true
822    }
823
824    /// Sets what `id` draws for and the layout node it draws for, and
825    /// returns whether either changed. A [`RecordKind::Leaf`] holds no layer
826    /// properties and no child layers.
827    #[inline]
828    pub fn set_kind(&mut self, id: RecordId, kind: RecordKind, node: Option<NodeId>) -> bool {
829        let index = id.index();
830        let changed =
831            self.tree[index].kind != kind || self.warm[index].node != node.map(RecordNode::of);
832        if changed {
833            self.change_kind(id, kind, node);
834        }
835        changed
836    }
837
838    #[inline(never)]
839    fn change_kind(&mut self, id: RecordId, kind: RecordKind, node: Option<NodeId>) {
840        let index = id.index();
841        self.log(RecordEvent::Released, id);
842        self.node_records
843            .release(id, self.tree[index].kind, self.node(id));
844        self.node_records.claim(id, kind, node);
845        self.tree[index].kind = kind;
846        self.warm[index].node = node.map(RecordNode::of);
847        self.stale_with_parent(index);
848        self.log(RecordEvent::Claimed, id);
849        self.touch(index);
850    }
851
852    // Removes every item of `id` for the scene builder, which notes the
853    // change itself.
854    pub(crate) fn drop_items(&mut self, id: RecordId) {
855        let index = id.index();
856        let span = self.tree[index].items;
857        if !super::facts::same_children(self.items.span(span), &[]) {
858            super::facts::forget_children(self, index);
859        }
860        for position in 0..span.len() {
861            let item = self.items.span(span)[position];
862            self.remove_item(item);
863        }
864        self.items.free_span(span);
865        self.tree[index].items = Span::default();
866        super::facts::forget_own(self, index);
867        self.stale(index);
868        if span.len() != 0 {
869            self.touch(index);
870        }
871    }
872
873    /// Notes that the update in progress changed what `id` draws: its own
874    /// draws, properties or children. Its ancestors take the update as their
875    /// subtree's.
876    pub fn note_content_change(&mut self, id: RecordId) {
877        let update = self.update;
878        let index = id.index();
879        self.redraw_pending(index);
880        self.stale(index);
881        super::facts::forget_own(self, index);
882        self.touch(index);
883        let tree = &mut self.tree[index];
884        tree.content_rev = update;
885        let raise = tree.subtree_rev != update;
886        self.note_content_run(index);
887        if raise {
888            self.raise_subtree_revs(id);
889        }
890    }
891
892    /// Notes that the update in progress changed the properties of `id`
893    /// without changing what it draws: its hashes go, while a raster cache
894    /// keyed on its content does not count the update as a content change.
895    pub fn note_property_change(&mut self, id: RecordId) {
896        let update = self.update;
897        let index = id.index();
898        if self.tree[index].content_rev != update {
899            self.log(RecordEvent::Changed, id);
900        }
901        self.touch(index);
902        let tree = &mut self.tree[index];
903        tree.content_rev = update;
904        tree.subtree_rev = update;
905        let parent = tree.parent;
906        self.note_subtree_change(parent);
907    }
908
909    // Notes that the update in progress moved the record at `index`, or its
910    // content within it. Its ancestors take the update as their subtree's.
911    #[inline]
912    pub(super) fn moved(&mut self, index: usize) {
913        if self.tree[index].place_rev != self.update {
914            self.touch(index);
915            self.tree[index].place_rev = self.update;
916            self.log(
917                RecordEvent::Moved,
918                RecordId::from_index(index).expect("a row is a record"),
919            );
920            self.note_subtree_change(self.tree[index].parent);
921        }
922    }
923
924    // Raises the subtree revision of `from` and its ancestors to the update
925    // in progress, and leaves their hashes to be worked out again, stopping
926    // at the first ancestor that holds the update already.
927    #[inline]
928    pub(super) fn note_subtree_change(&mut self, from: Option<RecordId>) {
929        if let Some(record) = from
930            && self.tree[record.index()].subtree_rev != self.update
931        {
932            self.raise_subtree_revs(record);
933        }
934    }
935
936    #[inline(never)]
937    fn raise_subtree_revs(&mut self, from: RecordId) {
938        let update = self.update;
939        let mut current = Some(from);
940        while let Some(record) = current {
941            let index = record.index();
942            let tree = &mut self.tree[index];
943            if tree.subtree_rev == update {
944                break;
945            }
946            tree.subtree_rev = update;
947            current = tree.parent;
948            self.note_content_run(index);
949        }
950    }
951
952    // Counts the update in progress in the content run of the record at
953    // `index`, which `LayerRef::content_churns` reads.
954    #[cfg(feature = "window-damage")]
955    #[inline]
956    fn note_content_run(&mut self, index: usize) {
957        if self.tree[index].flags.contains(RecordFlags::HAS_PROPS)
958            && let Some(props) = self.warm[index].props
959        {
960            self.props[props.index()].content_run.note(self.update);
961        }
962    }
963
964    // Without window damage no reader asks whether a record's content churns.
965    #[cfg(not(feature = "window-damage"))]
966    #[inline]
967    fn note_content_run(&mut self, _index: usize) {}
968
969    /// The update that last changed what `id` itself draws.
970    pub fn content_rev(&self, id: RecordId) -> SceneUpdate {
971        self.tree[id.index()].content_rev
972    }
973}