Skip to main content

strata_render/
kinetic_scroll.rs

1//! Kinetic Momentum Scrolling, Touch Physics, Rubber-Banding, and Scrollbar Geometry.
2//!
3//! Provides a 120 FPS inertial physics simulation with exponential velocity decay,
4//! critically damped overscroll spring recovery, and draggable scrollbar state machines.
5
6use strata_layout::Rect;
7
8/// Deceleration constant $\lambda$ for exponential velocity decay ($v(t) = v_0 e^{-\lambda t}$).
9pub const DEFAULT_FRICTION: f32 = 4.2;
10
11/// Velocity cutoff threshold in pixels per second.
12pub const REST_VELOCITY_THRESHOLD: f32 = 0.5;
13
14/// Maximum rubber-band displacement limit in pixels.
15pub const RUBBER_BAND_MAX_LIMIT: f32 = 120.0;
16
17/// Damped harmonic spring stiffness coefficient for boundary snapback.
18pub const SPRING_STIFFNESS: f32 = 280.0;
19
20/// Damped harmonic spring damping coefficient (critically damped: $2 \sqrt{k \cdot m}$).
21pub const SPRING_DAMPING: f32 = 33.5;
22
23/// State machine for a single 1D scrolling dimension (horizontal or vertical).
24#[derive(Debug, Clone, PartialEq)]
25pub struct ScrollAxis {
26    pub offset: f32,
27    pub velocity: f32,
28    pub content_size: f32,
29    pub viewport_size: f32,
30    pub is_dragging: bool,
31    pub is_coasting: bool,
32    pub is_bouncing_back: bool,
33}
34
35impl ScrollAxis {
36    pub fn new(viewport_size: f32, content_size: f32) -> Self {
37        Self {
38            offset: 0.0,
39            velocity: 0.0,
40            content_size: content_size.max(0.0),
41            viewport_size: viewport_size.max(0.0),
42            is_dragging: false,
43            is_coasting: false,
44            is_bouncing_back: false,
45        }
46    }
47
48    #[inline]
49    pub fn max_scroll(&self) -> f32 {
50        (self.content_size - self.viewport_size).max(0.0)
51    }
52
53    #[inline]
54    pub fn can_scroll(&self) -> bool {
55        self.content_size > self.viewport_size
56    }
57
58    #[inline]
59    pub fn scroll_ratio(&self) -> f32 {
60        let max = self.max_scroll();
61        if max <= 0.0 {
62            0.0
63        } else {
64            (self.offset / max).clamp(0.0, 1.0)
65        }
66    }
67
68    /// Handles pointer drag movement with rubber-band tension scaling when past boundaries.
69    pub fn handle_drag_delta(&mut self, delta: f32) {
70        self.is_dragging = true;
71        self.is_coasting = false;
72        self.is_bouncing_back = false;
73
74        let max = self.max_scroll();
75
76        if self.offset < 0.0 && delta < 0.0 {
77            // Already overscrolled at top and continuing to drag past top
78            let overscroll = -self.offset;
79            let resistance = (1.0 - (overscroll / RUBBER_BAND_MAX_LIMIT).min(0.95)).max(0.05);
80            self.offset += delta * resistance;
81        } else if self.offset > max && delta > 0.0 {
82            // Already overscrolled at bottom and continuing to drag past bottom
83            let overscroll = self.offset - max;
84            let resistance = (1.0 - (overscroll / RUBBER_BAND_MAX_LIMIT).min(0.95)).max(0.05);
85            self.offset += delta * resistance;
86        } else {
87            // Moving towards boundary or within valid range
88            let target = self.offset + delta;
89            if target < 0.0 {
90                let overscroll = -target;
91                let resistance = (1.0 - (overscroll / RUBBER_BAND_MAX_LIMIT).min(0.95)).max(0.05);
92                self.offset = -overscroll * resistance;
93            } else if target > max {
94                let overscroll = target - max;
95                let resistance = (1.0 - (overscroll / RUBBER_BAND_MAX_LIMIT).min(0.95)).max(0.05);
96                self.offset = max + overscroll * resistance;
97            } else {
98                self.offset = target;
99            }
100        }
101    }
102
103    /// Applies an instantaneous fling or wheel impulse.
104    pub fn apply_impulse(&mut self, delta_velocity: f32) {
105        self.velocity += delta_velocity;
106        self.is_coasting = true;
107        self.is_bouncing_back = false;
108    }
109
110    /// Initiates drag tracking.
111    pub fn start_drag(&mut self) {
112        self.is_dragging = true;
113        self.is_coasting = false;
114        self.is_bouncing_back = false;
115        self.velocity = 0.0;
116    }
117
118    /// Terminates pointer dragging, transitioning to overscroll spring or inertial coasting.
119    pub fn end_drag(&mut self, release_velocity: f32) {
120        self.is_dragging = false;
121        let max = self.max_scroll();
122
123        if self.offset < 0.0 || self.offset > max {
124            self.is_bouncing_back = true;
125            self.is_coasting = false;
126            self.velocity = release_velocity;
127        } else if release_velocity.abs() > REST_VELOCITY_THRESHOLD {
128            self.is_coasting = true;
129            self.is_bouncing_back = false;
130            self.velocity = release_velocity;
131        } else {
132            self.is_coasting = false;
133            self.is_bouncing_back = false;
134            self.velocity = 0.0;
135        }
136    }
137
138    /// Integrates physics simulation by delta time `dt` in seconds.
139    pub fn tick(&mut self, dt: f32) {
140        if self.is_dragging {
141            return;
142        }
143
144        let max = self.max_scroll();
145
146        if self.is_bouncing_back {
147            let target = if self.offset < 0.0 { 0.0 } else { max };
148            let displacement = self.offset - target;
149
150            // Damped harmonic oscillator: F = -k * x - c * v
151            let spring_force = -SPRING_STIFFNESS * displacement;
152            let damping_force = -SPRING_DAMPING * self.velocity;
153            let acceleration = spring_force + damping_force;
154
155            self.velocity += acceleration * dt;
156            self.offset += self.velocity * dt;
157
158            // Rest condition
159            if displacement.abs() < 0.25 && self.velocity.abs() < 1.0 {
160                self.offset = target;
161                self.velocity = 0.0;
162                self.is_bouncing_back = false;
163            }
164        } else if self.is_coasting {
165            self.offset += self.velocity * dt;
166
167            // Exponential velocity friction decay: v(t) = v0 * exp(-lambda * dt)
168            let decay = (-DEFAULT_FRICTION * dt).exp();
169            self.velocity *= decay;
170
171            // Boundary overshoot triggers snapback
172            if self.offset < 0.0 || self.offset > max {
173                self.is_coasting = false;
174                self.is_bouncing_back = true;
175            } else if self.velocity.abs() < REST_VELOCITY_THRESHOLD {
176                self.velocity = 0.0;
177                self.is_coasting = false;
178            }
179        }
180    }
181
182    #[inline]
183    pub fn is_animating(&self) -> bool {
184        self.is_coasting || self.is_bouncing_back
185    }
186}
187
188/// Interactive 2D Kinetic Momentum Scroll Controller.
189#[derive(Debug, Clone, PartialEq)]
190pub struct KineticScrollController {
191    pub x: ScrollAxis,
192    pub y: ScrollAxis,
193    pub last_interaction_time: f32,
194    pub scrollbar_fade_delay: f32,
195    pub scrollbar_fade_duration: f32,
196}
197
198impl KineticScrollController {
199    pub fn new(
200        viewport_width: f32,
201        viewport_height: f32,
202        content_width: f32,
203        content_height: f32,
204    ) -> Self {
205        Self {
206            x: ScrollAxis::new(viewport_width, content_width),
207            y: ScrollAxis::new(viewport_height, content_height),
208            last_interaction_time: 0.0,
209            scrollbar_fade_delay: 1.2,
210            scrollbar_fade_duration: 0.35,
211        }
212    }
213
214    pub fn update_dimensions(
215        &mut self,
216        viewport_width: f32,
217        viewport_height: f32,
218        content_width: f32,
219        content_height: f32,
220    ) {
221        self.x.viewport_size = viewport_width.max(0.0);
222        self.x.content_size = content_width.max(0.0);
223        self.y.viewport_size = viewport_height.max(0.0);
224        self.y.content_size = content_height.max(0.0);
225    }
226
227    #[inline]
228    pub fn scroll_offset(&self) -> (f32, f32) {
229        (self.x.offset, self.y.offset)
230    }
231
232    #[inline]
233    pub fn set_scroll_offset(&mut self, x: f32, y: f32) {
234        self.x.offset = x;
235        self.y.offset = y;
236        self.x.velocity = 0.0;
237        self.y.velocity = 0.0;
238        self.x.is_coasting = false;
239        self.y.is_coasting = false;
240        self.x.is_bouncing_back = false;
241        self.y.is_bouncing_back = false;
242    }
243
244    /// Handles pointer/touch drag start.
245    pub fn on_pointer_down(&mut self, current_time: f32) {
246        self.last_interaction_time = current_time;
247        self.x.start_drag();
248        self.y.start_drag();
249    }
250
251    /// Handles pointer/touch drag movement.
252    pub fn on_pointer_move(&mut self, dx: f32, dy: f32, current_time: f32) {
253        self.last_interaction_time = current_time;
254        self.x.handle_drag_delta(dx);
255        self.y.handle_drag_delta(dy);
256    }
257
258    /// Handles pointer/touch release with initial fling velocity (pixels/second).
259    pub fn on_pointer_up(&mut self, vx: f32, vy: f32, current_time: f32) {
260        self.last_interaction_time = current_time;
261        self.x.end_drag(vx);
262        self.y.end_drag(vy);
263    }
264
265    /// Handles wheel event delta.
266    pub fn on_wheel(&mut self, dx: f32, dy: f32, current_time: f32) {
267        self.last_interaction_time = current_time;
268        if dx.abs() > 0.0 {
269            self.x.apply_impulse(dx * 12.0);
270        }
271        if dy.abs() > 0.0 {
272            self.y.apply_impulse(dy * 12.0);
273        }
274    }
275
276    /// Advances simulation by time step `dt` (in seconds).
277    pub fn tick(&mut self, dt: f32) {
278        self.x.tick(dt);
279        self.y.tick(dt);
280    }
281
282    #[inline]
283    pub fn is_animating(&self) -> bool {
284        self.x.is_animating() || self.y.is_animating()
285    }
286
287    /// Calculates scrollbar opacity [0.0, 1.0] with auto-fadeout after inactivity.
288    pub fn scrollbar_opacity(&self, current_time: f32) -> f32 {
289        if self.x.is_dragging || self.y.is_dragging || self.is_animating() {
290            return 1.0;
291        }
292
293        let elapsed = current_time - self.last_interaction_time;
294        if elapsed < self.scrollbar_fade_delay {
295            1.0
296        } else {
297            let fade_elapsed = elapsed - self.scrollbar_fade_delay;
298            (1.0 - (fade_elapsed / self.scrollbar_fade_duration)).clamp(0.0, 1.0)
299        }
300    }
301
302    /// Computes the vertical scrollbar track and thumb bounding boxes.
303    pub fn vertical_scrollbar_geometry(
304        &self,
305        track_width: f32,
306        margin: f32,
307    ) -> Option<(Rect, Rect)> {
308        if !self.y.can_scroll() {
309            return None;
310        }
311
312        let vw = self.x.viewport_size;
313        let vh = self.y.viewport_size;
314        let ch = self.y.content_size;
315
316        let track_rect = Rect::new(
317            vw - track_width - margin,
318            margin,
319            track_width,
320            vh - margin * 2.0,
321        );
322        let min_thumb_len = 24.0f32;
323        let thumb_height = ((vh / ch) * track_rect.height)
324            .max(min_thumb_len)
325            .min(track_rect.height);
326        let available_travel = track_rect.height - thumb_height;
327        let thumb_y = track_rect.y + self.y.scroll_ratio() * available_travel;
328
329        let thumb_rect = Rect::new(track_rect.x, thumb_y, track_width, thumb_height);
330        Some((track_rect, thumb_rect))
331    }
332
333    /// Computes the horizontal scrollbar track and thumb bounding boxes.
334    pub fn horizontal_scrollbar_geometry(
335        &self,
336        track_height: f32,
337        margin: f32,
338    ) -> Option<(Rect, Rect)> {
339        if !self.x.can_scroll() {
340            return None;
341        }
342
343        let vw = self.x.viewport_size;
344        let vh = self.y.viewport_size;
345        let cw = self.x.content_size;
346
347        let track_rect = Rect::new(
348            margin,
349            vh - track_height - margin,
350            vw - margin * 2.0,
351            track_height,
352        );
353        let min_thumb_len = 24.0f32;
354        let thumb_width = ((vw / cw) * track_rect.width)
355            .max(min_thumb_len)
356            .min(track_rect.width);
357        let available_travel = track_rect.width - thumb_width;
358        let thumb_x = track_rect.x + self.x.scroll_ratio() * available_travel;
359
360        let thumb_rect = Rect::new(thumb_x, track_rect.y, thumb_width, track_height);
361        Some((track_rect, thumb_rect))
362    }
363}
364
365#[cfg(test)]
366mod tests {
367    use super::*;
368
369    #[test]
370    fn test_scroll_axis_basic_drag() {
371        let mut axis = ScrollAxis::new(500.0, 2000.0);
372        assert_eq!(axis.max_scroll(), 1500.0);
373        assert_eq!(axis.offset, 0.0);
374
375        // Drag downwards (content moves up)
376        axis.handle_drag_delta(200.0);
377        assert_eq!(axis.offset, 200.0);
378        assert_eq!(axis.scroll_ratio(), 200.0 / 1500.0);
379
380        // Drag past top boundary -> rubber-band resistance
381        axis.handle_drag_delta(-300.0);
382        assert!(axis.offset < 0.0);
383        assert!(
384            axis.offset > -100.0,
385            "Rubber banding must resist: {}",
386            axis.offset
387        );
388    }
389
390    #[test]
391    fn test_scroll_axis_inertia_decay() {
392        let mut axis = ScrollAxis::new(500.0, 2000.0);
393        axis.offset = 100.0;
394        axis.end_drag(1000.0); // 1000 px/sec downwards fling
395
396        assert!(axis.is_coasting);
397        assert!(!axis.is_bouncing_back);
398
399        // Step 16ms (60 FPS tick)
400        axis.tick(0.016);
401        assert!(axis.offset > 100.0);
402        assert!(axis.velocity.abs() < 1000.0);
403
404        // Step for 2 seconds -> should come to complete rest
405        for _ in 0..120 {
406            axis.tick(0.016);
407        }
408        assert!(!axis.is_coasting);
409        assert_eq!(axis.velocity, 0.0);
410    }
411
412    #[test]
413    fn test_scroll_axis_overscroll_spring_bounce() {
414        let mut axis = ScrollAxis::new(500.0, 2000.0);
415        axis.offset = -60.0; // Overscrolled 60px past top
416        axis.end_drag(0.0);
417
418        assert!(axis.is_bouncing_back);
419
420        // Step harmonic oscillator to rest
421        for _ in 0..100 {
422            axis.tick(0.016);
423        }
424
425        assert_eq!(axis.offset, 0.0);
426        assert!(!axis.is_bouncing_back);
427    }
428
429    #[test]
430    fn test_scrollbar_geometry_calculation() {
431        let mut controller = KineticScrollController::new(800.0, 600.0, 800.0, 2400.0);
432        controller.set_scroll_offset(0.0, 900.0); // 50% through 1800px max scroll
433
434        let (track, thumb) = controller.vertical_scrollbar_geometry(8.0, 4.0).unwrap();
435        assert_eq!(track.x, 800.0 - 8.0 - 4.0);
436        assert_eq!(thumb.width, 8.0);
437        assert!(thumb.height >= 24.0);
438
439        // Thumb should be roughly centered on the track
440        let track_mid = track.y + track.height * 0.5;
441        let thumb_mid = thumb.y + thumb.height * 0.5;
442        assert!((track_mid - thumb_mid).abs() < 5.0);
443    }
444}