diff --git a/crates/spline/src/lib.rs b/crates/spline/src/lib.rs index 9e794e509a5206a31884f0a56e0079c3a9a30468..ff42c0028668a9d4b8a730d699d4cb2d824d3cad 100644 --- a/crates/spline/src/lib.rs +++ b/crates/spline/src/lib.rs @@ -3,12 +3,22 @@ //! Features: //! - Both direct LMB drag AND Blender `G` (Grab), `R` (Rotate), `S` (Scale) modal editing //! - `X`/`Y` axis locks with red/green guides, integer-frame snapping (`Shift` for fine) -//! - `Cmd+F` / Numpad `.` / `F` fit-to-view, `L` Linear/Smooth, `T` Step, `I` Insert key, `Del/BS` Delete +//! - `V` Handle Type popup (`Free`/`Aligned`/`Auto`/`Vector`), `T` Easing/Interpolation popup +//! - `N` Normalize curves to `[0, 1]` with hover real-value readout pill +//! - `Cmd+F` / Numpad `.` / `F` fit-to-view, `L` Linear/Smooth, `I` Insert key, `X/Del/BS` Delete //! - Crisp high-contrast curves (zero XOR!), generous hit targets, live GPU Viewer feedback. +pub mod presets; + +pub use presets::EasingPreset; + use draw::{Glyphs, Primitive}; use model::spline::{cubic, segment_control_points}; -use model::{Comp, Keyframe, NodeId}; +use model::{Comp, CompHistory, HandleMode, Keyframe, NodeId}; +use presets::{ + apply_easing_preset, apply_handle_mode, compute_curve_bounds, display_to_value, + enforce_aligned_handle, value_to_display, +}; use std::collections::{HashMap, HashSet}; use std::sync::Arc; use winit::event::{ElementState, MouseButton}; @@ -16,6 +26,10 @@ use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey}; const RULER_H: f32 = 24.0; const SIDEBAR_W: f32 = 172.0; +const POPUP_W: f32 = 156.0; +const POPUP_HEADER_H: f32 = 22.0; +const POPUP_ROW_H: f32 = 22.0; +const POPUP_PAD: f32 = 4.0; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum HandlePart { @@ -49,11 +63,48 @@ pub enum AxisLock { struct ModalEdit { mode: TransformMode, axis: AxisLock, + /// Pivot in display coordinates `(time, display_value)`. pivot: [f64; 2], + /// Pointer at modal start in display coordinates `(time, display_value)`. start_pointer: [f64; 2], saved_splines: HashMap>, + /// Frozen per-spline `(min_v, max_v)` bounds captured when the modal began so normalized + /// drags stay stable without shifting scale mid-drag. + saved_bounds: HashMap, + /// Optional pre-edit `Comp` snapshot captured when a `CompHistory` is active. + pre_edit_snapshot: Option, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum PopupKind { + HandleType, + Easing, +} + +#[derive(Clone, Debug)] +struct PopupMenu { + kind: PopupKind, + pos: [f32; 2], +} + +const HANDLE_MENU_ITEMS: &[(HandleMode, &str)] = &[ + (HandleMode::Free, "1: Free"), + (HandleMode::Aligned, "2: Aligned"), + (HandleMode::Auto, "3: Auto"), + (HandleMode::Vector, "4: Vector"), +]; + +const EASING_MENU_ITEMS: &[(EasingPreset, &str)] = &[ + (EasingPreset::Linear, "1: Linear"), + (EasingPreset::Smooth, "2: Smooth"), + (EasingPreset::StepIn, "3: Step In"), + (EasingPreset::StepOut, "4: Step Out"), + (EasingPreset::EaseInOut, "5: Ease In-Out"), + (EasingPreset::EaseOut, "6: Ease Out"), + (EasingPreset::EaseIn, "7: Ease In"), + (EasingPreset::KnifeEase, "8: Knife Ease"), +]; + #[derive(Clone, Debug)] struct BoxSelect { start_local: [f32; 2], @@ -106,9 +157,11 @@ pub struct SplineView { pub channels: Vec<(String, String)>, pub hidden_splines: HashSet, pub selected: HashSet, + pub normalized: bool, pub palette: SplinePalette, hovered: Option, modal: Option, + popup: Option, lmb_drag_point: Option<([f32; 2], bool)>, box_select: Option, panning: Option<([f32; 2], [f64; 2], [f64; 2])>, @@ -116,6 +169,7 @@ pub struct SplineView { pointer_local: [f32; 2], current_node: Option, text_cache: HashMap, + last_hover_readout: String, } impl SplineView { @@ -127,9 +181,11 @@ impl SplineView { channels: Vec::new(), hidden_splines: HashSet::new(), selected: HashSet::new(), + normalized: false, palette: SplinePalette::from_ui(theme), hovered: None, modal: None, + popup: None, lmb_drag_point: None, box_select: None, panning: None, @@ -137,6 +193,7 @@ impl SplineView { pointer_local: [0.0, 0.0], current_node: None, text_cache: HashMap::new(), + last_hover_readout: String::new(), } } @@ -155,6 +212,7 @@ impl SplineView { self.current_node = selected_node; self.selected.clear(); self.modal = None; + self.popup = None; self.lmb_drag_point = None; let mut ch = selected_node @@ -178,6 +236,15 @@ impl SplineView { self.fit_all(comp); } + pub fn toggle_normalized(&mut self, comp: &Comp) { + self.normalized = !self.normalized; + if self.normalized { + self.v_range = [-0.12, 1.12]; + } else { + self.fit_all(comp); + } + } + pub fn fit_all(&mut self, comp: &Comp) { let mut t0 = f64::INFINITY; let mut t1 = f64::NEG_INFINITY; @@ -223,13 +290,17 @@ impl SplineView { if !t0.is_finite() { self.t_range = [comp.render_range[0] as f64, comp.render_range[1] as f64]; - self.v_range = [-0.2, 1.2]; + self.v_range = if self.normalized { [-0.12, 1.12] } else { [-0.2, 1.2] }; return; } let dt = (t1 - t0).max(20.0); - let dv = (v1 - v0).max(0.2); self.t_range = [t0 - dt * 0.14, t1 + dt * 0.14]; - self.v_range = [v0 - dv * 0.20, v1 + dv * 0.20]; + if self.normalized { + self.v_range = [-0.12, 1.12]; + } else { + let dv = (v1 - v0).max(0.2); + self.v_range = [v0 - dv * 0.20, v1 + dv * 0.20]; + } } fn plot_rect(&self) -> [f32; 4] { @@ -241,6 +312,22 @@ impl SplineView { ] } + fn normalize_pill_rect(&self) -> [f32; 4] { + [SIDEBAR_W - 46.0, 3.0, SIDEBAR_W - 6.0, RULER_H - 3.0] + } + + fn spline_bounds(&self, comp: &Comp, sname: &str) -> (f64, f64) { + if let Some(m) = &self.modal { + if let Some(&b) = m.saved_bounds.get(sname) { + return b; + } + } + comp.splines + .get(sname) + .map(compute_curve_bounds) + .unwrap_or((0.0, 1.0)) + } + fn data_to_local(&self, t: f64, v: f64) -> [f32; 2] { let r = self.plot_rect(); let tx = (t - self.t_range[0]) / (self.t_range[1] - self.t_range[0]).max(1e-6); @@ -251,6 +338,11 @@ impl SplineView { ] } + fn spline_to_local(&self, t: f64, v: f64, bounds: (f64, f64)) -> [f32; 2] { + let disp_v = value_to_display(v, bounds, self.normalized); + self.data_to_local(t, disp_v) + } + fn local_to_data(&self, l: [f32; 2]) -> [f64; 2] { let r = self.plot_rect(); let tx = f64::from((l[0] - r[0]) / (r[2] - r[0]).max(1.0)); @@ -270,8 +362,9 @@ impl SplineView { continue; } let Some(sp) = comp.splines.get(sname) else { continue }; + let bounds = self.spline_bounds(comp, sname); for (ki, kf) in sp.keyframes.iter().enumerate() { - let kp = self.data_to_local(kf.time, kf.value); + let kp = self.spline_to_local(kf.time, kf.value, bounds); let kd = hypot2(local, kp); if kd < 15.0 && best_key.as_ref().is_none_or(|(d, _)| kd < *d) { best_key = Some(( @@ -282,7 +375,7 @@ impl SplineView { if self.is_key_or_handle_selected(sname, ki) { if let Some(lh) = kf.lh { - let lp = self.data_to_local(lh[0], lh[1]); + let lp = self.spline_to_local(lh[0], lh[1], bounds); let ld = hypot2(local, lp); if ld < 14.0 && best_handle.as_ref().is_none_or(|(d, _)| ld < *d) { best_handle = Some(( @@ -292,7 +385,7 @@ impl SplineView { } } if let Some(rh) = kf.rh { - let rp = self.data_to_local(rh[0], rh[1]); + let rp = self.spline_to_local(rh[0], rh[1], bounds); let rd = hypot2(local, rp); if rd < 14.0 && best_handle.as_ref().is_none_or(|(d, _)| rd < *d) { best_handle = Some(( @@ -311,7 +404,7 @@ impl SplineView { self.selected.iter().any(|p| p.spline == spline && p.key_idx == key_idx) } - fn begin_modal(&mut self, comp: &Comp, mode: TransformMode) { + fn begin_modal(&mut self, comp: &Comp, capture_history: bool, mode: TransformMode) { if self.selected.is_empty() { return; } @@ -319,10 +412,14 @@ impl SplineView { let mut sum_v = 0.0; let mut count = 0usize; let mut saved = HashMap::new(); + let mut saved_bounds = HashMap::new(); for pref in &self.selected { if let Some(sp) = comp.splines.get(&pref.spline) { saved.entry(pref.spline.clone()).or_insert_with(|| sp.keyframes.clone()); + let bounds = *saved_bounds + .entry(pref.spline.clone()) + .or_insert_with(|| compute_curve_bounds(sp)); if let Some(kf) = sp.keyframes.get(pref.key_idx) { let pt = match pref.part { HandlePart::Key => [kf.time, kf.value], @@ -335,7 +432,7 @@ impl SplineView { pt }; sum_t += piv_pt[0]; - sum_v += piv_pt[1]; + sum_v += value_to_display(piv_pt[1], bounds, self.normalized); count += 1; } } @@ -349,6 +446,8 @@ impl SplineView { pivot: [sum_t / count as f64, sum_v / count as f64], start_pointer: self.local_to_data(self.pointer_local), saved_splines: saved, + saved_bounds, + pre_edit_snapshot: capture_history.then(|| comp.clone()), }); } @@ -356,8 +455,9 @@ impl SplineView { let Some(m) = &self.modal else { return false }; let cur = self.local_to_data(self.pointer_local); let dt = cur[0] - m.start_pointer[0]; - let dv = cur[1] - m.start_pointer[1]; + let dv_disp = cur[1] - m.start_pointer[1]; let piv = m.pivot; + let normalized = self.normalized; for (sname, orig_kfs) in &m.saved_splines { if let Some(sp) = comp.splines.get_mut(sname) { @@ -367,15 +467,47 @@ impl SplineView { let snap_t = |t: f64| if fine { t } else { t.round() }; + // Helper: convert Auto/Vector handles to Aligned/Free when manually dragged (Blender behavior), + // and mirror opposite handle if Aligned (and opposite handle isn't also explicitly selected). + let finalize_handle_drag = |kf: &mut Keyframe, pref: &PointRef, selected: &HashSet| { + kf.flags.linear = false; + match kf.handle_mode { + HandleMode::Auto => kf.handle_mode = HandleMode::Aligned, + HandleMode::Vector => kf.handle_mode = HandleMode::Free, + HandleMode::Aligned | HandleMode::Free => {} + } + if kf.handle_mode == HandleMode::Aligned { + let opp_part = match pref.part { + HandlePart::LeftHandle => HandlePart::RightHandle, + HandlePart::RightHandle => HandlePart::LeftHandle, + HandlePart::Key => return, + }; + let opp_selected = selected.contains(&PointRef { + spline: pref.spline.clone(), + key_idx: pref.key_idx, + part: opp_part, + }); + if !opp_selected { + enforce_aligned_handle(kf, pref.part); + } + } + }; + match m.mode { TransformMode::Grab => { - let (mt, mv) = match m.axis { - AxisLock::None => (dt, dv), + let (mt, mv_disp) = match m.axis { + AxisLock::None => (dt, dv_disp), AxisLock::X => (dt, 0.0), - AxisLock::Y => (0.0, dv), + AxisLock::Y => (0.0, dv_disp), }; for pref in &self.selected { let Some(sp) = comp.splines.get_mut(&pref.spline) else { continue }; + let bounds = m.saved_bounds.get(&pref.spline).copied().unwrap_or((0.0, 1.0)); + let mv = if normalized { + mv_disp * (bounds.1 - bounds.0).max(1e-9) + } else { + mv_disp + }; let Some(kf) = sp.keyframes.get_mut(pref.key_idx) else { continue }; match pref.part { HandlePart::Key => { @@ -397,14 +529,14 @@ impl SplineView { h[0] = (h[0] + mt).min(kf.time - 0.01); h[1] += mv; kf.lh = Some(h); - kf.flags.linear = false; + finalize_handle_drag(kf, pref, &self.selected); } HandlePart::RightHandle => { let mut h = kf.rh.unwrap_or([kf.time + 5.0, kf.value]); h[0] = (h[0] + mt).max(kf.time + 0.01); h[1] += mv; kf.rh = Some(h); - kf.flags.linear = false; + finalize_handle_drag(kf, pref, &self.selected); } } } @@ -412,9 +544,9 @@ impl SplineView { TransformMode::Scale => { let s0 = self.data_to_local(m.start_pointer[0], m.start_pointer[1]); let s1 = self.pointer_local; - let sp = self.data_to_local(piv[0], piv[1]); - let d0 = hypot2(s0, sp).max(10.0); - let d1 = hypot2(s1, sp); + let sp_px = self.data_to_local(piv[0], piv[1]); + let d0 = hypot2(s0, sp_px).max(10.0); + let d1 = hypot2(s1, sp_px); let f = f64::from((d1 / d0).clamp(0.05, 10.0)); let (st, sv) = match m.axis { AxisLock::None => (f, f), @@ -423,18 +555,20 @@ impl SplineView { }; for pref in &self.selected { let Some(sp) = comp.splines.get_mut(&pref.spline) else { continue }; + let bounds = m.saved_bounds.get(&pref.spline).copied().unwrap_or((0.0, 1.0)); + let piv_val = display_to_value(piv[1], bounds, normalized); let Some(kf) = sp.keyframes.get_mut(pref.key_idx) else { continue }; match pref.part { HandlePart::Key => { kf.time = snap_t(piv[0] + (kf.time - piv[0]) * st); - kf.value = piv[1] + (kf.value - piv[1]) * sv; + kf.value = piv_val + (kf.value - piv_val) * sv; if let Some(lh) = &mut kf.lh { lh[0] = piv[0] + (lh[0] - piv[0]) * st; - lh[1] = piv[1] + (lh[1] - piv[1]) * sv; + lh[1] = piv_val + (lh[1] - piv_val) * sv; } if let Some(rh) = &mut kf.rh { rh[0] = piv[0] + (rh[0] - piv[0]) * st; - rh[1] = piv[1] + (rh[1] - piv[1]) * sv; + rh[1] = piv_val + (rh[1] - piv_val) * sv; } } HandlePart::LeftHandle => { @@ -442,12 +576,14 @@ impl SplineView { lh[0] = (kf.time + (lh[0] - kf.time) * st).min(kf.time - 0.01); lh[1] = kf.value + (lh[1] - kf.value) * sv; } + finalize_handle_drag(kf, pref, &self.selected); } HandlePart::RightHandle => { if let Some(rh) = &mut kf.rh { rh[0] = (kf.time + (rh[0] - kf.time) * st).max(kf.time + 0.01); rh[1] = kf.value + (rh[1] - kf.value) * sv; } + finalize_handle_drag(kf, pref, &self.selected); } } } @@ -460,51 +596,53 @@ impl SplineView { let da = a1 - a0; let (c, s) = (da.cos(), da.sin()); - let rot = |pt: [f64; 2], center_px: [f32; 2]| -> [f64; 2] { - let p = self.data_to_local(pt[0], pt[1]); + let rot = |pt: [f64; 2], center_px: [f32; 2], bounds: (f64, f64)| -> [f64; 2] { + let p = self.spline_to_local(pt[0], pt[1], bounds); let rx = p[0] - center_px[0]; let ry = p[1] - center_px[1]; let np = [center_px[0] + rx * c - ry * s, center_px[1] + rx * s + ry * c]; - self.local_to_data(np) + let disp = self.local_to_data(np); + [disp[0], display_to_value(disp[1], bounds, normalized)] }; for pref in &self.selected { let Some(sp) = comp.splines.get_mut(&pref.spline) else { continue }; + let bounds = m.saved_bounds.get(&pref.spline).copied().unwrap_or((0.0, 1.0)); let Some(kf) = sp.keyframes.get_mut(pref.key_idx) else { continue }; match pref.part { HandlePart::Key => { if self.selected.len() == 1 { - let kp = self.data_to_local(kf.time, kf.value); + let kp = self.spline_to_local(kf.time, kf.value, bounds); ensure_handles(kf); if let Some(lh) = kf.lh { - let nl = rot(lh, kp); + let nl = rot(lh, kp, bounds); kf.lh = Some([nl[0].min(kf.time - 0.01), nl[1]]); } if let Some(rh) = kf.rh { - let nr = rot(rh, kp); + let nr = rot(rh, kp, bounds); kf.rh = Some([nr[0].max(kf.time + 0.01), nr[1]]); } kf.flags.linear = false; } else { - let nk = rot([kf.time, kf.value], sp_px); + let nk = rot([kf.time, kf.value], sp_px, bounds); kf.time = snap_t(nk[0]); kf.value = nk[1]; } } HandlePart::LeftHandle => { - let kp = self.data_to_local(kf.time, kf.value); + let kp = self.spline_to_local(kf.time, kf.value, bounds); if let Some(lh) = kf.lh { - let nl = rot(lh, kp); + let nl = rot(lh, kp, bounds); kf.lh = Some([nl[0].min(kf.time - 0.01), nl[1]]); - kf.flags.linear = false; + finalize_handle_drag(kf, pref, &self.selected); } } HandlePart::RightHandle => { - let kp = self.data_to_local(kf.time, kf.value); + let kp = self.spline_to_local(kf.time, kf.value, bounds); if let Some(rh) = kf.rh { - let nr = rot(rh, kp); + let nr = rot(rh, kp, bounds); kf.rh = Some([nr[0].max(kf.time + 0.01), nr[1]]); - kf.flags.linear = false; + finalize_handle_drag(kf, pref, &self.selected); } } } @@ -526,7 +664,7 @@ impl SplineView { } } - fn confirm_modal(&mut self, comp: &mut Comp) { + fn confirm_modal(&mut self, comp: &mut Comp, history: Option<&mut CompHistory>) { if let Some(m) = self.modal.take() { for sname in m.saved_splines.keys() { if let Some(sp) = comp.splines.get_mut(sname) { @@ -534,18 +672,182 @@ impl SplineView { } } comp.revision += 1; + if let (Some(h), Some(snap)) = (history, m.pre_edit_snapshot) { + let label = match m.mode { + TransformMode::Grab => "Grab Keyframes", + TransformMode::Rotate => "Rotate Keyframes", + TransformMode::Scale => "Scale Keyframes", + }; + h.push_snapshot(&snap, label); + } } } + fn popup_rect(&self, popup: &PopupMenu) -> [f32; 4] { + let count = match popup.kind { + PopupKind::HandleType => HANDLE_MENU_ITEMS.len(), + PopupKind::Easing => EASING_MENU_ITEMS.len(), + }; + let h = POPUP_HEADER_H + count as f32 * POPUP_ROW_H + POPUP_PAD; + let x = popup.pos[0].clamp(4.0, (self.size[0] - POPUP_W - 4.0).max(4.0)); + let y = popup.pos[1].clamp(4.0, (self.size[1] - h - 4.0).max(4.0)); + [x, y, x + POPUP_W, y + h] + } + + fn popup_item_at(&self, popup: &PopupMenu, local: [f32; 2]) -> Option { + let r = self.popup_rect(popup); + if local[0] < r[0] || local[0] > r[2] || local[1] < r[1] + POPUP_HEADER_H || local[1] > r[3] { + return None; + } + let idx = ((local[1] - (r[1] + POPUP_HEADER_H)) / POPUP_ROW_H).floor() as isize; + let count = match popup.kind { + PopupKind::HandleType => HANDLE_MENU_ITEMS.len(), + PopupKind::Easing => EASING_MENU_ITEMS.len(), + }; + if idx >= 0 && (idx as usize) < count { + Some(idx as usize) + } else { + None + } + } + + fn open_popup(&mut self, kind: PopupKind) { + self.popup = Some(PopupMenu { + kind, + pos: [self.pointer_local[0] + 6.0, self.pointer_local[1] + 6.0], + }); + } + + fn selected_keys_by_spline(&self, comp: &Comp) -> HashMap> { + let mut by_spline: HashMap> = HashMap::new(); + for pref in &self.selected { + if let Some(sp) = comp.splines.get(&pref.spline) { + if pref.key_idx < sp.keyframes.len() { + by_spline.entry(pref.spline.clone()).or_default().push(pref.key_idx); + } + } + } + for idxs in by_spline.values_mut() { + idxs.sort_unstable(); + idxs.dedup(); + } + by_spline + } + + fn apply_selected_handle_mode( + &mut self, + comp: &mut Comp, + history: Option<&mut CompHistory>, + mode: HandleMode, + ) -> bool { + let by_spline = self.selected_keys_by_spline(comp); + if by_spline.is_empty() { + return false; + } + if let Some(h) = history { + h.push_snapshot(comp, "Set Handle Type"); + } + for (sname, idxs) in by_spline { + if let Some(sp) = comp.splines.get_mut(&sname) { + for idx in idxs { + apply_handle_mode(sp, idx, mode); + } + } + } + comp.revision += 1; + true + } + + fn apply_selected_easing( + &mut self, + comp: &mut Comp, + history: Option<&mut CompHistory>, + preset: EasingPreset, + ) -> bool { + let by_spline = self.selected_keys_by_spline(comp); + if by_spline.is_empty() { + return false; + } + let pre_snap = history.as_ref().map(|_| comp.clone()); + let mut changed = false; + for (sname, idxs) in by_spline { + if let Some(sp) = comp.splines.get_mut(&sname) { + if apply_easing_preset(sp, &idxs, preset) { + changed = true; + } + } + } + if changed { + if let (Some(h), Some(snap)) = (history, pre_snap) { + h.push_snapshot(&snap, format!("Easing: {}", preset.label())); + } + comp.revision += 1; + } + changed + } + fn handle_key( &mut self, comp: &mut Comp, + mut history: Option<&mut CompHistory>, current_frame: f64, physical: Option, key: &Key, kmod: ModifiersState, actions: &mut Vec, ) { + if let Some(popup) = self.popup.clone() { + match key { + Key::Named(NamedKey::Escape) => { + self.popup = None; + } + Key::Character(c) => { + let lc = c.to_ascii_lowercase(); + if lc == "v" { + self.popup = if popup.kind == PopupKind::HandleType { + None + } else { + Some(PopupMenu { kind: PopupKind::HandleType, pos: popup.pos }) + }; + return; + } + if lc == "t" { + self.popup = if popup.kind == PopupKind::Easing { + None + } else { + Some(PopupMenu { kind: PopupKind::Easing, pos: popup.pos }) + }; + return; + } + if let Ok(num) = lc.parse::() { + if num >= 1 { + let idx = num - 1; + match popup.kind { + PopupKind::HandleType => { + if let Some(&(mode, _)) = HANDLE_MENU_ITEMS.get(idx) { + self.popup = None; + if self.apply_selected_handle_mode(comp, history, mode) { + actions.push(SplineAction::SplineEdited); + } + } + } + PopupKind::Easing => { + if let Some(&(preset, _)) = EASING_MENU_ITEMS.get(idx) { + self.popup = None; + if self.apply_selected_easing(comp, history, preset) { + actions.push(SplineAction::SplineEdited); + } + } + } + } + } + } + } + _ => {} + } + return; + } + if physical == Some(PhysicalKey::Code(KeyCode::NumpadDecimal)) { self.fit_all(comp); return; @@ -559,26 +861,35 @@ impl SplineView { } Key::Named(NamedKey::Enter) => { if self.modal.is_some() { - self.confirm_modal(comp); + self.confirm_modal(comp, history); actions.push(SplineAction::SplineEdited); } } Key::Named(NamedKey::Delete | NamedKey::Backspace) => { - if self.delete_selected(comp) { + if self.delete_selected(comp, history) { actions.push(SplineAction::SplineEdited); } } Key::Character(c) => match c.to_ascii_lowercase().as_str() { "f" if kmod.super_key() => self.fit_all(comp), "f" | "." if !kmod.super_key() => self.fit_all(comp), + "n" if !kmod.super_key() && self.modal.is_none() => { + self.toggle_normalized(comp); + } + "v" if !kmod.super_key() && self.modal.is_none() => { + self.open_popup(PopupKind::HandleType); + } + "t" if !kmod.super_key() && self.modal.is_none() => { + self.open_popup(PopupKind::Easing); + } "g" if !kmod.super_key() && self.modal.is_none() => { - self.begin_modal(comp, TransformMode::Grab); + self.begin_modal(comp, history.is_some(), TransformMode::Grab); } "r" if !kmod.super_key() && self.modal.is_none() => { - self.begin_modal(comp, TransformMode::Rotate); + self.begin_modal(comp, history.is_some(), TransformMode::Rotate); } "s" if !kmod.super_key() && self.modal.is_none() => { - self.begin_modal(comp, TransformMode::Scale); + self.begin_modal(comp, history.is_some(), TransformMode::Scale); } "x" if self.modal.is_some() => { if let Some(m) = &mut self.modal { @@ -590,7 +901,7 @@ impl SplineView { } "x" if self.modal.is_none() && !kmod.super_key() => { // Blender `X` deletes selected keys when not in a modal transform! - if self.delete_selected(comp) { + if self.delete_selected(comp, history) { actions.push(SplineAction::SplineEdited); } } @@ -605,21 +916,29 @@ impl SplineView { "i" if !kmod.super_key() && self.modal.is_none() => { // Blender `I` inserts keyframe at current integer frame on all visible channels let t = current_frame.round(); - let mut inserted = false; - for (_, sname) in &self.channels { - if self.hidden_splines.contains(sname) { - continue; + let will_insert = self.channels.iter().any(|(_, sname)| { + !self.hidden_splines.contains(sname) + && comp + .splines + .get(sname) + .is_some_and(|sp| !sp.keyframes.iter().any(|k| (k.time - t).abs() < 0.5)) + }); + if will_insert { + if let Some(h) = history.as_deref_mut() { + h.push_snapshot(comp, "Insert Keyframe"); } - if let Some(sp) = comp.splines.get_mut(sname) { - if !sp.keyframes.iter().any(|k| (k.time - t).abs() < 0.5) { - let v = sp.eval(t); - sp.keyframes.push(Keyframe::new(t, v)); - sp.sort(); - inserted = true; + for (_, sname) in &self.channels { + if self.hidden_splines.contains(sname) { + continue; + } + if let Some(sp) = comp.splines.get_mut(sname) { + if !sp.keyframes.iter().any(|k| (k.time - t).abs() < 0.5) { + let v = sp.eval(t); + sp.keyframes.push(Keyframe::new(t, v)); + sp.sort(); + } } } - } - if inserted { comp.revision += 1; actions.push(SplineAction::SplineEdited); } @@ -645,33 +964,27 @@ impl SplineView { } } "l" => { - for pref in &self.selected { - if let Some(sp) = comp.splines.get_mut(&pref.spline) { - if let Some(kf) = sp.keyframes.get_mut(pref.key_idx) { - kf.flags.linear = !kf.flags.linear; - if kf.flags.linear { - kf.lh = None; - kf.rh = None; - } else { - ensure_handles(kf); + let by_spline = self.selected_keys_by_spline(comp); + if !by_spline.is_empty() { + if let Some(h) = history.as_deref_mut() { + h.push_snapshot(comp, "Toggle Linear"); + } + for (sname, idxs) in by_spline { + if let Some(sp) = comp.splines.get_mut(&sname) { + for idx in idxs { + if let Some(kf) = sp.keyframes.get_mut(idx) { + kf.flags.linear = !kf.flags.linear; + if kf.flags.linear { + kf.lh = None; + kf.rh = None; + kf.handle_mode = HandleMode::Vector; + } else { + ensure_handles(kf); + } + } } } } - } - if !self.selected.is_empty() { - comp.revision += 1; - actions.push(SplineAction::SplineEdited); - } - } - "t" => { - for pref in &self.selected { - if let Some(sp) = comp.splines.get_mut(&pref.spline) { - if let Some(kf) = sp.keyframes.get_mut(pref.key_idx) { - kf.flags.step_in = !kf.flags.step_in; - } - } - } - if !self.selected.is_empty() { comp.revision += 1; actions.push(SplineAction::SplineEdited); } @@ -682,17 +995,30 @@ impl SplineView { } } - fn delete_selected(&mut self, comp: &mut Comp) -> bool { + fn delete_selected(&mut self, comp: &mut Comp, history: Option<&mut CompHistory>) -> bool { let mut by_spline: HashMap> = HashMap::new(); for pref in &self.selected { if pref.part == HandlePart::Key { by_spline.entry(pref.spline.clone()).or_default().push(pref.key_idx); } } - let mut changed = false; - for (sname, mut idxs) in by_spline { + for idxs in by_spline.values_mut() { idxs.sort_unstable(); idxs.dedup(); + } + let can_delete = by_spline.iter().any(|(sname, idxs)| { + comp.splines + .get(sname) + .is_some_and(|sp| sp.keyframes.len() > 1 && idxs.iter().any(|&i| i < sp.keyframes.len())) + }); + if !can_delete { + return false; + } + if let Some(h) = history { + h.push_snapshot(comp, "Delete Keyframes"); + } + let mut changed = false; + for (sname, idxs) in by_spline { if let Some(sp) = comp.splines.get_mut(&sname) { for &idx in idxs.iter().rev() { if sp.keyframes.len() > 1 && idx < sp.keyframes.len() { @@ -717,6 +1043,20 @@ impl SplineView { rect: [f32; 4], pointer_window: [f32; 2], modifiers: ModifiersState, + ) -> Vec { + self.input_with_history(comp, None, current_frame, event, rect, pointer_window, modifiers) + } + + #[allow(clippy::too_many_arguments)] + pub fn input_with_history( + &mut self, + comp: &mut Comp, + mut history: Option<&mut CompHistory>, + current_frame: f64, + event: ui::Event, + rect: [f32; 4], + pointer_window: [f32; 2], + modifiers: ModifiersState, ) -> Vec { let mut actions = Vec::new(); self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]]; @@ -725,6 +1065,9 @@ impl SplineView { match event { ui::Event::PointerMoved(p) => { self.pointer_local = [p[0] - rect[0], p[1] - rect[1]]; + if self.popup.is_some() { + return actions; + } if self.scrubbing { let t = self.local_to_data(self.pointer_local)[0].round(); actions.push(SplineAction::ScrubFrame(t)); @@ -742,7 +1085,7 @@ impl SplineView { } else if let Some((start_l, ref mut dragging)) = self.lmb_drag_point { if !*dragging && hypot2(self.pointer_local, start_l) > 3.5 { *dragging = true; - self.begin_modal(comp, TransformMode::Grab); + self.begin_modal(comp, history.is_some(), TransformMode::Grab); if self.apply_modal(comp, modifiers.shift_key()) { actions.push(SplineAction::SplineEdited); } @@ -754,6 +1097,37 @@ impl SplineView { } } ui::Event::Button { button, pressed, .. } => { + if let Some(popup) = self.popup.clone() { + if pressed { + if button == MouseButton::Left { + if let Some(idx) = self.popup_item_at(&popup, self.pointer_local) { + self.popup = None; + match popup.kind { + PopupKind::HandleType => { + if let Some(&(mode, _)) = HANDLE_MENU_ITEMS.get(idx) { + if self.apply_selected_handle_mode(comp, history, mode) { + actions.push(SplineAction::SplineEdited); + } + } + } + PopupKind::Easing => { + if let Some(&(preset, _)) = EASING_MENU_ITEMS.get(idx) { + if self.apply_selected_easing(comp, history, preset) { + actions.push(SplineAction::SplineEdited); + } + } + } + } + } else { + self.popup = None; + } + } else { + self.popup = None; + } + } + return actions; + } + if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) { if pressed { self.panning = Some((self.pointer_local, self.t_range, self.v_range)); @@ -769,9 +1143,11 @@ impl SplineView { } else if button == MouseButton::Left { if pressed { if self.modal.is_some() { - self.confirm_modal(comp); + self.confirm_modal(comp, history); self.lmb_drag_point = None; actions.push(SplineAction::SplineEdited); + } else if point_in_rect(self.pointer_local, self.normalize_pill_rect()) { + self.toggle_normalized(comp); } else if self.pointer_local[0] < SIDEBAR_W { let row = ((self.pointer_local[1] - RULER_H - 6.0) / 22.0).floor() as isize; if row >= 0 && (row as usize) < self.channels.len() { @@ -796,7 +1172,9 @@ impl SplineView { for pref in &self.selected { if let Some(sp) = comp.splines.get_mut(&pref.spline) { if let Some(kf) = sp.keyframes.get_mut(pref.key_idx) { - ensure_handles(kf); + if !kf.flags.linear { + ensure_handles(kf); + } } } } @@ -815,7 +1193,7 @@ impl SplineView { self.scrubbing = false; if let Some((_start, dragging)) = self.lmb_drag_point.take() { if dragging && self.modal.is_some() { - self.confirm_modal(comp); + self.confirm_modal(comp, history.as_deref_mut()); actions.push(SplineAction::SplineEdited); } } @@ -830,8 +1208,9 @@ impl SplineView { continue; } let Some(sp) = comp.splines.get(sname) else { continue }; + let bounds = self.spline_bounds(comp, sname); for (ki, kf) in sp.keyframes.iter().enumerate() { - let p = self.data_to_local(kf.time, kf.value); + let p = self.spline_to_local(kf.time, kf.value, bounds); if p[0] >= x0 && p[0] <= x1 && p[1] >= y0 && p[1] <= y1 { self.selected.insert(PointRef { spline: sname.clone(), @@ -868,10 +1247,10 @@ impl SplineView { self.zoom_at(f, f, self.pointer_local); } ui::Event::KeyInput { physical, key, state: ElementState::Pressed, repeat: false, modifiers: kmod, .. } => { - self.handle_key(comp, current_frame, Some(physical), &key, kmod, &mut actions); + self.handle_key(comp, history, current_frame, Some(physical), &key, kmod, &mut actions); } ui::Event::Key { key, modifiers: kmod, .. } => { - self.handle_key(comp, current_frame, None, &key, kmod, &mut actions); + self.handle_key(comp, history, current_frame, None, &key, kmod, &mut actions); } _ => {} } @@ -893,6 +1272,28 @@ impl SplineView { } } + fn hover_readout_string(&self, comp: &Comp) -> Option { + let hov = self.hovered.as_ref()?; + let sp = comp.splines.get(&hov.spline)?; + let kf = sp.keyframes.get(hov.key_idx)?; + let (t, v) = match hov.part { + HandlePart::Key => (kf.time, kf.value), + HandlePart::LeftHandle => { + let h = kf.lh?; + (h[0], h[1]) + } + HandlePart::RightHandle => { + let h = kf.rh?; + (h[0], h[1]) + } + }; + if (t - t.round()).abs() < 1e-3 { + Some(format!("(f{}, {:.3})", t.round() as i64, v)) + } else { + Some(format!("(f{t:.1}, {v:.3})")) + } + } + pub fn prepare_labels(&mut self, comp: &Comp) { let font_sm = text::Font { families: Arc::from([text::Family::Mono]), @@ -929,8 +1330,26 @@ impl SplineView { .map(|id| format!("Splines: {}", comp.node(id).name)) .unwrap_or_else(|| "Splines (Comp)".to_owned()); self.text_cache.entry(header.clone()).or_insert_with(|| make_layout(&header, &font_ch)); + self.text_cache + .entry("Norm".to_owned()) + .or_insert_with(|| make_layout("Norm", &font_sm)); + for popup_hdr in ["Set Handle Type", "Set Interpolation"] { + self.text_cache + .entry(popup_hdr.to_owned()) + .or_insert_with(|| make_layout(popup_hdr, &font_sm)); + } + for &(_, item_lbl) in HANDLE_MENU_ITEMS { + self.text_cache + .entry(item_lbl.to_owned()) + .or_insert_with(|| make_layout(item_lbl, &font_ch)); + } + for &(_, item_lbl) in EASING_MENU_ITEMS { + self.text_cache + .entry(item_lbl.to_owned()) + .or_insert_with(|| make_layout(item_lbl, &font_ch)); + } for hud in [ - "Drag or G/R/S X/Y: Axis I: Insert X/Del: Delete L: Linear T: Step Cmd+F / Num.: Fit", + "Drag or G/R/S X/Y: Axis V: Handle T: Easing N: Norm I: Insert X/Del: Delete L: Linear F: Fit", "GRAB [LMB/Enter confirm, RMB/Esc cancel, X: Frame / Y: Value]", "ROTATE [LMB/Enter confirm, RMB/Esc cancel]", "SCALE [LMB/Enter confirm, RMB/Esc cancel, X: Time / Y: Value]", @@ -938,6 +1357,14 @@ impl SplineView { self.text_cache.entry(hud.to_owned()).or_insert_with(|| make_layout(hud, &font_sm)); } + if let Some(readout) = self.hover_readout_string(comp) { + if readout != self.last_hover_readout || !self.text_cache.contains_key("__hover_readout") { + self.text_cache + .insert("__hover_readout".to_owned(), make_layout(&readout, &font_sm)); + self.last_hover_readout = readout; + } + } + let t_step = nice_step((self.t_range[1] - self.t_range[0]) / 8.0); let t_start = (self.t_range[0] / t_step).floor() as i64; let t_end = (self.t_range[1] / t_step).ceil() as i64; @@ -974,11 +1401,40 @@ impl SplineView { out.push(Primitive::Text { text: hl as &dyn Glyphs, origin: [10.0, 5.0], - clip: Some([8.0, 0.0, SIDEBAR_W - 8.0, RULER_H]), + clip: Some([8.0, 0.0, SIDEBAR_W - 70.0, RULER_H]), ink: self.palette.text, }); } + // Clickable "Normalize" pill in the sidebar header + let pill = self.normalize_pill_rect(); + let pill_fill = if self.normalized { + [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.28] + } else { + [self.palette.bg[0], self.palette.bg[1], self.palette.bg[2], 0.9] + }; + let pill_stroke = if self.normalized { self.palette.accent } else { self.palette.rule }; + out.push(Primitive::RoundedRect { + rect: pill, + radius: 4.0, + stroke: None, + color: pill_fill, + }); + out.push(Primitive::RoundedRect { + rect: pill, + radius: 4.0, + stroke: Some(1.0), + color: pill_stroke, + }); + if let Some(nl) = self.text_cache.get("Norm") { + out.push(Primitive::Text { + text: nl as &dyn Glyphs, + origin: [pill[0] + 7.0, pill[1] + 3.0], + clip: Some(pill), + ink: if self.normalized { self.palette.text } else { self.palette.text_dim }, + }); + } + for (i, (label, sname)) in self.channels.iter().enumerate() { let y = RULER_H + 6.0 + i as f32 * 22.0; if y > h - 24.0 { @@ -1086,6 +1542,7 @@ impl SplineView { continue; } let Some(sp) = comp.splines.get(sname) else { continue }; + let bounds = self.spline_bounds(comp, sname); let col = spline_color(comp, sname, ci); let any_sel = self.selected.iter().any(|p| p.spline == *sname); let curve_w = if any_sel { 2.4 } else { 1.7 }; @@ -1096,7 +1553,7 @@ impl SplineView { }; if let Some(first) = sp.keyframes.first() { - let p = self.data_to_local(first.time, first.value); + let p = self.spline_to_local(first.time, first.value, bounds); if p[0] > plot[0] { out.push(Primitive::Segment { from: [plot[0], p[1]], @@ -1107,7 +1564,7 @@ impl SplineView { } } if let Some(last) = sp.keyframes.last() { - let p = self.data_to_local(last.time, last.value); + let p = self.spline_to_local(last.time, last.value, bounds); if p[0] < plot[2] { out.push(Primitive::Segment { from: p, @@ -1125,25 +1582,32 @@ impl SplineView { if k1.time < self.t_range[0] || k0.time > self.t_range[1] { continue; } - if k1.flags.step_in { - let a = self.data_to_local(k0.time, k0.value); - let m = self.data_to_local(k1.time, k0.value); - let b = self.data_to_local(k1.time, k1.value); + if k0.flags.step_out { + // Vertical step at k0.time, then horizontal to k1.time (matches model::spline::eval_segment). + let a = self.spline_to_local(k0.time, k0.value, bounds); + let m = self.spline_to_local(k0.time, k1.value, bounds); + let b = self.spline_to_local(k1.time, k1.value, bounds); + out.push(Primitive::Segment { from: a, to: m, width: curve_w, color: curve_col }); + out.push(Primitive::Segment { from: m, to: b, width: curve_w, color: curve_col }); + } else if k1.flags.step_in { + let a = self.spline_to_local(k0.time, k0.value, bounds); + let m = self.spline_to_local(k1.time, k0.value, bounds); + let b = self.spline_to_local(k1.time, k1.value, bounds); out.push(Primitive::Segment { from: a, to: m, width: curve_w, color: curve_col }); out.push(Primitive::Segment { from: m, to: b, width: curve_w, color: curve_col }); } else if dense || (k1.flags.linear && k0.rh.is_none() && k1.lh.is_none()) { - let a = self.data_to_local(k0.time, k0.value); - let b = self.data_to_local(k1.time, k1.value); + let a = self.spline_to_local(k0.time, k0.value, bounds); + let b = self.spline_to_local(k1.time, k1.value, bounds); out.push(Primitive::Segment { from: a, to: b, width: curve_w, color: curve_col }); } else { let [p0, p1, p2, p3] = segment_control_points(k0, k1); const SUBS: usize = 20; - let mut prev = self.data_to_local(p0[0], p0[1]); + let mut prev = self.spline_to_local(p0[0], p0[1], bounds); for s in 1..=SUBS { let u = s as f64 / SUBS as f64; let t = cubic(p0[0], p1[0], p2[0], p3[0], u); let v = cubic(p0[1], p1[1], p2[1], p3[1], u); - let cur = self.data_to_local(t, v); + let cur = self.spline_to_local(t, v, bounds); out.push(Primitive::Segment { from: prev, to: cur, width: curve_w, color: curve_col }); prev = cur; } @@ -1155,7 +1619,7 @@ impl SplineView { if kf.time < self.t_range[0] - 5.0 || kf.time > self.t_range[1] + 5.0 { continue; } - let kp = self.data_to_local(kf.time, kf.value); + let kp = self.spline_to_local(kf.time, kf.value, bounds); let kref = PointRef { spline: sname.clone(), key_idx: ki, part: HandlePart::Key }; let ksel = self.selected.contains(&kref); let khov = self.hovered.as_ref() == Some(&kref); @@ -1164,7 +1628,7 @@ impl SplineView { if show_handles { for (part, hopt) in [(HandlePart::LeftHandle, kf.lh), (HandlePart::RightHandle, kf.rh)] { if let Some(h) = hopt { - let hp = self.data_to_local(h[0], h[1]); + let hp = self.spline_to_local(h[0], h[1], bounds); let href = PointRef { spline: sname.clone(), key_idx: ki, part }; let hsel = self.selected.contains(&href); let hhov = self.hovered.as_ref() == Some(&href); @@ -1202,6 +1666,46 @@ impl SplineView { } } + // Hover readout pill showing real `(f, )` for the hovered keyframe/handle + if let (Some(hov), Some(rl)) = (self.hovered.as_ref(), self.text_cache.get("__hover_readout")) { + if let Some(sp) = comp.splines.get(&hov.spline) { + if let Some(kf) = sp.keyframes.get(hov.key_idx) { + let bounds = self.spline_bounds(comp, &hov.spline); + let pt = match hov.part { + HandlePart::Key => Some([kf.time, kf.value]), + HandlePart::LeftHandle => kf.lh, + HandlePart::RightHandle => kf.rh, + }; + if let Some([t, v]) = pt { + let p = self.spline_to_local(t, v, bounds); + let pill_w = (self.last_hover_readout.len() as f32 * 6.4 + 12.0).max(76.0); + let pill_h = 18.0; + let rx = (p[0] + 10.0).clamp(plot[0] + 4.0, (plot[2] - pill_w - 4.0).max(plot[0] + 4.0)); + let ry = (p[1] - pill_h - 8.0).clamp(plot[1] + 4.0, (plot[3] - pill_h - 4.0).max(plot[1] + 4.0)); + let r = [rx, ry, rx + pill_w, ry + pill_h]; + out.push(Primitive::RoundedRect { + rect: r, + radius: 4.0, + stroke: None, + color: [0.08, 0.09, 0.11, 0.94], + }); + out.push(Primitive::RoundedRect { + rect: r, + radius: 4.0, + stroke: Some(1.0), + color: self.palette.accent, + }); + out.push(Primitive::Text { + text: rl as &dyn Glyphs, + origin: [rx + 6.0, ry + 3.0], + clip: Some(r), + ink: self.palette.text, + }); + } + } + } + } + if let Some(bs) = &self.box_select { let x0 = bs.start_local[0].min(bs.cur_local[0]); let x1 = bs.start_local[0].max(bs.cur_local[0]); @@ -1227,7 +1731,7 @@ impl SplineView { Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X: Frame / Y: Value]", Some(TransformMode::Rotate) => "ROTATE [LMB/Enter confirm, RMB/Esc cancel]", Some(TransformMode::Scale) => "SCALE [LMB/Enter confirm, RMB/Esc cancel, X: Time / Y: Value]", - None => "Drag or G/R/S X/Y: Axis I: Insert X/Del: Delete L: Linear T: Step Cmd+F / Num.: Fit", + None => "Drag or G/R/S X/Y: Axis V: Handle T: Easing N: Norm I: Insert X/Del: Delete L: Linear F: Fit", }; out.push(Primitive::Rect { rect: [SIDEBAR_W, h - 24.0, w, h], color: self.palette.ruler }); if let Some(hl) = self.text_cache.get(hud_key) { @@ -1239,10 +1743,74 @@ impl SplineView { }); } + // Floating Blender-style popup menu (`V` Handle Type / `T` Interpolation & Easing) + if let Some(popup) = &self.popup { + let pr = self.popup_rect(popup); + let hov_idx = self.popup_item_at(popup, self.pointer_local); + out.push(Primitive::RoundedRect { + rect: pr, + radius: 6.0, + stroke: None, + color: [0.09, 0.10, 0.12, 0.96], + }); + out.push(Primitive::RoundedRect { + rect: pr, + radius: 6.0, + stroke: Some(1.0), + color: self.palette.rule, + }); + let hdr_text = match popup.kind { + PopupKind::HandleType => "Set Handle Type", + PopupKind::Easing => "Set Interpolation", + }; + if let Some(hl) = self.text_cache.get(hdr_text) { + out.push(Primitive::Text { + text: hl as &dyn Glyphs, + origin: [pr[0] + 10.0, pr[1] + 5.0], + clip: Some([pr[0], pr[1], pr[2], pr[1] + POPUP_HEADER_H]), + ink: self.palette.text_dim, + }); + } + out.push(Primitive::Segment { + from: [pr[0] + 6.0, pr[1] + POPUP_HEADER_H - 1.0], + to: [pr[2] - 6.0, pr[1] + POPUP_HEADER_H - 1.0], + width: 1.0, + color: self.palette.rule, + }); + let labels: Vec<&'static str> = match popup.kind { + PopupKind::HandleType => HANDLE_MENU_ITEMS.iter().map(|&(_, l)| l).collect(), + PopupKind::Easing => EASING_MENU_ITEMS.iter().map(|&(_, l)| l).collect(), + }; + for (idx, lbl) in labels.into_iter().enumerate() { + let ry0 = pr[1] + POPUP_HEADER_H + idx as f32 * POPUP_ROW_H; + let ry1 = ry0 + POPUP_ROW_H; + if hov_idx == Some(idx) { + out.push(Primitive::RoundedRect { + rect: [pr[0] + 4.0, ry0 + 1.0, pr[2] - 4.0, ry1 - 1.0], + radius: 4.0, + stroke: None, + color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.25], + }); + } + if let Some(il) = self.text_cache.get(lbl) { + out.push(Primitive::Text { + text: il as &dyn Glyphs, + origin: [pr[0] + 10.0, ry0 + 4.0], + clip: Some([pr[0] + 4.0, ry0, pr[2] - 4.0, ry1]), + ink: self.palette.text, + }); + } + } + } + out } } +fn point_in_rect(p: [f32; 2], r: [f32; 4]) -> bool { + p[0] >= r[0] && p[0] <= r[2] && p[1] >= r[1] && p[1] <= r[3] +} + fn ensure_handles(kf: &mut Keyframe) { if kf.lh.is_none() { kf.lh = Some([kf.time - 8.0, kf.value]); @@ -1280,3 +1848,208 @@ fn nice_step(raw: f64) -> f64 { fn hypot2(a: [f32; 2], b: [f32; 2]) -> f32 { ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)).sqrt() } + +#[cfg(test)] +mod tests { + use super::*; + use model::BezierSpline; + + fn test_comp() -> Comp { + let mut comp = Comp::from_fusion_str("Composition {}").expect("empty comp"); + comp.splines.insert( + "Gain".to_owned(), + BezierSpline { + name: "Gain".to_owned(), + color: [220, 140, 255], + keyframes: vec![ + Keyframe::new(0.0, 10.0), + Keyframe::new(50.0, 110.0), + Keyframe::new(100.0, 10.0), + ], + }, + ); + comp + } + + fn key_event(ch: &str) -> ui::Event { + ui::Event::Key { + key: Key::Character(ch.into()), + modifiers: ModifiersState::empty(), + text: None, + } + } + + #[test] + fn normalize_toggle_via_key_and_pill_and_drag() { + let mut comp = test_comp(); + let mut view = SplineView::new(&ui::Theme::dark()); + view.resize([800.0, 360.0]); + view.set_target_node(&comp, None); + let rect = [0.0, 0.0, 800.0, 360.0]; + + assert!(!view.normalized); + view.input(&mut comp, 0.0, key_event("n"), rect, [300.0, 150.0], ModifiersState::empty()); + assert!(view.normalized); + assert_eq!(view.v_range, [-0.12, 1.12]); + + // Clicking Normalize pill toggles it back off + let pill = view.normalize_pill_rect(); + let pill_center = [0.5 * (pill[0] + pill[2]), 0.5 * (pill[1] + pill[3])]; + view.input( + &mut comp, + 0.0, + ui::Event::Button { + button: MouseButton::Left, + pressed: true, + at: std::time::Instant::now(), + }, + rect, + pill_center, + ModifiersState::empty(), + ); + assert!(!view.normalized); + + // Re-enable normalize and grab keyframe 0 upward by half the plot height (real span = 100) + view.toggle_normalized(&comp); + view.selected.insert(PointRef { + spline: "Gain".to_owned(), + key_idx: 0, + part: HandlePart::Key, + }); + let p0 = view.spline_to_local(0.0, 10.0, (10.0, 110.0)); + let p1 = view.spline_to_local(0.0, 60.0, (10.0, 110.0)); // +50 in real value (+0.5 normalized) + view.input(&mut comp, 0.0, key_event("g"), rect, p0, ModifiersState::empty()); + view.input( + &mut comp, + 0.0, + ui::Event::PointerMoved(p1), + rect, + p1, + ModifiersState::empty(), + ); + view.input( + &mut comp, + 0.0, + ui::Event::Key { + key: Key::Named(NamedKey::Enter), + modifiers: ModifiersState::empty(), + text: None, + }, + rect, + p1, + ModifiersState::empty(), + ); + assert!((comp.splines["Gain"].keyframes[0].value - 60.0).abs() < 0.5); + } + + #[test] + fn v_and_t_popups_apply_with_history_undo() { + let mut comp = test_comp(); + let mut history = CompHistory::new(); + let mut view = SplineView::new(&ui::Theme::dark()); + view.resize([800.0, 360.0]); + view.set_target_node(&comp, None); + let rect = [0.0, 0.0, 800.0, 360.0]; + + view.selected.insert(PointRef { + spline: "Gain".to_owned(), + key_idx: 1, + part: HandlePart::Key, + }); + + // Open V popup and press '3' (Auto) + view.input_with_history(&mut comp, Some(&mut history), 0.0, key_event("v"), rect, [300.0, 150.0], ModifiersState::empty()); + assert!(view.popup.is_some()); + let acts = view.input_with_history(&mut comp, Some(&mut history), 0.0, key_event("3"), rect, [300.0, 150.0], ModifiersState::empty()); + assert!(view.popup.is_none()); + assert_eq!(acts.len(), 1); + assert_eq!(comp.splines["Gain"].keyframes[1].handle_mode, HandleMode::Auto); + assert_eq!(history.undo_len(), 1); + + // Open T popup and press '8' (Knife Ease) on key 0 + view.selected.clear(); + view.selected.insert(PointRef { + spline: "Gain".to_owned(), + key_idx: 0, + part: HandlePart::Key, + }); + view.input_with_history(&mut comp, Some(&mut history), 0.0, key_event("t"), rect, [300.0, 150.0], ModifiersState::empty()); + let acts = view.input_with_history(&mut comp, Some(&mut history), 0.0, key_event("8"), rect, [300.0, 150.0], ModifiersState::empty()); + assert_eq!(acts.len(), 1); + assert_eq!(history.undo_len(), 2); + let rh = comp.splines["Gain"].keyframes[0].rh.unwrap(); + assert!((rh[0] - 11.0).abs() < 1e-6); // 0 + 50 * 0.22 = 11.0 + assert!((rh[1] - 110.0).abs() < 1e-6); // 10 + 100 * 1.0 = 110.0 + + // Undo restores pre-KnifeEase state + assert!(history.undo(&mut comp)); + assert!(comp.splines["Gain"].keyframes[0].flags.linear); + } + + #[test] + fn aligned_handle_drag_mirrors_opposite_and_history_cancel_vs_confirm() { + let mut comp = test_comp(); + let mut history = CompHistory::new(); + // Set key 1 to Auto handles first + apply_handle_mode(comp.splines.get_mut("Gain").unwrap(), 1, HandleMode::Auto); + let orig_rh = comp.splines["Gain"].keyframes[1].rh.unwrap(); + let orig_rh_len = ((orig_rh[0] - 50.0).powi(2) + (orig_rh[1] - 110.0).powi(2)).sqrt(); + + let mut view = SplineView::new(&ui::Theme::dark()); + view.resize([800.0, 360.0]); + view.set_target_node(&comp, None); + let rect = [0.0, 0.0, 800.0, 360.0]; + + view.selected.insert(PointRef { + spline: "Gain".to_owned(), + key_idx: 1, + part: HandlePart::LeftHandle, + }); + let lh = comp.splines["Gain"].keyframes[1].lh.unwrap(); + let p0 = view.data_to_local(lh[0], lh[1]); + let p1 = [p0[0], p0[1] + 40.0]; // drag left handle down + + // Grab and cancel -> no history entry pushed + view.input_with_history(&mut comp, Some(&mut history), 0.0, key_event("g"), rect, p0, ModifiersState::empty()); + view.input_with_history(&mut comp, Some(&mut history), 0.0, ui::Event::PointerMoved(p1), rect, p1, ModifiersState::empty()); + assert_eq!(comp.splines["Gain"].keyframes[1].handle_mode, HandleMode::Aligned); + let new_rh = comp.splines["Gain"].keyframes[1].rh.unwrap(); + let new_rh_len = ((new_rh[0] - 50.0).powi(2) + (new_rh[1] - 110.0).powi(2)).sqrt(); + assert!((new_rh_len - orig_rh_len).abs() < 1e-6); + assert!(new_rh[1] > 110.0, "right handle should counter-rotate upward when left goes down"); + + view.input_with_history( + &mut comp, + Some(&mut history), + 0.0, + ui::Event::Key { + key: Key::Named(NamedKey::Escape), + modifiers: ModifiersState::empty(), + text: None, + }, + rect, + p1, + ModifiersState::empty(), + ); + assert_eq!(history.undo_len(), 0); + assert_eq!(comp.splines["Gain"].keyframes[1].rh.unwrap(), orig_rh); + + // Grab and confirm -> pushes 1 undo snapshot + view.input_with_history(&mut comp, Some(&mut history), 0.0, key_event("g"), rect, p0, ModifiersState::empty()); + view.input_with_history(&mut comp, Some(&mut history), 0.0, ui::Event::PointerMoved(p1), rect, p1, ModifiersState::empty()); + view.input_with_history( + &mut comp, + Some(&mut history), + 0.0, + ui::Event::Key { + key: Key::Named(NamedKey::Enter), + modifiers: ModifiersState::empty(), + text: None, + }, + rect, + p1, + ModifiersState::empty(), + ); + assert_eq!(history.undo_len(), 1); + } +} diff --git a/crates/spline/src/presets.rs b/crates/spline/src/presets.rs new file mode 100644 index 0000000000000000000000000000000000000000..2a7bb61efe802efb6dfe3115cd9d7e6deffa2f7e --- /dev/null +++ b/crates/spline/src/presets.rs @@ -0,0 +1,499 @@ +//! Pure Bezier handle-mode, easing-preset, and curve-normalization helpers for the Spline Editor. + +use crate::HandlePart; +use model::{BezierSpline, HandleMode, Keyframe}; +use std::collections::HashSet; + +/// Built-in interpolation and easing presets exposed in the `T` popup menu. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EasingPreset { + Linear, + Smooth, + StepIn, + StepOut, + EaseInOut, + EaseOut, + EaseIn, + KnifeEase, +} + +impl EasingPreset { + /// Ordered list of all presets for menu display and `1`-`8` hotkey indexing. + pub const ALL: &'static [EasingPreset] = &[ + EasingPreset::Linear, + EasingPreset::Smooth, + EasingPreset::StepIn, + EasingPreset::StepOut, + EasingPreset::EaseInOut, + EasingPreset::EaseOut, + EasingPreset::EaseIn, + EasingPreset::KnifeEase, + ]; + + pub fn label(self) -> &'static str { + match self { + Self::Linear => "Linear", + Self::Smooth => "Smooth", + Self::StepIn => "Step In", + Self::StepOut => "Step Out", + Self::EaseInOut => "Ease In-Out", + Self::EaseOut => "Ease Out", + Self::EaseIn => "Ease In", + Self::KnifeEase => "Knife Ease", + } + } + + /// Returns normalized cubic-bezier `(x1, y1, x2, y2)` parameters for easing presets. + pub fn bezier_params(self) -> Option<(f64, f64, f64, f64)> { + match self { + Self::EaseInOut => Some((0.42, 0.0, 0.58, 1.0)), + Self::EaseOut => Some((0.0, 0.0, 0.58, 1.0)), + Self::EaseIn => Some((0.42, 0.0, 1.0, 1.0)), + Self::KnifeEase => Some((0.22, 1.0, 0.36, 1.0)), + Self::Linear | Self::Smooth | Self::StepIn | Self::StepOut => None, + } + } +} + +/// Applies an [`EasingPreset`] to the selected keyframes of `spline`. +/// Returns `true` if any keyframe was modified. +pub fn apply_easing_preset( + spline: &mut BezierSpline, + selected_indices: &[usize], + preset: EasingPreset, +) -> bool { + let len = spline.keyframes.len(); + if len == 0 { + return false; + } + + let mut valid: Vec = selected_indices + .iter() + .copied() + .filter(|&i| i < len) + .collect(); + valid.sort_unstable(); + valid.dedup(); + if valid.is_empty() { + return false; + } + + match preset { + EasingPreset::Linear => { + for &idx in &valid { + let kf = &mut spline.keyframes[idx]; + kf.flags.linear = true; + kf.flags.step_in = false; + kf.flags.step_out = false; + kf.lh = None; + kf.rh = None; + kf.handle_mode = HandleMode::Vector; + } + true + } + EasingPreset::Smooth => { + for &idx in &valid { + spline.keyframes[idx].flags.step_in = false; + spline.keyframes[idx].flags.step_out = false; + apply_handle_mode(spline, idx, HandleMode::Auto); + } + true + } + EasingPreset::StepIn => { + for &idx in &valid { + let kf = &mut spline.keyframes[idx]; + kf.flags.step_in = true; + kf.flags.step_out = false; + kf.flags.linear = false; + } + true + } + EasingPreset::StepOut => { + for &idx in &valid { + let kf = &mut spline.keyframes[idx]; + kf.flags.step_out = true; + kf.flags.step_in = false; + kf.flags.linear = false; + } + true + } + EasingPreset::EaseInOut + | EasingPreset::EaseOut + | EasingPreset::EaseIn + | EasingPreset::KnifeEase => { + if len < 2 { + return false; + } + let (x1, y1, x2, y2) = preset.bezier_params().expect("bezier preset has params"); + let selected_set: HashSet = valid.iter().copied().collect(); + + let mut seg_starts: Vec = (0..(len - 1)) + .filter(|seg| selected_set.contains(seg)) + .collect(); + if seg_starts.is_empty() && selected_set.contains(&(len - 1)) { + seg_starts.push(len - 2); + } + if seg_starts.is_empty() { + return false; + } + + for seg in seg_starts { + let t0 = spline.keyframes[seg].time; + let v0 = spline.keyframes[seg].value; + let t1 = spline.keyframes[seg + 1].time; + let v1 = spline.keyframes[seg + 1].value; + let dt = t1 - t0; + let dv = v1 - v0; + + let k0 = &mut spline.keyframes[seg]; + k0.rh = Some([t0 + dt * x1, v0 + dv * y1]); + k0.flags.linear = false; + k0.flags.step_in = false; + k0.flags.step_out = false; + k0.handle_mode = HandleMode::Free; + + let k1 = &mut spline.keyframes[seg + 1]; + k1.lh = Some([t0 + dt * x2, v0 + dv * y2]); + k1.flags.linear = false; + k1.flags.step_in = false; + k1.flags.step_out = false; + k1.handle_mode = HandleMode::Free; + } + true + } + } +} + +/// Applies a Blender-style [`HandleMode`] to `spline.keyframes[key_idx]`. +pub fn apply_handle_mode(spline: &mut BezierSpline, key_idx: usize, mode: HandleMode) { + let len = spline.keyframes.len(); + if key_idx >= len { + return; + } + + let t = spline.keyframes[key_idx].time; + let v = spline.keyframes[key_idx].value; + let prev = if key_idx > 0 { + Some((spline.keyframes[key_idx - 1].time, spline.keyframes[key_idx - 1].value)) + } else { + None + }; + let next = if key_idx + 1 < len { + Some((spline.keyframes[key_idx + 1].time, spline.keyframes[key_idx + 1].value)) + } else { + None + }; + + let dt_l = prev.map(|(pt, _)| ((t - pt) / 3.0).max(0.01)).unwrap_or(8.0); + let dt_r = next.map(|(nt, _)| ((nt - t) / 3.0).max(0.01)).unwrap_or(8.0); + + let kf = &mut spline.keyframes[key_idx]; + kf.flags.linear = false; + + match mode { + HandleMode::Free => { + if kf.lh.is_none() { + kf.lh = Some([t - dt_l, v]); + } + if kf.rh.is_none() { + kf.rh = Some([t + dt_r, v]); + } + kf.handle_mode = HandleMode::Free; + } + HandleMode::Aligned => { + let lh = kf.lh.unwrap_or([t - dt_l, v]); + let rh = kf.rh.unwrap_or([t + dt_r, v]); + let vl = [lh[0] - t, lh[1] - v]; + let vr = [rh[0] - t, rh[1] - v]; + let len_l = (vl[0] * vl[0] + vl[1] * vl[1]).sqrt().max(0.01); + let len_r = (vr[0] * vr[0] + vr[1] * vr[1]).sqrt().max(0.01); + + // Average rightward tangent direction from both handles. + let mut dx = vr[0] - vl[0]; + let mut dy = vr[1] - vl[1]; + let dlen = (dx * dx + dy * dy).sqrt(); + if dlen < 1e-9 { + dx = 1.0; + dy = 0.0; + } else { + dx /= dlen; + dy /= dlen; + if dx < 0.0 { + dx = -dx; + dy = -dy; + } + } + + kf.lh = Some([(t - dx * len_l).min(t - 0.01), v - dy * len_l]); + kf.rh = Some([(t + dx * len_r).max(t + 0.01), v + dy * len_r]); + kf.handle_mode = HandleMode::Aligned; + } + HandleMode::Vector => { + kf.lh = Some(match prev { + Some((pt, pv)) => [t + (pt - t) / 3.0, v + (pv - v) / 3.0], + None => [t - dt_l, v], + }); + kf.rh = Some(match next { + Some((nt, nv)) => [t + (nt - t) / 3.0, v + (nv - v) / 3.0], + None => [t + dt_r, v], + }); + kf.handle_mode = HandleMode::Vector; + } + HandleMode::Auto => { + let slope = match (prev, next) { + (Some((pt, pv)), Some((nt, nv))) => { + let dv_l = v - pv; + let dv_r = nv - v; + if dv_l * dv_r <= 0.0 { + // Local extremum (peak, trough, or plateau): flat tangent prevents overshoot. + 0.0 + } else { + let span = (nt - pt).max(1e-6); + let m_cr = (nv - pv) / span; + let max_l = (dv_l / dt_l).abs(); + let max_r = (dv_r / dt_r).abs(); + m_cr.signum() * m_cr.abs().min(max_l).min(max_r) + } + } + _ => 0.0, + }; + kf.lh = Some([t - dt_l, v - slope * dt_l]); + kf.rh = Some([t + dt_r, v + slope * dt_r]); + kf.handle_mode = HandleMode::Auto; + } + } +} + +/// For `HandleMode::Aligned`: counter-rotates the opposite handle so both handles remain +/// collinear through `(kf.time, kf.value)` while preserving the opposite handle's length. +pub fn enforce_aligned_handle(kf: &mut Keyframe, moved_part: HandlePart) { + match moved_part { + HandlePart::LeftHandle => { + let (Some(lh), Some(rh)) = (kf.lh, kf.rh) else { return }; + let dx = lh[0] - kf.time; + let dy = lh[1] - kf.value; + let moved_len = (dx * dx + dy * dy).sqrt(); + if moved_len < 1e-9 { + return; + } + let odx = rh[0] - kf.time; + let ody = rh[1] - kf.value; + let opp_len = (odx * odx + ody * ody).sqrt(); + let ux = -dx / moved_len; + let uy = -dy / moved_len; + kf.rh = Some([kf.time + ux * opp_len, kf.value + uy * opp_len]); + } + HandlePart::RightHandle => { + let (Some(lh), Some(rh)) = (kf.lh, kf.rh) else { return }; + let dx = rh[0] - kf.time; + let dy = rh[1] - kf.value; + let moved_len = (dx * dx + dy * dy).sqrt(); + if moved_len < 1e-9 { + return; + } + let odx = lh[0] - kf.time; + let ody = lh[1] - kf.value; + let opp_len = (odx * odx + ody * ody).sqrt(); + let ux = -dx / moved_len; + let uy = -dy / moved_len; + kf.lh = Some([kf.time + ux * opp_len, kf.value + uy * opp_len]); + } + HandlePart::Key => {} + } +} + +/// Computes `(min_v, max_v)` over a spline's keyframes and handles, with a safe +/// `(v - 0.5, v + 0.5)` fallback when the curve is constant. +pub fn compute_curve_bounds(spline: &BezierSpline) -> (f64, f64) { + if spline.keyframes.is_empty() { + return (0.0, 1.0); + } + let mut min_v = f64::INFINITY; + let mut max_v = f64::NEG_INFINITY; + for kf in &spline.keyframes { + min_v = min_v.min(kf.value); + max_v = max_v.max(kf.value); + if let Some(lh) = kf.lh { + min_v = min_v.min(lh[1]); + max_v = max_v.max(lh[1]); + } + if let Some(rh) = kf.rh { + min_v = min_v.min(rh[1]); + max_v = max_v.max(rh[1]); + } + } + if !min_v.is_finite() || !max_v.is_finite() { + return (0.0, 1.0); + } + if (max_v - min_v).abs() < 1e-9 { + let v = spline.keyframes[0].value; + return (v - 0.5, v + 0.5); + } + (min_v, max_v) +} + +/// Maps a real spline value to display space (`[0.0, 1.0]` when `normalized`, raw `val` otherwise). +#[inline] +pub fn value_to_display(val: f64, bounds: (f64, f64), normalized: bool) -> f64 { + if !normalized { + return val; + } + let span = (bounds.1 - bounds.0).max(1e-9); + (val - bounds.0) / span +} + +/// Inverse of [`value_to_display`]: maps a display-space value back to real spline value space. +#[inline] +pub fn display_to_value(disp: f64, bounds: (f64, f64), normalized: bool) -> f64 { + if !normalized { + return disp; + } + let span = (bounds.1 - bounds.0).max(1e-9); + bounds.0 + disp * span +} + +#[cfg(test)] +mod tests { + use super::*; + + fn make_spline(points: &[(f64, f64)]) -> BezierSpline { + BezierSpline { + name: "TestSpline".to_owned(), + color: [200, 140, 255], + keyframes: points.iter().map(|&(t, v)| Keyframe::new(t, v)).collect(), + } + } + + #[test] + fn normalize_roundtrip_and_constant_curve() { + let sp = make_spline(&[(0.0, 10.0), (50.0, 110.0)]); + let bounds = compute_curve_bounds(&sp); + assert_eq!(bounds, (10.0, 110.0)); + assert!((value_to_display(10.0, bounds, true) - 0.0).abs() < 1e-12); + assert!((value_to_display(60.0, bounds, true) - 0.5).abs() < 1e-12); + assert!((value_to_display(110.0, bounds, true) - 1.0).abs() < 1e-12); + for v in [10.0, 35.5, 60.0, 110.0, -20.0] { + let d = value_to_display(v, bounds, true); + let back = display_to_value(d, bounds, true); + assert!((back - v).abs() < 1e-9); + assert!((value_to_display(v, bounds, false) - v).abs() < 1e-12); + assert!((display_to_value(v, bounds, false) - v).abs() < 1e-12); + } + + // Constant curve fallback: (v - 0.5, v + 0.5) + let flat = make_spline(&[(0.0, 42.0), (100.0, 42.0)]); + let fb = compute_curve_bounds(&flat); + assert_eq!(fb, (41.5, 42.5)); + let d = value_to_display(42.0, fb, true); + assert!((d - 0.5).abs() < 1e-12); + assert!((display_to_value(d, fb, true) - 42.0).abs() < 1e-12); + } + + #[test] + fn enforce_aligned_handle_preserves_collinearity_and_length() { + let mut kf = Keyframe::new(50.0, 10.0); + kf.handle_mode = HandleMode::Aligned; + kf.lh = Some([40.0, 10.0]); + kf.rh = Some([65.0, 10.0]); // initial right length = 15.0 + + // Move left handle to (44.0, 2.0) -> vector (-6.0, -8.0), len = 10.0 + kf.lh = Some([44.0, 2.0]); + enforce_aligned_handle(&mut kf, HandlePart::LeftHandle); + + let rh = kf.rh.unwrap(); + let rdx = rh[0] - kf.time; + let rdy = rh[1] - kf.value; + let rlen = (rdx * rdx + rdy * rdy).sqrt(); + assert!((rlen - 15.0).abs() < 1e-9, "expected opposite len 15.0, got {rlen}"); + // Collinearity: cross product of lh_vec (-6, -8) and rh_vec (rdx, rdy) == 0 + let cross = (-6.0 * rdy - (-8.0) * rdx).abs(); + assert!(cross < 1e-9, "handles not collinear: cross={cross}"); + assert!(rdx > 0.0 && rdy > 0.0, "right handle should point opposite to left"); + + // Now move right handle and verify left handle preserves its length (10.0) + kf.rh = Some([62.0, 5.0]); // vector (12, -5), len = 13 + enforce_aligned_handle(&mut kf, HandlePart::RightHandle); + let lh = kf.lh.unwrap(); + let ldx = lh[0] - kf.time; + let ldy = lh[1] - kf.value; + let llen = (ldx * ldx + ldy * ldy).sqrt(); + assert!((llen - 10.0).abs() < 1e-9, "expected left len 10.0, got {llen}"); + let cross2 = (12.0 * ldy - (-5.0) * ldx).abs(); + assert!(cross2 < 1e-9, "handles not collinear after right move: cross={cross2}"); + assert!(ldx < 0.0 && ldy > 0.0); + } + + #[test] + fn apply_handle_mode_auto_and_vector() { + // Peak at middle keyframe (0,0) -> (30,10) -> (60,0): Auto should be flat (slope = 0) + let mut peak = make_spline(&[(0.0, 0.0), (30.0, 10.0), (60.0, 0.0)]); + apply_handle_mode(&mut peak, 1, HandleMode::Auto); + let k = &peak.keyframes[1]; + assert_eq!(k.handle_mode, HandleMode::Auto); + assert!(!k.flags.linear); + assert!((k.lh.unwrap()[1] - 10.0).abs() < 1e-9, "peak lh should be flat"); + assert!((k.rh.unwrap()[1] - 10.0).abs() < 1e-9, "peak rh should be flat"); + + // Monotonic (0,0) -> (30,30) -> (60,60): Auto should have positive slope = 1.0 + let mut mono = make_spline(&[(0.0, 0.0), (30.0, 30.0), (60.0, 60.0)]); + apply_handle_mode(&mut mono, 1, HandleMode::Auto); + let km = &mono.keyframes[1]; + assert_eq!(km.handle_mode, HandleMode::Auto); + let lh = km.lh.unwrap(); + let rh = km.rh.unwrap(); + assert!((lh[0] - 20.0).abs() < 1e-9 && (lh[1] - 20.0).abs() < 1e-9); + assert!((rh[0] - 40.0).abs() < 1e-9 && (rh[1] - 40.0).abs() < 1e-9); + + // Vector mode aims 1/3 toward neighbors + let mut vec_sp = make_spline(&[(0.0, 0.0), (30.0, 12.0), (90.0, 0.0)]); + apply_handle_mode(&mut vec_sp, 1, HandleMode::Vector); + let kv = &vec_sp.keyframes[1]; + assert_eq!(kv.handle_mode, HandleMode::Vector); + assert!(!kv.flags.linear); + let vlh = kv.lh.unwrap(); + let vrh = kv.rh.unwrap(); + assert!((vlh[0] - 20.0).abs() < 1e-9 && (vlh[1] - 8.0).abs() < 1e-9); + assert!((vrh[0] - 50.0).abs() < 1e-9 && (vrh[1] - 8.0).abs() < 1e-9); + } + + #[test] + fn apply_easing_presets_knife_linear_step_smooth() { + // KnifeEase (0.22, 1.0, 0.36, 1.0) on segment (10, 0) -> (110, 10) + let mut sp = make_spline(&[(10.0, 0.0), (110.0, 10.0)]); + assert!(apply_easing_preset(&mut sp, &[0], EasingPreset::KnifeEase)); + let k0 = &sp.keyframes[0]; + let k1 = &sp.keyframes[1]; + assert_eq!(k0.handle_mode, HandleMode::Free); + assert_eq!(k1.handle_mode, HandleMode::Free); + assert!(!k0.flags.linear && !k0.flags.step_in && !k0.flags.step_out); + assert!(!k1.flags.linear && !k1.flags.step_in && !k1.flags.step_out); + let rh = k0.rh.unwrap(); + let lh = k1.lh.unwrap(); + assert!((rh[0] - 32.0).abs() < 1e-9 && (rh[1] - 10.0).abs() < 1e-9); + assert!((lh[0] - 46.0).abs() < 1e-9 && (lh[1] - 10.0).abs() < 1e-9); + + // Selecting only the last key applies to incoming segment + let mut sp_last = make_spline(&[(0.0, 0.0), (100.0, 1.0)]); + assert!(apply_easing_preset(&mut sp_last, &[1], EasingPreset::KnifeEase)); + assert!((sp_last.keyframes[0].rh.unwrap()[0] - 22.0).abs() < 1e-9); + assert!((sp_last.keyframes[1].lh.unwrap()[0] - 36.0).abs() < 1e-9); + + // Linear clears handles and sets linear flag + assert!(apply_easing_preset(&mut sp, &[0, 1], EasingPreset::Linear)); + assert!(sp.keyframes[0].flags.linear && sp.keyframes[0].rh.is_none()); + assert!(sp.keyframes[1].flags.linear && sp.keyframes[1].lh.is_none()); + + // StepIn & StepOut + assert!(apply_easing_preset(&mut sp, &[1], EasingPreset::StepIn)); + assert!(sp.keyframes[1].flags.step_in && !sp.keyframes[1].flags.step_out); + assert!(apply_easing_preset(&mut sp, &[0], EasingPreset::StepOut)); + assert!(sp.keyframes[0].flags.step_out && !sp.keyframes[0].flags.step_in); + + // Smooth computes Auto handles and clears step/linear flags + assert!(apply_easing_preset(&mut sp, &[0, 1], EasingPreset::Smooth)); + assert!(!sp.keyframes[0].flags.step_out && !sp.keyframes[0].flags.linear); + assert!(!sp.keyframes[1].flags.step_in && !sp.keyframes[1].flags.linear); + assert_eq!(sp.keyframes[0].handle_mode, HandleMode::Auto); + assert!(sp.keyframes[0].rh.is_some() && sp.keyframes[1].lh.is_some()); + } +} diff --git a/crates/studio/src/keyframes.rs b/crates/studio/src/keyframes.rs new file mode 100644 index 0000000000000000000000000000000000000000..5ac7a0c569a666d70618df002bd54da52aeb9db1 --- /dev/null +++ b/crates/studio/src/keyframes.rs @@ -0,0 +1,1032 @@ +//! Docked Keyframes dope-sheet pane: animated node/channel tracks, audio waveform track, +//! green RAM cache bar, and interactive drag-to-retime keyframes with `CompHistory` undo. + +use draw::{Glyphs, Primitive}; +use model::{Comp, CompHistory, Keyframe, NodeId}; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; +use winit::event::{ElementState, MouseButton}; +use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey}; + +const RULER_H: f32 = 26.0; +const AUDIO_ROW_H: f32 = 24.0; +const ROW_H: f32 = 22.0; +const SIDEBAR_W: f32 = 188.0; +const FOOTER_H: f32 = 22.0; + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct DopeKeyRef { + pub spline: String, + pub key_idx: usize, +} + +#[derive(Clone, Debug)] +pub enum KeyframesAction { + ScrubFrame(f64), + SelectNode(NodeId), + KeyframesEdited, +} + +#[derive(Clone, Debug)] +pub enum TrackRow { + NodeHeader { + node_id: NodeId, + label: String, + splines: Vec, + }, + Channel { + node_id: NodeId, + label: String, + spline: String, + color: [f32; 4], + }, +} + +#[derive(Clone, Debug)] +struct RetimeDrag { + start_frame: f64, + saved_splines: HashMap>, + pre_edit_comp: Comp, + moved: bool, +} + +#[derive(Clone, Copy, Debug)] +pub struct KeyframesPalette { + pub bg: [f32; 4], + pub sidebar: [f32; 4], + pub ruler: [f32; 4], + pub rule: [f32; 4], + pub grid: [f32; 4], + pub row_alt: [f32; 4], + pub text: [f32; 4], + pub text_dim: [f32; 4], + pub accent: [f32; 4], +} + +impl KeyframesPalette { + pub fn from_ui(theme: &ui::Theme) -> Self { + let b = theme.base; + let lift = |c: [f32; 4], d: f32| { + [(c[0] + d).clamp(0.0, 1.0), (c[1] + d).clamp(0.0, 1.0), (c[2] + d).clamp(0.0, 1.0), 1.0] + }; + Self { + bg: b, + sidebar: lift(b, 0.012), + ruler: lift(b, 0.018), + rule: theme.rule, + grid: lift(b, 0.022), + row_alt: lift(b, 0.010), + text: theme.text, + text_dim: theme.text_dim, + accent: theme.accent, + } + } +} + +pub struct KeyframesView { + pub t_range: [f64; 2], + pub size: [f32; 2], + pub scroll_y: f32, + pub selected_only: bool, + pub selected_keys: HashSet, + pub cached_ranges: Vec<(i64, i64)>, + pub audio_peaks: Vec, + pub audio_range: [i64; 2], + pub palette: KeyframesPalette, + rows: Vec, + collapsed_nodes: HashSet, + hovered_key: Option, + retime_drag: Option, + box_select: Option<([f32; 2], [f32; 2])>, + panning: Option<([f32; 2], [f64; 2], f32)>, + scrubbing: bool, + pointer_local: [f32; 2], + fitted: bool, + text_cache: HashMap, +} + +impl KeyframesView { + pub fn new(theme: &ui::Theme) -> Self { + Self { + t_range: [0.0, 200.0], + size: [800.0, 320.0], + scroll_y: 0.0, + selected_only: false, + selected_keys: HashSet::new(), + cached_ranges: Vec::new(), + audio_peaks: Vec::new(), + audio_range: [0, 0], + palette: KeyframesPalette::from_ui(theme), + rows: Vec::new(), + collapsed_nodes: HashSet::new(), + hovered_key: None, + retime_drag: None, + box_select: None, + panning: None, + scrubbing: false, + pointer_local: [0.0, 0.0], + fitted: false, + text_cache: HashMap::new(), + } + } + + pub fn background(&self) -> [f32; 4] { + self.palette.bg + } + + pub fn resize(&mut self, size: [f32; 2]) { + self.size = [size[0].max(1.0), size[1].max(1.0)]; + } + + pub fn fit_comp(&mut self, comp: &Comp) { + let r0 = comp.render_range[0] as f64; + let r1 = comp.render_range[1].max(comp.render_range[0] + 10) as f64; + let pad = ((r1 - r0) * 0.04).max(4.0); + self.t_range = [r0 - pad, r1 + pad]; + self.fitted = true; + } + + pub fn sync_tracks(&mut self, comp: &Comp, selected_node: Option) { + if !self.fitted { + self.fit_comp(comp); + } + self.rows = build_tracks(comp, selected_node, self.selected_only, &self.collapsed_nodes); + } + + fn tracks_top(&self) -> f32 { + RULER_H + if self.audio_peaks.is_empty() { 0.0 } else { AUDIO_ROW_H } + } + + fn plot_rect(&self) -> [f32; 4] { + [ + SIDEBAR_W, + RULER_H, + self.size[0].max(SIDEBAR_W + 40.0), + (self.size[1] - FOOTER_H).max(RULER_H + 40.0), + ] + } + + fn time_to_x(&self, t: f64) -> f32 { + let r = self.plot_rect(); + let frac = (t - self.t_range[0]) / (self.t_range[1] - self.t_range[0]).max(1e-6); + r[0] + frac as f32 * (r[2] - r[0]) + } + + fn x_to_time(&self, x: f32) -> f64 { + let r = self.plot_rect(); + let frac = f64::from((x - r[0]) / (r[2] - r[0]).max(1.0)); + self.t_range[0] + frac * (self.t_range[1] - self.t_range[0]) + } + + fn row_y(&self, row_idx: usize) -> f32 { + self.tracks_top() + row_idx as f32 * ROW_H - self.scroll_y + } + + fn hit_key(&self, comp: &Comp, local: [f32; 2]) -> Option { + let top = self.tracks_top(); + if local[0] < SIDEBAR_W || local[1] < top || local[1] > self.size[1] - FOOTER_H { + return None; + } + let mut best: Option<(f32, DopeKeyRef)> = None; + for (ri, row) in self.rows.iter().enumerate() { + let cy = self.row_y(ri) + ROW_H * 0.5; + if (local[1] - cy).abs() > ROW_H * 0.52 { + continue; + } + if let TrackRow::Channel { spline, .. } = row { + let Some(sp) = comp.splines.get(spline) else { continue }; + for (ki, kf) in sp.keyframes.iter().enumerate() { + let kx = self.time_to_x(kf.time); + let d = ((local[0] - kx).powi(2) + (local[1] - cy).powi(2)).sqrt(); + if d <= 9.5 && best.as_ref().is_none_or(|(bd, _)| d < *bd) { + best = Some((d, DopeKeyRef { spline: spline.clone(), key_idx: ki })); + } + } + } + } + best.map(|(_, k)| k) + } + + fn hit_span_bar(&self, comp: &Comp, local: [f32; 2]) -> Option<(String, Vec)> { + let top = self.tracks_top(); + if local[0] < SIDEBAR_W || local[1] < top || local[1] > self.size[1] - FOOTER_H { + return None; + } + for (ri, row) in self.rows.iter().enumerate() { + let y0 = self.row_y(ri); + if local[1] < y0 || local[1] >= y0 + ROW_H { + continue; + } + if let TrackRow::Channel { spline, .. } = row { + let Some(sp) = comp.splines.get(spline) else { continue }; + if sp.keyframes.len() >= 2 { + let x0 = self.time_to_x(sp.keyframes.first().unwrap().time); + let x1 = self.time_to_x(sp.keyframes.last().unwrap().time); + if local[0] >= x0 && local[0] <= x1 { + return Some((spline.clone(), (0..sp.keyframes.len()).collect())); + } + } + } + } + None + } + + fn begin_retime_drag(&mut self, comp: &Comp) { + if self.selected_keys.is_empty() { + return; + } + let mut saved = HashMap::new(); + for kref in &self.selected_keys { + if let Some(sp) = comp.splines.get(&kref.spline) { + saved.entry(kref.spline.clone()).or_insert_with(|| sp.keyframes.clone()); + } + } + self.retime_drag = Some(RetimeDrag { + start_frame: self.x_to_time(self.pointer_local[0]).round(), + saved_splines: saved, + pre_edit_comp: comp.clone(), + moved: false, + }); + } + + fn apply_retime_drag(&mut self, comp: &mut Comp) -> bool { + let cur_frame = self.x_to_time(self.pointer_local[0]).round(); + let Some(drag) = &mut self.retime_drag else { return false }; + let dt = cur_frame - drag.start_frame; + if dt.abs() < 0.5 && !drag.moved { + return false; + } + drag.moved = true; + retime_selected_keys(comp, &drag.saved_splines, &self.selected_keys, dt); + true + } + + fn finish_retime_drag(&mut self, comp: &mut Comp, history: &mut CompHistory) -> bool { + let Some(drag) = self.retime_drag.take() else { return false }; + if !drag.moved { + return false; + } + for sname in drag.saved_splines.keys() { + if let Some(sp) = comp.splines.get_mut(sname) { + sp.sort(); + } + } + comp.revision += 1; + history.push_snapshot(&drag.pre_edit_comp, "Retime Keyframes"); + true + } + + fn delete_selected(&mut self, comp: &mut Comp, history: &mut CompHistory) -> bool { + if self.selected_keys.is_empty() { + return false; + } + let mut by_spline: HashMap> = HashMap::new(); + for kref in &self.selected_keys { + by_spline.entry(kref.spline.clone()).or_default().push(kref.key_idx); + } + let pre = comp.clone(); + let mut changed = false; + for (sname, mut idxs) in by_spline { + idxs.sort_unstable(); + idxs.dedup(); + if let Some(sp) = comp.splines.get_mut(&sname) { + for &idx in idxs.iter().rev() { + if sp.keyframes.len() > 1 && idx < sp.keyframes.len() { + sp.keyframes.remove(idx); + changed = true; + } + } + } + } + if changed { + self.selected_keys.clear(); + comp.revision += 1; + history.push_snapshot(&pre, "Delete Keyframes"); + } + changed + } + + pub fn input( + &mut self, + comp: &mut Comp, + history: &mut CompHistory, + selected_node: Option, + event: ui::Event, + rect: [f32; 4], + pointer_window: [f32; 2], + modifiers: ModifiersState, + ) -> Vec { + let mut actions = Vec::new(); + self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]]; + let plot = self.plot_rect(); + + match event { + ui::Event::PointerMoved(p) => { + self.pointer_local = [p[0] - rect[0], p[1] - rect[1]]; + if self.scrubbing { + actions.push(KeyframesAction::ScrubFrame(self.x_to_time(self.pointer_local[0]).round())); + } else if let Some((sp, tr, sy)) = self.panning { + let dx = f64::from((self.pointer_local[0] - sp[0]) / (plot[2] - plot[0]).max(1.0)); + let dt = dx * (tr[1] - tr[0]); + self.t_range = [tr[0] - dt, tr[1] - dt]; + self.scroll_y = (sy - (self.pointer_local[1] - sp[1])).max(0.0); + } else if self.retime_drag.is_some() { + if self.apply_retime_drag(comp) { + actions.push(KeyframesAction::KeyframesEdited); + } + } else if let Some((_, ref mut cur)) = self.box_select { + *cur = self.pointer_local; + } else { + self.hovered_key = self.hit_key(comp, self.pointer_local); + } + } + ui::Event::Button { button, pressed, .. } => { + if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) { + if pressed { + self.panning = Some((self.pointer_local, self.t_range, self.scroll_y)); + } else { + self.panning = None; + } + } else if button == MouseButton::Left { + if pressed { + // Sidebar header "All / Sel" toggle pill + if self.pointer_local[0] >= SIDEBAR_W - 48.0 + && self.pointer_local[0] <= SIDEBAR_W - 6.0 + && self.pointer_local[1] >= 4.0 + && self.pointer_local[1] <= RULER_H - 4.0 + { + self.selected_only = !self.selected_only; + self.scroll_y = 0.0; + self.sync_tracks(comp, selected_node); + } else if self.pointer_local[0] < SIDEBAR_W && self.pointer_local[1] >= self.tracks_top() { + let ri = ((self.pointer_local[1] - self.tracks_top() + self.scroll_y) / ROW_H).floor() as isize; + if ri >= 0 && (ri as usize) < self.rows.len() { + match &self.rows[ri as usize] { + TrackRow::NodeHeader { node_id, .. } => { + let id = *node_id; + if self.pointer_local[0] < 24.0 { + if !self.collapsed_nodes.remove(&id) { + self.collapsed_nodes.insert(id); + } + self.sync_tracks(comp, selected_node); + } else { + actions.push(KeyframesAction::SelectNode(id)); + } + } + TrackRow::Channel { node_id, .. } => { + actions.push(KeyframesAction::SelectNode(*node_id)); + } + } + } + } else if self.pointer_local[0] >= SIDEBAR_W && self.pointer_local[1] < RULER_H { + self.scrubbing = true; + actions.push(KeyframesAction::ScrubFrame(self.x_to_time(self.pointer_local[0]).round())); + } else if let Some(hit) = self.hit_key(comp, self.pointer_local) { + if modifiers.shift_key() { + if !self.selected_keys.remove(&hit) { + self.selected_keys.insert(hit); + } + } else if !self.selected_keys.contains(&hit) { + self.selected_keys.clear(); + self.selected_keys.insert(hit); + } + self.begin_retime_drag(comp); + } else if let Some((sname, idxs)) = self.hit_span_bar(comp, self.pointer_local) { + if !modifiers.shift_key() { + self.selected_keys.clear(); + } + for ki in idxs { + self.selected_keys.insert(DopeKeyRef { spline: sname.clone(), key_idx: ki }); + } + self.begin_retime_drag(comp); + } else if self.pointer_local[0] >= SIDEBAR_W { + if !modifiers.shift_key() { + self.selected_keys.clear(); + } + self.box_select = Some((self.pointer_local, self.pointer_local)); + } + } else { + self.scrubbing = false; + if self.finish_retime_drag(comp, history) { + actions.push(KeyframesAction::KeyframesEdited); + } + if let Some((a, b)) = self.box_select.take() { + let x0 = a[0].min(b[0]); + let x1 = a[0].max(b[0]); + let y0 = a[1].min(b[1]); + let y1 = a[1].max(b[1]); + if (x1 - x0) > 4.0 || (y1 - y0) > 4.0 { + for (ri, row) in self.rows.iter().enumerate() { + let cy = self.row_y(ri) + ROW_H * 0.5; + if cy < y0 || cy > y1 { + continue; + } + if let TrackRow::Channel { spline, .. } = row { + if let Some(sp) = comp.splines.get(spline) { + for (ki, kf) in sp.keyframes.iter().enumerate() { + let kx = self.time_to_x(kf.time); + if kx >= x0 && kx <= x1 { + self.selected_keys.insert(DopeKeyRef { + spline: spline.clone(), + key_idx: ki, + }); + } + } + } + } + } + } + } + } + } + } + ui::Event::Wheel(delta) => { + if self.pointer_local[0] < SIDEBAR_W || modifiers.shift_key() { + let max_scroll = (self.rows.len() as f32 * ROW_H - (self.size[1] - self.tracks_top() - FOOTER_H)).max(0.0); + self.scroll_y = (self.scroll_y - delta[1]).clamp(0.0, max_scroll); + } else { + let f = f64::from((1.0 - delta[1] * 0.0045).clamp(0.7, 1.4)); + let p = self.x_to_time(self.pointer_local[0]); + let t0 = p - (p - self.t_range[0]) * f; + let t1 = p + (self.t_range[1] - p) * f; + if (t1 - t0) > 4.0 && (t1 - t0) < 100_000.0 { + self.t_range = [t0, t1]; + } + } + } + ui::Event::KeyInput { physical, key, state: ElementState::Pressed, repeat: false, modifiers: kmod, .. } => { + if physical == PhysicalKey::Code(KeyCode::NumpadDecimal) { + self.fit_comp(comp); + } else { + self.handle_key(comp, history, &key, kmod, &mut actions); + } + } + ui::Event::Key { key, modifiers: kmod, .. } => { + self.handle_key(comp, history, &key, kmod, &mut actions); + } + _ => {} + } + + actions + } + + fn handle_key( + &mut self, + comp: &mut Comp, + history: &mut CompHistory, + key: &Key, + kmod: ModifiersState, + actions: &mut Vec, + ) { + match key { + Key::Named(NamedKey::Delete | NamedKey::Backspace) => { + if self.delete_selected(comp, history) { + actions.push(KeyframesAction::KeyframesEdited); + } + } + Key::Character(c) => match c.to_ascii_lowercase().as_str() { + "f" | "." => self.fit_comp(comp), + "x" if !kmod.super_key() => { + if self.delete_selected(comp, history) { + actions.push(KeyframesAction::KeyframesEdited); + } + } + _ => {} + }, + _ => {} + } + } + + pub fn prepare_labels(&mut self) { + let font_sm = text::Font { + families: Arc::from([text::Family::Mono]), + size: 10.0, + weight: 500, + italic: false, + }; + let font_row = text::Font { + families: Arc::from([text::Family::Sans]), + size: 11.0, + weight: 500, + italic: false, + }; + let font_hdr = text::Font { + families: Arc::from([text::Family::Sans]), + size: 11.0, + weight: 600, + italic: false, + }; + let make = |s: &str, font: &text::Font| { + let styles = [text::Style::new(font.clone())]; + text::Paragraph { + text: s, + styles: &styles, + spans: &[], + replacements: &[], + width: None, + indent: 0.0, + line_height: 1.2, + align: text::Align::Left, + tab: 32.0, + } + .layout() + }; + + for (k, txt, f) in [ + ("hdr:title", "Keyframes", &font_hdr), + ("hdr:all", "All", &font_sm), + ("hdr:sel", "Sel", &font_sm), + ("hdr:audio", "Audio", &font_row), + ("footer", "Drag keys/spans to retime · Ruler: Scrub · Wheel: Zoom · Del: Remove · F: Fit", &font_sm), + ] { + self.text_cache.entry(k.to_owned()).or_insert_with(|| make(txt, f)); + } + + for row in &self.rows { + match row { + TrackRow::NodeHeader { node_id, label, .. } => { + let glyph = if self.collapsed_nodes.contains(node_id) { "▸" } else { "▾" }; + let text = format!("{glyph} {label}"); + self.text_cache.entry(format!("nh:{text}")).or_insert_with(|| make(&text, &font_hdr)); + } + TrackRow::Channel { label, .. } => { + self.text_cache.entry(format!("ch:{label}")).or_insert_with(|| make(label, &font_row)); + } + } + } + + let plot = self.plot_rect(); + let max_ticks = f64::from(((plot[2] - plot[0]) / 56.0).max(2.0)); + let t_step = nice_step((self.t_range[1] - self.t_range[0]) / max_ticks); + let t_start = (self.t_range[0] / t_step).floor() as i64; + let t_end = (self.t_range[1] / t_step).ceil() as i64; + for ti in t_start..=t_end { + let key = format!("t:{}", (ti as f64 * t_step).round() as i64); + self.text_cache.entry(key.clone()).or_insert_with(|| make(&key[2..], &font_sm)); + } + } + + pub fn paint<'a>(&'a self, comp: &'a Comp, current_frame: f64) -> Vec> { + let mut out = Vec::with_capacity(512); + let [w, h] = self.size; + let plot = self.plot_rect(); + let top = self.tracks_top(); + + // Sidebar + Ruler chrome + out.push(Primitive::Rect { rect: [0.0, 0.0, SIDEBAR_W, h], color: self.palette.sidebar }); + out.push(Primitive::Rect { rect: [SIDEBAR_W, 0.0, w, RULER_H], color: self.palette.ruler }); + out.push(Primitive::Segment { from: [SIDEBAR_W, 0.0], to: [SIDEBAR_W, h], width: 1.0, color: self.palette.rule }); + out.push(Primitive::Segment { from: [0.0, RULER_H], to: [w, RULER_H], width: 1.0, color: self.palette.rule }); + + if let Some(tl) = self.text_cache.get("hdr:title") { + out.push(Primitive::Text { + text: tl as &dyn Glyphs, + origin: [10.0, 6.0], + clip: Some([8.0, 0.0, SIDEBAR_W - 52.0, RULER_H]), + ink: self.palette.text, + }); + } + // "All / Sel" filter pill + let pill_rect = [SIDEBAR_W - 46.0, 4.0, SIDEBAR_W - 8.0, RULER_H - 4.0]; + out.push(Primitive::RoundedRect { + rect: pill_rect, + radius: 4.0, + stroke: None, + color: if self.selected_only { + [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.28] + } else { + [self.palette.bg[0], self.palette.bg[1], self.palette.bg[2], 0.7] + }, + }); + out.push(Primitive::RoundedRect { + rect: pill_rect, + radius: 4.0, + stroke: Some(1.0), + color: if self.selected_only { self.palette.accent } else { self.palette.rule }, + }); + let mode_key = if self.selected_only { "hdr:sel" } else { "hdr:all" }; + if let Some(ml) = self.text_cache.get(mode_key) { + out.push(Primitive::Text { + text: ml as &dyn Glyphs, + origin: [pill_rect[0] + 9.0, 7.0], + clip: Some(pill_rect), + ink: if self.selected_only { self.palette.text } else { self.palette.text_dim }, + }); + } + + // Ruler frame ticks + let max_ticks = f64::from(((plot[2] - plot[0]) / 56.0).max(2.0)); + let t_step = nice_step((self.t_range[1] - self.t_range[0]) / max_ticks); + let t_start = (self.t_range[0] / t_step).floor() as i64; + let t_end = (self.t_range[1] / t_step).ceil() as i64; + for ti in t_start..=t_end { + let t = ti as f64 * t_step; + let x = self.time_to_x(t); + if x < plot[0] || x > plot[2] { + continue; + } + out.push(Primitive::Segment { from: [x, RULER_H], to: [x, plot[3]], width: 1.0, color: self.palette.grid }); + let key = format!("t:{}", t.round() as i64); + if let Some(tl) = self.text_cache.get(&key) { + out.push(Primitive::Text { + text: tl as &dyn Glyphs, + origin: [x + 3.0, 5.0], + clip: Some([plot[0], 0.0, plot[2], RULER_H]), + ink: self.palette.text_dim, + }); + } + } + + // Green RAM cache bar along bottom edge of ruler + for &(c0, c1) in &self.cached_ranges { + let x0 = self.time_to_x(c0 as f64).max(plot[0]); + let x1 = self.time_to_x((c1 + 1) as f64).min(plot[2]); + if x1 > x0 { + out.push(Primitive::Rect { + rect: [x0, RULER_H - 3.5, x1.max(x0 + 2.0), RULER_H - 0.5], + color: [0.22, 0.86, 0.48, 0.92], + }); + } + } + + // Dedicated Audio Waveform row when audio is present + if !self.audio_peaks.is_empty() { + let ay0 = RULER_H; + let ay1 = RULER_H + AUDIO_ROW_H; + out.push(Primitive::Rect { rect: [0.0, ay0, w, ay1], color: self.palette.row_alt }); + out.push(Primitive::Segment { from: [0.0, ay1], to: [w, ay1], width: 1.0, color: self.palette.rule }); + if let Some(al) = self.text_cache.get("hdr:audio") { + out.push(Primitive::Text { + text: al as &dyn Glyphs, + origin: [12.0, ay0 + 5.0], + clip: Some([8.0, ay0, SIDEBAR_W - 8.0, ay1]), + ink: [0.54, 0.80, 1.0, 0.95], + }); + } + out.push(Primitive::PushClip { rect: [plot[0], ay0, plot[2], ay1], radius: 0.0 }); + let mid_y = 0.5 * (ay0 + ay1); + let max_half = AUDIO_ROW_H * 0.42; + let a0 = self.audio_range[0]; + let n = self.audio_peaks.len() as i64; + let f_vis0 = (self.t_range[0].floor() as i64).max(a0); + let f_vis1 = (self.t_range[1].ceil() as i64).min(a0 + n - 1); + let bar_step = ((plot[2] - plot[0]) / ((self.t_range[1] - self.t_range[0]).max(1.0) as f32)).max(1.5); + let stride = ((1.8 / bar_step).ceil() as i64).max(1); + let mut f = f_vis0; + while f <= f_vis1 { + let mut peak = 0.0_f32; + for off in 0..stride { + let idx = (f + off - a0) as usize; + if let Some(&v) = self.audio_peaks.get(idx) { + if v > peak { peak = v; } + } + } + if peak > 0.01 { + let x = self.time_to_x(f as f64); + let hh = (peak * max_half).max(1.0); + let bw = (bar_step * stride as f32 - 0.6).max(1.2); + out.push(Primitive::Rect { + rect: [x, mid_y - hh, x + bw, mid_y + hh], + color: [0.46, 0.74, 0.98, 0.55], + }); + } + f += stride; + } + out.push(Primitive::PopClip); + } + + // Render range subtle shading + let rx0 = self.time_to_x(comp.render_range[0] as f64); + let rx1 = self.time_to_x(comp.render_range[1] as f64); + out.push(Primitive::PushClip { rect: [plot[0], top, plot[2], plot[3]], radius: 0.0 }); + if rx0 > plot[0] { + out.push(Primitive::Rect { rect: [plot[0], top, rx0.min(plot[2]), plot[3]], color: [0.0, 0.0, 0.0, 0.16] }); + } + if rx1 < plot[2] { + out.push(Primitive::Rect { rect: [rx1.max(plot[0]), top, plot[2], plot[3]], color: [0.0, 0.0, 0.0, 0.16] }); + } + out.push(Primitive::PopClip); + + // Track rows (clipped to track area) + out.push(Primitive::PushClip { rect: [0.0, top, w, plot[3]], radius: 0.0 }); + for (ri, row) in self.rows.iter().enumerate() { + let y0 = self.row_y(ri); + let y1 = y0 + ROW_H; + if y1 < top || y0 > plot[3] { + continue; + } + if ri % 2 == 1 { + out.push(Primitive::Rect { rect: [0.0, y0, w, y1], color: self.palette.row_alt }); + } + out.push(Primitive::Segment { from: [0.0, y1], to: [w, y1], width: 1.0, color: self.palette.grid }); + + match row { + TrackRow::NodeHeader { node_id, label, splines } => { + let glyph = if self.collapsed_nodes.contains(node_id) { "▸" } else { "▾" }; + let key = format!("nh:{glyph} {label}"); + if let Some(tl) = self.text_cache.get(&key) { + out.push(Primitive::Text { + text: tl as &dyn Glyphs, + origin: [10.0, y0 + 4.0], + clip: Some([6.0, y0, SIDEBAR_W - 6.0, y1]), + ink: self.palette.text, + }); + } + // Summary span + tick dots on node header row + let mut t_min = f64::INFINITY; + let mut t_max = f64::NEG_INFINITY; + for sname in splines { + if let Some(sp) = comp.splines.get(sname) { + for kf in &sp.keyframes { + t_min = t_min.min(kf.time); + t_max = t_max.max(kf.time); + } + } + } + if t_min.is_finite() { + let sx0 = self.time_to_x(t_min).max(plot[0]); + let sx1 = self.time_to_x(t_max).min(plot[2]); + if sx1 >= sx0 { + out.push(Primitive::RoundedRect { + rect: [sx0, y0 + 6.0, sx1.max(sx0 + 4.0), y1 - 6.0], + radius: 3.0, + stroke: None, + color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.22], + }); + } + } + } + TrackRow::Channel { label, spline, color, .. } => { + out.push(Primitive::RoundedRect { + rect: [20.0, y0 + 7.0, 28.0, y0 + 15.0], + radius: 2.0, + stroke: None, + color: *color, + }); + if let Some(tl) = self.text_cache.get(&format!("ch:{label}")) { + out.push(Primitive::Text { + text: tl as &dyn Glyphs, + origin: [34.0, y0 + 4.0], + clip: Some([32.0, y0, SIDEBAR_W - 6.0, y1]), + ink: self.palette.text_dim, + }); + } + + if let Some(sp) = comp.splines.get(spline) { + if sp.keyframes.len() >= 2 { + let sx0 = self.time_to_x(sp.keyframes.first().unwrap().time).max(plot[0]); + let sx1 = self.time_to_x(sp.keyframes.last().unwrap().time).min(plot[2]); + if sx1 > sx0 { + out.push(Primitive::RoundedRect { + rect: [sx0, y0 + 8.0, sx1, y1 - 8.0], + radius: 2.0, + stroke: None, + color: [color[0], color[1], color[2], 0.28], + }); + } + } + let cy = y0 + ROW_H * 0.5; + for (ki, kf) in sp.keyframes.iter().enumerate() { + let kx = self.time_to_x(kf.time); + if kx < plot[0] - 8.0 || kx > plot[2] + 8.0 { + continue; + } + let kref = DopeKeyRef { spline: spline.clone(), key_idx: ki }; + let sel = self.selected_keys.contains(&kref); + let hov = self.hovered_key.as_ref() == Some(&kref); + let r = if sel || hov { 5.0 } else { 4.0 }; + out.push(Primitive::RoundedRect { + rect: [kx - r, cy - r, kx + r, cy + r], + radius: 1.5, + stroke: None, + color: if sel { + [1.0, 0.84, 0.24, 1.0] + } else if hov { + [1.0, 1.0, 1.0, 1.0] + } else { + *color + }, + }); + out.push(Primitive::RoundedRect { + rect: [kx - r, cy - r, kx + r, cy + r], + radius: 1.5, + stroke: Some(1.0), + color: [0.04, 0.04, 0.06, 0.9], + }); + } + } + } + } + } + + // Box select overlay + if let Some((a, b)) = self.box_select { + let x0 = a[0].min(b[0]); + let x1 = a[0].max(b[0]); + let y0 = a[1].min(b[1]); + let y1 = a[1].max(b[1]); + out.push(Primitive::RoundedRect { + rect: [x0, y0, x1, y1], + radius: 2.0, + stroke: None, + color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.16], + }); + out.push(Primitive::RoundedRect { + rect: [x0, y0, x1, y1], + radius: 2.0, + stroke: Some(1.2), + color: self.palette.accent, + }); + } + out.push(Primitive::PopClip); + + // Playhead vertical line + let px = self.time_to_x(current_frame); + if px >= plot[0] && px <= plot[2] { + out.push(Primitive::Segment { + from: [px, 0.0], + to: [px, plot[3]], + width: 1.6, + color: [0.96, 0.36, 0.34, 0.92], + }); + } + + // Footer bar + out.push(Primitive::Rect { rect: [SIDEBAR_W, h - FOOTER_H, w, h], color: self.palette.ruler }); + if let Some(fl) = self.text_cache.get("footer") { + out.push(Primitive::Text { + text: fl as &dyn Glyphs, + origin: [SIDEBAR_W + 10.0, h - FOOTER_H + 5.0], + clip: Some([SIDEBAR_W + 6.0, h - FOOTER_H, w - 6.0, h]), + ink: self.palette.text_dim, + }); + } + + out + } +} + +pub fn build_tracks( + comp: &Comp, + selected_node: Option, + selected_only: bool, + collapsed: &HashSet, +) -> Vec { + let mut rows = Vec::new(); + let palette: &[[f32; 4]] = &[ + [0.98, 0.44, 0.62, 1.0], + [0.36, 0.84, 0.96, 1.0], + [0.50, 0.92, 0.46, 1.0], + [0.98, 0.78, 0.28, 1.0], + [0.74, 0.56, 0.98, 1.0], + ]; + let mut color_idx = 0usize; + + let iter_ids: Vec = if selected_only { + selected_node.into_iter().collect() + } else { + comp.nodes.iter().map(|n| n.id).collect() + }; + + for id in iter_ids { + if id.0 >= comp.nodes.len() { + continue; + } + let channels: Vec<(String, String)> = comp + .node_splines(id) + .into_iter() + .filter(|(_, sname)| !sname.contains("LUTIn")) + .collect(); + if channels.is_empty() { + continue; + } + let node = comp.node(id); + let spline_names: Vec = channels.iter().map(|(_, s)| s.clone()).collect(); + rows.push(TrackRow::NodeHeader { + node_id: id, + label: node.name.clone(), + splines: spline_names, + }); + if !collapsed.contains(&id) { + for (label, spline) in channels { + let col = comp + .splines + .get(&spline) + .map(|sp| { + let [r, g, b] = sp.color; + if r as u16 + g as u16 + b as u16 > 120 { + [r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0] + } else { + palette[color_idx % palette.len()] + } + }) + .unwrap_or_else(|| palette[color_idx % palette.len()]); + color_idx += 1; + rows.push(TrackRow::Channel { + node_id: id, + label, + spline, + color: col, + }); + } + } + } + rows +} + +pub fn retime_selected_keys( + comp: &mut Comp, + saved_splines: &HashMap>, + selected: &HashSet, + dt: f64, +) { + for (sname, orig) in saved_splines { + if let Some(sp) = comp.splines.get_mut(sname) { + sp.keyframes = orig.clone(); + } + } + for kref in selected { + let Some(sp) = comp.splines.get_mut(&kref.spline) else { continue }; + let Some(kf) = sp.keyframes.get_mut(kref.key_idx) else { continue }; + kf.time += dt; + if let Some(lh) = &mut kf.lh { + lh[0] += dt; + } + if let Some(rh) = &mut kf.rh { + rh[0] += dt; + } + } + comp.revision += 1; +} + +fn nice_step(raw: f64) -> f64 { + let raw = raw.max(1.0); + let pow = 10.0_f64.powf(raw.log10().floor()); + let frac = raw / pow; + let nice = if frac < 1.5 { 1.0 } else if frac < 3.5 { 2.0 } else if frac < 7.5 { 5.0 } else { 10.0 }; + (nice * pow).max(1.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample_animated_comp() -> Comp { + let src = r#"Composition { + CurrentTime = 10, + RenderRange = { 0, 100 }, + GlobalRange = { 0, 100 }, + Tools = ordered() { + XF1 = Transform { + Inputs = { + Size = Input { SourceOp = "XF1Size", Source = "Value", }, + }, + }, + XF1Size = BezierSpline { + SplineColor = { Red = 220, Green = 120, Blue = 80 }, + KeyFrames = { + [10] = { 1.0, RH = { 20.0, 1.0 }, Flags = { Linear = false } }, + [40] = { 2.0, LH = { 30.0, 2.0 }, Flags = { Linear = false } }, + }, + }, + }, + }"#; + Comp::from_fusion_str(src).expect("parse animated comp") + } + + #[test] + fn build_tracks_lists_animated_nodes_and_channels() { + let comp = sample_animated_comp(); + let xf = comp.find_node("XF1").unwrap(); + let rows = build_tracks(&comp, Some(xf), false, &HashSet::new()); + assert_eq!(rows.len(), 2); + assert!(matches!(&rows[0], TrackRow::NodeHeader { label, .. } if label == "XF1")); + assert!(matches!(&rows[1], TrackRow::Channel { spline, .. } if spline == "XF1Size")); + + let mut collapsed = HashSet::new(); + collapsed.insert(xf); + let collapsed_rows = build_tracks(&comp, Some(xf), false, &collapsed); + assert_eq!(collapsed_rows.len(), 1); + } + + #[test] + fn retime_shifts_key_and_handles_together_with_undo() { + let mut comp = sample_animated_comp(); + let mut history = CompHistory::new(); + let pre = comp.clone(); + let mut saved = HashMap::new(); + saved.insert("XF1Size".to_owned(), comp.splines["XF1Size"].keyframes.clone()); + let mut sel = HashSet::new(); + sel.insert(DopeKeyRef { spline: "XF1Size".to_owned(), key_idx: 1 }); + + retime_selected_keys(&mut comp, &saved, &sel, 15.0); + history.push_snapshot(&pre, "Retime Keyframes"); + + let kf1 = &comp.splines["XF1Size"].keyframes[1]; + assert!((kf1.time - 55.0).abs() < 1e-6); + assert!((kf1.lh.unwrap()[0] - 45.0).abs() < 1e-6, "left handle must shift with key"); + + assert!(history.undo(&mut comp)); + assert!((comp.splines["XF1Size"].keyframes[1].time - 40.0).abs() < 1e-6); + } +} diff --git a/crates/studio/src/main.rs b/crates/studio/src/main.rs index 45d7dcf4e511c9e238ee0aaf53b349fccac37efd..3e1aefbcfaa988f896c69f16e4c8b10742b65423 100644 --- a/crates/studio/src/main.rs +++ b/crates/studio/src/main.rs @@ -3,12 +3,17 @@ mod add_tool; mod inspector; +mod keyframes; use add_tool::{AddToolLauncher, ToolEntry}; use dock::{Axis as DockAxis, Command, Dock, Event, GroupId, Node as DockNode, Part as DockPart, Place, Plus, Side, SplitId, Tab}; -use engine::{AudioPlayer, AudioTrack, CacheMode, Engine, ExportOptions, export_saver_png_sequence}; +use engine::{ + AudioPlayer, AudioTrack, CacheMode, DEFAULT_RAM_CACHE_MB, Engine, ExportOptions, PrefetchJob, + RamFrameCache, RamPrefetcher, export_saver_png_sequence, +}; use flow::{FlowAction, FlowView}; use inspector::{InspectorAction, InspectorState}; +use keyframes::{KeyframesAction, KeyframesView}; use model::{Comp, CompHistory, NodeId, default_main_input_port}; use spline::{SplineAction, SplineView}; use std::collections::HashMap; @@ -28,13 +33,14 @@ use winit::keyboard::{Key, KeyCode, NamedKey, PhysicalKey}; use winit::window::{CursorIcon, Window, WindowId}; const DEFAULT_COMP: &str = "/Volumes/Project/trees/fusion/20_falling.comp"; -const PANES: &[&str] = &["Viewer 1", "Viewer 2", "Flow", "Spline", "Inspector"]; +const PANES: &[&str] = &["Viewer 1", "Viewer 2", "Flow", "Spline", "Keyframes", "Inspector"]; fn viewer_pane_id(slot: usize) -> ui::Id { ui::Id::ROOT.child(("pane-viewer", slot)) } fn viewer_canvas_id(slot: usize) -> ui::Id { ui::Id::ROOT.child(("canvas-viewer", slot)) } fn flow_pane_id() -> ui::Id { ui::Id::ROOT.child("pane-flow") } fn flow_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-flow") } fn spline_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-spline") } +fn keyframes_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-keyframes") } fn inspector_pane_id() -> ui::Id { ui::Id::ROOT.child("pane-inspector") } struct Cli { @@ -44,6 +50,7 @@ struct Cli { select_node: Option, dual_viewer: bool, open_add_tool: bool, + show_keyframes: bool, } fn parse_cli() -> Cli { @@ -54,6 +61,7 @@ fn parse_cli() -> Cli { let mut select_node = None; let mut dual_viewer = false; let mut open_add_tool = false; + let mut show_keyframes = false; let mut i = 1; while i < args.len() { match args[i].as_str() { @@ -77,6 +85,10 @@ fn parse_cli() -> Cli { open_add_tool = true; i += 1; } + "--show-keyframes" => { + show_keyframes = true; + i += 1; + } other if !other.starts_with("--") => { comp_path = PathBuf::from(other); i += 1; @@ -84,7 +96,7 @@ fn parse_cli() -> Cli { _ => i += 1, } } - Cli { comp_path, snapshot, frame, select_node, dual_viewer, open_add_tool } + Cli { comp_path, snapshot, frame, select_node, dual_viewer, open_add_tool, show_keyframes } } fn main() { @@ -116,8 +128,12 @@ struct Studio { viewers: [ViewerState; 2], flow: FlowView, spline: SplineView, + keyframes: KeyframesView, inspector: InspectorState, add_tool: AddToolLauncher, + ram_cache: RamFrameCache, + prefetcher: Option, + last_prefetch_sig: Option<(NodeId, i64, u64, u32, bool, bool)>, renaming_node: Option, rename_buf: String, rename_needs_focus: bool, @@ -133,6 +149,7 @@ impl Studio { init_frame: Option, select_node: Option<&str>, dual_viewer: bool, + show_keyframes: bool, enable_audio: bool, ) -> Self { let engine = Engine::new(renderer.device().clone(), renderer.queue().clone()); @@ -187,7 +204,12 @@ impl Studio { }, DockPart { share: 0.48, - node: DockNode::Group { id: g_spline, tabs: vec!["Spline".to_owned()], preview: None, rest: Default::default() }, + node: DockNode::Group { + id: g_spline, + tabs: vec!["Spline".to_owned(), "Keyframes".to_owned()], + preview: None, + rest: Default::default(), + }, rest: Default::default(), }, ], @@ -222,7 +244,10 @@ impl Studio { seen.active.insert(g_v2, "Viewer 2".to_owned()); } seen.active.insert(g_flow, "Flow".to_owned()); - seen.active.insert(g_spline, "Spline".to_owned()); + seen.active.insert( + g_spline, + if show_keyframes { "Keyframes" } else { "Spline" }.to_owned(), + ); seen.active.insert(g_inspector, "Inspector".to_owned()); seen.focused = Some(g_flow); let dock = Dock::new(); @@ -253,8 +278,20 @@ impl Studio { let mut spline = SplineView::new(&ui_theme); spline.set_target_node(&comp, default_sel); + let mut keyframes = KeyframesView::new(&ui_theme); + keyframes.sync_tracks(&comp, default_sel); + + v1.selected_node = default_sel; + v2.selected_node = default_sel; + let inspector = InspectorState::new(&ui_theme); let add_tool = AddToolLauncher::new(); + let ram_cache = RamFrameCache::new(DEFAULT_RAM_CACHE_MB); + let prefetcher = if enable_audio { + Some(RamPrefetcher::new(ram_cache.clone(), engine.vram_budget_mb())) + } else { + None + }; let (audio_player, audio_rx) = if enable_audio { let player = match AudioPlayer::new() { @@ -290,8 +327,12 @@ impl Studio { viewers: [v1, v2], flow, spline, + keyframes, inspector, add_tool, + ram_cache, + prefetcher, + last_prefetch_sig: None, renaming_node: None, rename_buf: String::new(), rename_needs_focus: false, @@ -315,6 +356,15 @@ impl Studio { track.duration_secs, track.sample_rate ); + let peaks = track.waveform_peaks( + self.comp.fps, + self.comp.audio_offset, + self.comp.render_range[0], + self.comp.render_range[1], + ); + self.viewers[0].audio_peaks = peaks.clone(); + self.keyframes.audio_peaks = peaks; + self.keyframes.audio_range = self.comp.render_range; let t = self.audio_time_secs(); let playing = self.playback.playing; if let Some(player) = &mut self.audio_player { @@ -362,12 +412,66 @@ impl Studio { } else { self.engine.bust_all_caches(); } + self.ram_cache.invalidate_other_revisions(self.comp.revision); + if let Some(pf) = &self.prefetcher { + pf.cancel(); + } + self.last_prefetch_sig = None; for v in &mut self.viewers { v.cached_frames.clear(); v.dirty = true; } } + fn sync_ram_ranges_and_prefetch(&mut self) { + let sel = self.flow.primary; + for v in &mut self.viewers { + v.selected_node = sel; + } + if let Some(target) = self.viewers[0].viewed_node { + let ranges = self.ram_cache.cached_frame_ranges( + target, + self.comp.revision, + self.engine.proxy_scale, + self.engine.hiq, + self.engine.use_proxy_clips, + ); + self.viewers[0].ram_cached_ranges = ranges.clone(); + self.keyframes.cached_ranges = ranges; + + if let Some(pf) = &mut self.prefetcher { + if self.engine.cache.mode == CacheMode::Enabled { + let cur_f = self.playback.current_frame.round() as i64; + let sig = ( + target, + cur_f, + self.comp.revision, + self.engine.proxy_scale, + self.engine.hiq, + self.engine.use_proxy_clips, + ); + if self.last_prefetch_sig != Some(sig) { + self.last_prefetch_sig = Some(sig); + self.ram_cache.invalidate_other_revisions(self.comp.revision); + pf.request_lookahead(PrefetchJob { + comp: self.comp.clone(), + target, + center_frame: cur_f, + range: self.comp.render_range, + lookahead: 24, + proxy_scale: self.engine.proxy_scale, + hiq: self.engine.hiq, + use_proxy_clips: self.engine.use_proxy_clips, + }); + } + } + } + } else { + self.viewers[0].ram_cached_ranges.clear(); + self.keyframes.cached_ranges.clear(); + } + } + fn undo(&mut self) { let label = self.history.undo_label().unwrap_or("Edit").to_owned(); if self.history.undo(&mut self.comp) { @@ -506,6 +610,16 @@ impl Studio { self.flow.primary = Some(id); } self.spline.set_target_node(&self.comp, default_sel); + self.keyframes.audio_peaks.clear(); + self.keyframes.cached_ranges.clear(); + self.keyframes.fit_comp(&self.comp); + self.keyframes.sync_tracks(&self.comp, default_sel); + self.viewers[0].audio_peaks.clear(); + self.ram_cache.clear(); + if let Some(pf) = &self.prefetcher { + pf.cancel(); + } + self.last_prefetch_sig = None; self.inspector.reset(); self.renaming_node = None; @@ -636,15 +750,24 @@ impl Studio { } } + self.sync_ram_ranges_and_prefetch(); let shown = self.dock.at(&mut self.layout, &mut self.seen, &String::clone).shown(); for (slot, pane_name) in [(0, "Viewer 1"), (1, "Viewer 2")] { if shown.contains(&pane_name.to_owned()) { - self.viewers[slot].ensure_rendered(&mut self.engine, &self.comp, self.playback.current_frame, self.scale); + self.viewers[slot].ensure_rendered_with_ram( + &mut self.engine, + Some(&self.ram_cache), + &self.comp, + self.playback.current_frame, + self.scale, + ); self.viewers[slot].prepare_hud(&self.comp, &self.engine, &self.playback); } } self.flow.prepare_labels(&self.comp); self.spline.prepare_labels(&self.comp); + self.keyframes.sync_tracks(&self.comp, self.flow.primary); + self.keyframes.prepare_labels(); self.ui.begin(self.size, self.scale, now); @@ -671,6 +794,7 @@ impl Studio { viewers, flow, spline, + keyframes, inspector, add_tool, renaming_node, @@ -684,6 +808,7 @@ impl Studio { let v2_bg = viewers[1].background(); let flow_bg = flow.background(); let spline_bg = spline.background(); + let keyframes_bg = keyframes.background(); let inspector_bg = inspector.background(); let mut viewer_actions: Vec<(usize, ViewerAction)> = Vec::new(); let mut inspector_actions: Vec = Vec::new(); @@ -709,6 +834,7 @@ impl Studio { "Viewer 2" => v2_bg, "Flow" => flow_bg, "Spline" => spline_bg, + "Keyframes" => keyframes_bg, "Inspector" => inspector_bg, _ => flow_bg, }; @@ -836,6 +962,18 @@ impl Studio { ui.close(); Some(id) } + "Keyframes" => { + let id = ui.open_as( + keyframes_canvas_id(), + ui::Spec { + flags: ui::Flags::CUSTOM | ui::Flags::FOCUSABLE | ui::Flags::KEY_INPUT, + size: [ui::fill(), ui::fill()], + ..ui::Spec::default() + }, + ); + ui.close(); + Some(id) + } "Inspector" => { let acts = inspector.build_ui( ui, @@ -998,7 +1136,15 @@ impl Studio { let mods = self.ui.modifiers(); let mut acts = Vec::new(); for ev in sig.events { - acts.extend(self.spline.input(&mut self.comp, self.playback.current_frame, ev, rect, ptr, mods)); + acts.extend(self.spline.input_with_history( + &mut self.comp, + Some(&mut self.history), + self.playback.current_frame, + ev, + rect, + ptr, + mods, + )); } for a in acts { match a { @@ -1023,11 +1169,58 @@ impl Studio { } } + if let Some(rect) = self.ui.laid_out(keyframes_canvas_id()) { + self.keyframes.resize([rect[2] - rect[0], rect[3] - rect[1]]); + let sig = self.ui.signal(keyframes_canvas_id()); + let ptr = self.ui.last_pointer(); + let mods = self.ui.modifiers(); + let mut acts = Vec::new(); + for ev in sig.events { + acts.extend(self.keyframes.input( + &mut self.comp, + &mut self.history, + self.flow.primary, + ev, + rect, + ptr, + mods, + )); + } + for a in acts { + match a { + KeyframesAction::ScrubFrame(f) => { + if self.playback.set_frame(&self.comp, f, now) { + self.sync_audio(false, true); + for v in &mut self.viewers { + v.dirty = true; + } + } + } + KeyframesAction::SelectNode(id) => { + self.flow.selected.clear(); + self.flow.selected.insert(id); + self.flow.primary = Some(id); + self.spline.set_target_node(&self.comp, Some(id)); + } + KeyframesAction::KeyframesEdited => { + self.invalidate_node(None); + } + } + } + } + // Immediately re-render any dirty visible viewer before painting this frame! + self.sync_ram_ranges_and_prefetch(); let shown_now = self.dock.at(&mut self.layout, &mut self.seen, &String::clone).shown(); for (slot, pane_name) in [(0, "Viewer 1"), (1, "Viewer 2")] { if shown_now.contains(&pane_name.to_owned()) && self.viewers[slot].dirty { - self.viewers[slot].ensure_rendered(&mut self.engine, &self.comp, self.playback.current_frame, self.scale); + self.viewers[slot].ensure_rendered_with_ram( + &mut self.engine, + Some(&self.ram_cache), + &self.comp, + self.playback.current_frame, + self.scale, + ); self.viewers[slot].prepare_hud(&self.comp, &self.engine, &self.playback); } } @@ -1061,6 +1254,8 @@ impl Studio { } ViewerAction::BustFrame(f) => { self.engine.bust_frame(f); + self.ram_cache.clear(); + self.last_prefetch_sig = None; for v in &mut self.viewers { v.cached_frames.remove(&f); v.dirty = true; @@ -1070,6 +1265,8 @@ impl Studio { if let Some(id) = self.flow.primary.or(self.viewers[slot].viewed_node) { self.engine.bust_subtree(id); } + self.ram_cache.clear(); + self.last_prefetch_sig = None; for v in &mut self.viewers { v.cached_frames.clear(); v.dirty = true; @@ -1077,6 +1274,8 @@ impl Studio { } ViewerAction::BustGpu => { self.engine.bust_gpu_cache(); + self.ram_cache.clear(); + self.last_prefetch_sig = None; for v in &mut self.viewers { v.cached_frames.clear(); v.dirty = true; @@ -1084,6 +1283,8 @@ impl Studio { } ViewerAction::BustAll => { self.engine.bust_all_caches(); + self.ram_cache.clear(); + self.last_prefetch_sig = None; for v in &mut self.viewers { v.cached_frames.clear(); v.dirty = true; @@ -1119,6 +1320,11 @@ impl Studio { ViewerAction::ClearViewers => { self.clear_viewers(); } + ViewerAction::GizmoEdited(edit) => { + self.history.push_coalesced(&self.comp, edit.label, &edit.coalesce_key); + self.comp.set_input_value(edit.node_id, edit.input, edit.value); + self.invalidate_node(Some(edit.node_id)); + } } } } @@ -1126,7 +1332,7 @@ impl Studio { fn paint(&mut self, target: &wgpu::TextureView, pixels: [u32; 2]) -> Result<(), Box> { let scale = self.scale; let cur_f = self.playback.current_frame; - let Studio { ui, renderer, comp, viewers, flow, spline, .. } = self; + let Studio { ui, renderer, comp, viewers, flow, spline, keyframes, .. } = self; let mut custom_prims: HashMap>)> = HashMap::new(); for slot in [0usize, 1] { @@ -1141,6 +1347,9 @@ impl Studio { if let Some(r) = ui.laid_out(spline_canvas_id()) { custom_prims.insert(spline_canvas_id(), (spline.background(), [r[0], r[1]], spline.paint(comp, cur_f))); } + if let Some(r) = ui.laid_out(keyframes_canvas_id()) { + custom_prims.insert(keyframes_canvas_id(), (keyframes.background(), [r[0], r[1]], keyframes.paint(comp, cur_f))); + } let interface = ui.layers(); let layers: Vec = interface @@ -1184,7 +1393,32 @@ fn run_snapshot(cli: &Cli, out_path: &Path) -> Result<(), Box> { }))?; let renderer = draw::Renderer::new(device, queue, wgpu::TextureFormat::Rgba8Unorm); - let mut studio = Studio::new(renderer, comp, cli.frame, cli.select_node.as_deref(), cli.dual_viewer, false); + let mut studio = Studio::new( + renderer, + comp, + cli.frame, + cli.select_node.as_deref(), + cli.dual_viewer, + cli.show_keyframes, + false, + ); + // Load audio waveform peaks if available so snapshot verifies the waveform overlay too + if let Some(af) = studio.comp.audio_filename.clone() { + let p = PathBuf::from(af); + if p.exists() { + if let Ok(track) = AudioTrack::load(&p) { + let peaks = track.waveform_peaks( + studio.comp.fps, + studio.comp.audio_offset, + studio.comp.render_range[0], + studio.comp.render_range[1], + ); + studio.viewers[0].audio_peaks = peaks.clone(); + studio.keyframes.audio_peaks = peaks; + studio.keyframes.audio_range = studio.comp.render_range; + } + } + } if cli.open_add_tool { studio.add_tool.open(); } @@ -1263,6 +1497,7 @@ fn run_window(cli: &Cli) -> Result<(), Box> { select_node: cli.select_node.clone(), dual_viewer: cli.dual_viewer, open_add_tool: cli.open_add_tool, + show_keyframes: cli.show_keyframes, }, host: None, error: None, @@ -1283,7 +1518,15 @@ impl WindowHost { .with_inner_size(LogicalSize::new(1440.0, 900.0)); let (window, access) = Accessibility::window(event_loop, attrs, [640.0, 420.0], proxy.clone(), ui::Id::ROOT)?; let (surface, renderer) = pollster::block_on(Surface::new(window.clone()))?; - let mut studio = Studio::new(renderer, comp, cli.frame, cli.select_node.as_deref(), cli.dual_viewer, true); + let mut studio = Studio::new( + renderer, + comp, + cli.frame, + cli.select_node.as_deref(), + cli.dual_viewer, + cli.show_keyframes, + true, + ); studio.ui.window_focused = window.has_focus(); studio.ui.clipboard = Clipboard::system(); window.request_redraw(); @@ -1523,11 +1766,18 @@ impl ApplicationHandler for App { fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { if let Some(host) = &self.host { - if host.studio.playback.playing && !host.occluded { - let wake = host.studio.playback.next_wake(&host.studio.comp); - event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + wake)); - host.window.request_redraw(); - return; + if !host.occluded { + if host.studio.playback.playing { + let wake = host.studio.playback.next_wake(&host.studio.comp); + event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + wake)); + host.window.request_redraw(); + return; + } + if host.studio.prefetcher.as_ref().is_some_and(RamPrefetcher::is_busy) { + event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(200))); + host.window.request_redraw(); + return; + } } } event_loop.set_control_flow(ControlFlow::Wait); diff --git a/crates/viewer/src/gizmos.rs b/crates/viewer/src/gizmos.rs new file mode 100644 index 0000000000000000000000000000000000000000..14b3a90a5505d5582c6bb99486792a8b8f20e617 --- /dev/null +++ b/crates/viewer/src/gizmos.rs @@ -0,0 +1,725 @@ +//! Interactive on-screen Viewer gizmos for selected Fusion nodes +//! (`Transform`, `Merge`, `EllipseMask`, `RectangleMask`, `PolylineMask`). + +use draw::Primitive; +use model::{Comp, ExprEngine, Node, NodeId, ParamValue}; +use std::f32::consts::TAU; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GizmoHandle { + Center, + AxisX, + AxisY, + Rotate, + Scale, + Width, + Height, +} + +#[derive(Clone, Debug)] +pub struct GizmoEdit { + pub node_id: NodeId, + pub input: &'static str, + pub value: ParamValue, + pub label: &'static str, + pub coalesce_key: String, +} + +#[derive(Clone, Debug)] +pub struct GizmoDrag { + pub node_id: NodeId, + pub handle: GizmoHandle, + pub start_local: [f32; 2], + pub start_center: [f64; 2], + pub start_size: f64, + pub start_angle: f64, + pub start_width: f64, + pub start_height: f64, + pub start_angle_ptr: f64, + pub start_dist_px: f32, +} + +pub struct GizmoState { + pub enabled: bool, + pub hovered: Option, + pub drag: Option, + expr: ExprEngine, +} + +impl Default for GizmoState { + fn default() -> Self { + Self::new() + } +} + +impl GizmoState { + pub fn new() -> Self { + Self { + enabled: true, + hovered: None, + drag: None, + expr: ExprEngine::new(), + } + } + + pub fn is_dragging(&self) -> bool { + self.drag.is_some() + } + + pub fn supports_node(comp: &Comp, node_id: NodeId) -> bool { + if node_id.0 >= comp.nodes.len() { + return false; + } + matches!( + comp.node(node_id).kind.as_str(), + "Transform" | "Merge" | "EllipseMask" | "RectangleMask" | "PolylineMask" + ) + } + + /// Maps Fusion normalized coordinates (`[0..1]`, Y-up) to viewer-local screen pixels. + pub fn fu_to_local(fu: [f64; 2], img_rect: [f32; 4]) -> [f32; 2] { + let w = (img_rect[2] - img_rect[0]).max(1.0); + let h = (img_rect[3] - img_rect[1]).max(1.0); + [ + img_rect[0] + fu[0] as f32 * w, + img_rect[3] - fu[1] as f32 * h, + ] + } + + /// Maps viewer-local screen pixels to Fusion normalized coordinates (`[0..1]`, Y-up). + pub fn local_to_fu(pt: [f32; 2], img_rect: [f32; 4]) -> [f64; 2] { + let w = (img_rect[2] - img_rect[0]).max(1.0); + let h = (img_rect[3] - img_rect[1]).max(1.0); + [ + f64::from((pt[0] - img_rect[0]) / w), + f64::from((img_rect[3] - pt[1]) / h), + ] + } + + fn eval_node_params(&self, comp: &Comp, node: &Node, time: f64) -> NodeGizmoParams { + let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr); + let size = comp.eval_number(node, "Size", time, 1.0, &self.expr); + let angle = comp.eval_number(node, "Angle", time, 0.0, &self.expr); + let width = comp.eval_number(node, "Width", time, 0.5, &self.expr); + let height = comp.eval_number(node, "Height", time, 0.5, &self.expr); + NodeGizmoParams { center, size, angle, width, height } + } + + fn handle_positions(&self, comp: &Comp, node: &Node, time: f64, img_rect: [f32; 4]) -> Vec<(GizmoHandle, [f32; 2])> { + let p = self.eval_node_params(comp, node, time); + let c = Self::fu_to_local(p.center, img_rect); + let rad = (p.angle as f32).to_radians(); + // Fusion CCW angle in Y-up => screen space (Y-down): +X dir is (cos, -sin), +Y dir is (-sin, -cos) + let ux = [rad.cos(), -rad.sin()]; + let uy = [-rad.sin(), -rad.cos()]; + let img_w = (img_rect[2] - img_rect[0]).max(1.0); + let img_h = (img_rect[3] - img_rect[1]).max(1.0); + + match node.kind.as_str() { + "Transform" | "Merge" => { + let arm = 58.0_f32; + let ring_r = 46.0_f32; + let diag = (0.7071_f32) * (ring_r + 12.0); + vec![ + (GizmoHandle::AxisX, [c[0] + ux[0] * arm, c[1] + ux[1] * arm]), + (GizmoHandle::AxisY, [c[0] + uy[0] * arm, c[1] + uy[1] * arm]), + (GizmoHandle::Rotate, [c[0] - uy[0] * ring_r, c[1] - uy[1] * ring_r]), + ( + GizmoHandle::Scale, + [ + c[0] + (ux[0] + uy[0]) * diag, + c[1] + (ux[1] + uy[1]) * diag, + ], + ), + (GizmoHandle::Center, c), + ] + } + "EllipseMask" | "RectangleMask" => { + let hw = (p.width.abs() as f32 * 0.5 * img_w).max(10.0); + let hh = if node.kind == "EllipseMask" { + // Fusion EllipseMask: both Width & Height are in frame-width units + (p.height.abs() as f32 * 0.5 * img_w).max(10.0) + } else { + // Fusion RectangleMask: Width in frame-width units, Height in frame-height units + (p.height.abs() as f32 * 0.5 * img_h).max(10.0) + }; + vec![ + (GizmoHandle::Width, [c[0] + ux[0] * hw, c[1] + ux[1] * hw]), + (GizmoHandle::Height, [c[0] + uy[0] * hh, c[1] + uy[1] * hh]), + (GizmoHandle::Rotate, [c[0] + ux[0] * (hw + 22.0), c[1] + ux[1] * (hw + 22.0)]), + (GizmoHandle::Center, c), + ] + } + "PolylineMask" => vec![(GizmoHandle::Center, c)], + _ => Vec::new(), + } + } + + pub fn hit_test( + &self, + comp: &Comp, + node_id: NodeId, + time: f64, + img_rect: [f32; 4], + pointer_local: [f32; 2], + ) -> Option { + if !self.enabled || !Self::supports_node(comp, node_id) { + return None; + } + let node = comp.node(node_id); + let handles = self.handle_positions(comp, node, time, img_rect); + let mut best: Option<(f32, GizmoHandle)> = None; + for (h, pos) in handles { + let d = hypot2(pointer_local, pos); + let tol = if h == GizmoHandle::Center { 13.0 } else { 11.0 }; + if d <= tol && best.is_none_or(|(bd, _)| d < bd) { + best = Some((d, h)); + } + } + best.map(|(_, h)| h) + } + + pub fn update_hover( + &mut self, + comp: &Comp, + node_id: Option, + time: f64, + img_rect: [f32; 4], + pointer_local: [f32; 2], + ) { + self.hovered = node_id.and_then(|id| self.hit_test(comp, id, time, img_rect, pointer_local)); + } + + pub fn begin_drag( + &mut self, + comp: &Comp, + node_id: NodeId, + time: f64, + img_rect: [f32; 4], + pointer_local: [f32; 2], + ) -> bool { + let Some(handle) = self.hit_test(comp, node_id, time, img_rect, pointer_local) else { + return false; + }; + let node = comp.node(node_id); + let p = self.eval_node_params(comp, node, time); + let c = Self::fu_to_local(p.center, img_rect); + let dx = f64::from(pointer_local[0] - c[0]); + let dy = f64::from(c[1] - pointer_local[1]); // Y-up + let start_angle_ptr = dy.atan2(dx).to_degrees(); + let start_dist_px = hypot2(pointer_local, c).max(8.0); + self.drag = Some(GizmoDrag { + node_id, + handle, + start_local: pointer_local, + start_center: p.center, + start_size: p.size, + start_angle: p.angle, + start_width: p.width, + start_height: p.height, + start_angle_ptr, + start_dist_px, + }); + true + } + + pub fn update_drag( + &mut self, + comp: &Comp, + img_rect: [f32; 4], + pointer_local: [f32; 2], + fine: bool, + ) -> Option { + let d = self.drag.as_ref()?; + if d.node_id.0 >= comp.nodes.len() { + return None; + } + let kind = comp.node(d.node_id).kind.as_str(); + let img_w = f64::from((img_rect[2] - img_rect[0]).max(1.0)); + let img_h = f64::from((img_rect[3] - img_rect[1]).max(1.0)); + let sens = if fine { 0.2 } else { 1.0 }; + let c = Self::fu_to_local(d.start_center, img_rect); + let dx_px = f64::from(pointer_local[0] - d.start_local[0]) * sens; + let dy_px = f64::from(d.start_local[1] - pointer_local[1]) * sens; // Y-up + + match d.handle { + GizmoHandle::Center => { + let nx = d.start_center[0] + dx_px / img_w; + let ny = d.start_center[1] + dy_px / img_h; + Some(GizmoEdit { + node_id: d.node_id, + input: "Center", + value: ParamValue::Point([nx, ny]), + label: "Move Center", + coalesce_key: format!("gizmo:{}:Center", d.node_id.0), + }) + } + GizmoHandle::AxisX => { + let nx = d.start_center[0] + dx_px / img_w; + Some(GizmoEdit { + node_id: d.node_id, + input: "Center", + value: ParamValue::Point([nx, d.start_center[1]]), + label: "Move Center X", + coalesce_key: format!("gizmo:{}:Center", d.node_id.0), + }) + } + GizmoHandle::AxisY => { + let ny = d.start_center[1] + dy_px / img_h; + Some(GizmoEdit { + node_id: d.node_id, + input: "Center", + value: ParamValue::Point([d.start_center[0], ny]), + label: "Move Center Y", + coalesce_key: format!("gizmo:{}:Center", d.node_id.0), + }) + } + GizmoHandle::Rotate => { + let rx = f64::from(pointer_local[0] - c[0]); + let ry = f64::from(c[1] - pointer_local[1]); + let cur_ang = ry.atan2(rx).to_degrees(); + let mut delta = cur_ang - d.start_angle_ptr; + if delta > 180.0 { delta -= 360.0; } + if delta < -180.0 { delta += 360.0; } + let new_ang = d.start_angle + delta * sens; + Some(GizmoEdit { + node_id: d.node_id, + input: "Angle", + value: ParamValue::Number(new_ang), + label: "Rotate Gizmo", + coalesce_key: format!("gizmo:{}:Angle", d.node_id.0), + }) + } + GizmoHandle::Scale => { + let cur_dist = hypot2(pointer_local, c).max(4.0); + let ratio = f64::from(cur_dist / d.start_dist_px); + let new_size = (d.start_size * (1.0 + (ratio - 1.0) * sens)).clamp(0.01, 20.0); + Some(GizmoEdit { + node_id: d.node_id, + input: "Size", + value: ParamValue::Number(new_size), + label: "Scale Gizmo", + coalesce_key: format!("gizmo:{}:Size", d.node_id.0), + }) + } + GizmoHandle::Width => { + let rad = d.start_angle.to_radians(); + let ux = [rad.cos(), -rad.sin()]; + let rx = f64::from(pointer_local[0] - c[0]); + let ry = f64::from(pointer_local[1] - c[1]); + let proj = (rx * ux[0] + ry * ux[1]).abs(); + let new_w = ((proj * 2.0) / img_w).clamp(0.005, 4.0); + Some(GizmoEdit { + node_id: d.node_id, + input: "Width", + value: ParamValue::Number(new_w), + label: "Resize Mask Width", + coalesce_key: format!("gizmo:{}:Width", d.node_id.0), + }) + } + GizmoHandle::Height => { + let rad = d.start_angle.to_radians(); + let uy = [-rad.sin(), -rad.cos()]; + let rx = f64::from(pointer_local[0] - c[0]); + let ry = f64::from(pointer_local[1] - c[1]); + let proj = (rx * uy[0] + ry * uy[1]).abs(); + let denom = if kind == "EllipseMask" { img_w } else { img_h }; + let new_h = ((proj * 2.0) / denom).clamp(0.005, 4.0); + Some(GizmoEdit { + node_id: d.node_id, + input: "Height", + value: ParamValue::Number(new_h), + label: "Resize Mask Height", + coalesce_key: format!("gizmo:{}:Height", d.node_id.0), + }) + } + } + } + + pub fn end_drag(&mut self) { + self.drag = None; + } + + pub fn paint<'a>( + &self, + comp: &Comp, + node_id: NodeId, + time: f64, + img_rect: [f32; 4], + vis_rect: [f32; 4], + ) -> Vec> { + let mut out = Vec::new(); + if !self.enabled || !Self::supports_node(comp, node_id) { + return out; + } + let node = comp.node(node_id); + let p = self.eval_node_params(comp, node, time); + let c = Self::fu_to_local(p.center, img_rect); + let rad = (p.angle as f32).to_radians(); + let ux = [rad.cos(), -rad.sin()]; + let uy = [-rad.sin(), -rad.cos()]; + let img_w = (img_rect[2] - img_rect[0]).max(1.0); + let img_h = (img_rect[3] - img_rect[1]).max(1.0); + let active_h = self.drag.as_ref().map(|d| d.handle).or(self.hovered); + + out.push(Primitive::PushClip { rect: vis_rect, radius: 0.0 }); + + match node.kind.as_str() { + "Transform" | "Merge" => { + let arm = 58.0_f32; + let ring_r = 46.0_f32; + let diag = 0.7071_f32 * (ring_r + 12.0); + + // Subtle rotation ring (28 segments) + let ring_col = if active_h == Some(GizmoHandle::Rotate) { + [1.0, 0.85, 0.30, 0.95] + } else { + [0.72, 0.78, 0.96, 0.45] + }; + const SEGS: usize = 28; + for i in 0..SEGS { + let a0 = (i as f32 / SEGS as f32) * TAU; + let a1 = ((i + 1) as f32 / SEGS as f32) * TAU; + out.push(Primitive::Segment { + from: [c[0] + a0.cos() * ring_r, c[1] + a0.sin() * ring_r], + to: [c[0] + a1.cos() * ring_r, c[1] + a1.sin() * ring_r], + width: 1.2, + color: ring_col, + }); + } + + // X axis arrow (coral red) + let px = [c[0] + ux[0] * arm, c[1] + ux[1] * arm]; + let col_x = if active_h == Some(GizmoHandle::AxisX) { + [1.0, 0.50, 0.48, 1.0] + } else { + [0.95, 0.34, 0.34, 0.92] + }; + out.push(Primitive::Segment { from: c, to: px, width: 1.8, color: col_x }); + push_handle_dot(&mut out, px, 4.5, col_x, active_h == Some(GizmoHandle::AxisX)); + + // Y axis arrow (emerald green) + let py = [c[0] + uy[0] * arm, c[1] + uy[1] * arm]; + let col_y = if active_h == Some(GizmoHandle::AxisY) { + [0.48, 1.0, 0.64, 1.0] + } else { + [0.30, 0.88, 0.48, 0.92] + }; + out.push(Primitive::Segment { from: c, to: py, width: 1.8, color: col_y }); + push_handle_dot(&mut out, py, 4.5, col_y, active_h == Some(GizmoHandle::AxisY)); + + // Rotation knob on bottom of ring + let pr = [c[0] - uy[0] * ring_r, c[1] - uy[1] * ring_r]; + push_handle_dot( + &mut out, + pr, + 4.5, + [0.58, 0.74, 1.0, 0.95], + active_h == Some(GizmoHandle::Rotate), + ); + + // Scale square handle (NE) + let ps = [c[0] + (ux[0] + uy[0]) * diag, c[1] + (ux[1] + uy[1]) * diag]; + out.push(Primitive::Segment { + from: c, + to: ps, + width: 1.0, + color: [0.96, 0.80, 0.32, 0.45], + }); + push_handle_square( + &mut out, + ps, + 4.5, + [0.98, 0.80, 0.30, 0.95], + active_h == Some(GizmoHandle::Scale), + ); + + // Center crosshair + push_center_crosshair(&mut out, c, active_h == Some(GizmoHandle::Center)); + } + "EllipseMask" => { + let hw = (p.width.abs() as f32 * 0.5 * img_w).max(4.0); + let hh = (p.height.abs() as f32 * 0.5 * img_w).max(4.0); + let outline_col = [0.30, 0.92, 0.62, 0.88]; + const SEGS: usize = 40; + for i in 0..SEGS { + let a0 = (i as f32 / SEGS as f32) * TAU; + let a1 = ((i + 1) as f32 / SEGS as f32) * TAU; + let p0 = [ + c[0] + ux[0] * (a0.cos() * hw) + uy[0] * (a0.sin() * hh), + c[1] + ux[1] * (a0.cos() * hw) + uy[1] * (a0.sin() * hh), + ]; + let p1 = [ + c[0] + ux[0] * (a1.cos() * hw) + uy[0] * (a1.sin() * hh), + c[1] + ux[1] * (a1.cos() * hw) + uy[1] * (a1.sin() * hh), + ]; + out.push(Primitive::Segment { from: p0, to: p1, width: 1.5, color: outline_col }); + } + let pw = [c[0] + ux[0] * hw, c[1] + ux[1] * hw]; + let ph = [c[0] + uy[0] * hh, c[1] + uy[1] * hh]; + let pr = [c[0] + ux[0] * (hw + 22.0), c[1] + ux[1] * (hw + 22.0)]; + out.push(Primitive::Segment { from: pw, to: pr, width: 1.1, color: [0.60, 0.80, 1.0, 0.6] }); + push_handle_square(&mut out, pw, 4.2, outline_col, active_h == Some(GizmoHandle::Width)); + push_handle_square(&mut out, ph, 4.2, outline_col, active_h == Some(GizmoHandle::Height)); + push_handle_dot(&mut out, pr, 4.2, [0.58, 0.74, 1.0, 0.95], active_h == Some(GizmoHandle::Rotate)); + push_center_crosshair(&mut out, c, active_h == Some(GizmoHandle::Center)); + } + "RectangleMask" => { + let hw = (p.width.abs() as f32 * 0.5 * img_w).max(4.0); + let hh = (p.height.abs() as f32 * 0.5 * img_h).max(4.0); + let outline_col = [0.30, 0.92, 0.62, 0.88]; + let corners = [ + [c[0] - ux[0] * hw - uy[0] * hh, c[1] - ux[1] * hw - uy[1] * hh], + [c[0] + ux[0] * hw - uy[0] * hh, c[1] + ux[1] * hw - uy[1] * hh], + [c[0] + ux[0] * hw + uy[0] * hh, c[1] + ux[1] * hw + uy[1] * hh], + [c[0] - ux[0] * hw + uy[0] * hh, c[1] - ux[1] * hw + uy[1] * hh], + ]; + for i in 0..4 { + out.push(Primitive::Segment { + from: corners[i], + to: corners[(i + 1) % 4], + width: 1.5, + color: outline_col, + }); + } + let pw = [c[0] + ux[0] * hw, c[1] + ux[1] * hw]; + let ph = [c[0] + uy[0] * hh, c[1] + uy[1] * hh]; + let pr = [c[0] + ux[0] * (hw + 22.0), c[1] + ux[1] * (hw + 22.0)]; + out.push(Primitive::Segment { from: pw, to: pr, width: 1.1, color: [0.60, 0.80, 1.0, 0.6] }); + push_handle_square(&mut out, pw, 4.2, outline_col, active_h == Some(GizmoHandle::Width)); + push_handle_square(&mut out, ph, 4.2, outline_col, active_h == Some(GizmoHandle::Height)); + push_handle_dot(&mut out, pr, 4.2, [0.58, 0.74, 1.0, 0.95], active_h == Some(GizmoHandle::Rotate)); + push_center_crosshair(&mut out, c, active_h == Some(GizmoHandle::Center)); + } + "PolylineMask" => { + let pts = extract_polyline_points(comp, node, time); + let poly_col = [0.34, 0.88, 0.98, 0.90]; + let handle_col = [0.88, 0.56, 0.98, 0.75]; + if pts.len() >= 2 { + for i in 0..pts.len() { + let a = &pts[i]; + let b = &pts[(i + 1) % pts.len()]; + let p0 = Self::fu_to_local([p.center[0] + a.x, p.center[1] + a.y], img_rect); + let p1 = Self::fu_to_local([p.center[0] + a.x + a.rx, p.center[1] + a.y + a.ry], img_rect); + let p2 = Self::fu_to_local([p.center[0] + b.x + b.lx, p.center[1] + b.y + b.ly], img_rect); + let p3 = Self::fu_to_local([p.center[0] + b.x, p.center[1] + b.y], img_rect); + let curved = a.rx.abs() + a.ry.abs() + b.lx.abs() + b.ly.abs() > 1e-5; + if curved { + let mut prev = p0; + for s in 1..=10 { + let t = s as f32 / 10.0; + let u = 1.0 - t; + let cur = [ + u * u * u * p0[0] + 3.0 * u * u * t * p1[0] + 3.0 * u * t * t * p2[0] + t * t * t * p3[0], + u * u * u * p0[1] + 3.0 * u * u * t * p1[1] + 3.0 * u * t * t * p2[1] + t * t * t * p3[1], + ]; + out.push(Primitive::Segment { from: prev, to: cur, width: 1.5, color: poly_col }); + prev = cur; + } + } else { + out.push(Primitive::Segment { from: p0, to: p3, width: 1.5, color: poly_col }); + } + if a.rx.abs() + a.ry.abs() > 1e-4 { + out.push(Primitive::Segment { from: p0, to: p1, width: 1.0, color: handle_col }); + push_handle_dot(&mut out, p1, 2.8, handle_col, false); + } + if a.lx.abs() + a.ly.abs() > 1e-4 { + let pl = Self::fu_to_local([p.center[0] + a.x + a.lx, p.center[1] + a.y + a.ly], img_rect); + out.push(Primitive::Segment { from: p0, to: pl, width: 1.0, color: handle_col }); + push_handle_dot(&mut out, pl, 2.8, handle_col, false); + } + push_handle_square(&mut out, p0, 3.4, poly_col, false); + } + } + push_center_crosshair(&mut out, c, active_h == Some(GizmoHandle::Center)); + } + _ => {} + } + + out.push(Primitive::PopClip); + out + } +} + +struct NodeGizmoParams { + center: [f64; 2], + size: f64, + angle: f64, + width: f64, + height: f64, +} + +fn extract_polyline_points(comp: &Comp, node: &Node, time: f64) -> Vec { + if let Some(src) = node.connected_node("Polyline") { + if let Some(pts) = comp.eval_polyline_spline(src, time) { + return pts; + } + if let Some(pp) = comp.poly_paths.get(src) { + return pp.points.clone(); + } + } + if let Some(pl_tbl) = node + .raw + .get_table("Inputs") + .and_then(|i| i.get_table("Polyline").or_else(|| i.get_table("PolyLine"))) + .and_then(|p| p.get_table("Value")) + { + return model::PolyPath::parse_polyline_table(pl_tbl).1; + } + Vec::new() +} + +fn push_center_crosshair(out: &mut Vec>, c: [f32; 2], hot: bool) { + let col = if hot { [1.0, 0.90, 0.35, 1.0] } else { [0.96, 0.96, 0.98, 0.92] }; + let r = if hot { 8.0 } else { 6.5 }; + out.push(Primitive::Segment { from: [c[0] - r, c[1]], to: [c[0] + r, c[1]], width: 1.6, color: col }); + out.push(Primitive::Segment { from: [c[0], c[1] - r], to: [c[0], c[1] + r], width: 1.6, color: col }); + out.push(Primitive::RoundedRect { + rect: [c[0] - 4.5, c[1] - 4.5, c[0] + 4.5, c[1] + 4.5], + radius: 4.5, + stroke: Some(1.4), + color: col, + }); +} + +fn push_handle_dot(out: &mut Vec>, p: [f32; 2], r: f32, col: [f32; 4], hot: bool) { + let rad = if hot { r + 1.5 } else { r }; + out.push(Primitive::RoundedRect { + rect: [p[0] - rad, p[1] - rad, p[0] + rad, p[1] + rad], + radius: rad, + stroke: None, + color: if hot { [1.0, 1.0, 1.0, 1.0] } else { col }, + }); + out.push(Primitive::RoundedRect { + rect: [p[0] - rad, p[1] - rad, p[0] + rad, p[1] + rad], + radius: rad, + stroke: Some(1.1), + color: [0.05, 0.05, 0.08, 0.9], + }); +} + +fn push_handle_square(out: &mut Vec>, p: [f32; 2], r: f32, col: [f32; 4], hot: bool) { + let rad = if hot { r + 1.4 } else { r }; + out.push(Primitive::RoundedRect { + rect: [p[0] - rad, p[1] - rad, p[0] + rad, p[1] + rad], + radius: 1.5, + stroke: None, + color: if hot { [1.0, 1.0, 1.0, 1.0] } else { col }, + }); + out.push(Primitive::RoundedRect { + rect: [p[0] - rad, p[1] - rad, p[0] + rad, p[1] + rad], + radius: 1.5, + stroke: Some(1.1), + color: [0.05, 0.05, 0.08, 0.9], + }); +} + +fn hypot2(a: [f32; 2], b: [f32; 2]) -> f32 { + ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)).sqrt() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample_gizmo_comp() -> Comp { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 100 }, + GlobalRange = { 0, 100 }, + Tools = ordered() { + XF1 = Transform { + Inputs = { + Center = Input { Value = { 0.5, 0.5 }, }, + Size = Input { Value = 1.0, }, + Angle = Input { Value = 0.0, }, + }, + }, + Ell1 = EllipseMask { + Inputs = { + Center = Input { Value = { 0.5, 0.5 }, }, + Width = Input { Value = 0.4, }, + Height = Input { Value = 0.2, }, + Angle = Input { Value = 0.0, }, + }, + }, + Rect1 = RectangleMask { + Inputs = { + Center = Input { Value = { 0.5, 0.5 }, }, + Width = Input { Value = 0.5, }, + Height = Input { Value = 0.5, }, + }, + }, + }, + }"#; + Comp::from_fusion_str(src).expect("parse gizmo test comp") + } + + #[test] + fn fu_to_local_roundtrip_is_exact() { + let rect = [100.0, 50.0, 900.0, 500.0]; // 800x450 + let fu = [0.25, 0.75]; + let local = GizmoState::fu_to_local(fu, rect); + assert!((local[0] - 300.0).abs() < 1e-4); + assert!((local[1] - 162.5).abs() < 1e-4); + let back = GizmoState::local_to_fu(local, rect); + assert!((back[0] - fu[0]).abs() < 1e-5); + assert!((back[1] - fu[1]).abs() < 1e-5); + } + + #[test] + fn transform_gizmo_hit_and_drag_updates_center_and_size() { + let comp = sample_gizmo_comp(); + let xf = comp.find_node("XF1").unwrap(); + let rect = [0.0, 0.0, 800.0, 450.0]; + let mut gz = GizmoState::new(); + + // Hit center at (400, 225) + assert_eq!(gz.hit_test(&comp, xf, 0.0, rect, [400.0, 225.0]), Some(GizmoHandle::Center)); + assert!(gz.begin_drag(&comp, xf, 0.0, rect, [400.0, 225.0])); + let edit = gz.update_drag(&comp, rect, [480.0, 180.0], false).unwrap(); + assert_eq!(edit.input, "Center"); + if let ParamValue::Point([x, y]) = edit.value { + assert!((x - 0.6).abs() < 1e-4); + assert!((y - 0.6).abs() < 1e-4); + } else { + panic!("expected Point"); + } + gz.end_drag(); + + // Hit X-axis handle at (458, 225) + assert_eq!(gz.hit_test(&comp, xf, 0.0, rect, [458.0, 225.0]), Some(GizmoHandle::AxisX)); + assert!(gz.begin_drag(&comp, xf, 0.0, rect, [458.0, 225.0])); + let edit_x = gz.update_drag(&comp, rect, [538.0, 100.0], false).unwrap(); + if let ParamValue::Point([x, y]) = edit_x.value { + assert!((x - 0.6).abs() < 1e-4); + assert!((y - 0.5).abs() < 1e-4, "AxisX must keep Y locked"); + } else { + panic!("expected Point"); + } + } + + #[test] + fn ellipse_and_rectangle_mask_gizmos_respect_fusion_units() { + let comp = sample_gizmo_comp(); + let ell = comp.find_node("Ell1").unwrap(); + let rect_node = comp.find_node("Rect1").unwrap(); + let img = [0.0, 0.0, 800.0, 400.0]; // 2:1 aspect + let mut gz = GizmoState::new(); + + // EllipseMask Height=0.2 in frame-width units -> half_h = 0.1 * 800 = 80px above center (400, 200) -> (400, 120) + assert_eq!(gz.hit_test(&comp, ell, 0.0, img, [400.0, 120.0]), Some(GizmoHandle::Height)); + assert!(gz.begin_drag(&comp, ell, 0.0, img, [400.0, 120.0])); + let edit = gz.update_drag(&comp, img, [400.0, 80.0], false).unwrap(); + assert_eq!(edit.input, "Height"); + if let ParamValue::Number(h) = edit.value { + assert!((h - 0.3).abs() < 1e-4, "expected 0.3, got {h}"); + } else { + panic!("expected Number"); + } + gz.end_drag(); + + // RectangleMask Height=0.5 in frame-height units -> half_h = 0.25 * 400 = 100px above center (400, 200) -> (400, 100) + assert_eq!(gz.hit_test(&comp, rect_node, 0.0, img, [400.0, 100.0]), Some(GizmoHandle::Height)); + } +} diff --git a/crates/viewer/src/lib.rs b/crates/viewer/src/lib.rs index d45025c2bc9e65bfa049f8f84d81a8b1614ab01d..20ec4d95bdfb39e1c5060c7ad2dad0617db8d102 100644 --- a/crates/viewer/src/lib.rs +++ b/crates/viewer/src/lib.rs @@ -6,8 +6,12 @@ //! - Proxy scaling (1:1, 1:2, 1:4) with identical framing & proportions //! - Surgical cache-busting controls + live GPU telemetry + `Cmd+F` / Numpad `.` fit-to-view. +pub mod gizmos; + +pub use gizmos::{GizmoEdit, GizmoHandle, GizmoState}; + use draw::{Glyphs, Primitive, RasterImage}; -use engine::{CacheMode, DisplaySettings, Engine, EvalStats}; +use engine::{CacheMode, DisplaySettings, Engine, EvalStats, RamFrameCache, RamFrameKey}; use model::{Comp, NodeId}; use std::collections::HashSet; use std::sync::Arc; @@ -141,6 +145,7 @@ pub enum ViewerAction { SetProxy(u32), ToggleHiQ, ClearViewers, + GizmoEdited(GizmoEdit), } #[derive(Clone, Copy, Debug)] @@ -180,6 +185,10 @@ pub struct ViewerState { pub size: [f32; 2], pub last_stats: EvalStats, pub cached_frames: HashSet, + pub ram_cached_ranges: Vec<(i64, i64)>, + pub audio_peaks: Vec, + pub selected_node: Option, + pub gizmos: GizmoState, pub dirty: bool, pub palette: ViewerPalette, last_revision: u64, @@ -207,6 +216,10 @@ impl ViewerState { size: [800.0, 500.0], last_stats: EvalStats::default(), cached_frames: HashSet::new(), + ram_cached_ranges: Vec::new(), + audio_peaks: Vec::new(), + selected_node: None, + gizmos: GizmoState::new(), dirty: true, palette: ViewerPalette::from_ui(theme), last_revision: 0, @@ -310,6 +323,17 @@ impl ViewerState { } pub fn ensure_rendered(&mut self, engine: &mut Engine, comp: &Comp, current_frame: f64, dpi_scale: f32) { + self.ensure_rendered_with_ram(engine, None, comp, current_frame, dpi_scale); + } + + pub fn ensure_rendered_with_ram( + &mut self, + engine: &mut Engine, + ram_cache: Option<&RamFrameCache>, + comp: &Comp, + current_frame: f64, + dpi_scale: f32, + ) { let Some(target) = self.viewed_node else { return; }; @@ -360,7 +384,25 @@ impl ViewerState { if let Some(tex) = &self.output_tex { let mut disp = self.display; disp.uv_rect = uv_rect; - self.last_stats = engine.render_into_viewer(comp, target, current_frame, tex, disp); + let ram_hit = if engine.cache.mode == CacheMode::Enabled { + ram_cache.and_then(|rc| { + rc.get(RamFrameKey { + target, + frame: frame_i, + revision: comp.revision, + proxy_scale: engine.proxy_scale, + hiq: engine.hiq, + use_proxy_clips: engine.use_proxy_clips, + }) + }) + } else { + None + }; + if let Some(frame) = ram_hit { + self.last_stats = engine.render_ram_frame_into_viewer(&frame, tex, disp); + } else { + self.last_stats = engine.render_into_viewer(comp, target, current_frame, tex, disp); + } if engine.cache.mode == CacheMode::Enabled { self.cached_frames.insert(frame_i); } @@ -511,6 +553,9 @@ impl ViewerState { if tool_btn(ui, ("fit", self.slot), "Fit", self.fit_mode).clicked { self.fit(); } + if tool_btn(ui, ("gizmo", self.slot), "Gizmo", self.gizmos.enabled).clicked { + self.gizmos.enabled = !self.gizmos.enabled; + } if self.slot == 0 { let bypass_lbl = match engine.cache.mode { @@ -624,6 +669,11 @@ impl ViewerState { self.pointer_local = [p[0] - rect[0], p[1] - rect[1]]; if self.scrubbing { actions.push(ViewerAction::SetFrame(self.frame_at_x(comp, self.pointer_local[0]))); + } else if self.gizmos.is_dragging() { + let (img_rect, _, _, _) = self.image_layout(comp); + if let Some(edit) = self.gizmos.update_drag(comp, img_rect, self.pointer_local, modifiers.shift_key()) { + actions.push(ViewerAction::GizmoEdited(edit)); + } } else if let Some((sp, span)) = self.panning { self.fit_mode = false; self.pan = [ @@ -631,6 +681,9 @@ impl ViewerState { span[1] + (self.pointer_local[1] - sp[1]), ]; self.dirty = true; + } else { + let (img_rect, _, _, _) = self.image_layout(comp); + self.gizmos.update_hover(comp, self.selected_node, clock.current_frame, img_rect, self.pointer_local); } } ui::Event::Button { button, pressed, .. } => { @@ -651,9 +704,13 @@ impl ViewerState { if self.pointer_local[1] >= scrub[1] - 6.0 { self.scrubbing = true; actions.push(ViewerAction::SetFrame(self.frame_at_x(comp, self.pointer_local[0]))); + } else if let Some(sel) = self.selected_node { + let (img_rect, _, _, _) = self.image_layout(comp); + self.gizmos.begin_drag(comp, sel, clock.current_frame, img_rect, self.pointer_local); } } else { self.scrubbing = false; + self.gizmos.end_drag(); } } } @@ -709,6 +766,9 @@ impl ViewerState { stroke: Some(1.0), color: self.palette.border, }); + if let Some(sel) = self.selected_node { + out.extend(self.gizmos.paint(comp, sel, current_frame, full_rect, vis)); + } } } } @@ -735,6 +795,47 @@ impl ViewerState { let span = (r1 - r0).max(1.0); let bar_w = (sr[2] - sr[0]).max(1.0); let tick_w = (bar_w / span as f32).max(2.0); + + // Audio waveform overlay across the timeline scrubber + if !self.audio_peaks.is_empty() && bar_w > 16.0 { + let max_bars = (bar_w / 3.0).floor().clamp(8.0, 480.0) as usize; + let n = self.audio_peaks.len(); + let mid_y = 0.5 * (sr[1] + sr[3] - 3.0); + let max_half = ((sr[3] - sr[1] - 5.0) * 0.5).max(1.5); + let step_w = bar_w / max_bars as f32; + for b in 0..max_bars { + let i0 = (b * n) / max_bars; + let i1 = (((b + 1) * n) / max_bars).max(i0 + 1).min(n); + let mut peak = 0.0_f32; + for &v in &self.audio_peaks[i0..i1] { + if v > peak { peak = v; } + } + if peak > 0.015 { + let h = (peak * max_half).max(1.0); + let x = sr[0] + b as f32 * step_w; + out.push(Primitive::Rect { + rect: [x, mid_y - h, (x + (step_w - 0.8).max(1.0)).min(sr[2]), mid_y + h], + color: [0.46, 0.72, 0.96, 0.36], + }); + } + } + } + + // Green RAM cache ranges along the bottom of the scrubber + for &(c0, c1) in &self.ram_cached_ranges { + let f0 = (c0 as f64).max(r0); + let f1 = (c1 as f64).min(r1); + if f1 < f0 { + continue; + } + let x0 = sr[0] + ((f0 - r0) / span) as f32 * bar_w; + let x1 = (sr[0] + ((f1 - r0) / span) as f32 * bar_w + tick_w).min(sr[2]); + out.push(Primitive::Rect { + rect: [x0, sr[3] - 4.0, x1.max(x0 + 2.0), sr[3] - 1.0], + color: [0.22, 0.86, 0.48, 0.92], + }); + } + // Individual GPU-cached frames from this session for &cf in &self.cached_frames { if (cf as f64) >= r0 && (cf as f64) <= r1 { let frac = ((cf as f64 - r0) / span) as f32;