1use crate::arena::{ScratchArena, SmallVec};
4use crate::element::{ExitTo, TransitionSpec};
5use crate::motion::draw_op::{pack_subpx_q4, DrawOp, DrawPayload};
6use crate::motion::spring::rubberband_i16;
7use crate::solver::Region;
8use crate::style::{Color, Easing, LoopMode};
9
10#[derive(Copy, Clone, PartialEq, Eq, Debug)]
12pub struct MotionState {
13 pub bounds: Region,
15 pub bg: Color,
17 pub border: Color,
19 pub opacity: u8,
21 pub subpx_q4: u8,
23}
24
25impl MotionState {
26 #[inline(always)]
28 pub const fn new(bounds: Region, bg: Color, border: Color) -> Self {
29 Self {
30 bounds,
31 bg,
32 border,
33 opacity: 255,
34 subpx_q4: 0,
35 }
36 }
37
38 #[inline(always)]
40 pub const fn with_opacity(mut self, opacity: u8) -> Self {
41 self.opacity = opacity;
42 self
43 }
44
45 #[inline]
46 fn lerp(self, to: Self, t_256: i32) -> Self {
47 let t_clamped = t_256.clamp(0, 256) as u16;
48 let op = self.opacity as i32 + (((to.opacity as i32 - self.opacity as i32) * t_256) >> 8);
49 let (bounds, subpx_q4) = lerp_region_signed_q4(self.bounds, to.bounds, t_256);
50 Self {
51 bounds,
52 bg: self.bg.lerp(to.bg, t_clamped),
53 border: self.border.lerp(to.border, t_clamped),
54 opacity: op.clamp(0, 255) as u8,
55 subpx_q4,
56 }
57 }
58}
59
60#[derive(Copy, Clone, Debug)]
65struct ActiveTransition {
66 id: u32,
67 path_hash: u32,
68 start_bounds: Region,
69 target_bounds: Region,
70 start_bg: Color,
71 target_bg: Color,
72 start_border: Color,
73 target_border: Color,
74 parent_x: i16,
76 parent_y: i16,
77 elapsed_ms: i16,
79 duration_ms: u16,
81 mode_flags: u8,
83 start_opacity: u8,
84 target_opacity: u8,
85 pos_q4: [i32; 4],
87 vel_q4: [i32; 4],
89 spring_t_q8: i32,
91 spring_vt_q8: i32,
93}
94
95const FLAG_REVERSE: u8 = 0x20;
96const FLAG_SEEN: u8 = 0x40;
97const FLAG_SPRING_PHYSICS: u8 = 0x80;
98
99#[inline(always)]
100const fn region_to_q4(r: Region) -> [i32; 4] {
101 [
102 (r.x as i32) << 4,
103 (r.y as i32) << 4,
104 (r.w as i32) << 4,
105 (r.h as i32) << 4,
106 ]
107}
108
109#[inline(always)]
110fn q4_to_region_and_subpx(p: [i32; 4]) -> (Region, u8) {
111 let round = |v: i32| -> i16 {
112 let r = if v >= 0 { (v + 8) >> 4 } else { -((-v + 8) >> 4) };
113 r.clamp(i16::MIN as i32, i16::MAX as i32) as i16
114 };
115 let rx = round(p[0]);
116 let ry = round(p[1]);
117 let dx_q4 = (p[0] - ((rx as i32) << 4)).clamp(-8, 7) as i8;
118 let dy_q4 = (p[1] - ((ry as i32) << 4)).clamp(-8, 7) as i8;
119 (
120 Region {
121 x: rx,
122 y: ry,
123 w: round(p[2]).max(0),
124 h: round(p[3]).max(0),
125 },
126 pack_subpx_q4(dx_q4, dy_q4),
127 )
128}
129
130#[inline(always)]
131fn div_round_i64(num: i64, den: i64) -> i64 {
132 if num >= 0 {
133 (num + (den >> 1)) / den
134 } else {
135 (num - (den >> 1)) / den
136 }
137}
138
139#[inline(always)]
142fn step_spring_axis_i32(pos: &mut i32, vel: &mut i32, target: i32, k: i64, c_q4: i64, sub_ms: i64) {
143 let disp = (*pos as i64) - (target as i64);
144 let v = *vel as i64;
145 let accel = -k * disp - ((c_q4 * v) >> 4);
146 let mut dv = div_round_i64(accel * sub_ms, 1000);
147 if dv == 0 && accel != 0 {
148 dv = accel.signum();
149 }
150 let next_v = (v + dv).clamp(-200_000_000, 200_000_000);
151 let mut dp = div_round_i64(next_v * sub_ms, 1000);
152 if dp == 0 && next_v.abs() >= 32 {
153 dp = next_v.signum();
154 }
155 let next_p = (*pos as i64 + dp).clamp(i32::MIN as i64 / 2, i32::MAX as i64 / 2);
156 *vel = next_v as i32;
157 *pos = next_p as i32;
158}
159
160impl ActiveTransition {
161 #[inline(always)]
162 const fn easing(&self) -> Easing {
163 Easing::from_bits(self.mode_flags)
164 }
165
166 #[inline(always)]
167 const fn loop_mode(&self) -> LoopMode {
168 match (self.mode_flags >> 3) & 0x03 {
169 1 => LoopMode::Infinite,
170 2 => LoopMode::PingPong,
171 _ => LoopMode::Once,
172 }
173 }
174
175 #[inline(always)]
176 const fn is_reverse(&self) -> bool {
177 (self.mode_flags & FLAG_REVERSE) != 0
178 }
179
180 #[inline(always)]
181 const fn seen(&self) -> bool {
182 (self.mode_flags & FLAG_SEEN) != 0
183 }
184
185 #[inline(always)]
186 const fn is_spring_physics(&self) -> bool {
187 (self.mode_flags & FLAG_SPRING_PHYSICS) != 0
188 }
189
190 #[inline(always)]
191 fn set_seen(&mut self, seen: bool) {
192 if seen {
193 self.mode_flags |= FLAG_SEEN;
194 } else {
195 self.mode_flags &= !FLAG_SEEN;
196 }
197 }
198
199 #[inline(always)]
201 fn set_mode(&mut self, easing: Easing, loop_mode: LoopMode) {
202 let spring_flag = if matches!(easing, Easing::Spring) && matches!(loop_mode, LoopMode::Once) {
203 FLAG_SPRING_PHYSICS
204 } else {
205 0
206 };
207 self.mode_flags = (easing as u8 & 0x07)
208 | ((loop_mode as u8 & 0x03) << 3)
209 | (self.mode_flags & (FLAG_REVERSE | FLAG_SEEN))
210 | spring_flag;
211 }
212
213 #[inline(always)]
214 const fn clamp_duration(ms: u16) -> u16 {
215 if ms > i16::MAX as u16 { i16::MAX as u16 } else { ms }
216 }
217
218 #[inline(always)]
219 const fn delay_to_elapsed(delay_ms: u16) -> i16 {
220 if delay_ms > i16::MAX as u16 {
221 i16::MIN + 1
222 } else {
223 -(delay_ms as i16)
224 }
225 }
226
227 #[inline(always)]
228 fn spring_settled(&self) -> bool {
229 let tgt = region_to_q4(self.target_bounds);
230 for i in 0..4 {
231 if (self.pos_q4[i] - tgt[i]).abs() > 4 || self.vel_q4[i].abs() > 32 {
232 return false;
233 }
234 }
235 (self.spring_t_q8 - 256).abs() <= 4 && self.spring_vt_q8.abs() <= 32
236 }
237
238 #[inline(always)]
239 fn is_active(&self) -> bool {
240 if self.duration_ms == 0 {
241 return false;
242 }
243 if self.is_spring_physics() {
244 return self.elapsed_ms < 0 || !self.spring_settled();
245 }
246 !matches!(self.loop_mode(), LoopMode::Once) || (self.elapsed_ms as i32) < self.duration_ms as i32
247 }
248
249 #[inline(always)]
250 fn start_state(&self) -> MotionState {
251 MotionState {
252 bounds: self.start_bounds,
253 bg: self.start_bg,
254 border: self.start_border,
255 opacity: self.start_opacity,
256 subpx_q4: 0,
257 }
258 }
259
260 #[inline(always)]
261 fn target_state(&self) -> MotionState {
262 MotionState {
263 bounds: self.target_bounds,
264 bg: self.target_bg,
265 border: self.target_border,
266 opacity: self.target_opacity,
267 subpx_q4: 0,
268 }
269 }
270
271 #[inline(always)]
272 fn set_start(&mut self, s: MotionState) {
273 self.start_bounds = s.bounds;
274 self.start_bg = s.bg;
275 self.start_border = s.border;
276 self.start_opacity = s.opacity;
277 }
278
279 #[inline(always)]
280 fn set_target(&mut self, s: MotionState) {
281 self.target_bounds = s.bounds;
282 self.target_bg = s.bg;
283 self.target_border = s.border;
284 self.target_opacity = s.opacity;
285 }
286
287 #[inline]
289 fn settle(&mut self, target: MotionState) {
290 self.set_start(target);
291 self.set_target(target);
292 self.pos_q4 = region_to_q4(target.bounds);
293 self.vel_q4 = [0; 4];
294 self.spring_t_q8 = 256;
295 self.spring_vt_q8 = 0;
296 self.elapsed_ms = self.duration_ms as i16;
297 self.mode_flags &= 0x07 | FLAG_SEEN | FLAG_SPRING_PHYSICS;
298 }
299
300 fn step_spring(&mut self, dt_ms: u16) {
303 let dt = dt_ms.min(100) as i32;
304 if self.elapsed_ms < 0 {
305 let rem = self.elapsed_ms as i32 + dt;
306 if rem <= 0 {
307 self.elapsed_ms = rem as i16;
308 return;
309 }
310 self.elapsed_ms = 0;
311 self.step_spring_substeps(rem as i64);
313 return;
314 }
315 self.step_spring_substeps(dt as i64);
316 }
317
318 fn step_spring_substeps(&mut self, total_ms: i64) {
319 if total_ms <= 0 {
320 return;
321 }
322 let dur = (self.duration_ms as i64).clamp(60, 1000);
323 let omega_q4 = (64_000 / dur).clamp(64, 640);
325 let k = (omega_q4 * omega_q4) >> 8;
326 let c_q4 = (omega_q4 * 16) / 10;
328
329 let sub_steps = ((total_ms + 3) / 4).max(1);
330 let sub_ms = (total_ms / sub_steps).max(1);
331 let rem_ms = total_ms - sub_ms * (sub_steps - 1);
332 let tgt = region_to_q4(self.target_bounds);
333
334 for step_idx in 0..sub_steps {
335 let h = if step_idx + 1 == sub_steps { rem_ms } else { sub_ms };
336 for axis in 0..4 {
337 step_spring_axis_i32(&mut self.pos_q4[axis], &mut self.vel_q4[axis], tgt[axis], k, c_q4, h);
338 }
339 step_spring_axis_i32(&mut self.spring_t_q8, &mut self.spring_vt_q8, 256, k, c_q4, h);
340 }
341
342 if self.spring_settled() {
343 self.pos_q4 = tgt;
344 self.vel_q4 = [0; 4];
345 self.spring_t_q8 = 256;
346 self.spring_vt_q8 = 0;
347 self.elapsed_ms = self.duration_ms as i16;
348 } else {
349 self.elapsed_ms = (self.elapsed_ms as i32 + total_ms as i32).min(i16::MAX as i32) as i16;
350 }
351 }
352
353 #[inline]
354 fn current_state(&self) -> MotionState {
355 if self.duration_ms == 0 {
356 return self.target_state();
357 }
358 if self.is_spring_physics() {
359 if self.elapsed_ms < 0 {
360 return self.start_state();
361 }
362 if self.spring_settled() {
363 return self.target_state();
364 }
365 let t_clamped = self.spring_t_q8.clamp(0, 256) as u16;
366 let op = self.start_opacity as i32
367 + (((self.target_opacity as i32 - self.start_opacity as i32) * self.spring_t_q8) >> 8);
368 let (bounds, subpx_q4) = q4_to_region_and_subpx(self.pos_q4);
369 return MotionState {
370 bounds,
371 bg: self.start_bg.lerp(self.target_bg, t_clamped),
372 border: self.start_border.lerp(self.target_border, t_clamped),
373 opacity: op.clamp(0, 255) as u8,
374 subpx_q4,
375 };
376 }
377 if matches!(self.loop_mode(), LoopMode::Once)
378 && (self.elapsed_ms as i32) >= self.duration_ms as i32
379 {
380 return self.target_state();
381 }
382 let phase = self.elapsed_ms.max(0) as u32;
383 let dur = self.duration_ms as u32;
384 let eff = if self.is_reverse() {
385 dur.saturating_sub(phase)
386 } else {
387 phase
388 };
389 let t_256 = self.easing().sample_256(eff, dur);
390 self.start_state().lerp(self.target_state(), t_256)
391 }
392}
393
394const GHOST_LABEL_MAX: usize = 48;
395
396#[derive(Copy, Clone, Debug)]
398struct GhostEntry {
399 id: u32,
400 path_hash: u32,
401 bounds: Region,
402 clip: Region,
403 clip_radius: u8,
404 bg: Color,
405 bg_grad: Color,
406 border_color: Color,
407 rounded: u8,
408 encoded_bw: u8,
409 start_opacity: u8,
410 exit_to: ExitTo,
411 elapsed_ms: u16,
412 duration_ms: u16,
413 easing: Easing,
414 label_len: u8,
415 label_bytes: [u8; GHOST_LABEL_MAX],
416 label_color: Color,
417 label_font_size: u8,
418 label_dx: i16,
420 label_dy: i16,
421 active_exiting: bool,
422 seen_this_frame: bool,
423}
424
425#[derive(Copy, Clone, Debug)]
427struct ScrollEntry {
428 id: u32,
429 offset_y: i16,
430 velocity_y: i16,
431 max_scroll: i16,
432 overscroll_q4: i32,
434 overscroll_vel_q4: i32,
436 drag_overscroll_raw: i16,
438 viewport_dim: i16,
440 is_dragging: bool,
442}
443
444#[derive(Debug)]
446pub struct MotionCache {
447 transitions: SmallVec<ActiveTransition, 16>,
448 scroll_offsets: SmallVec<ScrollEntry, 16>,
449 ghosts: SmallVec<GhostEntry, 4>,
450 scroll_stale_bits: u32,
452 reduced_motion: bool,
454 ime_caret_bounds: Option<Region>,
456}
457
458impl Default for MotionCache {
459 fn default() -> Self {
460 Self::new()
461 }
462}
463
464impl MotionCache {
465 pub const fn new() -> Self {
467 Self {
468 transitions: SmallVec::new(),
469 scroll_offsets: SmallVec::new(),
470 ghosts: SmallVec::new(),
471 scroll_stale_bits: 0,
472 reduced_motion: false,
473 ime_caret_bounds: None,
474 }
475 }
476
477 #[inline(always)]
479 pub(crate) fn set_ime_caret_bounds(&mut self, bounds: Option<Region>) {
480 self.ime_caret_bounds = bounds;
481 }
482
483 #[inline(always)]
485 pub const fn ime_caret_bounds(&self) -> Option<Region> {
486 self.ime_caret_bounds
487 }
488
489 #[inline]
491 pub fn set_reduced_motion(&mut self, reduced: bool) {
492 self.reduced_motion = reduced;
493 if reduced {
494 self.finish_all();
495 self.ghosts.clear();
496 for sc in self.scroll_offsets.iter_mut() {
497 sc.overscroll_q4 = 0;
498 sc.overscroll_vel_q4 = 0;
499 sc.drag_overscroll_raw = 0;
500 }
501 }
502 }
503
504 #[inline(always)]
506 pub const fn reduced_motion(&self) -> bool {
507 self.reduced_motion
508 }
509
510 #[inline]
512 pub fn active_ghost_count(&self) -> usize {
513 self.ghosts.iter().filter(|g| g.active_exiting).count()
514 }
515
516 pub fn current_velocity(&self, id: u32) -> Option<(i32, i32)> {
518 self.transitions
519 .iter()
520 .find(|t| t.id == id)
521 .map(|t| (t.vel_q4[0] >> 4, t.vel_q4[1] >> 4))
522 }
523
524 #[inline(always)]
525 fn stale_at(&self, idx: usize) -> u8 {
526 if idx < 16 {
527 ((self.scroll_stale_bits >> (idx * 2)) & 0x03) as u8
528 } else {
529 0
530 }
531 }
532
533 #[inline(always)]
534 fn set_stale_at(&mut self, idx: usize, val: u8) {
535 if idx < 16 {
536 let shift = idx * 2;
537 self.scroll_stale_bits = (self.scroll_stale_bits & !(0x03u32 << shift))
538 | (((val.min(3)) as u32) << shift);
539 }
540 }
541
542 pub fn tick(&mut self, dt_ms: u16) -> bool {
545 let mut any_stepped = false;
546 for tr in self.transitions.iter_mut() {
547 if tr.is_active() {
548 any_stepped = true;
549 if tr.is_spring_physics() {
550 tr.step_spring(dt_ms);
551 } else {
552 let dur = tr.duration_ms as i32;
553 let next = tr.elapsed_ms as i32 + dt_ms as i32;
554 if next >= dur {
555 match tr.loop_mode() {
556 LoopMode::Once => {
557 tr.elapsed_ms = dur as i16;
558 }
559 LoopMode::Infinite => {
560 tr.elapsed_ms = (next % dur.max(1)) as i16;
561 }
562 LoopMode::PingPong => {
563 tr.elapsed_ms = (next % dur.max(1)) as i16;
564 tr.mode_flags ^= FLAG_REVERSE;
565 }
566 }
567 } else {
568 tr.elapsed_ms = next as i16;
569 }
570 }
571 }
572 }
573
574 for g in self.ghosts.iter_mut() {
576 if g.active_exiting {
577 any_stepped = true;
578 g.elapsed_ms = g.elapsed_ms.saturating_add(dt_ms);
579 }
580 }
581
582 let reduced = self.reduced_motion;
584 let dt_clamped = dt_ms.clamp(1, 100) as i64;
585 for sc in self.scroll_offsets.iter_mut() {
586 if sc.velocity_y != 0 && !sc.is_dragging {
587 any_stepped = true;
588 let max_s = if sc.max_scroll >= 0 {
589 sc.max_scroll
590 } else {
591 i16::MAX
592 };
593 let step = (((sc.velocity_y as i32) * (dt_clamped as i32)) / 16)
594 .clamp(i16::MIN as i32, i16::MAX as i32) as i16;
595 let delta = if step != 0 {
596 step
597 } else if sc.velocity_y > 0 {
598 1
599 } else {
600 -1
601 };
602 let raw_next = (sc.offset_y as i32) + (delta as i32);
603 if raw_next < 0 || raw_next > (max_s as i32) {
604 let hit_edge = if raw_next < 0 { 0 } else { max_s };
606 let overshoot_px = raw_next - (hit_edge as i32);
607 sc.offset_y = hit_edge;
608 if !reduced {
609 let impulse_q4 = (sc.velocity_y as i32).saturating_mul(640);
611 sc.overscroll_q4 = sc
612 .overscroll_q4
613 .saturating_add(overshoot_px.clamp(-64, 64) << 4);
614 sc.overscroll_vel_q4 = sc.overscroll_vel_q4.saturating_add(impulse_q4);
615 }
616 sc.velocity_y = 0;
617 } else {
618 sc.offset_y = raw_next as i16;
619 sc.velocity_y = (((sc.velocity_y as i32) * 7) / 8) as i16;
620 if sc.velocity_y.abs() <= 1 {
621 sc.velocity_y = 0;
622 }
623 }
624 }
625
626 if !sc.is_dragging && (sc.overscroll_q4 != 0 || sc.overscroll_vel_q4 != 0) {
628 if reduced {
629 sc.overscroll_q4 = 0;
630 sc.overscroll_vel_q4 = 0;
631 } else {
632 any_stepped = true;
633 let sub_steps = ((dt_clamped + 3) / 4).max(1);
635 let sub_ms = (dt_clamped / sub_steps).max(1);
636 let rem_ms = dt_clamped - sub_ms * (sub_steps - 1);
637 for step_idx in 0..sub_steps {
638 let h = if step_idx + 1 == sub_steps { rem_ms } else { sub_ms };
639 step_spring_axis_i32(
640 &mut sc.overscroll_q4,
641 &mut sc.overscroll_vel_q4,
642 0,
643 240,
644 496,
645 h,
646 );
647 }
648 if sc.overscroll_q4.abs() <= 4 && sc.overscroll_vel_q4.abs() <= 48 {
649 sc.overscroll_q4 = 0;
650 sc.overscroll_vel_q4 = 0;
651 }
652 }
653 }
654 }
655 any_stepped
656 }
657
658 #[inline]
660 pub fn has_active_animations(&self) -> bool {
661 self.transitions.iter().any(|t| t.is_active())
662 || self.ghosts.iter().any(|g| g.active_exiting)
663 || self.scroll_offsets.iter().any(|s| {
664 s.velocity_y != 0
665 || (!s.is_dragging && (s.overscroll_q4 != 0 || s.overscroll_vel_q4 != 0))
666 })
667 }
668
669 #[inline]
671 pub fn transition_count(&self) -> usize {
672 self.transitions.len()
673 }
674
675 pub fn begin_frame(&mut self) {
677 self.ime_caret_bounds = None;
678 for tr in self.transitions.iter_mut() {
679 tr.set_seen(false);
680 }
681 for g in self.ghosts.iter_mut() {
682 g.seen_this_frame = false;
683 }
684 let n = self.scroll_offsets.len().min(16);
685 for idx in 0..n {
686 let next = self.stale_at(idx).saturating_add(1);
687 self.set_stale_at(idx, next);
688 }
689 }
690
691 #[allow(clippy::too_many_arguments)]
693 pub(crate) fn record_ghost_snapshot(
694 &mut self,
695 id: u32,
696 path_hash: u32,
697 bounds: Region,
698 clip: Region,
699 clip_radius: u8,
700 bg: Color,
701 bg_grad: Color,
702 border_color: Color,
703 rounded: u8,
704 encoded_bw: u8,
705 opacity: u8,
706 exit_to: ExitTo,
707 duration_ms: u16,
708 easing: Easing,
709 label: Option<(&str, Color, u8, i16, i16)>,
710 ) {
711 if self.reduced_motion || duration_ms == 0 {
712 return;
713 }
714 let mut label_bytes = [0u8; GHOST_LABEL_MAX];
715 let mut label_len = 0u8;
716 let mut label_color = Color::TRANSPARENT;
717 let mut label_font_size = 14u8;
718 let mut label_dx = i16::MIN;
719 let mut label_dy = i16::MIN;
720 if let Some((txt, col, fs, dx, dy)) = label {
721 let mut end = txt.len().min(GHOST_LABEL_MAX);
723 while end > 0 && !txt.is_char_boundary(end) {
724 end -= 1;
725 }
726 label_bytes[..end].copy_from_slice(&txt.as_bytes()[..end]);
727 label_len = end as u8;
728 label_color = col;
729 label_font_size = fs;
730 label_dx = dx;
731 label_dy = dy;
732 }
733 let exit_easing = match easing {
735 Easing::EaseOutBack | Easing::Spring => Easing::EaseOut,
736 other => other,
737 };
738
739 let entry = GhostEntry {
740 id,
741 path_hash,
742 bounds,
743 clip,
744 clip_radius,
745 bg,
746 bg_grad,
747 border_color,
748 rounded,
749 encoded_bw,
750 start_opacity: opacity,
751 exit_to,
752 elapsed_ms: 0,
753 duration_ms,
754 easing: exit_easing,
755 label_len,
756 label_bytes,
757 label_color,
758 label_font_size,
759 label_dx,
760 label_dy,
761 active_exiting: false,
762 seen_this_frame: true,
763 };
764
765 if let Some(slot) = self
766 .ghosts
767 .iter_mut()
768 .find(|g| g.id == id && g.path_hash == path_hash)
769 {
770 *slot = entry;
771 return;
772 }
773 if !self.ghosts.push(entry) {
774 if let Some(slot) = self.ghosts.iter_mut().find(|g| !g.active_exiting && !g.seen_this_frame) {
775 *slot = entry;
776 }
777 }
778 }
779
780 pub fn end_frame(&mut self) {
782 self.cleanup_transitions_and_scrolls();
783 let mut g_idx = 0;
784 while g_idx < self.ghosts.len() {
785 let g = &mut self.ghosts[g_idx];
786 if g.seen_this_frame {
787 g_idx += 1;
788 } else if !g.active_exiting && !self.reduced_motion && g.duration_ms > 0 {
789 g.active_exiting = true;
790 g.elapsed_ms = 0;
791 g_idx += 1;
792 } else if g.active_exiting && g.elapsed_ms < g.duration_ms {
793 g_idx += 1;
794 } else {
795 self.ghosts.swap_remove(g_idx);
796 }
797 }
798 }
799
800 pub(crate) fn end_frame_with_ghosts<'a, const MAX_OPS: usize>(
802 &mut self,
803 arena: &'a ScratchArena,
804 out_ops: &mut SmallVec<DrawOp<'a>, MAX_OPS>,
805 dropped_ops: &mut u32,
806 ) {
807 self.cleanup_transitions_and_scrolls();
808
809 let mut g_idx = 0;
810 while g_idx < self.ghosts.len() {
811 let g = &mut self.ghosts[g_idx];
812 if g.seen_this_frame {
813 g_idx += 1;
814 continue;
815 }
816 if !g.active_exiting {
817 if !self.reduced_motion && g.duration_ms > 0 {
818 g.active_exiting = true;
819 g.elapsed_ms = 0;
820 } else {
821 self.ghosts.swap_remove(g_idx);
822 continue;
823 }
824 }
825 if g.elapsed_ms >= g.duration_ms {
826 self.ghosts.swap_remove(g_idx);
827 continue;
828 }
829
830 let t_256 = g
831 .easing
832 .sample_256(g.elapsed_ms as u32, g.duration_ms.max(1) as u32);
833 let cur_op = (g.start_opacity as i32
834 + (((g.exit_to.opacity as i32 - g.start_opacity as i32) * t_256) >> 8))
835 .clamp(0, 255) as u8;
836 if cur_op > 0 {
837 let dx_q4_tot = ((g.exit_to.dx as i32) * t_256) >> 4;
838 let dy_q4_tot = ((g.exit_to.dy as i32) * t_256) >> 4;
839 let dx = ((dx_q4_tot + if dx_q4_tot >= 0 { 8 } else { -8 }) / 16) as i16;
840 let dy = ((dy_q4_tot + if dy_q4_tot >= 0 { 8 } else { -8 }) / 16) as i16;
841 let g_subpx = pack_subpx_q4(
842 (dx_q4_tot - (dx as i32) * 16).clamp(-8, 7) as i8,
843 (dy_q4_tot - (dy as i32) * 16).clamp(-8, 7) as i8,
844 );
845 let ghost_bounds = Region::new(
846 g.bounds.x.saturating_add(dx),
847 g.bounds.y.saturating_add(dy),
848 g.bounds.w,
849 g.bounds.h,
850 );
851 let ghost_bg = g.bg.scale_alpha(cur_op);
852 let ghost_grad = g.bg_grad.scale_alpha(cur_op);
853 let ghost_border = g.border_color.scale_alpha(cur_op);
854 if ghost_bg.a() > 0 || ghost_grad.a() > 0 || ghost_border.a() > 0 {
855 if !out_ops.push(DrawOp {
856 id: Some(g.id ^ 0x4748_0000),
857 bounds: ghost_bounds,
858 clip: g.clip,
859 clip_radius: g.clip_radius,
860 subpx_q4: g_subpx,
861 payload: DrawPayload::Quad {
862 bg: ghost_bg,
863 bg_grad: ghost_grad,
864 border_color: ghost_border,
865 rounded: g.rounded,
866 border_width: g.encoded_bw,
867 },
868 }) {
869 *dropped_ops = dropped_ops.saturating_add(1);
870 }
871 }
872 if g.label_len > 0 {
873 let s_bytes = &g.label_bytes[..(g.label_len as usize)];
874 if let Ok(txt) = core::str::from_utf8(s_bytes) {
875 if arena.can_alloc_slice::<u8>(txt.len()) {
876 let copied_str = arena.alloc_str(txt);
877 let tc = g.label_color.scale_alpha(cur_op);
878 if tc.a() > 0 {
879 let tx = if g.label_dx != i16::MIN {
880 ghost_bounds.x.saturating_add(g.label_dx)
881 } else {
882 ghost_bounds.x.saturating_add(8)
883 };
884 let ty = if g.label_dy != i16::MIN {
885 ghost_bounds.y.saturating_add(g.label_dy)
886 } else {
887 ghost_bounds.y.saturating_add(
888 ghost_bounds
889 .h
890 .saturating_sub(g.label_font_size as i16)
891 / 2,
892 )
893 };
894 let tw = ghost_bounds
895 .right()
896 .saturating_sub(tx)
897 .saturating_sub(8)
898 .max(1);
899 let text_bounds = Region::new(
900 tx,
901 ty,
902 tw,
903 (g.label_font_size as i16).saturating_add(4).max(8),
904 );
905 if !out_ops.push(DrawOp {
906 id: Some(g.id ^ 0x4749_0000),
907 bounds: text_bounds,
908 clip: g.clip.intersect(ghost_bounds),
909 clip_radius: 0,
910 subpx_q4: g_subpx,
911 payload: DrawPayload::TextRun {
912 text: copied_str,
913 color: tc,
914 font_size: g.label_font_size,
915 text_flags: 0,
916 },
917 }) {
918 *dropped_ops = dropped_ops.saturating_add(1);
919 }
920 }
921 }
922 }
923 }
924 }
925 g_idx += 1;
926 }
927 }
928
929 fn cleanup_transitions_and_scrolls(&mut self) {
930 let mut i = 0;
931 while i < self.transitions.len() {
932 if self.transitions[i].seen() {
933 i += 1;
934 } else {
935 self.transitions.swap_remove(i);
936 }
937 }
938 let mut s_idx = 0;
939 while s_idx < self.scroll_offsets.len() {
940 let stale = self.stale_at(s_idx);
941 let sc = &self.scroll_offsets[s_idx];
942 let idle = sc.velocity_y == 0
943 && !sc.is_dragging
944 && sc.overscroll_q4 == 0
945 && sc.overscroll_vel_q4 == 0;
946 let evict = idle
947 && (stale >= 3
948 || (stale >= 2 && (sc.offset_y == 0 || self.scroll_offsets.len() > 12)));
949 if evict {
950 let last_idx = self.scroll_offsets.len() - 1;
951 let last_stale = self.stale_at(last_idx);
952 self.scroll_offsets.swap_remove(s_idx);
953 self.set_stale_at(s_idx, last_stale);
954 self.set_stale_at(last_idx, 0);
955 } else {
956 s_idx += 1;
957 }
958 }
959 }
960
961 #[inline]
963 pub(crate) fn sync_scroll_bounds(&mut self, id: u32, max_scroll: i16) {
964 let clamped_max = max_scroll.max(0);
965 if let Some((idx, entry)) = self
966 .scroll_offsets
967 .iter_mut()
968 .enumerate()
969 .find(|(_, e)| e.id == id)
970 {
971 entry.max_scroll = clamped_max;
972 entry.offset_y = entry.offset_y.clamp(0, clamped_max);
973 self.set_stale_at(idx, 0);
974 }
975 }
976
977 pub fn finish_all(&mut self) {
979 for tr in self.transitions.iter_mut() {
980 if !matches!(tr.loop_mode(), LoopMode::Once) {
981 continue;
982 }
983 let target = tr.target_state();
984 tr.settle(target);
985 }
986 }
987
988 pub fn current_state(&self, id: u32) -> Option<MotionState> {
990 self.transitions
991 .iter()
992 .find(|t| t.id == id)
993 .map(|t| t.current_state())
994 }
995
996 pub(crate) fn peek_offset_opacity_scoped(
998 &self,
999 id: u32,
1000 path_hash: u32,
1001 ) -> Option<(i16, i16, u8)> {
1002 self.transitions
1003 .iter()
1004 .find(|t| t.id == id && t.path_hash == path_hash)
1005 .or_else(|| self.transitions.iter().find(|t| t.id == id))
1006 .map(|t| {
1007 let cur = t.current_state();
1008 (
1009 cur.bounds.x.saturating_sub(t.target_bounds.x),
1010 cur.bounds.y.saturating_sub(t.target_bounds.y),
1011 cur.opacity,
1012 )
1013 })
1014 }
1015
1016 pub fn resolve(
1018 &mut self,
1019 id: u32,
1020 target: MotionState,
1021 spec: Option<TransitionSpec>,
1022 ) -> MotionState {
1023 self.resolve_inner(id, id, (0, 0), (0, 0), target, spec, false)
1024 }
1025
1026 pub(crate) fn resolve_scoped_with_ancestor_offset(
1029 &mut self,
1030 id: u32,
1031 path_hash: u32,
1032 parent_origin: (i16, i16),
1033 ancestor_offset: (i16, i16),
1034 target: MotionState,
1035 spec: Option<TransitionSpec>,
1036 ) -> MotionState {
1037 self.resolve_inner(id, path_hash, parent_origin, ancestor_offset, target, spec, true)
1038 }
1039
1040 #[allow(clippy::too_many_arguments)]
1041 fn resolve_inner(
1042 &mut self,
1043 id: u32,
1044 path_hash: u32,
1045 parent_origin: (i16, i16),
1046 ancestor_offset: (i16, i16),
1047 target: MotionState,
1048 spec: Option<TransitionSpec>,
1049 guard_same_frame_dup: bool,
1050 ) -> MotionState {
1051 if self.reduced_motion {
1053 if let Some(s) = spec {
1054 if matches!(s.loop_mode, LoopMode::Once) {
1055 if let Some(tr) = self
1056 .transitions
1057 .iter_mut()
1058 .find(|t| t.id == id && t.path_hash == path_hash)
1059 {
1060 tr.set_seen(true);
1061 tr.settle(target);
1062 }
1063 return target;
1064 }
1065 }
1066 }
1067
1068 let matched_idx = self
1069 .transitions
1070 .iter()
1071 .position(|t| t.id == id && t.path_hash == path_hash)
1072 .or_else(|| {
1073 if spec.is_some() {
1074 self.transitions
1075 .iter()
1076 .position(|t| t.id == id && (!guard_same_frame_dup || !t.seen()))
1077 } else {
1078 None
1079 }
1080 });
1081
1082 if let Some(idx) = matched_idx {
1083 let tr = &mut self.transitions[idx];
1084 if guard_same_frame_dup && tr.seen() {
1085 return target;
1086 }
1087 let same_parent = tr.path_hash == path_hash;
1088 if same_parent {
1089 let pdx = parent_origin.0.saturating_sub(tr.parent_x);
1090 let pdy = parent_origin.1.saturating_sub(tr.parent_y);
1091 if pdx != 0 || pdy != 0 {
1092 tr.start_bounds.x = tr.start_bounds.x.saturating_add(pdx);
1093 tr.start_bounds.y = tr.start_bounds.y.saturating_add(pdy);
1094 tr.target_bounds.x = tr.target_bounds.x.saturating_add(pdx);
1095 tr.target_bounds.y = tr.target_bounds.y.saturating_add(pdy);
1096 tr.pos_q4[0] = tr.pos_q4[0].saturating_add((pdx as i32) << 4);
1097 tr.pos_q4[1] = tr.pos_q4[1].saturating_add((pdy as i32) << 4);
1098 }
1099 } else if ancestor_offset.0 != 0 || ancestor_offset.1 != 0 {
1100 let adx = ancestor_offset.0;
1102 let ady = ancestor_offset.1;
1103 tr.start_bounds.x = tr.start_bounds.x.saturating_sub(adx);
1104 tr.start_bounds.y = tr.start_bounds.y.saturating_sub(ady);
1105 tr.target_bounds.x = tr.target_bounds.x.saturating_sub(adx);
1106 tr.target_bounds.y = tr.target_bounds.y.saturating_sub(ady);
1107 tr.pos_q4[0] = tr.pos_q4[0].saturating_sub((adx as i32) << 4);
1108 tr.pos_q4[1] = tr.pos_q4[1].saturating_sub((ady as i32) << 4);
1109 }
1110 tr.parent_x = parent_origin.0;
1111 tr.parent_y = parent_origin.1;
1112 tr.path_hash = path_hash;
1113 tr.set_seen(true);
1114 let Some(s) = spec else {
1115 tr.settle(target);
1116 return target;
1117 };
1118 let was_spring = tr.is_spring_physics();
1119 tr.set_mode(s.easing, s.loop_mode);
1120 let now_spring = tr.is_spring_physics();
1121 if now_spring && !was_spring {
1122 let cur = tr.current_state();
1124 tr.pos_q4 = region_to_q4(cur.bounds);
1125 tr.vel_q4 = [0; 4];
1126 tr.spring_t_q8 = 256;
1127 tr.spring_vt_q8 = 0;
1128 }
1129
1130 if let Some(pulse_from) = s.pulse_from_bg {
1131 tr.set_start(MotionState {
1132 bg: pulse_from,
1133 ..target
1134 });
1135 tr.set_target(target);
1136 tr.duration_ms = ActiveTransition::clamp_duration(s.duration_ms.max(1));
1137 return tr.current_state();
1138 }
1139
1140 let color_changed = s.animate_color
1141 && (tr.target_bg != target.bg || tr.target_border != target.border);
1142 let bounds_changed = s.animate_bounds && tr.target_bounds != target.bounds;
1143 let opacity_changed = s.animate_opacity && tr.target_opacity != target.opacity;
1144
1145 if color_changed || bounds_changed || opacity_changed {
1146 let in_flight = tr.is_active();
1147 let cur = tr.current_state();
1148 tr.set_start(MotionState {
1149 bounds: if s.animate_bounds || in_flight {
1150 cur.bounds
1151 } else {
1152 target.bounds
1153 },
1154 bg: if s.animate_color || in_flight {
1155 cur.bg
1156 } else {
1157 target.bg
1158 },
1159 border: if (s.animate_color || in_flight)
1160 && cur.border.a() > 0
1161 && target.border.a() > 0
1162 {
1163 cur.border
1164 } else {
1165 target.border
1166 },
1167 opacity: if s.animate_opacity || in_flight {
1168 cur.opacity
1169 } else {
1170 target.opacity
1171 },
1172 subpx_q4: if s.animate_bounds || in_flight {
1173 cur.subpx_q4
1174 } else {
1175 0
1176 },
1177 });
1178 tr.set_target(target);
1179 tr.duration_ms = ActiveTransition::clamp_duration(s.duration_ms.max(1));
1180
1181 if now_spring {
1182 if !s.animate_bounds && !in_flight {
1185 tr.pos_q4 = region_to_q4(target.bounds);
1186 tr.vel_q4 = [0; 4];
1187 }
1188 if color_changed || opacity_changed {
1189 tr.spring_t_q8 = 0;
1190 tr.spring_vt_q8 = 0;
1192 }
1193 tr.elapsed_ms = if in_flight {
1194 0
1195 } else {
1196 ActiveTransition::delay_to_elapsed(s.delay_ms)
1197 };
1198 } else {
1199 tr.elapsed_ms = ActiveTransition::delay_to_elapsed(s.delay_ms);
1200 }
1201 } else if !tr.is_active() {
1202 tr.set_start(target);
1203 tr.set_target(target);
1204 tr.pos_q4 = region_to_q4(target.bounds);
1205 tr.vel_q4 = [0; 4];
1206 tr.spring_t_q8 = 256;
1207 tr.spring_vt_q8 = 0;
1208 } else {
1209 if tr.target_bounds != target.bounds {
1211 let dx = target.bounds.x.saturating_sub(tr.target_bounds.x);
1212 let dy = target.bounds.y.saturating_sub(tr.target_bounds.y);
1213 tr.start_bounds = Region::new(
1214 tr.start_bounds.x.saturating_add(dx),
1215 tr.start_bounds.y.saturating_add(dy),
1216 target.bounds.w,
1217 target.bounds.h,
1218 );
1219 tr.target_bounds = target.bounds;
1220 tr.pos_q4[0] = tr.pos_q4[0].saturating_add((dx as i32) << 4);
1221 tr.pos_q4[1] = tr.pos_q4[1].saturating_add((dy as i32) << 4);
1222 tr.pos_q4[2] = (target.bounds.w as i32) << 4;
1223 tr.pos_q4[3] = (target.bounds.h as i32) << 4;
1224 }
1225 if tr.target_bg != target.bg || tr.target_border != target.border {
1226 tr.start_bg = target.bg;
1227 tr.start_border = target.border;
1228 tr.target_bg = target.bg;
1229 tr.target_border = target.border;
1230 }
1231 tr.target_opacity = target.opacity;
1232 }
1233 return tr.current_state();
1234 }
1235
1236 let Some(s) = spec else {
1238 return target;
1239 };
1240 let mut start = target;
1241 if let Some(pulse_from) = s.pulse_from_bg {
1242 start.bg = pulse_from;
1243 }
1244 if let Some(enter) = s.enter {
1245 start.opacity = enter.opacity;
1246 start.bounds = Region::new(
1247 target.bounds.x.saturating_add(enter.dx),
1248 target.bounds.y.saturating_add(enter.dy),
1249 target.bounds.w,
1250 target.bounds.h,
1251 );
1252 }
1253 let animating = s.enter.is_some() || !matches!(s.loop_mode, LoopMode::Once);
1254 let duration_ms = ActiveTransition::clamp_duration(s.duration_ms);
1255 let mut entry = ActiveTransition {
1256 id,
1257 path_hash,
1258 start_bounds: start.bounds,
1259 target_bounds: target.bounds,
1260 start_bg: start.bg,
1261 target_bg: target.bg,
1262 start_border: start.border,
1263 target_border: target.border,
1264 parent_x: parent_origin.0,
1265 parent_y: parent_origin.1,
1266 elapsed_ms: if animating {
1267 ActiveTransition::delay_to_elapsed(s.delay_ms)
1268 } else {
1269 duration_ms as i16
1270 },
1271 duration_ms,
1272 mode_flags: FLAG_SEEN,
1273 start_opacity: start.opacity,
1274 target_opacity: target.opacity,
1275 pos_q4: region_to_q4(if animating { start.bounds } else { target.bounds }),
1276 vel_q4: [0; 4],
1277 spring_t_q8: if animating { 0 } else { 256 },
1278 spring_vt_q8: 0,
1279 };
1280 entry.set_mode(s.easing, s.loop_mode);
1281 let state = entry.current_state();
1282 if !self.transitions.push(entry) {
1283 if let Some(slot) = self.transitions.iter_mut().find(|t| !t.is_active()) {
1284 *slot = entry;
1285 } else {
1286 return target;
1287 }
1288 }
1289 state
1290 }
1291
1292 pub fn resolve_div(
1294 &mut self,
1295 id: u32,
1296 target_bounds: Region,
1297 target_bg: Color,
1298 target_border: Color,
1299 spec: Option<TransitionSpec>,
1300 ) -> (Region, Color, Color) {
1301 let st = self.resolve(
1302 id,
1303 MotionState::new(target_bounds, target_bg, target_border),
1304 spec,
1305 );
1306 (st.bounds, st.bg, st.border)
1307 }
1308
1309 pub fn resolve_text_color(&mut self, id: u32, target_color: Color, duration_ms: u16) -> Color {
1311 self.resolve_text_color_with(
1312 id,
1313 target_color,
1314 TransitionSpec {
1315 duration_ms,
1316 ..TransitionSpec::default()
1317 },
1318 )
1319 }
1320
1321 pub fn resolve_text_color_with(
1323 &mut self,
1324 id: u32,
1325 target_color: Color,
1326 parent: TransitionSpec,
1327 ) -> Color {
1328 let spec = TransitionSpec {
1329 duration_ms: parent.duration_ms,
1330 delay_ms: parent.delay_ms,
1331 easing: parent.easing,
1332 animate_color: true,
1333 ..TransitionSpec::default()
1334 };
1335 self.resolve(
1336 id,
1337 MotionState::new(Region::EMPTY, target_color, Color::TRANSPARENT),
1338 Some(spec),
1339 )
1340 .bg
1341 }
1342
1343 pub fn scroll_offset(&self, id: u32) -> i16 {
1345 self.scroll_offsets
1346 .iter()
1347 .find(|e| e.id == id)
1348 .map(|e| e.offset_y.saturating_add((e.overscroll_q4 >> 4) as i16))
1349 .unwrap_or(0)
1350 }
1351
1352 pub fn scroll_overscroll(&self, id: u32) -> i16 {
1354 self.scroll_offsets
1355 .iter()
1356 .find(|e| e.id == id)
1357 .map(|e| (e.overscroll_q4 >> 4) as i16)
1358 .unwrap_or(0)
1359 }
1360
1361 pub fn apply_scroll_drag(
1363 &mut self,
1364 id: u32,
1365 delta_scroll: i16,
1366 max_scroll: i16,
1367 viewport_dim: i16,
1368 ) {
1369 let clamped_max = max_scroll.max(0);
1370 let dim = viewport_dim.max(64);
1371 let reduced = self.reduced_motion;
1372
1373 let idx = if let Some(i) = self.scroll_offsets.iter().position(|e| e.id == id) {
1374 i
1375 } else {
1376 self.insert_scroll_entry(ScrollEntry {
1377 id,
1378 offset_y: 0,
1379 velocity_y: 0,
1380 max_scroll: clamped_max,
1381 overscroll_q4: 0,
1382 overscroll_vel_q4: 0,
1383 drag_overscroll_raw: 0,
1384 viewport_dim: dim,
1385 is_dragging: true,
1386 });
1387 match self.scroll_offsets.iter().position(|e| e.id == id) {
1388 Some(i) => i,
1389 None => return,
1390 }
1391 };
1392
1393 let entry = &mut self.scroll_offsets[idx];
1394 entry.max_scroll = clamped_max;
1395 entry.viewport_dim = dim;
1396 entry.is_dragging = true;
1397 entry.velocity_y = 0;
1398 entry.overscroll_vel_q4 = 0;
1399
1400 if entry.drag_overscroll_raw != 0 {
1401 let next_raw = (entry.drag_overscroll_raw as i32) + (delta_scroll as i32);
1402 if (entry.drag_overscroll_raw > 0 && next_raw <= 0)
1403 || (entry.drag_overscroll_raw < 0 && next_raw >= 0)
1404 {
1405 entry.drag_overscroll_raw = 0;
1406 entry.overscroll_q4 = 0;
1407 entry.offset_y = ((entry.offset_y as i32) + next_raw).clamp(0, clamped_max as i32) as i16;
1408 } else {
1409 entry.drag_overscroll_raw = next_raw.clamp(-4096, 4096) as i16;
1410 let damped = if reduced {
1411 0
1412 } else {
1413 rubberband_i16(entry.drag_overscroll_raw, dim, 140)
1414 };
1415 entry.overscroll_q4 = (damped as i32) << 4;
1416 }
1417 } else {
1418 let raw_next = (entry.offset_y as i32) + (delta_scroll as i32);
1419 if raw_next < 0 {
1420 entry.offset_y = 0;
1421 if !reduced {
1422 entry.drag_overscroll_raw = raw_next.clamp(-4096, 4096) as i16;
1423 entry.overscroll_q4 = (rubberband_i16(entry.drag_overscroll_raw, dim, 140) as i32) << 4;
1424 }
1425 } else if raw_next > clamped_max as i32 {
1426 entry.offset_y = clamped_max;
1427 if !reduced {
1428 let over = raw_next - clamped_max as i32;
1429 entry.drag_overscroll_raw = over.clamp(-4096, 4096) as i16;
1430 entry.overscroll_q4 = (rubberband_i16(entry.drag_overscroll_raw, dim, 140) as i32) << 4;
1431 }
1432 } else {
1433 entry.offset_y = raw_next as i16;
1434 entry.overscroll_q4 = 0;
1435 }
1436 }
1437 self.set_stale_at(idx, 0);
1438 }
1439
1440 pub fn release_scroll_drag(&mut self, id: u32, release_velocity_y: i16, max_scroll: i16) {
1442 if let Some((idx, entry)) = self
1443 .scroll_offsets
1444 .iter_mut()
1445 .enumerate()
1446 .find(|(_, e)| e.id == id)
1447 {
1448 entry.is_dragging = false;
1449 entry.drag_overscroll_raw = 0;
1450 if max_scroll >= 0 {
1451 entry.max_scroll = max_scroll;
1452 entry.offset_y = entry.offset_y.clamp(0, max_scroll);
1453 }
1454 if entry.overscroll_q4 != 0 {
1455 entry.velocity_y = 0;
1456 if self.reduced_motion {
1457 entry.overscroll_q4 = 0;
1458 entry.overscroll_vel_q4 = 0;
1459 } else {
1460 entry.overscroll_vel_q4 = (release_velocity_y as i32).saturating_mul(640);
1461 }
1462 } else {
1463 entry.velocity_y = release_velocity_y;
1464 }
1465 self.set_stale_at(idx, 0);
1466 } else if release_velocity_y != 0 {
1467 self.set_scroll_inertia(id, release_velocity_y, max_scroll);
1468 }
1469 }
1470
1471 fn insert_scroll_entry(&mut self, entry: ScrollEntry) {
1472 if self.scroll_offsets.len() >= 64 {
1473 if let Some((idx, _)) = (0..self.scroll_offsets.len())
1474 .filter(|&i| self.scroll_offsets[i].velocity_y == 0)
1475 .map(|i| (i, self.stale_at(i)))
1476 .max_by_key(|&(_, st)| st)
1477 {
1478 self.scroll_offsets[idx] = entry;
1479 self.set_stale_at(idx, 0);
1480 return;
1481 }
1482 self.scroll_offsets[0] = entry;
1483 self.set_stale_at(0, 0);
1484 return;
1485 }
1486 let new_idx = self.scroll_offsets.len();
1487 if self.scroll_offsets.push(entry) {
1488 self.set_stale_at(new_idx, 0);
1489 } else if let Some((idx, _)) = (0..self.scroll_offsets.len())
1490 .map(|i| (i, (self.scroll_offsets[i].velocity_y == 0, self.stale_at(i))))
1491 .max_by_key(|&(_, k)| k)
1492 {
1493 self.scroll_offsets[idx] = entry;
1494 self.set_stale_at(idx, 0);
1495 }
1496 }
1497
1498 pub fn set_scroll_offset(&mut self, id: u32, offset_y: i16) {
1500 if let Some((idx, entry)) = self
1501 .scroll_offsets
1502 .iter_mut()
1503 .enumerate()
1504 .find(|(_, e)| e.id == id)
1505 {
1506 let max_s = if entry.max_scroll >= 0 {
1507 entry.max_scroll
1508 } else {
1509 i16::MAX
1510 };
1511 entry.offset_y = offset_y.clamp(0, max_s);
1512 entry.overscroll_q4 = 0;
1513 entry.overscroll_vel_q4 = 0;
1514 entry.drag_overscroll_raw = 0;
1515 entry.is_dragging = false;
1516 self.set_stale_at(idx, 0);
1517 } else {
1518 self.insert_scroll_entry(ScrollEntry {
1519 id,
1520 offset_y: offset_y.max(0),
1521 velocity_y: 0,
1522 max_scroll: -1,
1523 overscroll_q4: 0,
1524 overscroll_vel_q4: 0,
1525 drag_overscroll_raw: 0,
1526 viewport_dim: 240,
1527 is_dragging: false,
1528 });
1529 }
1530 }
1531
1532 pub fn set_scroll_inertia(&mut self, id: u32, velocity_y: i16, max_scroll: i16) {
1534 if let Some((idx, entry)) = self
1535 .scroll_offsets
1536 .iter_mut()
1537 .enumerate()
1538 .find(|(_, e)| e.id == id)
1539 {
1540 entry.is_dragging = false;
1541 entry.velocity_y = velocity_y;
1542 if max_scroll >= 0 {
1543 entry.max_scroll = max_scroll;
1544 entry.offset_y = entry.offset_y.clamp(0, max_scroll);
1545 }
1546 self.set_stale_at(idx, 0);
1547 } else {
1548 let eff_max = if max_scroll >= 0 { max_scroll } else { -1 };
1549 self.insert_scroll_entry(ScrollEntry {
1550 id,
1551 offset_y: 0,
1552 velocity_y,
1553 max_scroll: eff_max,
1554 overscroll_q4: 0,
1555 overscroll_vel_q4: 0,
1556 drag_overscroll_raw: 0,
1557 viewport_dim: 240,
1558 is_dragging: false,
1559 });
1560 }
1561 }
1562}
1563
1564#[inline]
1565fn lerp_i16_signed(a: i16, b: i16, t_256: i32) -> i16 {
1566 let diff = (b as i32) - (a as i32);
1567 let val = (a as i32) + ((diff * t_256) >> 8);
1568 val.clamp(i16::MIN as i32, i16::MAX as i32) as i16
1569}
1570
1571#[inline]
1572fn lerp_i16_signed_q4(a: i16, b: i16, t_256: i32) -> (i16, i8) {
1573 let diff = (b as i32) - (a as i32);
1574 let q4 = ((a as i32) << 4) + ((diff * t_256) >> 4);
1575 let rounded = if q4 >= 0 { (q4 + 8) >> 4 } else { -((-q4 + 8) >> 4) };
1576 let r = rounded.clamp(i16::MIN as i32, i16::MAX as i32) as i16;
1577 let rem = (q4 - ((r as i32) << 4)).clamp(-8, 7) as i8;
1578 (r, rem)
1579}
1580
1581#[inline]
1582fn lerp_region_signed_q4(a: Region, b: Region, t_256: i32) -> (Region, u8) {
1583 let (x, dx) = lerp_i16_signed_q4(a.x, b.x, t_256);
1584 let (y, dy) = lerp_i16_signed_q4(a.y, b.y, t_256);
1585 (
1586 Region {
1587 x,
1588 y,
1589 w: lerp_i16_signed(a.w, b.w, t_256).max(0),
1590 h: lerp_i16_signed(a.h, b.h, t_256).max(0),
1591 },
1592 pack_subpx_q4(dx, dy),
1593 )
1594}
1595