1#[derive(Clone, Copy, Debug, Default)]
9pub struct EdgeStretch {
10 distance: f32,
11 velocity: f32,
12 pulling: bool,
13}
14
15impl EdgeStretch {
16 const NATURAL_FREQUENCY: f64 = 24.657;
18 const DAMPING_RATIO: f64 = 0.98;
19 const LINEAR_STRETCH_INTENSITY: f32 = 0.016;
20 const EXP_STRETCH_INTENSITY: f32 = 0.016;
21 const SCROLL_DIST_AFFECTED_BY_EXP_STRETCH: f32 = 0.33;
22 const LINEAR_VELOCITY_TAKE_OVER: f32 = 200.0;
23 const LINEAR_DISTANCE_TAKE_OVER: f32 = 8.0;
24 const VELOCITY_THRESHOLD: f32 = 0.01;
25 const VALUE_THRESHOLD: f32 = 0.001;
26
27 pub fn pull(&mut self, delta_dp: f32, extent_dp: f32) -> f32 {
30 let extent = extent_dp.max(120.0);
31 if delta_dp.abs() < 1e-5 {
32 return 0.0;
33 }
34 let prev = self.distance;
35 let next = (prev + delta_dp / extent).clamp(-1.0, 1.0);
36 if prev != 0.0 && prev.signum() != next.signum() && next != 0.0 {
39 self.distance = 0.0;
40 self.velocity = 0.0;
41 self.pulling = false;
42 return -prev * extent;
43 }
44 self.distance = next;
45 self.velocity = 0.0;
46 self.pulling = self.distance.abs() > 1e-5;
47 (next - prev) * extent
48 }
49
50 pub fn release(&mut self) {
52 self.pulling = false;
53 }
54
55 pub fn absorb(&mut self, impact_vel_dp_s: f32, extent_dp: f32) {
57 if impact_vel_dp_s.abs() < 100.0 {
58 return;
59 }
60 let extent = extent_dp.max(120.0);
61 self.pulling = false;
62 let v = (impact_vel_dp_s * 1.65).clamp(-8000.0, 8000.0);
64 self.velocity = v;
65 if self.distance.abs() < 1e-4 {
66 self.distance = (v * 0.002 / extent).clamp(-0.25, 0.25);
67 }
68 }
69
70 pub fn reset(&mut self) {
72 self.distance = 0.0;
73 self.velocity = 0.0;
74 self.pulling = false;
75 }
76
77 pub fn distance(&self) -> f32 {
79 self.distance
80 }
81
82 pub fn step(&mut self, dt: f32, extent_dp: f32, reduced: bool) -> bool {
84 if reduced {
85 self.reset();
86 return false;
87 }
88 if self.pulling {
89 return self.distance.abs() > 1e-4;
90 }
91 if self.distance.abs() <= 1e-5 && self.velocity.abs() <= Self::VELOCITY_THRESHOLD {
92 self.reset();
93 return false;
94 }
95 let dt = dt.clamp(0.0, 0.05);
96 if dt < 0.0005 {
97 return true;
98 }
99 let height = extent_dp.max(120.0);
100 let sign = if self.distance != 0.0 {
101 self.distance.signum()
102 } else {
103 self.velocity.signum()
104 };
105 let mut dist_pos = self.distance * sign;
106 let mut vel_pos = self.velocity * sign;
107
108 if vel_pos.abs() <= Self::LINEAR_VELOCITY_TAKE_OVER
109 && (dist_pos * height).abs() < Self::LINEAR_DISTANCE_TAKE_OVER
110 && vel_pos < 0.0
111 {
112 vel_pos = -Self::LINEAR_VELOCITY_TAKE_OVER;
113 let target = dist_pos + (vel_pos * dt / height);
114 if target <= 0.0 {
115 self.reset();
116 return false;
117 }
118 self.distance = target * sign;
119 self.velocity = vel_pos * sign;
120 return true;
121 }
122
123 let omega = Self::NATURAL_FREQUENCY;
124 let zeta = Self::DAMPING_RATIO;
125 let damped_freq = omega * (1.0 - zeta * zeta).sqrt();
126 let dt64 = f64::from(dt);
127 let h64 = f64::from(height);
128 let cos_coeff = f64::from(dist_pos) * h64;
129 let sin_coeff = (1.0 / damped_freq) * (zeta * omega * cos_coeff + f64::from(vel_pos));
130 let exp_decay = (-zeta * omega * dt64).exp();
131 let angle = damped_freq * dt64;
132 let next_disp = exp_decay * (cos_coeff * angle.cos() + sin_coeff * angle.sin());
133 let next_vel = next_disp * (-omega * zeta)
134 + exp_decay * (-damped_freq * cos_coeff * angle.sin() + damped_freq * sin_coeff * angle.cos());
135
136 dist_pos = (next_disp / h64) as f32;
137 vel_pos = next_vel as f32;
138 if dist_pos > 1.0 {
139 dist_pos = 1.0;
140 vel_pos = 0.0;
141 }
142 if dist_pos <= 0.0
144 || (vel_pos.abs() < Self::VELOCITY_THRESHOLD
145 && (dist_pos * height) < Self::VALUE_THRESHOLD)
146 {
147 self.reset();
148 return false;
149 }
150 self.distance = dist_pos * sign;
151 self.velocity = vel_pos * sign;
152 true
153 }
154
155 pub fn scale_and_sign(&self) -> (f32, f32) {
158 let overscroll = self.distance.abs().clamp(0.0, 1.0);
159 if overscroll <= 1e-5 {
160 return (1.0, 0.0);
161 }
162 let linear = Self::LINEAR_STRETCH_INTENSITY * overscroll;
163 let scalar = std::f32::consts::E / Self::SCROLL_DIST_AFFECTED_BY_EXP_STRETCH;
164 let exp_i = Self::EXP_STRETCH_INTENSITY * (1.0 - (-overscroll * scalar).exp());
165 let stretch = (1.0 + (linear + exp_i) * 4.2).clamp(1.0, 1.18);
166 (stretch, self.distance.signum())
167 }
168}
169
170#[derive(Clone, Debug, Default)]
171pub struct ScrollPhysics {
172 pub offset: f32,
173 pub dragging: bool,
174 touch: Option<(f32, f32)>,
175 sample_time: f64,
176 velocity: f32,
177 last: f64,
178 edge_velocity: f32,
179 flight: Option<(f64, f32, f32, f32)>,
180 destination: Option<f32>,
181 smooth_target: Option<(f64, f32, f32, f64)>,
182 horizontal_rtl: Option<bool>,
183 stretch: EdgeStretch,
184 last_viewport: f32,
185}
186impl ScrollPhysics {
187 pub fn begin(&mut self, y: f32, time: f64) {
188 self.cancel();
189 self.touch = Some((y, y));
190 self.sample_time = time;
191 self.last = time;
192 self.edge_velocity = 0.;
193 }
194 pub fn drag(&mut self, y: f32, time: f64, max: f32, viewport: f32) {
195 self.last_viewport = viewport.max(120.0);
196 if let Some((origin, last)) = self.touch {
197 self.dragging |= (y - origin).abs() > 6.;
198 let delta = last - y;
199 if self.dragging && delta.abs() > 0.01 {
200 let dt = (time - self.sample_time).clamp(0.001, 0.15) as f32;
201 self.velocity +=
202 ((delta / dt).clamp(-8000., 8000.) - self.velocity) * (1. - (-dt / 0.04).exp());
203 let outside = self.offset < 0. || self.offset > max;
204 if outside || (self.offset <= 0. && delta < 0.) || (self.offset >= max && delta > 0.) {
205 let _ = self.stretch.pull(-delta, self.last_viewport);
206 }
207 self.offset += delta * if outside { 0.3 } else { 1. };
208 let limit = viewport * 0.12;
209 self.offset = self.offset.clamp(-limit, max + limit);
210 self.sample_time = time;
211 } else if time - self.sample_time > 0.1 {
212 self.velocity = 0.;
213 }
214 self.touch = Some((origin, y));
215 }
216 }
217 pub(crate) fn drag_with_refresh(&mut self, y: f32, time: f64, max: f32, pull: &mut f32) {
220 if let Some((origin, last)) = self.touch {
221 self.dragging |= (y-origin).abs() > 6.0;
222 let mut delta = last-y;
223 if self.dragging && delta.abs() > 0.01 {
224 if delta > 0.0 && *pull > 0.0 {
225 let consumed=delta.min(*pull);
226 *pull-=consumed; delta-=consumed;
227 }
228 let old=self.offset.clamp(0.0,max);
229 let new=(old+delta).clamp(0.0,max);
230 if delta < 0.0 { *pull += (new-old-delta).max(0.0); }
231 self.offset=new;
232 let dt=(time-self.sample_time).clamp(0.001,0.15) as f32;
233 if *pull > 0.0 { self.velocity=0.0; }
234 else { self.velocity += (((new-old)/dt).clamp(-8000.0,8000.0)-self.velocity)*(1.0-(-dt/0.04).exp()); }
235 self.sample_time=time;
236 } else if time-self.sample_time > 0.1 { self.velocity=0.0; }
237 self.touch=Some((origin,y));
238 }
239 }
240 pub fn release(&mut self, time: f64, reduced: bool) {
241 self.stretch.release();
242 if self.touch.is_none() {
243 return;
244 }
245 self.touch = None;
246 self.dragging = false;
247 if time - self.sample_time > 0.1 || reduced {
248 self.velocity = 0.;
249 }
250 if self.velocity.abs() >= 50. {
251 let physical = 9.80665_f32 * 39.37 * 160. * 0.84;
253 let friction = 0.015 * physical;
254 let rate = 0.78_f32.ln() / 0.9_f32.ln();
255 let l = (0.35 * self.velocity.abs() / friction).ln();
256 let duration = (l / (rate - 1.)).exp();
257 let distance = friction * (rate / (rate - 1.) * l).exp() * self.velocity.signum();
258 self.flight = Some((time, self.offset, distance, duration));
259 }
260 self.last = time;
261 }
262 pub(crate) fn fling_from_velocity(&mut self, velocity:f32, time:f64, reduced:bool) {
263 self.cancel();self.touch=Some((0.0,0.0));self.sample_time=time;self.velocity=velocity.clamp(-8000.0,8000.0);self.release(time,reduced);
264 }
265 pub fn cancel(&mut self) {
266 self.touch = None;
267 self.dragging = false;
268 self.velocity = 0.;
269 self.flight = None;
270 self.destination = None;
271 self.smooth_target = None;
272 self.stretch.release();
273 }
274 pub fn scroll_to(&mut self, target: f32, max: f32, time: f64, duration_s: f64, reduced: bool) {
277 self.cancel();
278 let clamped = target.clamp(0.0, max.max(0.0));
279 if reduced || duration_s <= 0.0 || (clamped - self.offset).abs() < 0.1 {
280 self.offset = clamped;
281 self.smooth_target = None;
282 } else {
283 self.smooth_target = Some((time, self.offset, clamped, duration_s));
284 self.last = time;
285 }
286 }
287 pub fn finish_scroll_to(&mut self) {
289 if let Some((_, _, target, _)) = self.smooth_target.take() {
290 self.offset = target;
291 }
292 }
293 pub fn is_scrolling_to(&self) -> bool {
295 self.smooth_target.is_some()
296 }
297 pub fn touching(&self) -> bool {
298 self.touch.is_some()
299 }
300 pub fn edge_stretch(&self) -> (f32, f32) {
301 self.stretch.scale_and_sign()
302 }
303 pub fn wheel(&mut self, delta: f32, max: f32, reduced: bool) {
304 if delta == 0. {
305 return;
306 }
307 self.flight = None;
308 self.smooth_target = None;
309 let target = (self.destination.unwrap_or(self.offset) + delta).clamp(0., max);
310 if reduced {
311 self.offset = target;
312 self.destination = None;
313 } else {
314 self.destination = Some(target);
315 }
316 }
317 pub fn advance(&mut self, time: f64, max: f32, reduced: bool) -> bool {
318 let dt = (time - self.last).clamp(0., 0.05) as f32;
319 self.last = time;
320 let vp = self.last_viewport.max(120.0);
321 if self.touch.is_some() {
322 return self.stretch.step(dt, vp, reduced);
323 }
324 if reduced {
325 let final_target = self
326 .smooth_target
327 .map(|(_, _, t, _)| t)
328 .or(self.destination)
329 .unwrap_or(self.offset);
330 self.offset = final_target.clamp(0., max);
331 self.cancel();
332 self.stretch.reset();
333 return false;
334 }
335 if let Some((start, origin, target, duration)) = self.smooth_target {
336 let clamped = target.clamp(0.0, max.max(0.0));
337 let progress = ((time - start) / duration.max(1e-6)).clamp(0.0, 1.0) as f32;
338 let eased = crate::timing::Easing::Standard.sample(progress);
339 self.offset = origin + (clamped - origin) * eased;
340 if progress >= 1.0 {
341 self.offset = clamped;
342 self.smooth_target = None;
343 }
344 }
345 if let Some(target) = self.destination {
346 self.offset += (target - self.offset) * (1. - (-18. * dt).exp());
347 if (target - self.offset).abs() < 0.1 {
348 self.offset = target;
349 self.destination = None;
350 }
351 }
352 if let Some((start, origin, distance, duration)) = self.flight {
353 let prev = self.offset;
354 let t = ((time - start) as f32 / duration).clamp(0., 1.);
355 self.offset = origin + distance * spline(t);
356 if t >= 1. || self.offset < 0. || self.offset > max {
357 if self.offset < 0. || self.offset > max {
358 let impact_vel = if dt > 0.001 {
359 (self.offset - prev) / dt
360 } else {
361 distance / duration.max(0.05)
362 };
363 self.stretch.absorb(-impact_vel, vp);
364 }
365 self.flight = None;
366 self.offset = self.offset.clamp(-48., max + 48.);
367 }
368 }
369 let edge = self.offset.clamp(0., max);
370 if self.offset != edge {
371 let displacement = self.offset - edge;
373 let c = self.edge_velocity + 18. * displacement;
374 let decay = (-18. * dt).exp();
375 self.offset = edge + (displacement + c * dt) * decay;
376 self.edge_velocity = (self.edge_velocity - 18. * c * dt) * decay;
377 if (self.offset - edge).abs() < 0.1 {
378 self.offset = edge;
379 self.edge_velocity = 0.;
380 }
381 }
382 let stretch_active = self.stretch.step(dt, vp, reduced);
383 self.flight.is_some()
384 || self.destination.is_some()
385 || self.smooth_target.is_some()
386 || self.offset != edge
387 || stretch_active
388 }
389}
390fn spline(t: f32) -> f32 {
391 let (mut lo, mut hi) = (0., 1.);
392 for _ in 0..16 {
393 let x = (lo + hi) * 0.5;
394 let coef = 3. * x * (1. - x);
395 let tx = coef * ((1. - x) * 0.175 + x * 0.35) + x * x * x;
396 if tx < t {
397 lo = x;
398 } else {
399 hi = x;
400 }
401 }
402 let x = (lo + hi) * 0.5;
403 3. * x * (1. - x) * ((1. - x) * 0.5 + x) + x * x * x
404}
405#[cfg(test)]
406mod tests {
407 use super::*;
408 fn fling() -> ScrollPhysics {
409 let mut s = ScrollPhysics::default();
410 s.begin(500., 0.);
411 s.drag(450., 0.02, 10000., 800.);
412 s.drag(400., 0.04, 10000., 800.);
413 s.release(0.04, false);
414 s
415 }
416 #[test]
417 fn refresh_rate_does_not_change_fling_distance() {
418 let mut a = fling();
419 let mut b = a.clone();
420 for i in 1..=60 {
421 a.advance(0.04 + i as f64 / 60., 10000., false);
422 }
423 for i in 1..=120 {
424 b.advance(0.04 + i as f64 / 120., 10000., false);
425 }
426 assert!((a.offset - b.offset).abs() < 0.01);
427 }
428 #[test]
429 fn edge_returns_and_reduced_motion_stops() {
430 let mut a = ScrollPhysics::default();
431 a.begin(100., 0.);
432 a.drag(250., 0.03, 1000., 800.);
433 assert!(a.offset < 0.);
434 a.release(0.2, false);
435 for i in 1..120 {
436 a.advance(0.2 + i as f64 / 60., 1000., false);
437 }
438 assert_eq!(a.offset, 0.);
439 let mut b = fling();
440 let before = b.offset;
441 b.advance(0.1, 10000., true);
442 assert_eq!(b.offset, before);
443 }
444 #[test]
445 fn edge_stretch_pull_release_and_absorb_spring_recoil() {
446 let mut s = EdgeStretch::default();
447 assert_eq!(s.scale_and_sign(), (1.0, 0.0));
448 let consumed = s.pull(200.0, 800.0);
450 assert!((consumed - 200.0).abs() < 0.01);
451 let (sc, sign) = s.scale_and_sign();
452 assert!(sc > 1.04 && sc < 1.16 && sign > 0.0);
453 let back = s.pull(-300.0, 800.0);
455 assert!((back + 200.0).abs() < 0.01);
456 assert_eq!(s.distance(), 0.0);
457 s.pull(-250.0, 800.0);
459 assert!(s.scale_and_sign().1 < 0.0);
460 s.release();
461 for _ in 0..60 {
462 s.step(1.0 / 60.0, 800.0, false);
463 assert!(s.distance() <= 0.0, "stretch must never bounce through 0 to opposite edge");
464 }
465 assert_eq!(s.distance(), 0.0);
466 s.absorb(2400.0, 800.0);
468 assert!(s.step(1.0 / 60.0, 800.0, false));
469 assert!(s.scale_and_sign().0 > 1.005);
470 for _ in 0..90 {
471 s.step(1.0 / 60.0, 800.0, false);
472 }
473 assert_eq!(s.distance(), 0.0);
474 }
475 #[test]
476 fn scroll_to_animates_smoothly_and_respects_reduced_motion() {
477 let mut s = ScrollPhysics::default();
478 s.scroll_to(600.0, 1000.0, 1.0, 0.5, false);
479 assert!(s.is_scrolling_to());
480 assert!(s.advance(1.25, 1000.0, false));
481 assert!(s.offset > 100.0 && s.offset < 600.0);
482 assert!(!s.advance(1.55, 1000.0, false));
483 assert!((s.offset - 600.0).abs() < 0.01);
484
485 let mut r = ScrollPhysics::default();
486 r.scroll_to(1200.0, 1000.0, 0.0, 0.5, true);
487 assert!(!r.is_scrolling_to());
488 assert_eq!(r.offset, 1000.0);
489 }
490}
491
492impl crate::Frame<'_> {
493 pub fn scroll_stretch(&self, id: u64) -> (f32, f32) {
495 self.ui
496 .scrolls
497 .get(&id)
498 .map_or((1.0, 0.0), ScrollPhysics::edge_stretch)
499 }
500
501 pub fn with_edge_stretch(
505 &mut self,
506 bounds: crate::Rect,
507 horizontal: bool,
508 stretch_scale: f32,
509 edge_sign: f32,
510 build: impl FnOnce(&mut Self),
511 ) {
512 let s = stretch_scale.clamp(1.0, 1.20);
513 if s > 1.0005 && edge_sign.abs() > 0.01 {
514 let (pivot, scale) = if horizontal {
515 let px = if edge_sign > 0.0 {
516 bounds.x
517 } else {
518 bounds.x + bounds.width
519 };
520 ([px, bounds.y + bounds.height * 0.5], [s, 1.0])
521 } else {
522 let py = if edge_sign > 0.0 {
523 bounds.y
524 } else {
525 bounds.y + bounds.height
526 };
527 ([bounds.x + bounds.width * 0.5, py], [1.0, s])
528 };
529 self.push_transform(pivot, [0.0, 0.0], scale, 0.0);
530 build(self);
531 self.pop_transform();
532 } else {
533 build(self);
534 }
535 }
536
537 pub fn scroll_viewport(&mut self, id: u64, b: crate::Rect, offset: &mut f32, max: f32) -> bool {
540 self.scroll_viewport_axis(id, b, offset, max, false, false)
541 }
542
543 pub fn cancel_scroll(&mut self, id: u64) {
545 if let Some(state) = self.ui.scrolls.get_mut(&id) { state.cancel(); }
546 }
547
548 pub fn scroll_viewport_horizontal(&mut self, id: u64, b: crate::Rect, offset: &mut f32, max: f32) -> bool {
550 self.scroll_viewport_axis(id, b, offset, max, true, false)
551 }
552
553 pub fn scroll_viewport_horizontal_rtl(&mut self, id: u64, b: crate::Rect, offset: &mut f32, max: f32, rtl: bool) -> bool {
555 self.scroll_viewport_axis(id, b, offset, max, true, rtl)
556 }
557
558 fn scroll_viewport_axis(&mut self, id: u64, b: crate::Rect, offset: &mut f32, max: f32, horizontal: bool, rtl: bool) -> bool {
559 let input = self.input;
560 let inside = self.pointer_in(b);
561 let reduced = self.reduced_motion();
562 let wheel = if horizontal && inside { if input.scroll[0] != 0.0 { if rtl {-input.scroll[0]}else{input.scroll[0]} } else { input.scroll[1] } } else if horizontal { 0.0 } else { self.scroll_y(b) };
563 let state = self.ui.scrolls.entry(id).or_default();
564 if horizontal {
565 if state.horizontal_rtl.is_some_and(|previous|previous!=rtl) {
566 state.cancel();
567 *offset=offset.clamp(0.0,max);
568 }
569 state.horizontal_rtl=Some(rtl);
570 }
571 if input.key.is_some() || (state.offset - *offset).abs() > 0.1 {
572 state.cancel();
573 }
574 state.offset = *offset;
575 if wheel != 0. {
576 state.cancel();
577 state.offset = (state.offset + wheel).clamp(0., max);
578 }
579 if input.pointer_kind == crate::PointerKind::Touch {
580 let coordinate = |p: [f32; 2]| if horizontal && rtl { -p[0] } else { p[usize::from(!horizontal)] };
581 if input.pressed && inside {
582 state.begin(coordinate(input.pointer.unwrap()), input.time);
583 }
584 if let Some(p) = input.pointer {
585 state.drag(coordinate(p), input.time, max, if horizontal { b.width } else { b.height });
586 }
587 }
588 let dragged = state.dragging;
589 if input.released {
590 state.release(input.time, reduced);
591 }
592 if input.cancelled || input.blurred {
593 state.cancel();
594 }
595 let active = state.advance(input.time, max, reduced);
596 *offset = state.offset;
597 if active {
598 self.continuous(b);
599 }
600 if dragged {
601 self.input.pressed = false;
602 self.input.released = false;
603 self.input.cancelled = true;
604 }
605 dragged
606 }
607}
608
609#[derive(Clone, Copy, Debug, Default)]
611pub struct SplineFling {
612 start: f64,
613 duration: f32,
614 distance: f32,
615 previous: f32,
616}
617impl SplineFling {
618 pub fn start(&mut self, velocity: f32, time: f64) {
619 let friction = 0.015 * 9.80665_f32 * 39.37 * 160. * 0.84;
620 let rate = 0.78_f32.ln() / 0.9_f32.ln();
621 let l = (0.35 * velocity.abs().max(1.) / friction).ln();
622 *self = Self {
623 start: time,
624 duration: (l / (rate - 1.)).exp(),
625 distance: friction * (rate / (rate - 1.) * l).exp() * velocity.signum(),
626 previous: 0.,
627 };
628 }
629 pub fn step(&mut self, time: f64) -> (f32, bool) {
630 let t = if self.duration > 0. {
631 ((time - self.start) as f32 / self.duration).clamp(0., 1.)
632 } else {
633 1.
634 };
635 let position = self.distance * spline(t);
636 let delta = position - self.previous;
637 self.previous = position;
638 (delta, t < 1.)
639 }
640}