Skip to main content

nativeview_scroll_physics/pool/
mod.rs

1//! Reusable zero-allocation fixed-cap active pool ([`PooledScrollPhysics<B>`]) tracking only
2//! currently animating/stretched `Scroll` containers (`0 B` on idle containers).
3
4mod engine_impl;
5
6use nativeview_layout::{
7    MAX_TREE_DEPTH, ScrollBoundsLookup, ScrollContainerCtx, ScrollInputKind, ScrollOffsets,
8    ScrollTimestampMs, ScrollTouchPhase, scroll_axes_allow,
9};
10use nativeview_store::{NodeId, NodeStore, NvTable};
11use nativeview_tables::tables::{OverscrollBehavior, Scroll};
12
13use crate::axis::{ActiveScrollAxis, AxisPhase};
14use crate::behavior::ScrollBehavior;
15use nativeview_layout::push_unique_node;
16
17use crate::resolve::{resolve_bounce, resolve_decay, resolve_smooth_wheel, resolve_spring};
18use crate::table::ScrollPhysics;
19
20/// Upper bound on concurrently active/stretched scroll containers tracked in [`PooledScrollPhysics`].
21pub const MAX_ACTIVE_SCROLL_ENTRIES: usize = 16;
22
23/// Active scroll physics record for one animated/stretched `Scroll` container (`Copy`, 0 heap).
24#[derive(Debug, Clone, Copy, Default)]
25pub struct ActiveScrollEntry {
26    pub node: NodeId,
27    pub x: ActiveScrollAxis,
28    pub y: ActiveScrollAxis,
29}
30
31impl ActiveScrollEntry {
32    #[inline]
33    pub(super) fn new(node: NodeId, x_pos: f32, y_pos: f32, now_ms: ScrollTimestampMs) -> Self {
34        let x = ActiveScrollAxis {
35            pos: x_pos,
36            target: x_pos,
37            last_input_ms: now_ms,
38            ..Default::default()
39        };
40        let y = ActiveScrollAxis {
41            pos: y_pos,
42            target: y_pos,
43            last_input_ms: now_ms,
44            ..Default::default()
45        };
46        Self { node, x, y }
47    }
48
49    #[inline]
50    pub(super) fn last_activity_ms(&self) -> ScrollTimestampMs {
51        self.x.last_input_ms.max(self.y.last_input_ms)
52    }
53
54    #[inline]
55    pub(super) fn axis_mut(&mut self, is_y: bool) -> &mut ActiveScrollAxis {
56        if is_y { &mut self.y } else { &mut self.x }
57    }
58
59    #[inline]
60    pub(super) fn is_idle(&self) -> bool {
61        self.x.is_idle() && self.y.is_idle()
62    }
63
64    #[inline]
65    pub(super) fn is_animating(&self) -> bool {
66        self.x.phase.is_animating() || self.y.phase.is_animating()
67    }
68}
69
70#[derive(Debug, Clone, Copy, Default)]
71pub(super) struct GestureLatch {
72    pub(super) target: NodeId,
73    pub(super) active_phase: bool,
74    pub(super) last_event_ms: ScrollTimestampMs,
75}
76
77/// Sparse, zero-allocation active scroll physics engine parameterized by any [`ScrollBehavior`].
78///
79/// Tracks at most [`MAX_ACTIVE_SCROLL_ENTRIES`] concurrently animating/stretched containers
80/// (`0 B` on idle containers), reads per-container [`ScrollPhysics`] sparse table overrides in
81/// `O(1)` (`CountingAlloc == 0`), and enforces macOS native-momentum rules by default.
82#[repr(transparent)]
83#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
84pub(super) struct PoolEntryLen(pub(super) usize);
85
86#[derive(Debug, Clone)]
87pub struct PooledScrollPhysics<B: ScrollBehavior> {
88    pub(super) behavior: B,
89    pub(super) entries: [ActiveScrollEntry; MAX_ACTIVE_SCROLL_ENTRIES],
90    pub(super) entry_len: PoolEntryLen,
91    pub(super) latch: GestureLatch,
92    pub(super) reduced_motion: bool,
93    pub(super) synthetic_momentum: bool,
94}
95
96impl<B: ScrollBehavior + Default> Default for PooledScrollPhysics<B> {
97    fn default() -> Self {
98        Self::new(B::default())
99    }
100}
101
102impl<B: ScrollBehavior> PooledScrollPhysics<B> {
103    pub fn new(behavior: B) -> Self {
104        // Initialize `nv.scroll_physics` slot metadata outside hot paths so steady-state
105        // `store.try_row::<ScrollPhysics>(node)` calls perform 0 allocations.
106        let _ = ScrollPhysics::slot();
107        Self {
108            behavior,
109            entries: [ActiveScrollEntry::default(); MAX_ACTIVE_SCROLL_ENTRIES],
110            entry_len: PoolEntryLen(0),
111            latch: GestureLatch::default(),
112            reduced_motion: false,
113            // CRITICAL macOS rule: AppKit already delivers native OS momentum via winit PixelDelta
114            // + TouchPhase (and collapses Cancelled into Ended). Never spawn synthetic Momentum
115            // from PixelDelta on macOS by default.
116            synthetic_momentum: cfg!(not(target_os = "macos")),
117        }
118    }
119
120    #[inline]
121    pub fn behavior(&self) -> &B {
122        &self.behavior
123    }
124
125    #[inline]
126    pub fn behavior_mut(&mut self) -> &mut B {
127        &mut self.behavior
128    }
129
130    #[inline]
131    pub fn reduced_motion(&self) -> bool {
132        self.reduced_motion
133    }
134
135    #[inline]
136    pub fn synthetic_momentum(&self) -> bool {
137        self.synthetic_momentum
138    }
139
140    #[inline]
141    pub fn active_count(&self) -> usize {
142        self.entry_len.0
143    }
144
145    #[inline]
146    pub(super) fn active_entries(&self) -> &[ActiveScrollEntry] {
147        &self.entries[..self.entry_len.0]
148    }
149
150    #[inline]
151    pub(super) fn swap_remove_entry(&mut self, idx: usize) {
152        debug_assert!(idx < self.entry_len.0);
153        self.entry_len.0 -= 1;
154        if idx < self.entry_len.0 {
155            self.entries[idx] = self.entries[self.entry_len.0];
156        }
157        self.entries[self.entry_len.0] = ActiveScrollEntry::default();
158    }
159
160    #[inline]
161    pub fn entry(&self, id: NodeId) -> Option<&ActiveScrollEntry> {
162        self.active_entries().iter().find(|e| e.node == id)
163    }
164
165    #[inline]
166    pub(super) fn entry_idx(&self, id: NodeId) -> Option<usize> {
167        self.active_entries().iter().position(|e| e.node == id)
168    }
169
170    pub(super) fn get_or_insert_idx(
171        &mut self,
172        id: NodeId,
173        x_pos: f32,
174        y_pos: f32,
175        now_ms: ScrollTimestampMs,
176    ) -> usize {
177        if let Some(idx) = self.entry_idx(id) {
178            return idx;
179        }
180        if self.entry_len.0 >= MAX_ACTIVE_SCROLL_ENTRIES {
181            let mut evict_idx = 0usize;
182            for i in 1..self.entry_len.0 {
183                let e = &self.entries[i];
184                let best = &self.entries[evict_idx];
185                let prefer = (!e.is_animating() && best.is_animating())
186                    || (e.is_animating() == best.is_animating()
187                        && e.last_activity_ms() < best.last_activity_ms());
188                if prefer {
189                    evict_idx = i;
190                }
191            }
192            self.entries[evict_idx] = ActiveScrollEntry::new(id, x_pos, y_pos, now_ms);
193            return evict_idx;
194        }
195        let idx = self.entry_len.0;
196        self.entries[idx] = ActiveScrollEntry::new(id, x_pos, y_pos, now_ms);
197        self.entry_len.0 += 1;
198        idx
199    }
200
201    #[inline]
202    pub(super) fn prune_idle(&mut self) {
203        let mut i = 0;
204        while i < self.entry_len.0 {
205            if self.entries[i].is_idle() {
206                self.swap_remove_entry(i);
207            } else {
208                i += 1;
209            }
210        }
211    }
212
213    #[inline]
214    pub(super) fn seed_ms(
215        &self,
216        is_phased_drag: bool,
217        now_ms: ScrollTimestampMs,
218    ) -> ScrollTimestampMs {
219        if is_phased_drag && self.latch.active_phase && self.latch.last_event_ms.as_u64() > 0 {
220            self.latch.last_event_ms
221        } else {
222            now_ms
223        }
224    }
225
226    #[allow(clippy::too_many_arguments)]
227    pub(super) fn apply_axis_delta(
228        &mut self,
229        ctx: &ScrollContainerCtx<'_>,
230        is_y: bool,
231        kind: ScrollInputKind,
232        rem: &mut f32,
233        other_cur: f32,
234        next_pos: &mut f32,
235        consumed: &mut bool,
236        visual_changed: &mut bool,
237        clamped_changed: &mut bool,
238        auto_overscroll: &mut bool,
239    ) {
240        if !rem.is_finite() {
241            *rem = 0.0;
242            return;
243        }
244        if rem.abs() <= 1e-4 {
245            return;
246        }
247        let (allow, ob, cur, max, viewport) = if is_y {
248            (
249                ctx.allow_axes.1,
250                ctx.overscroll_behavior.1,
251                ctx.offset.1,
252                ctx.max_offset.1,
253                ctx.viewport.1,
254            )
255        } else {
256            (
257                ctx.allow_axes.0,
258                ctx.overscroll_behavior.0,
259                ctx.offset.0,
260                ctx.max_offset.0,
261                ctx.viewport.0,
262            )
263        };
264        let bounce = resolve_bounce(&self.behavior, ctx.store, ctx.node, ctx.bounce_requested, ob);
265        let smooth_wheel = matches!(kind, ScrollInputKind::DiscreteLines)
266            && resolve_smooth_wheel(&self.behavior, ctx.store, ctx.node, self.reduced_motion)
267                .is_some();
268        let (is_smooth_px, touch_phase, now_ms) = match kind {
269            ScrollInputKind::SmoothPixels {
270                phase,
271                timestamp_ms,
272            } => (true, phase, ScrollTimestampMs::new(timestamp_ms)),
273            _ => (false, ScrollTouchPhase::None, ScrollTimestampMs::new(0)),
274        };
275        let is_phased_drag = is_smooth_px && touch_phase != ScrollTouchPhase::None;
276        let seed_ms = self.seed_ms(is_phased_drag, now_ms);
277
278        if let Some(idx) = self.entry_idx(ctx.node) {
279            let ax = self.entries[idx].axis_mut(is_y);
280            ax.sync_bounds(cur, max, viewport, bounce, ob);
281            let dt_ms = now_ms.saturating_sub(ax.last_input_ms);
282            let (unwound, left) = ax.unwind_overscroll(*rem, is_phased_drag, dt_ms);
283            if unwound {
284                ax.last_input_ms = now_ms;
285                *consumed = true;
286                *visual_changed = true;
287                *rem = left;
288            }
289        }
290
291        if allow && max > 0.0 && rem.abs() > 1e-4 {
292            let (init_x, init_y) = if is_y {
293                (other_cur, cur)
294            } else {
295                (cur, other_cur)
296            };
297            if smooth_wheel {
298                let idx = self.get_or_insert_idx(ctx.node, init_x, init_y, now_ms);
299                let ax = self.entries[idx].axis_mut(is_y);
300                ax.sync_bounds(cur, max, viewport, bounce, ob);
301                let base = if ax.phase == AxisPhase::SmoothWheel {
302                    ax.target
303                } else {
304                    cur
305                };
306                let used = (base + *rem).clamp(0.0, max) - base;
307                if used.abs() > 1e-4 {
308                    if ax.accumulate_smooth_wheel(cur, used) {
309                        *visual_changed = true;
310                    }
311                    *rem -= used;
312                    *consumed = true;
313                }
314            } else {
315                let used = (cur + *rem).clamp(0.0, max) - cur;
316                if used.abs() > 1e-4 {
317                    *next_pos = cur + used;
318                    *rem -= used;
319                    *consumed = true;
320                    *visual_changed = true;
321                    *clamped_changed = true;
322                    if is_phased_drag {
323                        let (nx, ny) = if is_y {
324                            (other_cur, *next_pos)
325                        } else {
326                            (*next_pos, other_cur)
327                        };
328                        let idx = self.get_or_insert_idx(ctx.node, nx, ny, seed_ms);
329                        let ax = self.entries[idx].axis_mut(is_y);
330                        let dt_ms = now_ms.saturating_sub(ax.last_input_ms);
331                        ax.sync_bounds(*next_pos, max, viewport, bounce, ob);
332                        ax.pos = *next_pos;
333                        ax.phase = AxisPhase::Dragging;
334                        ax.record_drag_velocity(used, dt_ms);
335                        ax.last_input_ms = now_ms;
336                    } else if let Some(idx) = self.entry_idx(ctx.node) {
337                        let ax = self.entries[idx].axis_mut(is_y);
338                        ax.pos = *next_pos;
339                        ax.target = *next_pos;
340                        ax.vel = 0.0;
341                        ax.phase = AxisPhase::Idle;
342                    }
343                }
344            }
345        }
346
347        if rem.abs() > 1e-4 && allow {
348            match ob {
349                OverscrollBehavior::Auto => {
350                    if is_smooth_px && max > 0.0 && bounce.is_some() {
351                        *auto_overscroll = true;
352                    }
353                }
354                OverscrollBehavior::Contain => {
355                    if is_smooth_px && max > 0.0 && bounce.is_some() {
356                        let (nx, ny) = if is_y {
357                            (other_cur, *next_pos)
358                        } else {
359                            (*next_pos, other_cur)
360                        };
361                        let idx = self.get_or_insert_idx(ctx.node, nx, ny, seed_ms);
362                        let spring = resolve_spring(&self.behavior, ctx.store, ctx.node);
363                        let ax = self.entries[idx].axis_mut(is_y);
364                        let dt_ms = now_ms.saturating_sub(ax.last_input_ms);
365                        ax.sync_bounds(*next_pos, max, viewport, bounce, ob);
366                        if ax.apply_rubber_band_drag(*rem, dt_ms) {
367                            *visual_changed = true;
368                        }
369                        ax.last_input_ms = now_ms;
370                        if !is_phased_drag {
371                            let _ = ax.finish_drag(
372                                true,
373                                false,
374                                self.reduced_motion,
375                                None,
376                                self.behavior.min_fling_velocity(),
377                                spring,
378                                |_| None,
379                                0,
380                            );
381                        }
382                    }
383                    *rem = 0.0;
384                }
385                OverscrollBehavior::None => {
386                    *rem = 0.0;
387                }
388            }
389        }
390    }
391
392    pub(super) fn find_ancestor_with_room(
393        store: &NodeStore,
394        bounds: &dyn ScrollBoundsLookup,
395        scroll: &ScrollOffsets,
396        start: NodeId,
397        is_y: bool,
398        vel: f32,
399    ) -> Option<NodeId> {
400        if bounds.is_top_layer_boundary(start) {
401            return None;
402        }
403        let mut cur = store.parent(start).filter(|&p| p != start);
404        for _ in 0..MAX_TREE_DEPTH {
405            let id = cur?;
406            if store.is_live(id)
407                && store.has::<Scroll>(id)
408                && let Some((_, _, max_x, max_y)) = bounds.scroll_bounds(store, id)
409            {
410                let (allow_x, allow_y) = scroll_axes_allow(store, id);
411                let (cx, cy) = scroll.get(id);
412                let (allow, cur_v, max_v) = if is_y {
413                    (allow_y, cy, max_y)
414                } else {
415                    (allow_x, cx, max_x)
416                };
417                if allow
418                    && max_v > 0.0
419                    && ((vel > 0.0 && cur_v < max_v - 1e-3) || (vel < 0.0 && cur_v > 1e-3))
420                {
421                    return Some(id);
422                }
423                if allow && let Some(sc) = store.try_row::<Scroll>(id) {
424                    let ob = if is_y {
425                        sc.overscroll_behavior_y()
426                    } else {
427                        sc.overscroll_behavior_x()
428                    };
429                    if ob != OverscrollBehavior::Auto {
430                        return None;
431                    }
432                }
433            }
434            if bounds.is_top_layer_boundary(id) {
435                return None;
436            }
437            cur = store.parent(id).filter(|&p| p != id);
438        }
439        None
440    }
441
442    #[allow(clippy::too_many_arguments)]
443    pub(super) fn chain_momentum_to_ancestor(
444        &mut self,
445        store: &NodeStore,
446        bounds: &dyn ScrollBoundsLookup,
447        scroll: &mut ScrollOffsets,
448        anc: NodeId,
449        is_y: bool,
450        vel: f32,
451        t_rem: f32,
452        out_visual: &mut Vec<NodeId>,
453        out_clamped: &mut Vec<NodeId>,
454    ) {
455        let Some((vw, vh, max_x, max_y)) = bounds.scroll_bounds(store, anc) else {
456            return;
457        };
458        let Some(sc) = store.try_row::<Scroll>(anc) else {
459            return;
460        };
461        let Some(decay) = resolve_decay(&self.behavior, store, anc) else {
462            return;
463        };
464        let (cx, cy) = scroll.get(anc);
465        let idx = self.get_or_insert_idx(anc, cx, cy, ScrollTimestampMs::new(0));
466        let ob = if is_y {
467            sc.overscroll_behavior_y()
468        } else {
469            sc.overscroll_behavior_x()
470        };
471        let bounce = resolve_bounce(&self.behavior, store, anc, sc.bounce(), ob);
472        let spring = resolve_spring(&self.behavior, store, anc);
473        let wheel = resolve_smooth_wheel(&self.behavior, store, anc, self.reduced_motion);
474        let min_fling = self.behavior.min_fling_velocity();
475        let max_vel = decay.max_velocity;
476        let (pos, max, vp) = if is_y {
477            (cy, max_y, vh)
478        } else {
479            (cx, max_x, vw)
480        };
481        let ax = self.entries[idx].axis_mut(is_y);
482        ax.sync_bounds(pos, max, vp, bounce, ob);
483        ax.start_momentum(pos, vel, min_fling, max_vel);
484        let (visual, clamped, _) = ax.step(t_rem, Some(decay), min_fling, spring, wheel, false);
485        let nx = self.entries[idx].x.pos;
486        let ny = self.entries[idx].y.pos;
487        if clamped {
488            scroll.set_raw(anc, nx, ny);
489            push_unique_node(out_clamped, anc);
490        }
491        if visual {
492            push_unique_node(out_visual, anc);
493        }
494    }
495}