1use crate::arena::SmallVec;
4use crate::element::TransitionSpec;
5use crate::solver::Region;
6use crate::style::{Color, Easing, LoopMode};
7
8#[derive(Copy, Clone, PartialEq, Eq, Debug)]
10pub struct MotionState {
11 pub bounds: Region,
13 pub bg: Color,
15 pub border: Color,
17 pub opacity: u8,
19}
20
21impl MotionState {
22 #[inline(always)]
24 pub const fn new(bounds: Region, bg: Color, border: Color) -> Self {
25 Self {
26 bounds,
27 bg,
28 border,
29 opacity: 255,
30 }
31 }
32
33 #[inline(always)]
35 pub const fn with_opacity(mut self, opacity: u8) -> Self {
36 self.opacity = opacity;
37 self
38 }
39
40 #[inline]
41 fn lerp(self, to: Self, t_256: i32) -> Self {
42 let t_clamped = t_256.clamp(0, 256) as u16;
43 let op = self.opacity as i32 + (((to.opacity as i32 - self.opacity as i32) * t_256) >> 8);
44 Self {
45 bounds: lerp_region_signed(self.bounds, to.bounds, t_256),
46 bg: self.bg.lerp(to.bg, t_clamped),
47 border: self.border.lerp(to.border, t_clamped),
48 opacity: op.clamp(0, 255) as u8,
49 }
50 }
51}
52
53#[derive(Copy, Clone, Debug)]
58struct ActiveTransition {
59 id: u32,
60 path_hash: u32,
61 start_bounds: Region,
62 target_bounds: Region,
63 start_bg: Color,
64 target_bg: Color,
65 start_border: Color,
66 target_border: Color,
67 parent_x: i16,
69 parent_y: i16,
70 elapsed_ms: i16,
72 duration_ms: u16,
74 mode_flags: u8,
76 start_opacity: u8,
77 target_opacity: u8,
78}
79
80const FLAG_REVERSE: u8 = 0x20;
81const FLAG_SEEN: u8 = 0x40;
82
83impl ActiveTransition {
84 #[inline(always)]
85 const fn easing(&self) -> Easing {
86 Easing::from_bits(self.mode_flags)
87 }
88
89 #[inline(always)]
90 const fn loop_mode(&self) -> LoopMode {
91 match (self.mode_flags >> 3) & 0x03 {
92 1 => LoopMode::Infinite,
93 2 => LoopMode::PingPong,
94 _ => LoopMode::Once,
95 }
96 }
97
98 #[inline(always)]
99 const fn is_reverse(&self) -> bool {
100 (self.mode_flags & FLAG_REVERSE) != 0
101 }
102
103 #[inline(always)]
104 const fn seen(&self) -> bool {
105 (self.mode_flags & FLAG_SEEN) != 0
106 }
107
108 #[inline(always)]
109 fn set_seen(&mut self, seen: bool) {
110 if seen {
111 self.mode_flags |= FLAG_SEEN;
112 } else {
113 self.mode_flags &= !FLAG_SEEN;
114 }
115 }
116
117 #[inline(always)]
119 fn set_mode(&mut self, easing: Easing, loop_mode: LoopMode) {
120 self.mode_flags = (easing as u8 & 0x07)
121 | ((loop_mode as u8 & 0x03) << 3)
122 | (self.mode_flags & (FLAG_REVERSE | FLAG_SEEN));
123 }
124
125 #[inline(always)]
126 const fn clamp_duration(ms: u16) -> u16 {
127 if ms > i16::MAX as u16 { i16::MAX as u16 } else { ms }
128 }
129
130 #[inline(always)]
131 const fn delay_to_elapsed(delay_ms: u16) -> i16 {
132 if delay_ms > i16::MAX as u16 {
133 i16::MIN + 1
134 } else {
135 -(delay_ms as i16)
136 }
137 }
138
139 #[inline(always)]
140 const fn is_active(&self) -> bool {
141 if self.duration_ms == 0 {
142 return false;
143 }
144 !matches!(self.loop_mode(), LoopMode::Once) || (self.elapsed_ms as i32) < self.duration_ms as i32
145 }
146
147 #[inline(always)]
148 fn start_state(&self) -> MotionState {
149 MotionState {
150 bounds: self.start_bounds,
151 bg: self.start_bg,
152 border: self.start_border,
153 opacity: self.start_opacity,
154 }
155 }
156
157 #[inline(always)]
158 fn target_state(&self) -> MotionState {
159 MotionState {
160 bounds: self.target_bounds,
161 bg: self.target_bg,
162 border: self.target_border,
163 opacity: self.target_opacity,
164 }
165 }
166
167 #[inline(always)]
168 fn set_start(&mut self, s: MotionState) {
169 self.start_bounds = s.bounds;
170 self.start_bg = s.bg;
171 self.start_border = s.border;
172 self.start_opacity = s.opacity;
173 }
174
175 #[inline(always)]
176 fn set_target(&mut self, s: MotionState) {
177 self.target_bounds = s.bounds;
178 self.target_bg = s.bg;
179 self.target_border = s.border;
180 self.target_opacity = s.opacity;
181 }
182
183 #[inline]
185 fn settle(&mut self, target: MotionState) {
186 self.set_start(target);
187 self.set_target(target);
188 self.elapsed_ms = self.duration_ms as i16;
189 self.mode_flags &= 0x07 | FLAG_SEEN;
190 }
191
192 #[inline]
193 fn current_state(&self) -> MotionState {
194 if self.duration_ms == 0
195 || (matches!(self.loop_mode(), LoopMode::Once)
196 && (self.elapsed_ms as i32) >= self.duration_ms as i32)
197 {
198 return self.target_state();
199 }
200 let phase = self.elapsed_ms.max(0) as u32;
201 let dur = self.duration_ms as u32;
202 let eff = if self.is_reverse() {
203 dur.saturating_sub(phase)
204 } else {
205 phase
206 };
207 let t_256 = self.easing().sample_256(eff, dur);
208 self.start_state().lerp(self.target_state(), t_256)
209 }
210}
211
212#[derive(Copy, Clone, Debug)]
214struct ScrollEntry {
215 id: u32,
216 offset_y: i16,
217 velocity_y: i16,
218 max_scroll: i16,
219}
220
221#[derive(Debug)]
226pub struct MotionCache {
227 transitions: SmallVec<ActiveTransition, 16>,
228 scroll_offsets: SmallVec<ScrollEntry, 16>,
229 scroll_stale_bits: u32,
231}
232
233impl Default for MotionCache {
234 fn default() -> Self {
235 Self::new()
236 }
237}
238
239impl MotionCache {
240 pub const fn new() -> Self {
242 Self {
243 transitions: SmallVec::new(),
244 scroll_offsets: SmallVec::new(),
245 scroll_stale_bits: 0,
246 }
247 }
248
249 #[inline(always)]
250 fn stale_at(&self, idx: usize) -> u8 {
251 if idx < 16 {
252 ((self.scroll_stale_bits >> (idx * 2)) & 0x03) as u8
253 } else {
254 0
255 }
256 }
257
258 #[inline(always)]
259 fn set_stale_at(&mut self, idx: usize, val: u8) {
260 if idx < 16 {
261 let shift = idx * 2;
262 self.scroll_stale_bits = (self.scroll_stale_bits & !(0x03u32 << shift))
263 | (((val.min(3)) as u32) << shift);
264 }
265 }
266
267 pub fn tick(&mut self, dt_ms: u16) -> bool {
270 let mut any_stepped = false;
271 for tr in self.transitions.iter_mut() {
272 if tr.is_active() {
273 any_stepped = true;
274 let dur = tr.duration_ms as i32;
275 let next = tr.elapsed_ms as i32 + dt_ms as i32;
276 if next >= dur {
277 match tr.loop_mode() {
278 LoopMode::Once => {
279 tr.elapsed_ms = dur as i16;
280 }
281 LoopMode::Infinite => {
282 tr.elapsed_ms = (next % dur.max(1)) as i16;
283 }
284 LoopMode::PingPong => {
285 tr.elapsed_ms = (next % dur.max(1)) as i16;
286 tr.mode_flags ^= FLAG_REVERSE;
287 }
288 }
289 } else {
290 tr.elapsed_ms = next as i16;
291 }
292 }
293 }
294
295 for sc in self.scroll_offsets.iter_mut() {
297 if sc.velocity_y != 0 {
298 any_stepped = true;
299 let max_s = if sc.max_scroll >= 0 {
300 sc.max_scroll
301 } else {
302 i16::MAX
303 };
304 let step = (((sc.velocity_y as i32) * (dt_ms.max(1) as i32)) / 16)
305 .clamp(i16::MIN as i32, i16::MAX as i32) as i16;
306 let delta = if step != 0 {
307 step
308 } else if sc.velocity_y > 0 {
309 1
310 } else {
311 -1
312 };
313 let next_off = sc.offset_y.saturating_add(delta).clamp(0, max_s);
314 if next_off == sc.offset_y {
315 sc.velocity_y = 0;
316 } else {
317 sc.offset_y = next_off;
318 sc.velocity_y = (((sc.velocity_y as i32) * 7) / 8) as i16;
319 if sc.velocity_y.abs() <= 1 {
320 sc.velocity_y = 0;
321 }
322 }
323 }
324 }
325 any_stepped
326 }
327
328 #[inline]
330 pub fn has_active_animations(&self) -> bool {
331 self.transitions.iter().any(|t| t.is_active())
332 || self.scroll_offsets.iter().any(|s| s.velocity_y != 0)
333 }
334
335 #[inline]
337 pub fn transition_count(&self) -> usize {
338 self.transitions.len()
339 }
340
341 pub fn begin_frame(&mut self) {
343 for tr in self.transitions.iter_mut() {
344 tr.set_seen(false);
345 }
346 let n = self.scroll_offsets.len().min(16);
347 for idx in 0..n {
348 let next = self.stale_at(idx).saturating_add(1);
349 self.set_stale_at(idx, next);
350 }
351 }
352
353 pub fn end_frame(&mut self) {
355 let mut i = 0;
356 while i < self.transitions.len() {
357 if self.transitions[i].seen() {
358 i += 1;
359 } else {
360 self.transitions.swap_remove(i);
361 }
362 }
363 let mut s_idx = 0;
364 while s_idx < self.scroll_offsets.len() {
365 let stale = self.stale_at(s_idx);
366 let sc = &self.scroll_offsets[s_idx];
367 let evict = sc.velocity_y == 0
368 && (stale >= 3
369 || (stale >= 2 && (sc.offset_y == 0 || self.scroll_offsets.len() > 12)));
370 if evict {
371 let last_idx = self.scroll_offsets.len() - 1;
372 let last_stale = self.stale_at(last_idx);
373 self.scroll_offsets.swap_remove(s_idx);
374 self.set_stale_at(s_idx, last_stale);
375 self.set_stale_at(last_idx, 0);
376 } else {
377 s_idx += 1;
378 }
379 }
380 }
381
382 #[inline]
384 pub(crate) fn sync_scroll_bounds(&mut self, id: u32, max_scroll: i16) {
385 let clamped_max = max_scroll.max(0);
386 if let Some((idx, entry)) = self
387 .scroll_offsets
388 .iter_mut()
389 .enumerate()
390 .find(|(_, e)| e.id == id)
391 {
392 entry.max_scroll = clamped_max;
393 entry.offset_y = entry.offset_y.clamp(0, clamped_max);
394 self.set_stale_at(idx, 0);
395 }
396 }
397
398 pub fn finish_all(&mut self) {
400 for tr in self.transitions.iter_mut() {
401 if !matches!(tr.loop_mode(), LoopMode::Once) {
402 continue;
403 }
404 let target = tr.target_state();
405 tr.settle(target);
406 }
407 }
408
409 pub fn current_state(&self, id: u32) -> Option<MotionState> {
411 self.transitions
412 .iter()
413 .find(|t| t.id == id)
414 .map(|t| t.current_state())
415 }
416
417 pub(crate) fn peek_offset_opacity_scoped(
419 &self,
420 id: u32,
421 path_hash: u32,
422 ) -> Option<(i16, i16, u8)> {
423 self.transitions
424 .iter()
425 .find(|t| t.id == id && t.path_hash == path_hash)
426 .or_else(|| self.transitions.iter().find(|t| t.id == id))
427 .map(|t| {
428 let cur = t.current_state();
429 (
430 cur.bounds.x.saturating_sub(t.target_bounds.x),
431 cur.bounds.y.saturating_sub(t.target_bounds.y),
432 cur.opacity,
433 )
434 })
435 }
436
437 pub fn resolve(
439 &mut self,
440 id: u32,
441 target: MotionState,
442 spec: Option<TransitionSpec>,
443 ) -> MotionState {
444 self.resolve_inner(id, id, (0, 0), target, spec, false)
445 }
446
447 pub(crate) fn resolve_scoped(
454 &mut self,
455 id: u32,
456 path_hash: u32,
457 parent_origin: (i16, i16),
458 target: MotionState,
459 spec: Option<TransitionSpec>,
460 ) -> MotionState {
461 self.resolve_inner(id, path_hash, parent_origin, target, spec, true)
462 }
463
464 fn resolve_inner(
465 &mut self,
466 id: u32,
467 path_hash: u32,
468 parent_origin: (i16, i16),
469 target: MotionState,
470 spec: Option<TransitionSpec>,
471 guard_same_frame_dup: bool,
472 ) -> MotionState {
473 let matched_idx = self
474 .transitions
475 .iter()
476 .position(|t| t.id == id && t.path_hash == path_hash)
477 .or_else(|| {
478 if spec.is_some() {
479 self.transitions
480 .iter()
481 .position(|t| t.id == id && (!guard_same_frame_dup || !t.seen()))
482 } else {
483 None
484 }
485 });
486
487 if let Some(idx) = matched_idx {
488 let tr = &mut self.transitions[idx];
489 if guard_same_frame_dup && tr.seen() {
490 return target;
492 }
493 let same_parent = tr.path_hash == path_hash;
494 if same_parent {
495 let pdx = parent_origin.0.saturating_sub(tr.parent_x);
496 let pdy = parent_origin.1.saturating_sub(tr.parent_y);
497 if pdx != 0 || pdy != 0 {
498 tr.start_bounds.x = tr.start_bounds.x.saturating_add(pdx);
499 tr.start_bounds.y = tr.start_bounds.y.saturating_add(pdy);
500 tr.target_bounds.x = tr.target_bounds.x.saturating_add(pdx);
501 tr.target_bounds.y = tr.target_bounds.y.saturating_add(pdy);
502 }
503 }
504 tr.parent_x = parent_origin.0;
505 tr.parent_y = parent_origin.1;
506 tr.path_hash = path_hash;
507 tr.set_seen(true);
508 let Some(s) = spec else {
509 tr.settle(target);
510 return target;
511 };
512 tr.set_mode(s.easing, s.loop_mode);
513
514 if let Some(pulse_from) = s.pulse_from_bg {
515 tr.set_start(MotionState {
516 bg: pulse_from,
517 ..target
518 });
519 tr.set_target(target);
520 tr.duration_ms = ActiveTransition::clamp_duration(s.duration_ms.max(1));
521 return tr.current_state();
522 }
523
524 let color_changed = s.animate_color
525 && (tr.target_bg != target.bg || tr.target_border != target.border);
526 let bounds_changed = s.animate_bounds && tr.target_bounds != target.bounds;
527 let opacity_changed = s.animate_opacity && tr.target_opacity != target.opacity;
528
529 if color_changed || bounds_changed || opacity_changed {
530 let in_flight = tr.is_active();
532 let cur = tr.current_state();
533 tr.set_start(MotionState {
534 bounds: if s.animate_bounds || in_flight {
535 cur.bounds
536 } else {
537 target.bounds
538 },
539 bg: if s.animate_color || in_flight {
540 cur.bg
541 } else {
542 target.bg
543 },
544 border: if (s.animate_color || in_flight)
545 && cur.border.a() > 0
546 && target.border.a() > 0
547 {
548 cur.border
549 } else {
550 target.border
551 },
552 opacity: if s.animate_opacity || in_flight {
553 cur.opacity
554 } else {
555 target.opacity
556 },
557 });
558 tr.set_target(target);
559 tr.duration_ms = ActiveTransition::clamp_duration(s.duration_ms.max(1));
560 tr.elapsed_ms = ActiveTransition::delay_to_elapsed(s.delay_ms);
561 } else if !tr.is_active() {
562 tr.set_start(target);
563 tr.set_target(target);
564 } else {
565 if tr.target_bounds != target.bounds {
567 let dx = target.bounds.x.saturating_sub(tr.target_bounds.x);
568 let dy = target.bounds.y.saturating_sub(tr.target_bounds.y);
569 tr.start_bounds = Region::new(
570 tr.start_bounds.x.saturating_add(dx),
571 tr.start_bounds.y.saturating_add(dy),
572 target.bounds.w,
573 target.bounds.h,
574 );
575 tr.target_bounds = target.bounds;
576 }
577 if tr.target_bg != target.bg || tr.target_border != target.border {
578 tr.start_bg = target.bg;
579 tr.start_border = target.border;
580 tr.target_bg = target.bg;
581 tr.target_border = target.border;
582 }
583 tr.target_opacity = target.opacity;
584 }
585 return tr.current_state();
586 }
587
588 let Some(s) = spec else {
590 return target;
591 };
592 let mut start = target;
593 if let Some(pulse_from) = s.pulse_from_bg {
594 start.bg = pulse_from;
595 }
596 if let Some(enter) = s.enter {
597 start.opacity = enter.opacity;
598 start.bounds = Region::new(
599 target.bounds.x.saturating_add(enter.dx),
600 target.bounds.y.saturating_add(enter.dy),
601 target.bounds.w,
602 target.bounds.h,
603 );
604 }
605 let animating = s.enter.is_some() || !matches!(s.loop_mode, LoopMode::Once);
606 let duration_ms = ActiveTransition::clamp_duration(s.duration_ms);
607 let mut entry = ActiveTransition {
608 id,
609 path_hash,
610 start_bounds: start.bounds,
611 target_bounds: target.bounds,
612 start_bg: start.bg,
613 target_bg: target.bg,
614 start_border: start.border,
615 target_border: target.border,
616 parent_x: parent_origin.0,
617 parent_y: parent_origin.1,
618 elapsed_ms: if animating {
619 ActiveTransition::delay_to_elapsed(s.delay_ms)
620 } else {
621 duration_ms as i16
622 },
623 duration_ms,
624 mode_flags: FLAG_SEEN,
625 start_opacity: start.opacity,
626 target_opacity: target.opacity,
627 };
628 entry.set_mode(s.easing, s.loop_mode);
629 let state = entry.current_state();
630 if !self.transitions.push(entry) {
631 if let Some(slot) = self.transitions.iter_mut().find(|t| !t.is_active()) {
633 *slot = entry;
634 } else {
635 return target;
636 }
637 }
638 state
639 }
640
641 pub fn resolve_div(
643 &mut self,
644 id: u32,
645 target_bounds: Region,
646 target_bg: Color,
647 target_border: Color,
648 spec: Option<TransitionSpec>,
649 ) -> (Region, Color, Color) {
650 let st = self.resolve(
651 id,
652 MotionState::new(target_bounds, target_bg, target_border),
653 spec,
654 );
655 (st.bounds, st.bg, st.border)
656 }
657
658 pub fn resolve_text_color(&mut self, id: u32, target_color: Color, duration_ms: u16) -> Color {
660 self.resolve_text_color_with(
661 id,
662 target_color,
663 TransitionSpec {
664 duration_ms,
665 ..TransitionSpec::default()
666 },
667 )
668 }
669
670 pub fn resolve_text_color_with(
672 &mut self,
673 id: u32,
674 target_color: Color,
675 parent: TransitionSpec,
676 ) -> Color {
677 let spec = TransitionSpec {
678 duration_ms: parent.duration_ms,
679 delay_ms: parent.delay_ms,
680 easing: parent.easing,
681 animate_color: true,
682 ..TransitionSpec::default()
683 };
684 self.resolve(
685 id,
686 MotionState::new(Region::EMPTY, target_color, Color::TRANSPARENT),
687 Some(spec),
688 )
689 .bg
690 }
691
692 pub fn scroll_offset(&self, id: u32) -> i16 {
694 self.scroll_offsets
695 .iter()
696 .find(|e| e.id == id)
697 .map(|e| e.offset_y)
698 .unwrap_or(0)
699 }
700
701 fn insert_scroll_entry(&mut self, entry: ScrollEntry) {
702 if self.scroll_offsets.len() >= 64 {
703 if let Some((idx, _)) = (0..self.scroll_offsets.len())
704 .filter(|&i| self.scroll_offsets[i].velocity_y == 0)
705 .map(|i| (i, self.stale_at(i)))
706 .max_by_key(|&(_, st)| st)
707 {
708 self.scroll_offsets[idx] = entry;
709 self.set_stale_at(idx, 0);
710 return;
711 }
712 self.scroll_offsets[0] = entry;
713 self.set_stale_at(0, 0);
714 return;
715 }
716 let new_idx = self.scroll_offsets.len();
717 if self.scroll_offsets.push(entry) {
718 self.set_stale_at(new_idx, 0);
719 } else if let Some((idx, _)) = (0..self.scroll_offsets.len())
720 .map(|i| (i, (self.scroll_offsets[i].velocity_y == 0, self.stale_at(i))))
721 .max_by_key(|&(_, k)| k)
722 {
723 self.scroll_offsets[idx] = entry;
724 self.set_stale_at(idx, 0);
725 }
726 }
727
728 pub fn set_scroll_offset(&mut self, id: u32, offset_y: i16) {
730 if let Some((idx, entry)) = self
731 .scroll_offsets
732 .iter_mut()
733 .enumerate()
734 .find(|(_, e)| e.id == id)
735 {
736 let max_s = if entry.max_scroll >= 0 {
737 entry.max_scroll
738 } else {
739 i16::MAX
740 };
741 entry.offset_y = offset_y.clamp(0, max_s);
742 self.set_stale_at(idx, 0);
743 } else {
744 self.insert_scroll_entry(ScrollEntry {
745 id,
746 offset_y: offset_y.max(0),
747 velocity_y: 0,
748 max_scroll: -1,
749 });
750 }
751 }
752
753 pub fn set_scroll_inertia(&mut self, id: u32, velocity_y: i16, max_scroll: i16) {
755 if let Some((idx, entry)) = self
756 .scroll_offsets
757 .iter_mut()
758 .enumerate()
759 .find(|(_, e)| e.id == id)
760 {
761 entry.velocity_y = velocity_y;
762 if max_scroll >= 0 {
763 entry.max_scroll = max_scroll;
764 entry.offset_y = entry.offset_y.clamp(0, max_scroll);
765 }
766 self.set_stale_at(idx, 0);
767 } else {
768 let eff_max = if max_scroll >= 0 { max_scroll } else { -1 };
769 self.insert_scroll_entry(ScrollEntry {
770 id,
771 offset_y: 0,
772 velocity_y,
773 max_scroll: eff_max,
774 });
775 }
776 }
777}
778
779#[inline]
780fn lerp_i16_signed(a: i16, b: i16, t_256: i32) -> i16 {
781 let diff = (b as i32) - (a as i32);
782 let val = (a as i32) + ((diff * t_256) >> 8);
783 val.clamp(i16::MIN as i32, i16::MAX as i32) as i16
784}
785
786#[inline]
787fn lerp_region_signed(a: Region, b: Region, t_256: i32) -> Region {
788 Region {
789 x: lerp_i16_signed(a.x, b.x, t_256),
790 y: lerp_i16_signed(a.y, b.y, t_256),
791 w: lerp_i16_signed(a.w, b.w, t_256).max(0),
792 h: lerp_i16_signed(a.h, b.h, t_256).max(0),
793 }
794}
795