Skip to main content

nativeview_layout/inspector/
heat.rs

1//! Dense zero-steady-state-allocation per-node dirty & paint-flash heat tracker.
2//!
3//! Lives inside `Option<Box<InspectorState>>` on backends so disabled frames allocate 0 bytes.
4
5use nativeview_store::NodeId;
6
7use super::{DEFAULT_FLASH_TTL, MAX_FLASH_RECTS, SceneDirtyKind};
8
9/// Flag bit in [`NodeHeat::flags`]: slot has been populated for a live `NodeId` (disambiguates
10/// untouched/removed slots from live `generation == 0` nodes).
11pub const NODE_HEAT_OCCUPIED: u8 = 1 << 0;
12/// Flag bit in [`NodeHeat::flags`]: slot index is currently tracked in
13/// [`InspectorHeatTracker::active_flashes`].
14pub const NODE_HEAT_FLASHING: u8 = 1 << 1;
15
16/// Dense per-node dirty/paint heat slot indexed by `NodeId::index()` (16 B `Copy` POD).
17#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
18pub struct NodeHeat {
19    pub generation: u8,
20    pub last_kind: u8,
21    pub ttl_frames: u8,
22    /// Bitmask of [`NODE_HEAT_OCCUPIED`] | [`NODE_HEAT_FLASHING`].
23    pub flags: u8,
24    pub dirty_commits: u32,
25    pub paint_reemits: u32,
26    pub layout_commits: u32,
27}
28
29impl NodeHeat {
30    #[inline]
31    pub const fn is_occupied(self) -> bool {
32        (self.flags & NODE_HEAT_OCCUPIED) != 0
33    }
34
35    #[inline]
36    pub const fn is_flashing(self) -> bool {
37        (self.flags & NODE_HEAT_FLASHING) != 0
38    }
39}
40
41const _: () = assert!(core::mem::size_of::<NodeHeat>() == 16);
42
43/// Zero-steady-state-allocation per-node dirty & paint-flash tracker.
44#[derive(Debug, Clone)]
45pub struct InspectorHeatTracker {
46    heat: Vec<NodeHeat>,
47    active_flashes: Vec<NodeId>,
48    total_commits: u64,
49    last_commit_dirty_count: u32,
50    last_commit_paint_count: u32,
51    last_commit_kind: u8,
52}
53
54impl Default for InspectorHeatTracker {
55    fn default() -> Self {
56        Self::new()
57    }
58}
59
60impl InspectorHeatTracker {
61    pub fn new() -> Self {
62        Self {
63            heat: Vec::new(),
64            active_flashes: Vec::new(),
65            total_commits: 0,
66            last_commit_dirty_count: 0,
67            last_commit_paint_count: 0,
68            last_commit_kind: SceneDirtyKind::None.as_u8(),
69        }
70    }
71
72    #[inline]
73    pub fn ensure_capacity(&mut self, store_cap: usize) {
74        if self.heat.len() < store_cap {
75            self.heat.resize(store_cap, NodeHeat::default());
76        }
77        if self.active_flashes.capacity() < MAX_FLASH_RECTS {
78            let need = MAX_FLASH_RECTS.saturating_sub(self.active_flashes.len());
79            self.active_flashes.reserve_exact(need);
80        }
81    }
82
83    #[inline]
84    pub fn begin_commit(&mut self, store_cap: usize, kind: SceneDirtyKind) {
85        self.ensure_capacity(store_cap);
86        self.total_commits = self.total_commits.wrapping_add(1);
87        self.last_commit_dirty_count = 0;
88        self.last_commit_paint_count = 0;
89        self.last_commit_kind = kind.as_u8();
90    }
91
92    #[inline]
93    pub fn set_last_commit_kind(&mut self, kind: SceneDirtyKind) {
94        self.last_commit_kind = kind.as_u8();
95    }
96
97    fn slot_mut_for(&mut self, id: NodeId) -> Option<&mut NodeHeat> {
98        if id.is_null() {
99            return None;
100        }
101        let idx = id.index();
102        if idx >= self.heat.len() {
103            self.heat.resize(idx + 1, NodeHeat::default());
104        }
105        let slot = &mut self.heat[idx];
106        if !slot.is_occupied() || slot.generation != id.generation() {
107            let was_active = slot.is_occupied() && slot.is_flashing();
108            *slot = NodeHeat {
109                generation: id.generation(),
110                flags: NODE_HEAT_OCCUPIED | if was_active { NODE_HEAT_FLASHING } else { 0 },
111                ..NodeHeat::default()
112            };
113            if was_active {
114                if let Some(entry) = self.active_flashes.iter_mut().find(|n| n.index() == idx) {
115                    *entry = id;
116                } else {
117                    slot.flags &= !NODE_HEAT_FLASHING;
118                }
119            }
120        }
121        Some(slot)
122    }
123
124    #[inline]
125    fn activate_flash(&mut self, id: NodeId, kind: u8) {
126        let idx = id.index();
127        if self.heat[idx].is_flashing() {
128            self.heat[idx].last_kind = self.heat[idx].last_kind.max(kind);
129            self.heat[idx].ttl_frames = DEFAULT_FLASH_TTL;
130            return;
131        }
132        self.heat[idx].last_kind = kind;
133        if self.active_flashes.len() < MAX_FLASH_RECTS {
134            if self.active_flashes.capacity() < MAX_FLASH_RECTS {
135                let need = MAX_FLASH_RECTS.saturating_sub(self.active_flashes.len());
136                self.active_flashes.reserve_exact(need);
137            }
138            self.heat[idx].flags |= NODE_HEAT_FLASHING;
139            self.heat[idx].ttl_frames = DEFAULT_FLASH_TTL;
140            self.active_flashes.push(id);
141        }
142    }
143
144    /// Records a commit touching/creating `id` with `kind`.
145    #[inline]
146    pub fn record_dirty(&mut self, id: NodeId, kind: SceneDirtyKind) {
147        let k = kind.as_u8();
148        let Some(slot) = self.slot_mut_for(id) else {
149            return;
150        };
151        slot.dirty_commits = slot.dirty_commits.saturating_add(1);
152        if kind == SceneDirtyKind::LayoutOrTree {
153            slot.layout_commits = slot.layout_commits.saturating_add(1);
154        }
155        self.last_commit_dirty_count = self.last_commit_dirty_count.saturating_add(1);
156        if k != SceneDirtyKind::None.as_u8() {
157            self.activate_flash(id, k);
158        }
159    }
160
161    /// Records a paint chunk / DOM style re-emission for `id`.
162    #[inline]
163    pub fn record_paint_reemit(&mut self, id: NodeId, kind: SceneDirtyKind) {
164        let k = kind.as_u8();
165        let Some(slot) = self.slot_mut_for(id) else {
166            return;
167        };
168        slot.paint_reemits = slot.paint_reemits.saturating_add(1);
169        self.last_commit_paint_count = self.last_commit_paint_count.saturating_add(1);
170        if k != SceneDirtyKind::None.as_u8() {
171            self.activate_flash(id, k);
172        }
173    }
174
175    /// Retires heat and flash state for a removed node.
176    #[inline]
177    pub fn record_removed(&mut self, id: NodeId) {
178        let idx = id.index();
179        if let Some(slot) = self.heat.get_mut(idx)
180            && slot.is_occupied()
181            && slot.generation == id.generation()
182        {
183            let was_active = slot.is_flashing();
184            *slot = NodeHeat::default();
185            if was_active
186                && let Some(pos) = self.active_flashes.iter().position(|n| n.index() == idx)
187            {
188                self.active_flashes.swap_remove(pos);
189            }
190        }
191    }
192
193    /// Decays every active flash by 1 frame, retiring settled entries in O(active) with 0 allocs.
194    /// Returns `true` while at least one flash remains visible.
195    pub fn decay_frame(&mut self) -> bool {
196        let mut i = 0;
197        while i < self.active_flashes.len() {
198            let id = self.active_flashes[i];
199            let idx = id.index();
200            let keep = if let Some(slot) = self.heat.get_mut(idx)
201                && slot.is_occupied()
202                && slot.generation == id.generation()
203                && slot.ttl_frames > 1
204            {
205                slot.ttl_frames -= 1;
206                true
207            } else {
208                if let Some(slot) = self.heat.get_mut(idx)
209                    && slot.is_occupied()
210                    && slot.generation == id.generation()
211                {
212                    slot.ttl_frames = 0;
213                    slot.flags &= !NODE_HEAT_FLASHING;
214                }
215                false
216            };
217            if keep {
218                i += 1;
219            } else {
220                self.active_flashes.swap_remove(i);
221            }
222        }
223        !self.active_flashes.is_empty()
224    }
225
226    /// Retires every active flash immediately while preserving cumulative dirty/paint counters.
227    /// Used by DOM/CSS-transition backends whose flash fade-out runs in the browser compositor.
228    pub fn clear_active_flashes(&mut self) {
229        for id in self.active_flashes.drain(..) {
230            if let Some(slot) = self.heat.get_mut(id.index())
231                && slot.is_occupied()
232                && slot.generation == id.generation()
233            {
234                slot.ttl_frames = 0;
235                slot.flags &= !NODE_HEAT_FLASHING;
236            }
237        }
238    }
239
240    #[inline]
241    pub fn needs_next_frame(&self) -> bool {
242        !self.active_flashes.is_empty()
243    }
244
245    #[inline]
246    pub fn heat_of(&self, id: NodeId) -> Option<NodeHeat> {
247        let slot = self.heat.get(id.index()).copied()?;
248        (slot.is_occupied() && slot.generation == id.generation()).then_some(slot)
249    }
250
251    #[inline]
252    pub fn active_flashes(&self) -> &[NodeId] {
253        &self.active_flashes
254    }
255
256    #[inline]
257    pub fn total_commits(&self) -> u64 {
258        self.total_commits
259    }
260
261    #[inline]
262    pub fn last_commit_dirty_count(&self) -> u32 {
263        self.last_commit_dirty_count
264    }
265
266    #[inline]
267    pub fn last_commit_paint_count(&self) -> u32 {
268        self.last_commit_paint_count
269    }
270
271    #[inline]
272    pub fn last_commit_kind(&self) -> SceneDirtyKind {
273        SceneDirtyKind::from_u8(self.last_commit_kind)
274    }
275
276    pub fn clear(&mut self) {
277        self.heat.clear();
278        self.active_flashes.clear();
279        self.total_commits = 0;
280        self.last_commit_dirty_count = 0;
281        self.last_commit_paint_count = 0;
282        self.last_commit_kind = SceneDirtyKind::None.as_u8();
283    }
284}