authoravatarclover caruso<git@paperclover.net>2026-11-30 13:12:59-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 14:11:43-08:00
log7de1736f7facb72ef19b0be821d574d3f7903bea
treefb445c819358558f00c67e7f684fbb1207d6e181
parent76fc78f911b8eff80bf8ebe824e6d289ad9e8335
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Spline handles/easing/normalize, Keyframes dope-sheet/waveform/RAM cache bar, and Viewer gizmos (#15)


6 files changed, 3501 insertions(+), 121 deletions(-)

crates/spline/src/lib.rs+876-103
...@@ -3,12 +3,22 @@...@@ -3,12 +3,22 @@
3//! Features:3//! Features:
4//! - Both direct LMB drag AND Blender `G` (Grab), `R` (Rotate), `S` (Scale) modal editing4//! - Both direct LMB drag AND Blender `G` (Grab), `R` (Rotate), `S` (Scale) modal editing
5//! - `X`/`Y` axis locks with red/green guides, integer-frame snapping (`Shift` for fine)5//! - `X`/`Y` axis locks with red/green guides, integer-frame snapping (`Shift` for fine)
6//! - `Cmd+F` / Numpad `.` / `F` fit-to-view, `L` Linear/Smooth, `T` Step, `I` Insert key, `Del/BS` Delete6//! - `V` Handle Type popup (`Free`/`Aligned`/`Auto`/`Vector`), `T` Easing/Interpolation popup
7//! - `N` Normalize curves to `[0, 1]` with hover real-value readout pill
8//! - `Cmd+F` / Numpad `.` / `F` fit-to-view, `L` Linear/Smooth, `I` Insert key, `X/Del/BS` Delete
7//! - Crisp high-contrast curves (zero XOR!), generous hit targets, live GPU Viewer feedback.9//! - Crisp high-contrast curves (zero XOR!), generous hit targets, live GPU Viewer feedback.
810
11pub mod presets;
12
13pub use presets::EasingPreset;
14
9use draw::{Glyphs, Primitive};15use draw::{Glyphs, Primitive};
10use model::spline::{cubic, segment_control_points};16use model::spline::{cubic, segment_control_points};
11use model::{Comp, Keyframe, NodeId};17use model::{Comp, CompHistory, HandleMode, Keyframe, NodeId};
18use presets::{
19 apply_easing_preset, apply_handle_mode, compute_curve_bounds, display_to_value,
20 enforce_aligned_handle, value_to_display,
21};
12use std::collections::{HashMap, HashSet};22use std::collections::{HashMap, HashSet};
13use std::sync::Arc;23use std::sync::Arc;
14use winit::event::{ElementState, MouseButton};24use winit::event::{ElementState, MouseButton};
...@@ -16,6 +26,10 @@ use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey};...@@ -16,6 +26,10 @@ use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey};
1626
17const RULER_H: f32 = 24.0;27const RULER_H: f32 = 24.0;
18const SIDEBAR_W: f32 = 172.0;28const SIDEBAR_W: f32 = 172.0;
29const POPUP_W: f32 = 156.0;
30const POPUP_HEADER_H: f32 = 22.0;
31const POPUP_ROW_H: f32 = 22.0;
32const POPUP_PAD: f32 = 4.0;
1933
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]34#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
21pub enum HandlePart {35pub enum HandlePart {
...@@ -49,11 +63,48 @@ pub enum AxisLock {...@@ -49,11 +63,48 @@ pub enum AxisLock {
49struct ModalEdit {63struct ModalEdit {
50 mode: TransformMode,64 mode: TransformMode,
51 axis: AxisLock,65 axis: AxisLock,
66 /// Pivot in display coordinates `(time, display_value)`.
52 pivot: [f64; 2],67 pivot: [f64; 2],
68 /// Pointer at modal start in display coordinates `(time, display_value)`.
53 start_pointer: [f64; 2],69 start_pointer: [f64; 2],
54 saved_splines: HashMap<String, Vec<Keyframe>>,70 saved_splines: HashMap<String, Vec<Keyframe>>,
71 /// Frozen per-spline `(min_v, max_v)` bounds captured when the modal began so normalized
72 /// drags stay stable without shifting scale mid-drag.
73 saved_bounds: HashMap<String, (f64, f64)>,
74 /// Optional pre-edit `Comp` snapshot captured when a `CompHistory` is active.
75 pre_edit_snapshot: Option<Comp>,
76}
77
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79enum PopupKind {
80 HandleType,
81 Easing,
55}82}
5683
84#[derive(Clone, Debug)]
85struct PopupMenu {
86 kind: PopupKind,
87 pos: [f32; 2],
88}
89
90const HANDLE_MENU_ITEMS: &[(HandleMode, &str)] = &[
91 (HandleMode::Free, "1: Free"),
92 (HandleMode::Aligned, "2: Aligned"),
93 (HandleMode::Auto, "3: Auto"),
94 (HandleMode::Vector, "4: Vector"),
95];
96
97const EASING_MENU_ITEMS: &[(EasingPreset, &str)] = &[
98 (EasingPreset::Linear, "1: Linear"),
99 (EasingPreset::Smooth, "2: Smooth"),
100 (EasingPreset::StepIn, "3: Step In"),
101 (EasingPreset::StepOut, "4: Step Out"),
102 (EasingPreset::EaseInOut, "5: Ease In-Out"),
103 (EasingPreset::EaseOut, "6: Ease Out"),
104 (EasingPreset::EaseIn, "7: Ease In"),
105 (EasingPreset::KnifeEase, "8: Knife Ease"),
106];
107
57#[derive(Clone, Debug)]108#[derive(Clone, Debug)]
58struct BoxSelect {109struct BoxSelect {
59 start_local: [f32; 2],110 start_local: [f32; 2],
...@@ -106,9 +157,11 @@ pub struct SplineView {...@@ -106,9 +157,11 @@ pub struct SplineView {
106 pub channels: Vec<(String, String)>,157 pub channels: Vec<(String, String)>,
107 pub hidden_splines: HashSet<String>,158 pub hidden_splines: HashSet<String>,
108 pub selected: HashSet<PointRef>,159 pub selected: HashSet<PointRef>,
160 pub normalized: bool,
109 pub palette: SplinePalette,161 pub palette: SplinePalette,
110 hovered: Option<PointRef>,162 hovered: Option<PointRef>,
111 modal: Option<ModalEdit>,163 modal: Option<ModalEdit>,
164 popup: Option<PopupMenu>,
112 lmb_drag_point: Option<([f32; 2], bool)>,165 lmb_drag_point: Option<([f32; 2], bool)>,
113 box_select: Option<BoxSelect>,166 box_select: Option<BoxSelect>,
114 panning: Option<([f32; 2], [f64; 2], [f64; 2])>,167 panning: Option<([f32; 2], [f64; 2], [f64; 2])>,
...@@ -116,6 +169,7 @@ pub struct SplineView {...@@ -116,6 +169,7 @@ pub struct SplineView {
116 pointer_local: [f32; 2],169 pointer_local: [f32; 2],
117 current_node: Option<NodeId>,170 current_node: Option<NodeId>,
118 text_cache: HashMap<String, text::Layout>,171 text_cache: HashMap<String, text::Layout>,
172 last_hover_readout: String,
119}173}
120174
121impl SplineView {175impl SplineView {
...@@ -127,9 +181,11 @@ impl SplineView {...@@ -127,9 +181,11 @@ impl SplineView {
127 channels: Vec::new(),181 channels: Vec::new(),
128 hidden_splines: HashSet::new(),182 hidden_splines: HashSet::new(),
129 selected: HashSet::new(),183 selected: HashSet::new(),
184 normalized: false,
130 palette: SplinePalette::from_ui(theme),185 palette: SplinePalette::from_ui(theme),
131 hovered: None,186 hovered: None,
132 modal: None,187 modal: None,
188 popup: None,
133 lmb_drag_point: None,189 lmb_drag_point: None,
134 box_select: None,190 box_select: None,
135 panning: None,191 panning: None,
...@@ -137,6 +193,7 @@ impl SplineView {...@@ -137,6 +193,7 @@ impl SplineView {
137 pointer_local: [0.0, 0.0],193 pointer_local: [0.0, 0.0],
138 current_node: None,194 current_node: None,
139 text_cache: HashMap::new(),195 text_cache: HashMap::new(),
196 last_hover_readout: String::new(),
140 }197 }
141 }198 }
142199
...@@ -155,6 +212,7 @@ impl SplineView {...@@ -155,6 +212,7 @@ impl SplineView {
155 self.current_node = selected_node;212 self.current_node = selected_node;
156 self.selected.clear();213 self.selected.clear();
157 self.modal = None;214 self.modal = None;
215 self.popup = None;
158 self.lmb_drag_point = None;216 self.lmb_drag_point = None;
159217
160 let mut ch = selected_node218 let mut ch = selected_node
...@@ -178,6 +236,15 @@ impl SplineView {...@@ -178,6 +236,15 @@ impl SplineView {
178 self.fit_all(comp);236 self.fit_all(comp);
179 }237 }
180238
239 pub fn toggle_normalized(&mut self, comp: &Comp) {
240 self.normalized = !self.normalized;
241 if self.normalized {
242 self.v_range = [-0.12, 1.12];
243 } else {
244 self.fit_all(comp);
245 }
246 }
247
181 pub fn fit_all(&mut self, comp: &Comp) {248 pub fn fit_all(&mut self, comp: &Comp) {
182 let mut t0 = f64::INFINITY;249 let mut t0 = f64::INFINITY;
183 let mut t1 = f64::NEG_INFINITY;250 let mut t1 = f64::NEG_INFINITY;
...@@ -223,13 +290,17 @@ impl SplineView {...@@ -223,13 +290,17 @@ impl SplineView {
223290
224 if !t0.is_finite() {291 if !t0.is_finite() {
225 self.t_range = [comp.render_range[0] as f64, comp.render_range[1] as f64];292 self.t_range = [comp.render_range[0] as f64, comp.render_range[1] as f64];
226 self.v_range = [-0.2, 1.2];293 self.v_range = if self.normalized { [-0.12, 1.12] } else { [-0.2, 1.2] };
227 return;294 return;
228 }295 }
229 let dt = (t1 - t0).max(20.0);296 let dt = (t1 - t0).max(20.0);
230 let dv = (v1 - v0).max(0.2);
231 self.t_range = [t0 - dt * 0.14, t1 + dt * 0.14];297 self.t_range = [t0 - dt * 0.14, t1 + dt * 0.14];
232 self.v_range = [v0 - dv * 0.20, v1 + dv * 0.20];298 if self.normalized {
299 self.v_range = [-0.12, 1.12];
300 } else {
301 let dv = (v1 - v0).max(0.2);
302 self.v_range = [v0 - dv * 0.20, v1 + dv * 0.20];
303 }
233 }304 }
234305
235 fn plot_rect(&self) -> [f32; 4] {306 fn plot_rect(&self) -> [f32; 4] {
...@@ -241,6 +312,22 @@ impl SplineView {...@@ -241,6 +312,22 @@ impl SplineView {
241 ]312 ]
242 }313 }
243314
315 fn normalize_pill_rect(&self) -> [f32; 4] {
316 [SIDEBAR_W - 46.0, 3.0, SIDEBAR_W - 6.0, RULER_H - 3.0]
317 }
318
319 fn spline_bounds(&self, comp: &Comp, sname: &str) -> (f64, f64) {
320 if let Some(m) = &self.modal {
321 if let Some(&b) = m.saved_bounds.get(sname) {
322 return b;
323 }
324 }
325 comp.splines
326 .get(sname)
327 .map(compute_curve_bounds)
328 .unwrap_or((0.0, 1.0))
329 }
330
244 fn data_to_local(&self, t: f64, v: f64) -> [f32; 2] {331 fn data_to_local(&self, t: f64, v: f64) -> [f32; 2] {
245 let r = self.plot_rect();332 let r = self.plot_rect();
246 let tx = (t - self.t_range[0]) / (self.t_range[1] - self.t_range[0]).max(1e-6);333 let tx = (t - self.t_range[0]) / (self.t_range[1] - self.t_range[0]).max(1e-6);
...@@ -251,6 +338,11 @@ impl SplineView {...@@ -251,6 +338,11 @@ impl SplineView {
251 ]338 ]
252 }339 }
253340
341 fn spline_to_local(&self, t: f64, v: f64, bounds: (f64, f64)) -> [f32; 2] {
342 let disp_v = value_to_display(v, bounds, self.normalized);
343 self.data_to_local(t, disp_v)
344 }
345
254 fn local_to_data(&self, l: [f32; 2]) -> [f64; 2] {346 fn local_to_data(&self, l: [f32; 2]) -> [f64; 2] {
255 let r = self.plot_rect();347 let r = self.plot_rect();
256 let tx = f64::from((l[0] - r[0]) / (r[2] - r[0]).max(1.0));348 let tx = f64::from((l[0] - r[0]) / (r[2] - r[0]).max(1.0));
...@@ -270,8 +362,9 @@ impl SplineView {...@@ -270,8 +362,9 @@ impl SplineView {
270 continue;362 continue;
271 }363 }
272 let Some(sp) = comp.splines.get(sname) else { continue };364 let Some(sp) = comp.splines.get(sname) else { continue };
365 let bounds = self.spline_bounds(comp, sname);
273 for (ki, kf) in sp.keyframes.iter().enumerate() {366 for (ki, kf) in sp.keyframes.iter().enumerate() {
274 let kp = self.data_to_local(kf.time, kf.value);367 let kp = self.spline_to_local(kf.time, kf.value, bounds);
275 let kd = hypot2(local, kp);368 let kd = hypot2(local, kp);
276 if kd < 15.0 && best_key.as_ref().is_none_or(|(d, _)| kd < *d) {369 if kd < 15.0 && best_key.as_ref().is_none_or(|(d, _)| kd < *d) {
277 best_key = Some((370 best_key = Some((
...@@ -282,7 +375,7 @@ impl SplineView {...@@ -282,7 +375,7 @@ impl SplineView {
282375
283 if self.is_key_or_handle_selected(sname, ki) {376 if self.is_key_or_handle_selected(sname, ki) {
284 if let Some(lh) = kf.lh {377 if let Some(lh) = kf.lh {
285 let lp = self.data_to_local(lh[0], lh[1]);378 let lp = self.spline_to_local(lh[0], lh[1], bounds);
286 let ld = hypot2(local, lp);379 let ld = hypot2(local, lp);
287 if ld < 14.0 && best_handle.as_ref().is_none_or(|(d, _)| ld < *d) {380 if ld < 14.0 && best_handle.as_ref().is_none_or(|(d, _)| ld < *d) {
288 best_handle = Some((381 best_handle = Some((
...@@ -292,7 +385,7 @@ impl SplineView {...@@ -292,7 +385,7 @@ impl SplineView {
292 }385 }
293 }386 }
294 if let Some(rh) = kf.rh {387 if let Some(rh) = kf.rh {
295 let rp = self.data_to_local(rh[0], rh[1]);388 let rp = self.spline_to_local(rh[0], rh[1], bounds);
296 let rd = hypot2(local, rp);389 let rd = hypot2(local, rp);
297 if rd < 14.0 && best_handle.as_ref().is_none_or(|(d, _)| rd < *d) {390 if rd < 14.0 && best_handle.as_ref().is_none_or(|(d, _)| rd < *d) {
298 best_handle = Some((391 best_handle = Some((
...@@ -311,7 +404,7 @@ impl SplineView {...@@ -311,7 +404,7 @@ impl SplineView {
311 self.selected.iter().any(|p| p.spline == spline && p.key_idx == key_idx)404 self.selected.iter().any(|p| p.spline == spline && p.key_idx == key_idx)
312 }405 }
313406
314 fn begin_modal(&mut self, comp: &Comp, mode: TransformMode) {407 fn begin_modal(&mut self, comp: &Comp, capture_history: bool, mode: TransformMode) {
315 if self.selected.is_empty() {408 if self.selected.is_empty() {
316 return;409 return;
317 }410 }
...@@ -319,10 +412,14 @@ impl SplineView {...@@ -319,10 +412,14 @@ impl SplineView {
319 let mut sum_v = 0.0;412 let mut sum_v = 0.0;
320 let mut count = 0usize;413 let mut count = 0usize;
321 let mut saved = HashMap::new();414 let mut saved = HashMap::new();
415 let mut saved_bounds = HashMap::new();
322416
323 for pref in &self.selected {417 for pref in &self.selected {
324 if let Some(sp) = comp.splines.get(&pref.spline) {418 if let Some(sp) = comp.splines.get(&pref.spline) {
325 saved.entry(pref.spline.clone()).or_insert_with(|| sp.keyframes.clone());419 saved.entry(pref.spline.clone()).or_insert_with(|| sp.keyframes.clone());
420 let bounds = *saved_bounds
421 .entry(pref.spline.clone())
422 .or_insert_with(|| compute_curve_bounds(sp));
326 if let Some(kf) = sp.keyframes.get(pref.key_idx) {423 if let Some(kf) = sp.keyframes.get(pref.key_idx) {
327 let pt = match pref.part {424 let pt = match pref.part {
328 HandlePart::Key => [kf.time, kf.value],425 HandlePart::Key => [kf.time, kf.value],
...@@ -335,7 +432,7 @@ impl SplineView {...@@ -335,7 +432,7 @@ impl SplineView {
335 pt432 pt
336 };433 };
337 sum_t += piv_pt[0];434 sum_t += piv_pt[0];
338 sum_v += piv_pt[1];435 sum_v += value_to_display(piv_pt[1], bounds, self.normalized);
339 count += 1;436 count += 1;
340 }437 }
341 }438 }
...@@ -349,6 +446,8 @@ impl SplineView {...@@ -349,6 +446,8 @@ impl SplineView {
349 pivot: [sum_t / count as f64, sum_v / count as f64],446 pivot: [sum_t / count as f64, sum_v / count as f64],
350 start_pointer: self.local_to_data(self.pointer_local),447 start_pointer: self.local_to_data(self.pointer_local),
351 saved_splines: saved,448 saved_splines: saved,
449 saved_bounds,
450 pre_edit_snapshot: capture_history.then(|| comp.clone()),
352 });451 });
353 }452 }
354453
...@@ -356,8 +455,9 @@ impl SplineView {...@@ -356,8 +455,9 @@ impl SplineView {
356 let Some(m) = &self.modal else { return false };455 let Some(m) = &self.modal else { return false };
357 let cur = self.local_to_data(self.pointer_local);456 let cur = self.local_to_data(self.pointer_local);
358 let dt = cur[0] - m.start_pointer[0];457 let dt = cur[0] - m.start_pointer[0];
359 let dv = cur[1] - m.start_pointer[1];458 let dv_disp = cur[1] - m.start_pointer[1];
360 let piv = m.pivot;459 let piv = m.pivot;
460 let normalized = self.normalized;
361461
362 for (sname, orig_kfs) in &m.saved_splines {462 for (sname, orig_kfs) in &m.saved_splines {
363 if let Some(sp) = comp.splines.get_mut(sname) {463 if let Some(sp) = comp.splines.get_mut(sname) {
...@@ -367,15 +467,47 @@ impl SplineView {...@@ -367,15 +467,47 @@ impl SplineView {
367467
368 let snap_t = |t: f64| if fine { t } else { t.round() };468 let snap_t = |t: f64| if fine { t } else { t.round() };
369469
470 // Helper: convert Auto/Vector handles to Aligned/Free when manually dragged (Blender behavior),
471 // and mirror opposite handle if Aligned (and opposite handle isn't also explicitly selected).
472 let finalize_handle_drag = |kf: &mut Keyframe, pref: &PointRef, selected: &HashSet<PointRef>| {
473 kf.flags.linear = false;
474 match kf.handle_mode {
475 HandleMode::Auto => kf.handle_mode = HandleMode::Aligned,
476 HandleMode::Vector => kf.handle_mode = HandleMode::Free,
477 HandleMode::Aligned | HandleMode::Free => {}
478 }
479 if kf.handle_mode == HandleMode::Aligned {
480 let opp_part = match pref.part {
481 HandlePart::LeftHandle => HandlePart::RightHandle,
482 HandlePart::RightHandle => HandlePart::LeftHandle,
483 HandlePart::Key => return,
484 };
485 let opp_selected = selected.contains(&PointRef {
486 spline: pref.spline.clone(),
487 key_idx: pref.key_idx,
488 part: opp_part,
489 });
490 if !opp_selected {
491 enforce_aligned_handle(kf, pref.part);
492 }
493 }
494 };
495
370 match m.mode {496 match m.mode {
371 TransformMode::Grab => {497 TransformMode::Grab => {
372 let (mt, mv) = match m.axis {498 let (mt, mv_disp) = match m.axis {
373 AxisLock::None => (dt, dv),499 AxisLock::None => (dt, dv_disp),
374 AxisLock::X => (dt, 0.0),500 AxisLock::X => (dt, 0.0),
375 AxisLock::Y => (0.0, dv),501 AxisLock::Y => (0.0, dv_disp),
376 };502 };
377 for pref in &self.selected {503 for pref in &self.selected {
378 let Some(sp) = comp.splines.get_mut(&pref.spline) else { continue };504 let Some(sp) = comp.splines.get_mut(&pref.spline) else { continue };
505 let bounds = m.saved_bounds.get(&pref.spline).copied().unwrap_or((0.0, 1.0));
506 let mv = if normalized {
507 mv_disp * (bounds.1 - bounds.0).max(1e-9)
508 } else {
509 mv_disp
510 };
379 let Some(kf) = sp.keyframes.get_mut(pref.key_idx) else { continue };511 let Some(kf) = sp.keyframes.get_mut(pref.key_idx) else { continue };
380 match pref.part {512 match pref.part {
381 HandlePart::Key => {513 HandlePart::Key => {
...@@ -397,14 +529,14 @@ impl SplineView {...@@ -397,14 +529,14 @@ impl SplineView {
397 h[0] = (h[0] + mt).min(kf.time - 0.01);529 h[0] = (h[0] + mt).min(kf.time - 0.01);
398 h[1] += mv;530 h[1] += mv;
399 kf.lh = Some(h);531 kf.lh = Some(h);
400 kf.flags.linear = false;532 finalize_handle_drag(kf, pref, &self.selected);
401 }533 }
402 HandlePart::RightHandle => {534 HandlePart::RightHandle => {
403 let mut h = kf.rh.unwrap_or([kf.time + 5.0, kf.value]);535 let mut h = kf.rh.unwrap_or([kf.time + 5.0, kf.value]);
404 h[0] = (h[0] + mt).max(kf.time + 0.01);536 h[0] = (h[0] + mt).max(kf.time + 0.01);
405 h[1] += mv;537 h[1] += mv;
406 kf.rh = Some(h);538 kf.rh = Some(h);
407 kf.flags.linear = false;539 finalize_handle_drag(kf, pref, &self.selected);
408 }540 }
409 }541 }
410 }542 }
...@@ -412,9 +544,9 @@ impl SplineView {...@@ -412,9 +544,9 @@ impl SplineView {
412 TransformMode::Scale => {544 TransformMode::Scale => {
413 let s0 = self.data_to_local(m.start_pointer[0], m.start_pointer[1]);545 let s0 = self.data_to_local(m.start_pointer[0], m.start_pointer[1]);
414 let s1 = self.pointer_local;546 let s1 = self.pointer_local;
415 let sp = self.data_to_local(piv[0], piv[1]);547 let sp_px = self.data_to_local(piv[0], piv[1]);
416 let d0 = hypot2(s0, sp).max(10.0);548 let d0 = hypot2(s0, sp_px).max(10.0);
417 let d1 = hypot2(s1, sp);549 let d1 = hypot2(s1, sp_px);
418 let f = f64::from((d1 / d0).clamp(0.05, 10.0));550 let f = f64::from((d1 / d0).clamp(0.05, 10.0));
419 let (st, sv) = match m.axis {551 let (st, sv) = match m.axis {
420 AxisLock::None => (f, f),552 AxisLock::None => (f, f),
...@@ -423,18 +555,20 @@ impl SplineView {...@@ -423,18 +555,20 @@ impl SplineView {
423 };555 };
424 for pref in &self.selected {556 for pref in &self.selected {
425 let Some(sp) = comp.splines.get_mut(&pref.spline) else { continue };557 let Some(sp) = comp.splines.get_mut(&pref.spline) else { continue };
558 let bounds = m.saved_bounds.get(&pref.spline).copied().unwrap_or((0.0, 1.0));
559 let piv_val = display_to_value(piv[1], bounds, normalized);
426 let Some(kf) = sp.keyframes.get_mut(pref.key_idx) else { continue };560 let Some(kf) = sp.keyframes.get_mut(pref.key_idx) else { continue };
427 match pref.part {561 match pref.part {
428 HandlePart::Key => {562 HandlePart::Key => {
429 kf.time = snap_t(piv[0] + (kf.time - piv[0]) * st);563 kf.time = snap_t(piv[0] + (kf.time - piv[0]) * st);
430 kf.value = piv[1] + (kf.value - piv[1]) * sv;564 kf.value = piv_val + (kf.value - piv_val) * sv;
431 if let Some(lh) = &mut kf.lh {565 if let Some(lh) = &mut kf.lh {
432 lh[0] = piv[0] + (lh[0] - piv[0]) * st;566 lh[0] = piv[0] + (lh[0] - piv[0]) * st;
433 lh[1] = piv[1] + (lh[1] - piv[1]) * sv;567 lh[1] = piv_val + (lh[1] - piv_val) * sv;
434 }568 }
435 if let Some(rh) = &mut kf.rh {569 if let Some(rh) = &mut kf.rh {
436 rh[0] = piv[0] + (rh[0] - piv[0]) * st;570 rh[0] = piv[0] + (rh[0] - piv[0]) * st;
437 rh[1] = piv[1] + (rh[1] - piv[1]) * sv;571 rh[1] = piv_val + (rh[1] - piv_val) * sv;
438 }572 }
439 }573 }
440 HandlePart::LeftHandle => {574 HandlePart::LeftHandle => {
...@@ -442,12 +576,14 @@ impl SplineView {...@@ -442,12 +576,14 @@ impl SplineView {
442 lh[0] = (kf.time + (lh[0] - kf.time) * st).min(kf.time - 0.01);576 lh[0] = (kf.time + (lh[0] - kf.time) * st).min(kf.time - 0.01);
443 lh[1] = kf.value + (lh[1] - kf.value) * sv;577 lh[1] = kf.value + (lh[1] - kf.value) * sv;
444 }578 }
579 finalize_handle_drag(kf, pref, &self.selected);
445 }580 }
446 HandlePart::RightHandle => {581 HandlePart::RightHandle => {
447 if let Some(rh) = &mut kf.rh {582 if let Some(rh) = &mut kf.rh {
448 rh[0] = (kf.time + (rh[0] - kf.time) * st).max(kf.time + 0.01);583 rh[0] = (kf.time + (rh[0] - kf.time) * st).max(kf.time + 0.01);
449 rh[1] = kf.value + (rh[1] - kf.value) * sv;584 rh[1] = kf.value + (rh[1] - kf.value) * sv;
450 }585 }
586 finalize_handle_drag(kf, pref, &self.selected);
451 }587 }
452 }588 }
453 }589 }
...@@ -460,51 +596,53 @@ impl SplineView {...@@ -460,51 +596,53 @@ impl SplineView {
460 let da = a1 - a0;596 let da = a1 - a0;
461 let (c, s) = (da.cos(), da.sin());597 let (c, s) = (da.cos(), da.sin());
462598
463 let rot = |pt: [f64; 2], center_px: [f32; 2]| -> [f64; 2] {599 let rot = |pt: [f64; 2], center_px: [f32; 2], bounds: (f64, f64)| -> [f64; 2] {
464 let p = self.data_to_local(pt[0], pt[1]);600 let p = self.spline_to_local(pt[0], pt[1], bounds);
465 let rx = p[0] - center_px[0];601 let rx = p[0] - center_px[0];
466 let ry = p[1] - center_px[1];602 let ry = p[1] - center_px[1];
467 let np = [center_px[0] + rx * c - ry * s, center_px[1] + rx * s + ry * c];603 let np = [center_px[0] + rx * c - ry * s, center_px[1] + rx * s + ry * c];
468 self.local_to_data(np)604 let disp = self.local_to_data(np);
605 [disp[0], display_to_value(disp[1], bounds, normalized)]
469 };606 };
470607
471 for pref in &self.selected {608 for pref in &self.selected {
472 let Some(sp) = comp.splines.get_mut(&pref.spline) else { continue };609 let Some(sp) = comp.splines.get_mut(&pref.spline) else { continue };
610 let bounds = m.saved_bounds.get(&pref.spline).copied().unwrap_or((0.0, 1.0));
473 let Some(kf) = sp.keyframes.get_mut(pref.key_idx) else { continue };611 let Some(kf) = sp.keyframes.get_mut(pref.key_idx) else { continue };
474 match pref.part {612 match pref.part {
475 HandlePart::Key => {613 HandlePart::Key => {
476 if self.selected.len() == 1 {614 if self.selected.len() == 1 {
477 let kp = self.data_to_local(kf.time, kf.value);615 let kp = self.spline_to_local(kf.time, kf.value, bounds);
478 ensure_handles(kf);616 ensure_handles(kf);
479 if let Some(lh) = kf.lh {617 if let Some(lh) = kf.lh {
480 let nl = rot(lh, kp);618 let nl = rot(lh, kp, bounds);
481 kf.lh = Some([nl[0].min(kf.time - 0.01), nl[1]]);619 kf.lh = Some([nl[0].min(kf.time - 0.01), nl[1]]);
482 }620 }
483 if let Some(rh) = kf.rh {621 if let Some(rh) = kf.rh {
484 let nr = rot(rh, kp);622 let nr = rot(rh, kp, bounds);
485 kf.rh = Some([nr[0].max(kf.time + 0.01), nr[1]]);623 kf.rh = Some([nr[0].max(kf.time + 0.01), nr[1]]);
486 }624 }
487 kf.flags.linear = false;625 kf.flags.linear = false;
488 } else {626 } else {
489 let nk = rot([kf.time, kf.value], sp_px);627 let nk = rot([kf.time, kf.value], sp_px, bounds);
490 kf.time = snap_t(nk[0]);628 kf.time = snap_t(nk[0]);
491 kf.value = nk[1];629 kf.value = nk[1];
492 }630 }
493 }631 }
494 HandlePart::LeftHandle => {632 HandlePart::LeftHandle => {
495 let kp = self.data_to_local(kf.time, kf.value);633 let kp = self.spline_to_local(kf.time, kf.value, bounds);
496 if let Some(lh) = kf.lh {634 if let Some(lh) = kf.lh {
497 let nl = rot(lh, kp);635 let nl = rot(lh, kp, bounds);
498 kf.lh = Some([nl[0].min(kf.time - 0.01), nl[1]]);636 kf.lh = Some([nl[0].min(kf.time - 0.01), nl[1]]);
499 kf.flags.linear = false;637 finalize_handle_drag(kf, pref, &self.selected);
500 }638 }
501 }639 }
502 HandlePart::RightHandle => {640 HandlePart::RightHandle => {
503 let kp = self.data_to_local(kf.time, kf.value);641 let kp = self.spline_to_local(kf.time, kf.value, bounds);
504 if let Some(rh) = kf.rh {642 if let Some(rh) = kf.rh {
505 let nr = rot(rh, kp);643 let nr = rot(rh, kp, bounds);
506 kf.rh = Some([nr[0].max(kf.time + 0.01), nr[1]]);644 kf.rh = Some([nr[0].max(kf.time + 0.01), nr[1]]);
507 kf.flags.linear = false;645 finalize_handle_drag(kf, pref, &self.selected);
508 }646 }
509 }647 }
510 }648 }
...@@ -526,7 +664,7 @@ impl SplineView {...@@ -526,7 +664,7 @@ impl SplineView {
526 }664 }
527 }665 }
528666
529 fn confirm_modal(&mut self, comp: &mut Comp) {667 fn confirm_modal(&mut self, comp: &mut Comp, history: Option<&mut CompHistory>) {
530 if let Some(m) = self.modal.take() {668 if let Some(m) = self.modal.take() {
531 for sname in m.saved_splines.keys() {669 for sname in m.saved_splines.keys() {
532 if let Some(sp) = comp.splines.get_mut(sname) {670 if let Some(sp) = comp.splines.get_mut(sname) {
...@@ -534,18 +672,182 @@ impl SplineView {...@@ -534,18 +672,182 @@ impl SplineView {
534 }672 }
535 }673 }
536 comp.revision += 1;674 comp.revision += 1;
675 if let (Some(h), Some(snap)) = (history, m.pre_edit_snapshot) {
676 let label = match m.mode {
677 TransformMode::Grab => "Grab Keyframes",
678 TransformMode::Rotate => "Rotate Keyframes",
679 TransformMode::Scale => "Scale Keyframes",
680 };
681 h.push_snapshot(&snap, label);
682 }
683 }
684 }
685
686 fn popup_rect(&self, popup: &PopupMenu) -> [f32; 4] {
687 let count = match popup.kind {
688 PopupKind::HandleType => HANDLE_MENU_ITEMS.len(),
689 PopupKind::Easing => EASING_MENU_ITEMS.len(),
690 };
691 let h = POPUP_HEADER_H + count as f32 * POPUP_ROW_H + POPUP_PAD;
692 let x = popup.pos[0].clamp(4.0, (self.size[0] - POPUP_W - 4.0).max(4.0));
693 let y = popup.pos[1].clamp(4.0, (self.size[1] - h - 4.0).max(4.0));
694 [x, y, x + POPUP_W, y + h]
695 }
696
697 fn popup_item_at(&self, popup: &PopupMenu, local: [f32; 2]) -> Option<usize> {
698 let r = self.popup_rect(popup);
699 if local[0] < r[0] || local[0] > r[2] || local[1] < r[1] + POPUP_HEADER_H || local[1] > r[3] {
700 return None;
701 }
702 let idx = ((local[1] - (r[1] + POPUP_HEADER_H)) / POPUP_ROW_H).floor() as isize;
703 let count = match popup.kind {
704 PopupKind::HandleType => HANDLE_MENU_ITEMS.len(),
705 PopupKind::Easing => EASING_MENU_ITEMS.len(),
706 };
707 if idx >= 0 && (idx as usize) < count {
708 Some(idx as usize)
709 } else {
710 None
711 }
712 }
713
714 fn open_popup(&mut self, kind: PopupKind) {
715 self.popup = Some(PopupMenu {
716 kind,
717 pos: [self.pointer_local[0] + 6.0, self.pointer_local[1] + 6.0],
718 });
719 }
720
721 fn selected_keys_by_spline(&self, comp: &Comp) -> HashMap<String, Vec<usize>> {
722 let mut by_spline: HashMap<String, Vec<usize>> = HashMap::new();
723 for pref in &self.selected {
724 if let Some(sp) = comp.splines.get(&pref.spline) {
725 if pref.key_idx < sp.keyframes.len() {
726 by_spline.entry(pref.spline.clone()).or_default().push(pref.key_idx);
727 }
728 }
729 }
730 for idxs in by_spline.values_mut() {
731 idxs.sort_unstable();
732 idxs.dedup();
537 }733 }
734 by_spline
735 }
736
737 fn apply_selected_handle_mode(
738 &mut self,
739 comp: &mut Comp,
740 history: Option<&mut CompHistory>,
741 mode: HandleMode,
742 ) -> bool {
743 let by_spline = self.selected_keys_by_spline(comp);
744 if by_spline.is_empty() {
745 return false;
746 }
747 if let Some(h) = history {
748 h.push_snapshot(comp, "Set Handle Type");
749 }
750 for (sname, idxs) in by_spline {
751 if let Some(sp) = comp.splines.get_mut(&sname) {
752 for idx in idxs {
753 apply_handle_mode(sp, idx, mode);
754 }
755 }
756 }
757 comp.revision += 1;
758 true
759 }
760
761 fn apply_selected_easing(
762 &mut self,
763 comp: &mut Comp,
764 history: Option<&mut CompHistory>,
765 preset: EasingPreset,
766 ) -> bool {
767 let by_spline = self.selected_keys_by_spline(comp);
768 if by_spline.is_empty() {
769 return false;
770 }
771 let pre_snap = history.as_ref().map(|_| comp.clone());
772 let mut changed = false;
773 for (sname, idxs) in by_spline {
774 if let Some(sp) = comp.splines.get_mut(&sname) {
775 if apply_easing_preset(sp, &idxs, preset) {
776 changed = true;
777 }
778 }
779 }
780 if changed {
781 if let (Some(h), Some(snap)) = (history, pre_snap) {
782 h.push_snapshot(&snap, format!("Easing: {}", preset.label()));
783 }
784 comp.revision += 1;
785 }
786 changed
538 }787 }
539788
540 fn handle_key(789 fn handle_key(
541 &mut self,790 &mut self,
542 comp: &mut Comp,791 comp: &mut Comp,
792 mut history: Option<&mut CompHistory>,
543 current_frame: f64,793 current_frame: f64,
544 physical: Option<PhysicalKey>,794 physical: Option<PhysicalKey>,
545 key: &Key,795 key: &Key,
546 kmod: ModifiersState,796 kmod: ModifiersState,
547 actions: &mut Vec<SplineAction>,797 actions: &mut Vec<SplineAction>,
548 ) {798 ) {
799 if let Some(popup) = self.popup.clone() {
800 match key {
801 Key::Named(NamedKey::Escape) => {
802 self.popup = None;
803 }
804 Key::Character(c) => {
805 let lc = c.to_ascii_lowercase();
806 if lc == "v" {
807 self.popup = if popup.kind == PopupKind::HandleType {
808 None
809 } else {
810 Some(PopupMenu { kind: PopupKind::HandleType, pos: popup.pos })
811 };
812 return;
813 }
814 if lc == "t" {
815 self.popup = if popup.kind == PopupKind::Easing {
816 None
817 } else {
818 Some(PopupMenu { kind: PopupKind::Easing, pos: popup.pos })
819 };
820 return;
821 }
822 if let Ok(num) = lc.parse::<usize>() {
823 if num >= 1 {
824 let idx = num - 1;
825 match popup.kind {
826 PopupKind::HandleType => {
827 if let Some(&(mode, _)) = HANDLE_MENU_ITEMS.get(idx) {
828 self.popup = None;
829 if self.apply_selected_handle_mode(comp, history, mode) {
830 actions.push(SplineAction::SplineEdited);
831 }
832 }
833 }
834 PopupKind::Easing => {
835 if let Some(&(preset, _)) = EASING_MENU_ITEMS.get(idx) {
836 self.popup = None;
837 if self.apply_selected_easing(comp, history, preset) {
838 actions.push(SplineAction::SplineEdited);
839 }
840 }
841 }
842 }
843 }
844 }
845 }
846 _ => {}
847 }
848 return;
849 }
850
549 if physical == Some(PhysicalKey::Code(KeyCode::NumpadDecimal)) {851 if physical == Some(PhysicalKey::Code(KeyCode::NumpadDecimal)) {
550 self.fit_all(comp);852 self.fit_all(comp);
551 return;853 return;
...@@ -559,26 +861,35 @@ impl SplineView {...@@ -559,26 +861,35 @@ impl SplineView {
559 }861 }
560 Key::Named(NamedKey::Enter) => {862 Key::Named(NamedKey::Enter) => {
561 if self.modal.is_some() {863 if self.modal.is_some() {
562 self.confirm_modal(comp);864 self.confirm_modal(comp, history);
563 actions.push(SplineAction::SplineEdited);865 actions.push(SplineAction::SplineEdited);
564 }866 }
565 }867 }
566 Key::Named(NamedKey::Delete | NamedKey::Backspace) => {868 Key::Named(NamedKey::Delete | NamedKey::Backspace) => {
567 if self.delete_selected(comp) {869 if self.delete_selected(comp, history) {
568 actions.push(SplineAction::SplineEdited);870 actions.push(SplineAction::SplineEdited);
569 }871 }
570 }872 }
571 Key::Character(c) => match c.to_ascii_lowercase().as_str() {873 Key::Character(c) => match c.to_ascii_lowercase().as_str() {
572 "f" if kmod.super_key() => self.fit_all(comp),874 "f" if kmod.super_key() => self.fit_all(comp),
573 "f" | "." if !kmod.super_key() => self.fit_all(comp),875 "f" | "." if !kmod.super_key() => self.fit_all(comp),
876 "n" if !kmod.super_key() && self.modal.is_none() => {
877 self.toggle_normalized(comp);
878 }
879 "v" if !kmod.super_key() && self.modal.is_none() => {
880 self.open_popup(PopupKind::HandleType);
881 }
882 "t" if !kmod.super_key() && self.modal.is_none() => {
883 self.open_popup(PopupKind::Easing);
884 }
574 "g" if !kmod.super_key() && self.modal.is_none() => {885 "g" if !kmod.super_key() && self.modal.is_none() => {
575 self.begin_modal(comp, TransformMode::Grab);886 self.begin_modal(comp, history.is_some(), TransformMode::Grab);
576 }887 }
577 "r" if !kmod.super_key() && self.modal.is_none() => {888 "r" if !kmod.super_key() && self.modal.is_none() => {
578 self.begin_modal(comp, TransformMode::Rotate);889 self.begin_modal(comp, history.is_some(), TransformMode::Rotate);
579 }890 }
580 "s" if !kmod.super_key() && self.modal.is_none() => {891 "s" if !kmod.super_key() && self.modal.is_none() => {
581 self.begin_modal(comp, TransformMode::Scale);892 self.begin_modal(comp, history.is_some(), TransformMode::Scale);
582 }893 }
583 "x" if self.modal.is_some() => {894 "x" if self.modal.is_some() => {
584 if let Some(m) = &mut self.modal {895 if let Some(m) = &mut self.modal {
...@@ -590,7 +901,7 @@ impl SplineView {...@@ -590,7 +901,7 @@ impl SplineView {
590 }901 }
591 "x" if self.modal.is_none() && !kmod.super_key() => {902 "x" if self.modal.is_none() && !kmod.super_key() => {
592 // Blender `X` deletes selected keys when not in a modal transform!903 // Blender `X` deletes selected keys when not in a modal transform!
593 if self.delete_selected(comp) {904 if self.delete_selected(comp, history) {
594 actions.push(SplineAction::SplineEdited);905 actions.push(SplineAction::SplineEdited);
595 }906 }
596 }907 }
...@@ -605,21 +916,29 @@ impl SplineView {...@@ -605,21 +916,29 @@ impl SplineView {
605 "i" if !kmod.super_key() && self.modal.is_none() => {916 "i" if !kmod.super_key() && self.modal.is_none() => {
606 // Blender `I` inserts keyframe at current integer frame on all visible channels917 // Blender `I` inserts keyframe at current integer frame on all visible channels
607 let t = current_frame.round();918 let t = current_frame.round();
608 let mut inserted = false;919 let will_insert = self.channels.iter().any(|(_, sname)| {
609 for (_, sname) in &self.channels {920 !self.hidden_splines.contains(sname)
610 if self.hidden_splines.contains(sname) {921 && comp
611 continue;922 .splines
923 .get(sname)
924 .is_some_and(|sp| !sp.keyframes.iter().any(|k| (k.time - t).abs() < 0.5))
925 });
926 if will_insert {
927 if let Some(h) = history.as_deref_mut() {
928 h.push_snapshot(comp, "Insert Keyframe");
612 }929 }
613 if let Some(sp) = comp.splines.get_mut(sname) {930 for (_, sname) in &self.channels {
614 if !sp.keyframes.iter().any(|k| (k.time - t).abs() < 0.5) {931 if self.hidden_splines.contains(sname) {
615 let v = sp.eval(t);932 continue;
616 sp.keyframes.push(Keyframe::new(t, v));933 }
617 sp.sort();934 if let Some(sp) = comp.splines.get_mut(sname) {
618 inserted = true;935 if !sp.keyframes.iter().any(|k| (k.time - t).abs() < 0.5) {
936 let v = sp.eval(t);
937 sp.keyframes.push(Keyframe::new(t, v));
938 sp.sort();
939 }
619 }940 }
620 }941 }
621 }
622 if inserted {
623 comp.revision += 1;942 comp.revision += 1;
624 actions.push(SplineAction::SplineEdited);943 actions.push(SplineAction::SplineEdited);
625 }944 }
...@@ -645,33 +964,27 @@ impl SplineView {...@@ -645,33 +964,27 @@ impl SplineView {
645 }964 }
646 }965 }
647 "l" => {966 "l" => {
648 for pref in &self.selected {967 let by_spline = self.selected_keys_by_spline(comp);
649 if let Some(sp) = comp.splines.get_mut(&pref.spline) {968 if !by_spline.is_empty() {
650 if let Some(kf) = sp.keyframes.get_mut(pref.key_idx) {969 if let Some(h) = history.as_deref_mut() {
651 kf.flags.linear = !kf.flags.linear;970 h.push_snapshot(comp, "Toggle Linear");
652 if kf.flags.linear {
653 kf.lh = None;
654 kf.rh = None;
655 } else {
656 ensure_handles(kf);
657 }
658 }
659 }971 }
660 }972 for (sname, idxs) in by_spline {
661 if !self.selected.is_empty() {973 if let Some(sp) = comp.splines.get_mut(&sname) {
662 comp.revision += 1;974 for idx in idxs {
663 actions.push(SplineAction::SplineEdited);975 if let Some(kf) = sp.keyframes.get_mut(idx) {
664 }976 kf.flags.linear = !kf.flags.linear;
665 }977 if kf.flags.linear {
666 "t" => {978 kf.lh = None;
667 for pref in &self.selected {979 kf.rh = None;
668 if let Some(sp) = comp.splines.get_mut(&pref.spline) {980 kf.handle_mode = HandleMode::Vector;
669 if let Some(kf) = sp.keyframes.get_mut(pref.key_idx) {981 } else {
670 kf.flags.step_in = !kf.flags.step_in;982 ensure_handles(kf);
983 }
984 }
985 }
671 }986 }
672 }987 }
673 }
674 if !self.selected.is_empty() {
675 comp.revision += 1;988 comp.revision += 1;
676 actions.push(SplineAction::SplineEdited);989 actions.push(SplineAction::SplineEdited);
677 }990 }
...@@ -682,17 +995,30 @@ impl SplineView {...@@ -682,17 +995,30 @@ impl SplineView {
682 }995 }
683 }996 }
684997
685 fn delete_selected(&mut self, comp: &mut Comp) -> bool {998 fn delete_selected(&mut self, comp: &mut Comp, history: Option<&mut CompHistory>) -> bool {
686 let mut by_spline: HashMap<String, Vec<usize>> = HashMap::new();999 let mut by_spline: HashMap<String, Vec<usize>> = HashMap::new();
687 for pref in &self.selected {1000 for pref in &self.selected {
688 if pref.part == HandlePart::Key {1001 if pref.part == HandlePart::Key {
689 by_spline.entry(pref.spline.clone()).or_default().push(pref.key_idx);1002 by_spline.entry(pref.spline.clone()).or_default().push(pref.key_idx);
690 }1003 }
691 }1004 }
692 let mut changed = false;1005 for idxs in by_spline.values_mut() {
693 for (sname, mut idxs) in by_spline {
694 idxs.sort_unstable();1006 idxs.sort_unstable();
695 idxs.dedup();1007 idxs.dedup();
1008 }
1009 let can_delete = by_spline.iter().any(|(sname, idxs)| {
1010 comp.splines
1011 .get(sname)
1012 .is_some_and(|sp| sp.keyframes.len() > 1 && idxs.iter().any(|&i| i < sp.keyframes.len()))
1013 });
1014 if !can_delete {
1015 return false;
1016 }
1017 if let Some(h) = history {
1018 h.push_snapshot(comp, "Delete Keyframes");
1019 }
1020 let mut changed = false;
1021 for (sname, idxs) in by_spline {
696 if let Some(sp) = comp.splines.get_mut(&sname) {1022 if let Some(sp) = comp.splines.get_mut(&sname) {
697 for &idx in idxs.iter().rev() {1023 for &idx in idxs.iter().rev() {
698 if sp.keyframes.len() > 1 && idx < sp.keyframes.len() {1024 if sp.keyframes.len() > 1 && idx < sp.keyframes.len() {
...@@ -717,6 +1043,20 @@ impl SplineView {...@@ -717,6 +1043,20 @@ impl SplineView {
717 rect: [f32; 4],1043 rect: [f32; 4],
718 pointer_window: [f32; 2],1044 pointer_window: [f32; 2],
719 modifiers: ModifiersState,1045 modifiers: ModifiersState,
1046 ) -> Vec<SplineAction> {
1047 self.input_with_history(comp, None, current_frame, event, rect, pointer_window, modifiers)
1048 }
1049
1050 #[allow(clippy::too_many_arguments)]
1051 pub fn input_with_history(
1052 &mut self,
1053 comp: &mut Comp,
1054 mut history: Option<&mut CompHistory>,
1055 current_frame: f64,
1056 event: ui::Event,
1057 rect: [f32; 4],
1058 pointer_window: [f32; 2],
1059 modifiers: ModifiersState,
720 ) -> Vec<SplineAction> {1060 ) -> Vec<SplineAction> {
721 let mut actions = Vec::new();1061 let mut actions = Vec::new();
722 self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]];1062 self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]];
...@@ -725,6 +1065,9 @@ impl SplineView {...@@ -725,6 +1065,9 @@ impl SplineView {
725 match event {1065 match event {
726 ui::Event::PointerMoved(p) => {1066 ui::Event::PointerMoved(p) => {
727 self.pointer_local = [p[0] - rect[0], p[1] - rect[1]];1067 self.pointer_local = [p[0] - rect[0], p[1] - rect[1]];
1068 if self.popup.is_some() {
1069 return actions;
1070 }
728 if self.scrubbing {1071 if self.scrubbing {
729 let t = self.local_to_data(self.pointer_local)[0].round();1072 let t = self.local_to_data(self.pointer_local)[0].round();
730 actions.push(SplineAction::ScrubFrame(t));1073 actions.push(SplineAction::ScrubFrame(t));
...@@ -742,7 +1085,7 @@ impl SplineView {...@@ -742,7 +1085,7 @@ impl SplineView {
742 } else if let Some((start_l, ref mut dragging)) = self.lmb_drag_point {1085 } else if let Some((start_l, ref mut dragging)) = self.lmb_drag_point {
743 if !*dragging && hypot2(self.pointer_local, start_l) > 3.5 {1086 if !*dragging && hypot2(self.pointer_local, start_l) > 3.5 {
744 *dragging = true;1087 *dragging = true;
745 self.begin_modal(comp, TransformMode::Grab);1088 self.begin_modal(comp, history.is_some(), TransformMode::Grab);
746 if self.apply_modal(comp, modifiers.shift_key()) {1089 if self.apply_modal(comp, modifiers.shift_key()) {
747 actions.push(SplineAction::SplineEdited);1090 actions.push(SplineAction::SplineEdited);
748 }1091 }
...@@ -754,6 +1097,37 @@ impl SplineView {...@@ -754,6 +1097,37 @@ impl SplineView {
754 }1097 }
755 }1098 }
756 ui::Event::Button { button, pressed, .. } => {1099 ui::Event::Button { button, pressed, .. } => {
1100 if let Some(popup) = self.popup.clone() {
1101 if pressed {
1102 if button == MouseButton::Left {
1103 if let Some(idx) = self.popup_item_at(&popup, self.pointer_local) {
1104 self.popup = None;
1105 match popup.kind {
1106 PopupKind::HandleType => {
1107 if let Some(&(mode, _)) = HANDLE_MENU_ITEMS.get(idx) {
1108 if self.apply_selected_handle_mode(comp, history, mode) {
1109 actions.push(SplineAction::SplineEdited);
1110 }
1111 }
1112 }
1113 PopupKind::Easing => {
1114 if let Some(&(preset, _)) = EASING_MENU_ITEMS.get(idx) {
1115 if self.apply_selected_easing(comp, history, preset) {
1116 actions.push(SplineAction::SplineEdited);
1117 }
1118 }
1119 }
1120 }
1121 } else {
1122 self.popup = None;
1123 }
1124 } else {
1125 self.popup = None;
1126 }
1127 }
1128 return actions;
1129 }
1130
757 if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) {1131 if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) {
758 if pressed {1132 if pressed {
759 self.panning = Some((self.pointer_local, self.t_range, self.v_range));1133 self.panning = Some((self.pointer_local, self.t_range, self.v_range));
...@@ -769,9 +1143,11 @@ impl SplineView {...@@ -769,9 +1143,11 @@ impl SplineView {
769 } else if button == MouseButton::Left {1143 } else if button == MouseButton::Left {
770 if pressed {1144 if pressed {
771 if self.modal.is_some() {1145 if self.modal.is_some() {
772 self.confirm_modal(comp);1146 self.confirm_modal(comp, history);
773 self.lmb_drag_point = None;1147 self.lmb_drag_point = None;
774 actions.push(SplineAction::SplineEdited);1148 actions.push(SplineAction::SplineEdited);
1149 } else if point_in_rect(self.pointer_local, self.normalize_pill_rect()) {
1150 self.toggle_normalized(comp);
775 } else if self.pointer_local[0] < SIDEBAR_W {1151 } else if self.pointer_local[0] < SIDEBAR_W {
776 let row = ((self.pointer_local[1] - RULER_H - 6.0) / 22.0).floor() as isize;1152 let row = ((self.pointer_local[1] - RULER_H - 6.0) / 22.0).floor() as isize;
777 if row >= 0 && (row as usize) < self.channels.len() {1153 if row >= 0 && (row as usize) < self.channels.len() {
...@@ -796,7 +1172,9 @@ impl SplineView {...@@ -796,7 +1172,9 @@ impl SplineView {
796 for pref in &self.selected {1172 for pref in &self.selected {
797 if let Some(sp) = comp.splines.get_mut(&pref.spline) {1173 if let Some(sp) = comp.splines.get_mut(&pref.spline) {
798 if let Some(kf) = sp.keyframes.get_mut(pref.key_idx) {1174 if let Some(kf) = sp.keyframes.get_mut(pref.key_idx) {
799 ensure_handles(kf);1175 if !kf.flags.linear {
1176 ensure_handles(kf);
1177 }
800 }1178 }
801 }1179 }
802 }1180 }
...@@ -815,7 +1193,7 @@ impl SplineView {...@@ -815,7 +1193,7 @@ impl SplineView {
815 self.scrubbing = false;1193 self.scrubbing = false;
816 if let Some((_start, dragging)) = self.lmb_drag_point.take() {1194 if let Some((_start, dragging)) = self.lmb_drag_point.take() {
817 if dragging && self.modal.is_some() {1195 if dragging && self.modal.is_some() {
818 self.confirm_modal(comp);1196 self.confirm_modal(comp, history.as_deref_mut());
819 actions.push(SplineAction::SplineEdited);1197 actions.push(SplineAction::SplineEdited);
820 }1198 }
821 }1199 }
...@@ -830,8 +1208,9 @@ impl SplineView {...@@ -830,8 +1208,9 @@ impl SplineView {
830 continue;1208 continue;
831 }1209 }
832 let Some(sp) = comp.splines.get(sname) else { continue };1210 let Some(sp) = comp.splines.get(sname) else { continue };
1211 let bounds = self.spline_bounds(comp, sname);
833 for (ki, kf) in sp.keyframes.iter().enumerate() {1212 for (ki, kf) in sp.keyframes.iter().enumerate() {
834 let p = self.data_to_local(kf.time, kf.value);1213 let p = self.spline_to_local(kf.time, kf.value, bounds);
835 if p[0] >= x0 && p[0] <= x1 && p[1] >= y0 && p[1] <= y1 {1214 if p[0] >= x0 && p[0] <= x1 && p[1] >= y0 && p[1] <= y1 {
836 self.selected.insert(PointRef {1215 self.selected.insert(PointRef {
837 spline: sname.clone(),1216 spline: sname.clone(),
...@@ -868,10 +1247,10 @@ impl SplineView {...@@ -868,10 +1247,10 @@ impl SplineView {
868 self.zoom_at(f, f, self.pointer_local);1247 self.zoom_at(f, f, self.pointer_local);
869 }1248 }
870 ui::Event::KeyInput { physical, key, state: ElementState::Pressed, repeat: false, modifiers: kmod, .. } => {1249 ui::Event::KeyInput { physical, key, state: ElementState::Pressed, repeat: false, modifiers: kmod, .. } => {
871 self.handle_key(comp, current_frame, Some(physical), &key, kmod, &mut actions);1250 self.handle_key(comp, history, current_frame, Some(physical), &key, kmod, &mut actions);
872 }1251 }
873 ui::Event::Key { key, modifiers: kmod, .. } => {1252 ui::Event::Key { key, modifiers: kmod, .. } => {
874 self.handle_key(comp, current_frame, None, &key, kmod, &mut actions);1253 self.handle_key(comp, history, current_frame, None, &key, kmod, &mut actions);
875 }1254 }
876 _ => {}1255 _ => {}
877 }1256 }
...@@ -893,6 +1272,28 @@ impl SplineView {...@@ -893,6 +1272,28 @@ impl SplineView {
893 }1272 }
894 }1273 }
8951274
1275 fn hover_readout_string(&self, comp: &Comp) -> Option<String> {
1276 let hov = self.hovered.as_ref()?;
1277 let sp = comp.splines.get(&hov.spline)?;
1278 let kf = sp.keyframes.get(hov.key_idx)?;
1279 let (t, v) = match hov.part {
1280 HandlePart::Key => (kf.time, kf.value),
1281 HandlePart::LeftHandle => {
1282 let h = kf.lh?;
1283 (h[0], h[1])
1284 }
1285 HandlePart::RightHandle => {
1286 let h = kf.rh?;
1287 (h[0], h[1])
1288 }
1289 };
1290 if (t - t.round()).abs() < 1e-3 {
1291 Some(format!("(f{}, {:.3})", t.round() as i64, v))
1292 } else {
1293 Some(format!("(f{t:.1}, {v:.3})"))
1294 }
1295 }
1296
896 pub fn prepare_labels(&mut self, comp: &Comp) {1297 pub fn prepare_labels(&mut self, comp: &Comp) {
897 let font_sm = text::Font {1298 let font_sm = text::Font {
898 families: Arc::from([text::Family::Mono]),1299 families: Arc::from([text::Family::Mono]),
...@@ -929,8 +1330,26 @@ impl SplineView {...@@ -929,8 +1330,26 @@ impl SplineView {
929 .map(|id| format!("Splines: {}", comp.node(id).name))1330 .map(|id| format!("Splines: {}", comp.node(id).name))
930 .unwrap_or_else(|| "Splines (Comp)".to_owned());1331 .unwrap_or_else(|| "Splines (Comp)".to_owned());
931 self.text_cache.entry(header.clone()).or_insert_with(|| make_layout(&header, &font_ch));1332 self.text_cache.entry(header.clone()).or_insert_with(|| make_layout(&header, &font_ch));
1333 self.text_cache
1334 .entry("Norm".to_owned())
1335 .or_insert_with(|| make_layout("Norm", &font_sm));
1336 for popup_hdr in ["Set Handle Type", "Set Interpolation"] {
1337 self.text_cache
1338 .entry(popup_hdr.to_owned())
1339 .or_insert_with(|| make_layout(popup_hdr, &font_sm));
1340 }
1341 for &(_, item_lbl) in HANDLE_MENU_ITEMS {
1342 self.text_cache
1343 .entry(item_lbl.to_owned())
1344 .or_insert_with(|| make_layout(item_lbl, &font_ch));
1345 }
1346 for &(_, item_lbl) in EASING_MENU_ITEMS {
1347 self.text_cache
1348 .entry(item_lbl.to_owned())
1349 .or_insert_with(|| make_layout(item_lbl, &font_ch));
1350 }
932 for hud in [1351 for hud in [
933 "Drag or G/R/S X/Y: Axis I: Insert X/Del: Delete L: Linear T: Step Cmd+F / Num.: Fit",1352 "Drag or G/R/S X/Y: Axis V: Handle T: Easing N: Norm I: Insert X/Del: Delete L: Linear F: Fit",
934 "GRAB [LMB/Enter confirm, RMB/Esc cancel, X: Frame / Y: Value]",1353 "GRAB [LMB/Enter confirm, RMB/Esc cancel, X: Frame / Y: Value]",
935 "ROTATE [LMB/Enter confirm, RMB/Esc cancel]",1354 "ROTATE [LMB/Enter confirm, RMB/Esc cancel]",
936 "SCALE [LMB/Enter confirm, RMB/Esc cancel, X: Time / Y: Value]",1355 "SCALE [LMB/Enter confirm, RMB/Esc cancel, X: Time / Y: Value]",
...@@ -938,6 +1357,14 @@ impl SplineView {...@@ -938,6 +1357,14 @@ impl SplineView {
938 self.text_cache.entry(hud.to_owned()).or_insert_with(|| make_layout(hud, &font_sm));1357 self.text_cache.entry(hud.to_owned()).or_insert_with(|| make_layout(hud, &font_sm));
939 }1358 }
9401359
1360 if let Some(readout) = self.hover_readout_string(comp) {
1361 if readout != self.last_hover_readout || !self.text_cache.contains_key("__hover_readout") {
1362 self.text_cache
1363 .insert("__hover_readout".to_owned(), make_layout(&readout, &font_sm));
1364 self.last_hover_readout = readout;
1365 }
1366 }
1367
941 let t_step = nice_step((self.t_range[1] - self.t_range[0]) / 8.0);1368 let t_step = nice_step((self.t_range[1] - self.t_range[0]) / 8.0);
942 let t_start = (self.t_range[0] / t_step).floor() as i64;1369 let t_start = (self.t_range[0] / t_step).floor() as i64;
943 let t_end = (self.t_range[1] / t_step).ceil() as i64;1370 let t_end = (self.t_range[1] / t_step).ceil() as i64;
...@@ -974,11 +1401,40 @@ impl SplineView {...@@ -974,11 +1401,40 @@ impl SplineView {
974 out.push(Primitive::Text {1401 out.push(Primitive::Text {
975 text: hl as &dyn Glyphs,1402 text: hl as &dyn Glyphs,
976 origin: [10.0, 5.0],1403 origin: [10.0, 5.0],
977 clip: Some([8.0, 0.0, SIDEBAR_W - 8.0, RULER_H]),1404 clip: Some([8.0, 0.0, SIDEBAR_W - 70.0, RULER_H]),
978 ink: self.palette.text,1405 ink: self.palette.text,
979 });1406 });
980 }1407 }
9811408
1409 // Clickable "Normalize" pill in the sidebar header
1410 let pill = self.normalize_pill_rect();
1411 let pill_fill = if self.normalized {
1412 [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.28]
1413 } else {
1414 [self.palette.bg[0], self.palette.bg[1], self.palette.bg[2], 0.9]
1415 };
1416 let pill_stroke = if self.normalized { self.palette.accent } else { self.palette.rule };
1417 out.push(Primitive::RoundedRect {
1418 rect: pill,
1419 radius: 4.0,
1420 stroke: None,
1421 color: pill_fill,
1422 });
1423 out.push(Primitive::RoundedRect {
1424 rect: pill,
1425 radius: 4.0,
1426 stroke: Some(1.0),
1427 color: pill_stroke,
1428 });
1429 if let Some(nl) = self.text_cache.get("Norm") {
1430 out.push(Primitive::Text {
1431 text: nl as &dyn Glyphs,
1432 origin: [pill[0] + 7.0, pill[1] + 3.0],
1433 clip: Some(pill),
1434 ink: if self.normalized { self.palette.text } else { self.palette.text_dim },
1435 });
1436 }
1437
982 for (i, (label, sname)) in self.channels.iter().enumerate() {1438 for (i, (label, sname)) in self.channels.iter().enumerate() {
983 let y = RULER_H + 6.0 + i as f32 * 22.0;1439 let y = RULER_H + 6.0 + i as f32 * 22.0;
984 if y > h - 24.0 {1440 if y > h - 24.0 {
...@@ -1086,6 +1542,7 @@ impl SplineView {...@@ -1086,6 +1542,7 @@ impl SplineView {
1086 continue;1542 continue;
1087 }1543 }
1088 let Some(sp) = comp.splines.get(sname) else { continue };1544 let Some(sp) = comp.splines.get(sname) else { continue };
1545 let bounds = self.spline_bounds(comp, sname);
1089 let col = spline_color(comp, sname, ci);1546 let col = spline_color(comp, sname, ci);
1090 let any_sel = self.selected.iter().any(|p| p.spline == *sname);1547 let any_sel = self.selected.iter().any(|p| p.spline == *sname);
1091 let curve_w = if any_sel { 2.4 } else { 1.7 };1548 let curve_w = if any_sel { 2.4 } else { 1.7 };
...@@ -1096,7 +1553,7 @@ impl SplineView {...@@ -1096,7 +1553,7 @@ impl SplineView {
1096 };1553 };
10971554
1098 if let Some(first) = sp.keyframes.first() {1555 if let Some(first) = sp.keyframes.first() {
1099 let p = self.data_to_local(first.time, first.value);1556 let p = self.spline_to_local(first.time, first.value, bounds);
1100 if p[0] > plot[0] {1557 if p[0] > plot[0] {
1101 out.push(Primitive::Segment {1558 out.push(Primitive::Segment {
1102 from: [plot[0], p[1]],1559 from: [plot[0], p[1]],
...@@ -1107,7 +1564,7 @@ impl SplineView {...@@ -1107,7 +1564,7 @@ impl SplineView {
1107 }1564 }
1108 }1565 }
1109 if let Some(last) = sp.keyframes.last() {1566 if let Some(last) = sp.keyframes.last() {
1110 let p = self.data_to_local(last.time, last.value);1567 let p = self.spline_to_local(last.time, last.value, bounds);
1111 if p[0] < plot[2] {1568 if p[0] < plot[2] {
1112 out.push(Primitive::Segment {1569 out.push(Primitive::Segment {
1113 from: p,1570 from: p,
...@@ -1125,25 +1582,32 @@ impl SplineView {...@@ -1125,25 +1582,32 @@ impl SplineView {
1125 if k1.time < self.t_range[0] || k0.time > self.t_range[1] {1582 if k1.time < self.t_range[0] || k0.time > self.t_range[1] {
1126 continue;1583 continue;
1127 }1584 }
1128 if k1.flags.step_in {1585 if k0.flags.step_out {
1129 let a = self.data_to_local(k0.time, k0.value);1586 // Vertical step at k0.time, then horizontal to k1.time (matches model::spline::eval_segment).
1130 let m = self.data_to_local(k1.time, k0.value);1587 let a = self.spline_to_local(k0.time, k0.value, bounds);
1131 let b = self.data_to_local(k1.time, k1.value);1588 let m = self.spline_to_local(k0.time, k1.value, bounds);
1589 let b = self.spline_to_local(k1.time, k1.value, bounds);
1590 out.push(Primitive::Segment { from: a, to: m, width: curve_w, color: curve_col });
1591 out.push(Primitive::Segment { from: m, to: b, width: curve_w, color: curve_col });
1592 } else if k1.flags.step_in {
1593 let a = self.spline_to_local(k0.time, k0.value, bounds);
1594 let m = self.spline_to_local(k1.time, k0.value, bounds);
1595 let b = self.spline_to_local(k1.time, k1.value, bounds);
1132 out.push(Primitive::Segment { from: a, to: m, width: curve_w, color: curve_col });1596 out.push(Primitive::Segment { from: a, to: m, width: curve_w, color: curve_col });
1133 out.push(Primitive::Segment { from: m, to: b, width: curve_w, color: curve_col });1597 out.push(Primitive::Segment { from: m, to: b, width: curve_w, color: curve_col });
1134 } else if dense || (k1.flags.linear && k0.rh.is_none() && k1.lh.is_none()) {1598 } else if dense || (k1.flags.linear && k0.rh.is_none() && k1.lh.is_none()) {
1135 let a = self.data_to_local(k0.time, k0.value);1599 let a = self.spline_to_local(k0.time, k0.value, bounds);
1136 let b = self.data_to_local(k1.time, k1.value);1600 let b = self.spline_to_local(k1.time, k1.value, bounds);
1137 out.push(Primitive::Segment { from: a, to: b, width: curve_w, color: curve_col });1601 out.push(Primitive::Segment { from: a, to: b, width: curve_w, color: curve_col });
1138 } else {1602 } else {
1139 let [p0, p1, p2, p3] = segment_control_points(k0, k1);1603 let [p0, p1, p2, p3] = segment_control_points(k0, k1);
1140 const SUBS: usize = 20;1604 const SUBS: usize = 20;
1141 let mut prev = self.data_to_local(p0[0], p0[1]);1605 let mut prev = self.spline_to_local(p0[0], p0[1], bounds);
1142 for s in 1..=SUBS {1606 for s in 1..=SUBS {
1143 let u = s as f64 / SUBS as f64;1607 let u = s as f64 / SUBS as f64;
1144 let t = cubic(p0[0], p1[0], p2[0], p3[0], u);1608 let t = cubic(p0[0], p1[0], p2[0], p3[0], u);
1145 let v = cubic(p0[1], p1[1], p2[1], p3[1], u);1609 let v = cubic(p0[1], p1[1], p2[1], p3[1], u);
1146 let cur = self.data_to_local(t, v);1610 let cur = self.spline_to_local(t, v, bounds);
1147 out.push(Primitive::Segment { from: prev, to: cur, width: curve_w, color: curve_col });1611 out.push(Primitive::Segment { from: prev, to: cur, width: curve_w, color: curve_col });
1148 prev = cur;1612 prev = cur;
1149 }1613 }
...@@ -1155,7 +1619,7 @@ impl SplineView {...@@ -1155,7 +1619,7 @@ impl SplineView {
1155 if kf.time < self.t_range[0] - 5.0 || kf.time > self.t_range[1] + 5.0 {1619 if kf.time < self.t_range[0] - 5.0 || kf.time > self.t_range[1] + 5.0 {
1156 continue;1620 continue;
1157 }1621 }
1158 let kp = self.data_to_local(kf.time, kf.value);1622 let kp = self.spline_to_local(kf.time, kf.value, bounds);
1159 let kref = PointRef { spline: sname.clone(), key_idx: ki, part: HandlePart::Key };1623 let kref = PointRef { spline: sname.clone(), key_idx: ki, part: HandlePart::Key };
1160 let ksel = self.selected.contains(&kref);1624 let ksel = self.selected.contains(&kref);
1161 let khov = self.hovered.as_ref() == Some(&kref);1625 let khov = self.hovered.as_ref() == Some(&kref);
...@@ -1164,7 +1628,7 @@ impl SplineView {...@@ -1164,7 +1628,7 @@ impl SplineView {
1164 if show_handles {1628 if show_handles {
1165 for (part, hopt) in [(HandlePart::LeftHandle, kf.lh), (HandlePart::RightHandle, kf.rh)] {1629 for (part, hopt) in [(HandlePart::LeftHandle, kf.lh), (HandlePart::RightHandle, kf.rh)] {
1166 if let Some(h) = hopt {1630 if let Some(h) = hopt {
1167 let hp = self.data_to_local(h[0], h[1]);1631 let hp = self.spline_to_local(h[0], h[1], bounds);
1168 let href = PointRef { spline: sname.clone(), key_idx: ki, part };1632 let href = PointRef { spline: sname.clone(), key_idx: ki, part };
1169 let hsel = self.selected.contains(&href);1633 let hsel = self.selected.contains(&href);
1170 let hhov = self.hovered.as_ref() == Some(&href);1634 let hhov = self.hovered.as_ref() == Some(&href);
...@@ -1202,6 +1666,46 @@ impl SplineView {...@@ -1202,6 +1666,46 @@ impl SplineView {
1202 }1666 }
1203 }1667 }
12041668
1669 // Hover readout pill showing real `(f<t>, <val>)` for the hovered keyframe/handle
1670 if let (Some(hov), Some(rl)) = (self.hovered.as_ref(), self.text_cache.get("__hover_readout")) {
1671 if let Some(sp) = comp.splines.get(&hov.spline) {
1672 if let Some(kf) = sp.keyframes.get(hov.key_idx) {
1673 let bounds = self.spline_bounds(comp, &hov.spline);
1674 let pt = match hov.part {
1675 HandlePart::Key => Some([kf.time, kf.value]),
1676 HandlePart::LeftHandle => kf.lh,
1677 HandlePart::RightHandle => kf.rh,
1678 };
1679 if let Some([t, v]) = pt {
1680 let p = self.spline_to_local(t, v, bounds);
1681 let pill_w = (self.last_hover_readout.len() as f32 * 6.4 + 12.0).max(76.0);
1682 let pill_h = 18.0;
1683 let rx = (p[0] + 10.0).clamp(plot[0] + 4.0, (plot[2] - pill_w - 4.0).max(plot[0] + 4.0));
1684 let ry = (p[1] - pill_h - 8.0).clamp(plot[1] + 4.0, (plot[3] - pill_h - 4.0).max(plot[1] + 4.0));
1685 let r = [rx, ry, rx + pill_w, ry + pill_h];
1686 out.push(Primitive::RoundedRect {
1687 rect: r,
1688 radius: 4.0,
1689 stroke: None,
1690 color: [0.08, 0.09, 0.11, 0.94],
1691 });
1692 out.push(Primitive::RoundedRect {
1693 rect: r,
1694 radius: 4.0,
1695 stroke: Some(1.0),
1696 color: self.palette.accent,
1697 });
1698 out.push(Primitive::Text {
1699 text: rl as &dyn Glyphs,
1700 origin: [rx + 6.0, ry + 3.0],
1701 clip: Some(r),
1702 ink: self.palette.text,
1703 });
1704 }
1705 }
1706 }
1707 }
1708
1205 if let Some(bs) = &self.box_select {1709 if let Some(bs) = &self.box_select {
1206 let x0 = bs.start_local[0].min(bs.cur_local[0]);1710 let x0 = bs.start_local[0].min(bs.cur_local[0]);
1207 let x1 = bs.start_local[0].max(bs.cur_local[0]);1711 let x1 = bs.start_local[0].max(bs.cur_local[0]);
...@@ -1227,7 +1731,7 @@ impl SplineView {...@@ -1227,7 +1731,7 @@ impl SplineView {
1227 Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X: Frame / Y: Value]",1731 Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X: Frame / Y: Value]",
1228 Some(TransformMode::Rotate) => "ROTATE [LMB/Enter confirm, RMB/Esc cancel]",1732 Some(TransformMode::Rotate) => "ROTATE [LMB/Enter confirm, RMB/Esc cancel]",
1229 Some(TransformMode::Scale) => "SCALE [LMB/Enter confirm, RMB/Esc cancel, X: Time / Y: Value]",1733 Some(TransformMode::Scale) => "SCALE [LMB/Enter confirm, RMB/Esc cancel, X: Time / Y: Value]",
1230 None => "Drag or G/R/S X/Y: Axis I: Insert X/Del: Delete L: Linear T: Step Cmd+F / Num.: Fit",1734 None => "Drag or G/R/S X/Y: Axis V: Handle T: Easing N: Norm I: Insert X/Del: Delete L: Linear F: Fit",
1231 };1735 };
1232 out.push(Primitive::Rect { rect: [SIDEBAR_W, h - 24.0, w, h], color: self.palette.ruler });1736 out.push(Primitive::Rect { rect: [SIDEBAR_W, h - 24.0, w, h], color: self.palette.ruler });
1233 if let Some(hl) = self.text_cache.get(hud_key) {1737 if let Some(hl) = self.text_cache.get(hud_key) {
...@@ -1239,10 +1743,74 @@ impl SplineView {...@@ -1239,10 +1743,74 @@ impl SplineView {
1239 });1743 });
1240 }1744 }
12411745
1746 // Floating Blender-style popup menu (`V` Handle Type / `T` Interpolation & Easing)
1747 if let Some(popup) = &self.popup {
1748 let pr = self.popup_rect(popup);
1749 let hov_idx = self.popup_item_at(popup, self.pointer_local);
1750 out.push(Primitive::RoundedRect {
1751 rect: pr,
1752 radius: 6.0,
1753 stroke: None,
1754 color: [0.09, 0.10, 0.12, 0.96],
1755 });
1756 out.push(Primitive::RoundedRect {
1757 rect: pr,
1758 radius: 6.0,
1759 stroke: Some(1.0),
1760 color: self.palette.rule,
1761 });
1762 let hdr_text = match popup.kind {
1763 PopupKind::HandleType => "Set Handle Type",
1764 PopupKind::Easing => "Set Interpolation",
1765 };
1766 if let Some(hl) = self.text_cache.get(hdr_text) {
1767 out.push(Primitive::Text {
1768 text: hl as &dyn Glyphs,
1769 origin: [pr[0] + 10.0, pr[1] + 5.0],
1770 clip: Some([pr[0], pr[1], pr[2], pr[1] + POPUP_HEADER_H]),
1771 ink: self.palette.text_dim,
1772 });
1773 }
1774 out.push(Primitive::Segment {
1775 from: [pr[0] + 6.0, pr[1] + POPUP_HEADER_H - 1.0],
1776 to: [pr[2] - 6.0, pr[1] + POPUP_HEADER_H - 1.0],
1777 width: 1.0,
1778 color: self.palette.rule,
1779 });
1780 let labels: Vec<&'static str> = match popup.kind {
1781 PopupKind::HandleType => HANDLE_MENU_ITEMS.iter().map(|&(_, l)| l).collect(),
1782 PopupKind::Easing => EASING_MENU_ITEMS.iter().map(|&(_, l)| l).collect(),
1783 };
1784 for (idx, lbl) in labels.into_iter().enumerate() {
1785 let ry0 = pr[1] + POPUP_HEADER_H + idx as f32 * POPUP_ROW_H;
1786 let ry1 = ry0 + POPUP_ROW_H;
1787 if hov_idx == Some(idx) {
1788 out.push(Primitive::RoundedRect {
1789 rect: [pr[0] + 4.0, ry0 + 1.0, pr[2] - 4.0, ry1 - 1.0],
1790 radius: 4.0,
1791 stroke: None,
1792 color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.25],
1793 });
1794 }
1795 if let Some(il) = self.text_cache.get(lbl) {
1796 out.push(Primitive::Text {
1797 text: il as &dyn Glyphs,
1798 origin: [pr[0] + 10.0, ry0 + 4.0],
1799 clip: Some([pr[0] + 4.0, ry0, pr[2] - 4.0, ry1]),
1800 ink: self.palette.text,
1801 });
1802 }
1803 }
1804 }
1805
1242 out1806 out
1243 }1807 }
1244}1808}
12451809
1810fn point_in_rect(p: [f32; 2], r: [f32; 4]) -> bool {
1811 p[0] >= r[0] && p[0] <= r[2] && p[1] >= r[1] && p[1] <= r[3]
1812}
1813
1246fn ensure_handles(kf: &mut Keyframe) {1814fn ensure_handles(kf: &mut Keyframe) {
1247 if kf.lh.is_none() {1815 if kf.lh.is_none() {
1248 kf.lh = Some([kf.time - 8.0, kf.value]);1816 kf.lh = Some([kf.time - 8.0, kf.value]);
...@@ -1280,3 +1848,208 @@ fn nice_step(raw: f64) -> f64 {...@@ -1280,3 +1848,208 @@ fn nice_step(raw: f64) -> f64 {
1280fn hypot2(a: [f32; 2], b: [f32; 2]) -> f32 {1848fn hypot2(a: [f32; 2], b: [f32; 2]) -> f32 {
1281 ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)).sqrt()1849 ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)).sqrt()
1282}1850}
1851
1852#[cfg(test)]
1853mod tests {
1854 use super::*;
1855 use model::BezierSpline;
1856
1857 fn test_comp() -> Comp {
1858 let mut comp = Comp::from_fusion_str("Composition {}").expect("empty comp");
1859 comp.splines.insert(
1860 "Gain".to_owned(),
1861 BezierSpline {
1862 name: "Gain".to_owned(),
1863 color: [220, 140, 255],
1864 keyframes: vec![
1865 Keyframe::new(0.0, 10.0),
1866 Keyframe::new(50.0, 110.0),
1867 Keyframe::new(100.0, 10.0),
1868 ],
1869 },
1870 );
1871 comp
1872 }
1873
1874 fn key_event(ch: &str) -> ui::Event {
1875 ui::Event::Key {
1876 key: Key::Character(ch.into()),
1877 modifiers: ModifiersState::empty(),
1878 text: None,
1879 }
1880 }
1881
1882 #[test]
1883 fn normalize_toggle_via_key_and_pill_and_drag() {
1884 let mut comp = test_comp();
1885 let mut view = SplineView::new(&ui::Theme::dark());
1886 view.resize([800.0, 360.0]);
1887 view.set_target_node(&comp, None);
1888 let rect = [0.0, 0.0, 800.0, 360.0];
1889
1890 assert!(!view.normalized);
1891 view.input(&mut comp, 0.0, key_event("n"), rect, [300.0, 150.0], ModifiersState::empty());
1892 assert!(view.normalized);
1893 assert_eq!(view.v_range, [-0.12, 1.12]);
1894
1895 // Clicking Normalize pill toggles it back off
1896 let pill = view.normalize_pill_rect();
1897 let pill_center = [0.5 * (pill[0] + pill[2]), 0.5 * (pill[1] + pill[3])];
1898 view.input(
1899 &mut comp,
1900 0.0,
1901 ui::Event::Button {
1902 button: MouseButton::Left,
1903 pressed: true,
1904 at: std::time::Instant::now(),
1905 },
1906 rect,
1907 pill_center,
1908 ModifiersState::empty(),
1909 );
1910 assert!(!view.normalized);
1911
1912 // Re-enable normalize and grab keyframe 0 upward by half the plot height (real span = 100)
1913 view.toggle_normalized(&comp);
1914 view.selected.insert(PointRef {
1915 spline: "Gain".to_owned(),
1916 key_idx: 0,
1917 part: HandlePart::Key,
1918 });
1919 let p0 = view.spline_to_local(0.0, 10.0, (10.0, 110.0));
1920 let p1 = view.spline_to_local(0.0, 60.0, (10.0, 110.0)); // +50 in real value (+0.5 normalized)
1921 view.input(&mut comp, 0.0, key_event("g"), rect, p0, ModifiersState::empty());
1922 view.input(
1923 &mut comp,
1924 0.0,
1925 ui::Event::PointerMoved(p1),
1926 rect,
1927 p1,
1928 ModifiersState::empty(),
1929 );
1930 view.input(
1931 &mut comp,
1932 0.0,
1933 ui::Event::Key {
1934 key: Key::Named(NamedKey::Enter),
1935 modifiers: ModifiersState::empty(),
1936 text: None,
1937 },
1938 rect,
1939 p1,
1940 ModifiersState::empty(),
1941 );
1942 assert!((comp.splines["Gain"].keyframes[0].value - 60.0).abs() < 0.5);
1943 }
1944
1945 #[test]
1946 fn v_and_t_popups_apply_with_history_undo() {
1947 let mut comp = test_comp();
1948 let mut history = CompHistory::new();
1949 let mut view = SplineView::new(&ui::Theme::dark());
1950 view.resize([800.0, 360.0]);
1951 view.set_target_node(&comp, None);
1952 let rect = [0.0, 0.0, 800.0, 360.0];
1953
1954 view.selected.insert(PointRef {
1955 spline: "Gain".to_owned(),
1956 key_idx: 1,
1957 part: HandlePart::Key,
1958 });
1959
1960 // Open V popup and press '3' (Auto)
1961 view.input_with_history(&mut comp, Some(&mut history), 0.0, key_event("v"), rect, [300.0, 150.0], ModifiersState::empty());
1962 assert!(view.popup.is_some());
1963 let acts = view.input_with_history(&mut comp, Some(&mut history), 0.0, key_event("3"), rect, [300.0, 150.0], ModifiersState::empty());
1964 assert!(view.popup.is_none());
1965 assert_eq!(acts.len(), 1);
1966 assert_eq!(comp.splines["Gain"].keyframes[1].handle_mode, HandleMode::Auto);
1967 assert_eq!(history.undo_len(), 1);
1968
1969 // Open T popup and press '8' (Knife Ease) on key 0
1970 view.selected.clear();
1971 view.selected.insert(PointRef {
1972 spline: "Gain".to_owned(),
1973 key_idx: 0,
1974 part: HandlePart::Key,
1975 });
1976 view.input_with_history(&mut comp, Some(&mut history), 0.0, key_event("t"), rect, [300.0, 150.0], ModifiersState::empty());
1977 let acts = view.input_with_history(&mut comp, Some(&mut history), 0.0, key_event("8"), rect, [300.0, 150.0], ModifiersState::empty());
1978 assert_eq!(acts.len(), 1);
1979 assert_eq!(history.undo_len(), 2);
1980 let rh = comp.splines["Gain"].keyframes[0].rh.unwrap();
1981 assert!((rh[0] - 11.0).abs() < 1e-6); // 0 + 50 * 0.22 = 11.0
1982 assert!((rh[1] - 110.0).abs() < 1e-6); // 10 + 100 * 1.0 = 110.0
1983
1984 // Undo restores pre-KnifeEase state
1985 assert!(history.undo(&mut comp));
1986 assert!(comp.splines["Gain"].keyframes[0].flags.linear);
1987 }
1988
1989 #[test]
1990 fn aligned_handle_drag_mirrors_opposite_and_history_cancel_vs_confirm() {
1991 let mut comp = test_comp();
1992 let mut history = CompHistory::new();
1993 // Set key 1 to Auto handles first
1994 apply_handle_mode(comp.splines.get_mut("Gain").unwrap(), 1, HandleMode::Auto);
1995 let orig_rh = comp.splines["Gain"].keyframes[1].rh.unwrap();
1996 let orig_rh_len = ((orig_rh[0] - 50.0).powi(2) + (orig_rh[1] - 110.0).powi(2)).sqrt();
1997
1998 let mut view = SplineView::new(&ui::Theme::dark());
1999 view.resize([800.0, 360.0]);
2000 view.set_target_node(&comp, None);
2001 let rect = [0.0, 0.0, 800.0, 360.0];
2002
2003 view.selected.insert(PointRef {
2004 spline: "Gain".to_owned(),
2005 key_idx: 1,
2006 part: HandlePart::LeftHandle,
2007 });
2008 let lh = comp.splines["Gain"].keyframes[1].lh.unwrap();
2009 let p0 = view.data_to_local(lh[0], lh[1]);
2010 let p1 = [p0[0], p0[1] + 40.0]; // drag left handle down
2011
2012 // Grab and cancel -> no history entry pushed
2013 view.input_with_history(&mut comp, Some(&mut history), 0.0, key_event("g"), rect, p0, ModifiersState::empty());
2014 view.input_with_history(&mut comp, Some(&mut history), 0.0, ui::Event::PointerMoved(p1), rect, p1, ModifiersState::empty());
2015 assert_eq!(comp.splines["Gain"].keyframes[1].handle_mode, HandleMode::Aligned);
2016 let new_rh = comp.splines["Gain"].keyframes[1].rh.unwrap();
2017 let new_rh_len = ((new_rh[0] - 50.0).powi(2) + (new_rh[1] - 110.0).powi(2)).sqrt();
2018 assert!((new_rh_len - orig_rh_len).abs() < 1e-6);
2019 assert!(new_rh[1] > 110.0, "right handle should counter-rotate upward when left goes down");
2020
2021 view.input_with_history(
2022 &mut comp,
2023 Some(&mut history),
2024 0.0,
2025 ui::Event::Key {
2026 key: Key::Named(NamedKey::Escape),
2027 modifiers: ModifiersState::empty(),
2028 text: None,
2029 },
2030 rect,
2031 p1,
2032 ModifiersState::empty(),
2033 );
2034 assert_eq!(history.undo_len(), 0);
2035 assert_eq!(comp.splines["Gain"].keyframes[1].rh.unwrap(), orig_rh);
2036
2037 // Grab and confirm -> pushes 1 undo snapshot
2038 view.input_with_history(&mut comp, Some(&mut history), 0.0, key_event("g"), rect, p0, ModifiersState::empty());
2039 view.input_with_history(&mut comp, Some(&mut history), 0.0, ui::Event::PointerMoved(p1), rect, p1, ModifiersState::empty());
2040 view.input_with_history(
2041 &mut comp,
2042 Some(&mut history),
2043 0.0,
2044 ui::Event::Key {
2045 key: Key::Named(NamedKey::Enter),
2046 modifiers: ModifiersState::empty(),
2047 text: None,
2048 },
2049 rect,
2050 p1,
2051 ModifiersState::empty(),
2052 );
2053 assert_eq!(history.undo_len(), 1);
2054 }
2055}
crates/spline/src/presets.rs created+499
...@@ -0,0 +1,499 @@
1//! Pure Bezier handle-mode, easing-preset, and curve-normalization helpers for the Spline Editor.
2
3use crate::HandlePart;
4use model::{BezierSpline, HandleMode, Keyframe};
5use std::collections::HashSet;
6
7/// Built-in interpolation and easing presets exposed in the `T` popup menu.
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum EasingPreset {
10 Linear,
11 Smooth,
12 StepIn,
13 StepOut,
14 EaseInOut,
15 EaseOut,
16 EaseIn,
17 KnifeEase,
18}
19
20impl EasingPreset {
21 /// Ordered list of all presets for menu display and `1`-`8` hotkey indexing.
22 pub const ALL: &'static [EasingPreset] = &[
23 EasingPreset::Linear,
24 EasingPreset::Smooth,
25 EasingPreset::StepIn,
26 EasingPreset::StepOut,
27 EasingPreset::EaseInOut,
28 EasingPreset::EaseOut,
29 EasingPreset::EaseIn,
30 EasingPreset::KnifeEase,
31 ];
32
33 pub fn label(self) -> &'static str {
34 match self {
35 Self::Linear => "Linear",
36 Self::Smooth => "Smooth",
37 Self::StepIn => "Step In",
38 Self::StepOut => "Step Out",
39 Self::EaseInOut => "Ease In-Out",
40 Self::EaseOut => "Ease Out",
41 Self::EaseIn => "Ease In",
42 Self::KnifeEase => "Knife Ease",
43 }
44 }
45
46 /// Returns normalized cubic-bezier `(x1, y1, x2, y2)` parameters for easing presets.
47 pub fn bezier_params(self) -> Option<(f64, f64, f64, f64)> {
48 match self {
49 Self::EaseInOut => Some((0.42, 0.0, 0.58, 1.0)),
50 Self::EaseOut => Some((0.0, 0.0, 0.58, 1.0)),
51 Self::EaseIn => Some((0.42, 0.0, 1.0, 1.0)),
52 Self::KnifeEase => Some((0.22, 1.0, 0.36, 1.0)),
53 Self::Linear | Self::Smooth | Self::StepIn | Self::StepOut => None,
54 }
55 }
56}
57
58/// Applies an [`EasingPreset`] to the selected keyframes of `spline`.
59/// Returns `true` if any keyframe was modified.
60pub fn apply_easing_preset(
61 spline: &mut BezierSpline,
62 selected_indices: &[usize],
63 preset: EasingPreset,
64) -> bool {
65 let len = spline.keyframes.len();
66 if len == 0 {
67 return false;
68 }
69
70 let mut valid: Vec<usize> = selected_indices
71 .iter()
72 .copied()
73 .filter(|&i| i < len)
74 .collect();
75 valid.sort_unstable();
76 valid.dedup();
77 if valid.is_empty() {
78 return false;
79 }
80
81 match preset {
82 EasingPreset::Linear => {
83 for &idx in &valid {
84 let kf = &mut spline.keyframes[idx];
85 kf.flags.linear = true;
86 kf.flags.step_in = false;
87 kf.flags.step_out = false;
88 kf.lh = None;
89 kf.rh = None;
90 kf.handle_mode = HandleMode::Vector;
91 }
92 true
93 }
94 EasingPreset::Smooth => {
95 for &idx in &valid {
96 spline.keyframes[idx].flags.step_in = false;
97 spline.keyframes[idx].flags.step_out = false;
98 apply_handle_mode(spline, idx, HandleMode::Auto);
99 }
100 true
101 }
102 EasingPreset::StepIn => {
103 for &idx in &valid {
104 let kf = &mut spline.keyframes[idx];
105 kf.flags.step_in = true;
106 kf.flags.step_out = false;
107 kf.flags.linear = false;
108 }
109 true
110 }
111 EasingPreset::StepOut => {
112 for &idx in &valid {
113 let kf = &mut spline.keyframes[idx];
114 kf.flags.step_out = true;
115 kf.flags.step_in = false;
116 kf.flags.linear = false;
117 }
118 true
119 }
120 EasingPreset::EaseInOut
121 | EasingPreset::EaseOut
122 | EasingPreset::EaseIn
123 | EasingPreset::KnifeEase => {
124 if len < 2 {
125 return false;
126 }
127 let (x1, y1, x2, y2) = preset.bezier_params().expect("bezier preset has params");
128 let selected_set: HashSet<usize> = valid.iter().copied().collect();
129
130 let mut seg_starts: Vec<usize> = (0..(len - 1))
131 .filter(|seg| selected_set.contains(seg))
132 .collect();
133 if seg_starts.is_empty() && selected_set.contains(&(len - 1)) {
134 seg_starts.push(len - 2);
135 }
136 if seg_starts.is_empty() {
137 return false;
138 }
139
140 for seg in seg_starts {
141 let t0 = spline.keyframes[seg].time;
142 let v0 = spline.keyframes[seg].value;
143 let t1 = spline.keyframes[seg + 1].time;
144 let v1 = spline.keyframes[seg + 1].value;
145 let dt = t1 - t0;
146 let dv = v1 - v0;
147
148 let k0 = &mut spline.keyframes[seg];
149 k0.rh = Some([t0 + dt * x1, v0 + dv * y1]);
150 k0.flags.linear = false;
151 k0.flags.step_in = false;
152 k0.flags.step_out = false;
153 k0.handle_mode = HandleMode::Free;
154
155 let k1 = &mut spline.keyframes[seg + 1];
156 k1.lh = Some([t0 + dt * x2, v0 + dv * y2]);
157 k1.flags.linear = false;
158 k1.flags.step_in = false;
159 k1.flags.step_out = false;
160 k1.handle_mode = HandleMode::Free;
161 }
162 true
163 }
164 }
165}
166
167/// Applies a Blender-style [`HandleMode`] to `spline.keyframes[key_idx]`.
168pub fn apply_handle_mode(spline: &mut BezierSpline, key_idx: usize, mode: HandleMode) {
169 let len = spline.keyframes.len();
170 if key_idx >= len {
171 return;
172 }
173
174 let t = spline.keyframes[key_idx].time;
175 let v = spline.keyframes[key_idx].value;
176 let prev = if key_idx > 0 {
177 Some((spline.keyframes[key_idx - 1].time, spline.keyframes[key_idx - 1].value))
178 } else {
179 None
180 };
181 let next = if key_idx + 1 < len {
182 Some((spline.keyframes[key_idx + 1].time, spline.keyframes[key_idx + 1].value))
183 } else {
184 None
185 };
186
187 let dt_l = prev.map(|(pt, _)| ((t - pt) / 3.0).max(0.01)).unwrap_or(8.0);
188 let dt_r = next.map(|(nt, _)| ((nt - t) / 3.0).max(0.01)).unwrap_or(8.0);
189
190 let kf = &mut spline.keyframes[key_idx];
191 kf.flags.linear = false;
192
193 match mode {
194 HandleMode::Free => {
195 if kf.lh.is_none() {
196 kf.lh = Some([t - dt_l, v]);
197 }
198 if kf.rh.is_none() {
199 kf.rh = Some([t + dt_r, v]);
200 }
201 kf.handle_mode = HandleMode::Free;
202 }
203 HandleMode::Aligned => {
204 let lh = kf.lh.unwrap_or([t - dt_l, v]);
205 let rh = kf.rh.unwrap_or([t + dt_r, v]);
206 let vl = [lh[0] - t, lh[1] - v];
207 let vr = [rh[0] - t, rh[1] - v];
208 let len_l = (vl[0] * vl[0] + vl[1] * vl[1]).sqrt().max(0.01);
209 let len_r = (vr[0] * vr[0] + vr[1] * vr[1]).sqrt().max(0.01);
210
211 // Average rightward tangent direction from both handles.
212 let mut dx = vr[0] - vl[0];
213 let mut dy = vr[1] - vl[1];
214 let dlen = (dx * dx + dy * dy).sqrt();
215 if dlen < 1e-9 {
216 dx = 1.0;
217 dy = 0.0;
218 } else {
219 dx /= dlen;
220 dy /= dlen;
221 if dx < 0.0 {
222 dx = -dx;
223 dy = -dy;
224 }
225 }
226
227 kf.lh = Some([(t - dx * len_l).min(t - 0.01), v - dy * len_l]);
228 kf.rh = Some([(t + dx * len_r).max(t + 0.01), v + dy * len_r]);
229 kf.handle_mode = HandleMode::Aligned;
230 }
231 HandleMode::Vector => {
232 kf.lh = Some(match prev {
233 Some((pt, pv)) => [t + (pt - t) / 3.0, v + (pv - v) / 3.0],
234 None => [t - dt_l, v],
235 });
236 kf.rh = Some(match next {
237 Some((nt, nv)) => [t + (nt - t) / 3.0, v + (nv - v) / 3.0],
238 None => [t + dt_r, v],
239 });
240 kf.handle_mode = HandleMode::Vector;
241 }
242 HandleMode::Auto => {
243 let slope = match (prev, next) {
244 (Some((pt, pv)), Some((nt, nv))) => {
245 let dv_l = v - pv;
246 let dv_r = nv - v;
247 if dv_l * dv_r <= 0.0 {
248 // Local extremum (peak, trough, or plateau): flat tangent prevents overshoot.
249 0.0
250 } else {
251 let span = (nt - pt).max(1e-6);
252 let m_cr = (nv - pv) / span;
253 let max_l = (dv_l / dt_l).abs();
254 let max_r = (dv_r / dt_r).abs();
255 m_cr.signum() * m_cr.abs().min(max_l).min(max_r)
256 }
257 }
258 _ => 0.0,
259 };
260 kf.lh = Some([t - dt_l, v - slope * dt_l]);
261 kf.rh = Some([t + dt_r, v + slope * dt_r]);
262 kf.handle_mode = HandleMode::Auto;
263 }
264 }
265}
266
267/// For `HandleMode::Aligned`: counter-rotates the opposite handle so both handles remain
268/// collinear through `(kf.time, kf.value)` while preserving the opposite handle's length.
269pub fn enforce_aligned_handle(kf: &mut Keyframe, moved_part: HandlePart) {
270 match moved_part {
271 HandlePart::LeftHandle => {
272 let (Some(lh), Some(rh)) = (kf.lh, kf.rh) else { return };
273 let dx = lh[0] - kf.time;
274 let dy = lh[1] - kf.value;
275 let moved_len = (dx * dx + dy * dy).sqrt();
276 if moved_len < 1e-9 {
277 return;
278 }
279 let odx = rh[0] - kf.time;
280 let ody = rh[1] - kf.value;
281 let opp_len = (odx * odx + ody * ody).sqrt();
282 let ux = -dx / moved_len;
283 let uy = -dy / moved_len;
284 kf.rh = Some([kf.time + ux * opp_len, kf.value + uy * opp_len]);
285 }
286 HandlePart::RightHandle => {
287 let (Some(lh), Some(rh)) = (kf.lh, kf.rh) else { return };
288 let dx = rh[0] - kf.time;
289 let dy = rh[1] - kf.value;
290 let moved_len = (dx * dx + dy * dy).sqrt();
291 if moved_len < 1e-9 {
292 return;
293 }
294 let odx = lh[0] - kf.time;
295 let ody = lh[1] - kf.value;
296 let opp_len = (odx * odx + ody * ody).sqrt();
297 let ux = -dx / moved_len;
298 let uy = -dy / moved_len;
299 kf.lh = Some([kf.time + ux * opp_len, kf.value + uy * opp_len]);
300 }
301 HandlePart::Key => {}
302 }
303}
304
305/// Computes `(min_v, max_v)` over a spline's keyframes and handles, with a safe
306/// `(v - 0.5, v + 0.5)` fallback when the curve is constant.
307pub fn compute_curve_bounds(spline: &BezierSpline) -> (f64, f64) {
308 if spline.keyframes.is_empty() {
309 return (0.0, 1.0);
310 }
311 let mut min_v = f64::INFINITY;
312 let mut max_v = f64::NEG_INFINITY;
313 for kf in &spline.keyframes {
314 min_v = min_v.min(kf.value);
315 max_v = max_v.max(kf.value);
316 if let Some(lh) = kf.lh {
317 min_v = min_v.min(lh[1]);
318 max_v = max_v.max(lh[1]);
319 }
320 if let Some(rh) = kf.rh {
321 min_v = min_v.min(rh[1]);
322 max_v = max_v.max(rh[1]);
323 }
324 }
325 if !min_v.is_finite() || !max_v.is_finite() {
326 return (0.0, 1.0);
327 }
328 if (max_v - min_v).abs() < 1e-9 {
329 let v = spline.keyframes[0].value;
330 return (v - 0.5, v + 0.5);
331 }
332 (min_v, max_v)
333}
334
335/// Maps a real spline value to display space (`[0.0, 1.0]` when `normalized`, raw `val` otherwise).
336#[inline]
337pub fn value_to_display(val: f64, bounds: (f64, f64), normalized: bool) -> f64 {
338 if !normalized {
339 return val;
340 }
341 let span = (bounds.1 - bounds.0).max(1e-9);
342 (val - bounds.0) / span
343}
344
345/// Inverse of [`value_to_display`]: maps a display-space value back to real spline value space.
346#[inline]
347pub fn display_to_value(disp: f64, bounds: (f64, f64), normalized: bool) -> f64 {
348 if !normalized {
349 return disp;
350 }
351 let span = (bounds.1 - bounds.0).max(1e-9);
352 bounds.0 + disp * span
353}
354
355#[cfg(test)]
356mod tests {
357 use super::*;
358
359 fn make_spline(points: &[(f64, f64)]) -> BezierSpline {
360 BezierSpline {
361 name: "TestSpline".to_owned(),
362 color: [200, 140, 255],
363 keyframes: points.iter().map(|&(t, v)| Keyframe::new(t, v)).collect(),
364 }
365 }
366
367 #[test]
368 fn normalize_roundtrip_and_constant_curve() {
369 let sp = make_spline(&[(0.0, 10.0), (50.0, 110.0)]);
370 let bounds = compute_curve_bounds(&sp);
371 assert_eq!(bounds, (10.0, 110.0));
372 assert!((value_to_display(10.0, bounds, true) - 0.0).abs() < 1e-12);
373 assert!((value_to_display(60.0, bounds, true) - 0.5).abs() < 1e-12);
374 assert!((value_to_display(110.0, bounds, true) - 1.0).abs() < 1e-12);
375 for v in [10.0, 35.5, 60.0, 110.0, -20.0] {
376 let d = value_to_display(v, bounds, true);
377 let back = display_to_value(d, bounds, true);
378 assert!((back - v).abs() < 1e-9);
379 assert!((value_to_display(v, bounds, false) - v).abs() < 1e-12);
380 assert!((display_to_value(v, bounds, false) - v).abs() < 1e-12);
381 }
382
383 // Constant curve fallback: (v - 0.5, v + 0.5)
384 let flat = make_spline(&[(0.0, 42.0), (100.0, 42.0)]);
385 let fb = compute_curve_bounds(&flat);
386 assert_eq!(fb, (41.5, 42.5));
387 let d = value_to_display(42.0, fb, true);
388 assert!((d - 0.5).abs() < 1e-12);
389 assert!((display_to_value(d, fb, true) - 42.0).abs() < 1e-12);
390 }
391
392 #[test]
393 fn enforce_aligned_handle_preserves_collinearity_and_length() {
394 let mut kf = Keyframe::new(50.0, 10.0);
395 kf.handle_mode = HandleMode::Aligned;
396 kf.lh = Some([40.0, 10.0]);
397 kf.rh = Some([65.0, 10.0]); // initial right length = 15.0
398
399 // Move left handle to (44.0, 2.0) -> vector (-6.0, -8.0), len = 10.0
400 kf.lh = Some([44.0, 2.0]);
401 enforce_aligned_handle(&mut kf, HandlePart::LeftHandle);
402
403 let rh = kf.rh.unwrap();
404 let rdx = rh[0] - kf.time;
405 let rdy = rh[1] - kf.value;
406 let rlen = (rdx * rdx + rdy * rdy).sqrt();
407 assert!((rlen - 15.0).abs() < 1e-9, "expected opposite len 15.0, got {rlen}");
408 // Collinearity: cross product of lh_vec (-6, -8) and rh_vec (rdx, rdy) == 0
409 let cross = (-6.0 * rdy - (-8.0) * rdx).abs();
410 assert!(cross < 1e-9, "handles not collinear: cross={cross}");
411 assert!(rdx > 0.0 && rdy > 0.0, "right handle should point opposite to left");
412
413 // Now move right handle and verify left handle preserves its length (10.0)
414 kf.rh = Some([62.0, 5.0]); // vector (12, -5), len = 13
415 enforce_aligned_handle(&mut kf, HandlePart::RightHandle);
416 let lh = kf.lh.unwrap();
417 let ldx = lh[0] - kf.time;
418 let ldy = lh[1] - kf.value;
419 let llen = (ldx * ldx + ldy * ldy).sqrt();
420 assert!((llen - 10.0).abs() < 1e-9, "expected left len 10.0, got {llen}");
421 let cross2 = (12.0 * ldy - (-5.0) * ldx).abs();
422 assert!(cross2 < 1e-9, "handles not collinear after right move: cross={cross2}");
423 assert!(ldx < 0.0 && ldy > 0.0);
424 }
425
426 #[test]
427 fn apply_handle_mode_auto_and_vector() {
428 // Peak at middle keyframe (0,0) -> (30,10) -> (60,0): Auto should be flat (slope = 0)
429 let mut peak = make_spline(&[(0.0, 0.0), (30.0, 10.0), (60.0, 0.0)]);
430 apply_handle_mode(&mut peak, 1, HandleMode::Auto);
431 let k = &peak.keyframes[1];
432 assert_eq!(k.handle_mode, HandleMode::Auto);
433 assert!(!k.flags.linear);
434 assert!((k.lh.unwrap()[1] - 10.0).abs() < 1e-9, "peak lh should be flat");
435 assert!((k.rh.unwrap()[1] - 10.0).abs() < 1e-9, "peak rh should be flat");
436
437 // Monotonic (0,0) -> (30,30) -> (60,60): Auto should have positive slope = 1.0
438 let mut mono = make_spline(&[(0.0, 0.0), (30.0, 30.0), (60.0, 60.0)]);
439 apply_handle_mode(&mut mono, 1, HandleMode::Auto);
440 let km = &mono.keyframes[1];
441 assert_eq!(km.handle_mode, HandleMode::Auto);
442 let lh = km.lh.unwrap();
443 let rh = km.rh.unwrap();
444 assert!((lh[0] - 20.0).abs() < 1e-9 && (lh[1] - 20.0).abs() < 1e-9);
445 assert!((rh[0] - 40.0).abs() < 1e-9 && (rh[1] - 40.0).abs() < 1e-9);
446
447 // Vector mode aims 1/3 toward neighbors
448 let mut vec_sp = make_spline(&[(0.0, 0.0), (30.0, 12.0), (90.0, 0.0)]);
449 apply_handle_mode(&mut vec_sp, 1, HandleMode::Vector);
450 let kv = &vec_sp.keyframes[1];
451 assert_eq!(kv.handle_mode, HandleMode::Vector);
452 assert!(!kv.flags.linear);
453 let vlh = kv.lh.unwrap();
454 let vrh = kv.rh.unwrap();
455 assert!((vlh[0] - 20.0).abs() < 1e-9 && (vlh[1] - 8.0).abs() < 1e-9);
456 assert!((vrh[0] - 50.0).abs() < 1e-9 && (vrh[1] - 8.0).abs() < 1e-9);
457 }
458
459 #[test]
460 fn apply_easing_presets_knife_linear_step_smooth() {
461 // KnifeEase (0.22, 1.0, 0.36, 1.0) on segment (10, 0) -> (110, 10)
462 let mut sp = make_spline(&[(10.0, 0.0), (110.0, 10.0)]);
463 assert!(apply_easing_preset(&mut sp, &[0], EasingPreset::KnifeEase));
464 let k0 = &sp.keyframes[0];
465 let k1 = &sp.keyframes[1];
466 assert_eq!(k0.handle_mode, HandleMode::Free);
467 assert_eq!(k1.handle_mode, HandleMode::Free);
468 assert!(!k0.flags.linear && !k0.flags.step_in && !k0.flags.step_out);
469 assert!(!k1.flags.linear && !k1.flags.step_in && !k1.flags.step_out);
470 let rh = k0.rh.unwrap();
471 let lh = k1.lh.unwrap();
472 assert!((rh[0] - 32.0).abs() < 1e-9 && (rh[1] - 10.0).abs() < 1e-9);
473 assert!((lh[0] - 46.0).abs() < 1e-9 && (lh[1] - 10.0).abs() < 1e-9);
474
475 // Selecting only the last key applies to incoming segment
476 let mut sp_last = make_spline(&[(0.0, 0.0), (100.0, 1.0)]);
477 assert!(apply_easing_preset(&mut sp_last, &[1], EasingPreset::KnifeEase));
478 assert!((sp_last.keyframes[0].rh.unwrap()[0] - 22.0).abs() < 1e-9);
479 assert!((sp_last.keyframes[1].lh.unwrap()[0] - 36.0).abs() < 1e-9);
480
481 // Linear clears handles and sets linear flag
482 assert!(apply_easing_preset(&mut sp, &[0, 1], EasingPreset::Linear));
483 assert!(sp.keyframes[0].flags.linear && sp.keyframes[0].rh.is_none());
484 assert!(sp.keyframes[1].flags.linear && sp.keyframes[1].lh.is_none());
485
486 // StepIn & StepOut
487 assert!(apply_easing_preset(&mut sp, &[1], EasingPreset::StepIn));
488 assert!(sp.keyframes[1].flags.step_in && !sp.keyframes[1].flags.step_out);
489 assert!(apply_easing_preset(&mut sp, &[0], EasingPreset::StepOut));
490 assert!(sp.keyframes[0].flags.step_out && !sp.keyframes[0].flags.step_in);
491
492 // Smooth computes Auto handles and clears step/linear flags
493 assert!(apply_easing_preset(&mut sp, &[0, 1], EasingPreset::Smooth));
494 assert!(!sp.keyframes[0].flags.step_out && !sp.keyframes[0].flags.linear);
495 assert!(!sp.keyframes[1].flags.step_in && !sp.keyframes[1].flags.linear);
496 assert_eq!(sp.keyframes[0].handle_mode, HandleMode::Auto);
497 assert!(sp.keyframes[0].rh.is_some() && sp.keyframes[1].lh.is_some());
498 }
499}
crates/studio/src/keyframes.rs created+1032
...@@ -0,0 +1,1032 @@
1//! Docked Keyframes dope-sheet pane: animated node/channel tracks, audio waveform track,
2//! green RAM cache bar, and interactive drag-to-retime keyframes with `CompHistory` undo.
3
4use draw::{Glyphs, Primitive};
5use model::{Comp, CompHistory, Keyframe, NodeId};
6use std::collections::{HashMap, HashSet};
7use std::sync::Arc;
8use winit::event::{ElementState, MouseButton};
9use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey};
10
11const RULER_H: f32 = 26.0;
12const AUDIO_ROW_H: f32 = 24.0;
13const ROW_H: f32 = 22.0;
14const SIDEBAR_W: f32 = 188.0;
15const FOOTER_H: f32 = 22.0;
16
17#[derive(Clone, Debug, PartialEq, Eq, Hash)]
18pub struct DopeKeyRef {
19 pub spline: String,
20 pub key_idx: usize,
21}
22
23#[derive(Clone, Debug)]
24pub enum KeyframesAction {
25 ScrubFrame(f64),
26 SelectNode(NodeId),
27 KeyframesEdited,
28}
29
30#[derive(Clone, Debug)]
31pub enum TrackRow {
32 NodeHeader {
33 node_id: NodeId,
34 label: String,
35 splines: Vec<String>,
36 },
37 Channel {
38 node_id: NodeId,
39 label: String,
40 spline: String,
41 color: [f32; 4],
42 },
43}
44
45#[derive(Clone, Debug)]
46struct RetimeDrag {
47 start_frame: f64,
48 saved_splines: HashMap<String, Vec<Keyframe>>,
49 pre_edit_comp: Comp,
50 moved: bool,
51}
52
53#[derive(Clone, Copy, Debug)]
54pub struct KeyframesPalette {
55 pub bg: [f32; 4],
56 pub sidebar: [f32; 4],
57 pub ruler: [f32; 4],
58 pub rule: [f32; 4],
59 pub grid: [f32; 4],
60 pub row_alt: [f32; 4],
61 pub text: [f32; 4],
62 pub text_dim: [f32; 4],
63 pub accent: [f32; 4],
64}
65
66impl KeyframesPalette {
67 pub fn from_ui(theme: &ui::Theme) -> Self {
68 let b = theme.base;
69 let lift = |c: [f32; 4], d: f32| {
70 [(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]
71 };
72 Self {
73 bg: b,
74 sidebar: lift(b, 0.012),
75 ruler: lift(b, 0.018),
76 rule: theme.rule,
77 grid: lift(b, 0.022),
78 row_alt: lift(b, 0.010),
79 text: theme.text,
80 text_dim: theme.text_dim,
81 accent: theme.accent,
82 }
83 }
84}
85
86pub struct KeyframesView {
87 pub t_range: [f64; 2],
88 pub size: [f32; 2],
89 pub scroll_y: f32,
90 pub selected_only: bool,
91 pub selected_keys: HashSet<DopeKeyRef>,
92 pub cached_ranges: Vec<(i64, i64)>,
93 pub audio_peaks: Vec<f32>,
94 pub audio_range: [i64; 2],
95 pub palette: KeyframesPalette,
96 rows: Vec<TrackRow>,
97 collapsed_nodes: HashSet<NodeId>,
98 hovered_key: Option<DopeKeyRef>,
99 retime_drag: Option<RetimeDrag>,
100 box_select: Option<([f32; 2], [f32; 2])>,
101 panning: Option<([f32; 2], [f64; 2], f32)>,
102 scrubbing: bool,
103 pointer_local: [f32; 2],
104 fitted: bool,
105 text_cache: HashMap<String, text::Layout>,
106}
107
108impl KeyframesView {
109 pub fn new(theme: &ui::Theme) -> Self {
110 Self {
111 t_range: [0.0, 200.0],
112 size: [800.0, 320.0],
113 scroll_y: 0.0,
114 selected_only: false,
115 selected_keys: HashSet::new(),
116 cached_ranges: Vec::new(),
117 audio_peaks: Vec::new(),
118 audio_range: [0, 0],
119 palette: KeyframesPalette::from_ui(theme),
120 rows: Vec::new(),
121 collapsed_nodes: HashSet::new(),
122 hovered_key: None,
123 retime_drag: None,
124 box_select: None,
125 panning: None,
126 scrubbing: false,
127 pointer_local: [0.0, 0.0],
128 fitted: false,
129 text_cache: HashMap::new(),
130 }
131 }
132
133 pub fn background(&self) -> [f32; 4] {
134 self.palette.bg
135 }
136
137 pub fn resize(&mut self, size: [f32; 2]) {
138 self.size = [size[0].max(1.0), size[1].max(1.0)];
139 }
140
141 pub fn fit_comp(&mut self, comp: &Comp) {
142 let r0 = comp.render_range[0] as f64;
143 let r1 = comp.render_range[1].max(comp.render_range[0] + 10) as f64;
144 let pad = ((r1 - r0) * 0.04).max(4.0);
145 self.t_range = [r0 - pad, r1 + pad];
146 self.fitted = true;
147 }
148
149 pub fn sync_tracks(&mut self, comp: &Comp, selected_node: Option<NodeId>) {
150 if !self.fitted {
151 self.fit_comp(comp);
152 }
153 self.rows = build_tracks(comp, selected_node, self.selected_only, &self.collapsed_nodes);
154 }
155
156 fn tracks_top(&self) -> f32 {
157 RULER_H + if self.audio_peaks.is_empty() { 0.0 } else { AUDIO_ROW_H }
158 }
159
160 fn plot_rect(&self) -> [f32; 4] {
161 [
162 SIDEBAR_W,
163 RULER_H,
164 self.size[0].max(SIDEBAR_W + 40.0),
165 (self.size[1] - FOOTER_H).max(RULER_H + 40.0),
166 ]
167 }
168
169 fn time_to_x(&self, t: f64) -> f32 {
170 let r = self.plot_rect();
171 let frac = (t - self.t_range[0]) / (self.t_range[1] - self.t_range[0]).max(1e-6);
172 r[0] + frac as f32 * (r[2] - r[0])
173 }
174
175 fn x_to_time(&self, x: f32) -> f64 {
176 let r = self.plot_rect();
177 let frac = f64::from((x - r[0]) / (r[2] - r[0]).max(1.0));
178 self.t_range[0] + frac * (self.t_range[1] - self.t_range[0])
179 }
180
181 fn row_y(&self, row_idx: usize) -> f32 {
182 self.tracks_top() + row_idx as f32 * ROW_H - self.scroll_y
183 }
184
185 fn hit_key(&self, comp: &Comp, local: [f32; 2]) -> Option<DopeKeyRef> {
186 let top = self.tracks_top();
187 if local[0] < SIDEBAR_W || local[1] < top || local[1] > self.size[1] - FOOTER_H {
188 return None;
189 }
190 let mut best: Option<(f32, DopeKeyRef)> = None;
191 for (ri, row) in self.rows.iter().enumerate() {
192 let cy = self.row_y(ri) + ROW_H * 0.5;
193 if (local[1] - cy).abs() > ROW_H * 0.52 {
194 continue;
195 }
196 if let TrackRow::Channel { spline, .. } = row {
197 let Some(sp) = comp.splines.get(spline) else { continue };
198 for (ki, kf) in sp.keyframes.iter().enumerate() {
199 let kx = self.time_to_x(kf.time);
200 let d = ((local[0] - kx).powi(2) + (local[1] - cy).powi(2)).sqrt();
201 if d <= 9.5 && best.as_ref().is_none_or(|(bd, _)| d < *bd) {
202 best = Some((d, DopeKeyRef { spline: spline.clone(), key_idx: ki }));
203 }
204 }
205 }
206 }
207 best.map(|(_, k)| k)
208 }
209
210 fn hit_span_bar(&self, comp: &Comp, local: [f32; 2]) -> Option<(String, Vec<usize>)> {
211 let top = self.tracks_top();
212 if local[0] < SIDEBAR_W || local[1] < top || local[1] > self.size[1] - FOOTER_H {
213 return None;
214 }
215 for (ri, row) in self.rows.iter().enumerate() {
216 let y0 = self.row_y(ri);
217 if local[1] < y0 || local[1] >= y0 + ROW_H {
218 continue;
219 }
220 if let TrackRow::Channel { spline, .. } = row {
221 let Some(sp) = comp.splines.get(spline) else { continue };
222 if sp.keyframes.len() >= 2 {
223 let x0 = self.time_to_x(sp.keyframes.first().unwrap().time);
224 let x1 = self.time_to_x(sp.keyframes.last().unwrap().time);
225 if local[0] >= x0 && local[0] <= x1 {
226 return Some((spline.clone(), (0..sp.keyframes.len()).collect()));
227 }
228 }
229 }
230 }
231 None
232 }
233
234 fn begin_retime_drag(&mut self, comp: &Comp) {
235 if self.selected_keys.is_empty() {
236 return;
237 }
238 let mut saved = HashMap::new();
239 for kref in &self.selected_keys {
240 if let Some(sp) = comp.splines.get(&kref.spline) {
241 saved.entry(kref.spline.clone()).or_insert_with(|| sp.keyframes.clone());
242 }
243 }
244 self.retime_drag = Some(RetimeDrag {
245 start_frame: self.x_to_time(self.pointer_local[0]).round(),
246 saved_splines: saved,
247 pre_edit_comp: comp.clone(),
248 moved: false,
249 });
250 }
251
252 fn apply_retime_drag(&mut self, comp: &mut Comp) -> bool {
253 let cur_frame = self.x_to_time(self.pointer_local[0]).round();
254 let Some(drag) = &mut self.retime_drag else { return false };
255 let dt = cur_frame - drag.start_frame;
256 if dt.abs() < 0.5 && !drag.moved {
257 return false;
258 }
259 drag.moved = true;
260 retime_selected_keys(comp, &drag.saved_splines, &self.selected_keys, dt);
261 true
262 }
263
264 fn finish_retime_drag(&mut self, comp: &mut Comp, history: &mut CompHistory) -> bool {
265 let Some(drag) = self.retime_drag.take() else { return false };
266 if !drag.moved {
267 return false;
268 }
269 for sname in drag.saved_splines.keys() {
270 if let Some(sp) = comp.splines.get_mut(sname) {
271 sp.sort();
272 }
273 }
274 comp.revision += 1;
275 history.push_snapshot(&drag.pre_edit_comp, "Retime Keyframes");
276 true
277 }
278
279 fn delete_selected(&mut self, comp: &mut Comp, history: &mut CompHistory) -> bool {
280 if self.selected_keys.is_empty() {
281 return false;
282 }
283 let mut by_spline: HashMap<String, Vec<usize>> = HashMap::new();
284 for kref in &self.selected_keys {
285 by_spline.entry(kref.spline.clone()).or_default().push(kref.key_idx);
286 }
287 let pre = comp.clone();
288 let mut changed = false;
289 for (sname, mut idxs) in by_spline {
290 idxs.sort_unstable();
291 idxs.dedup();
292 if let Some(sp) = comp.splines.get_mut(&sname) {
293 for &idx in idxs.iter().rev() {
294 if sp.keyframes.len() > 1 && idx < sp.keyframes.len() {
295 sp.keyframes.remove(idx);
296 changed = true;
297 }
298 }
299 }
300 }
301 if changed {
302 self.selected_keys.clear();
303 comp.revision += 1;
304 history.push_snapshot(&pre, "Delete Keyframes");
305 }
306 changed
307 }
308
309 pub fn input(
310 &mut self,
311 comp: &mut Comp,
312 history: &mut CompHistory,
313 selected_node: Option<NodeId>,
314 event: ui::Event,
315 rect: [f32; 4],
316 pointer_window: [f32; 2],
317 modifiers: ModifiersState,
318 ) -> Vec<KeyframesAction> {
319 let mut actions = Vec::new();
320 self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]];
321 let plot = self.plot_rect();
322
323 match event {
324 ui::Event::PointerMoved(p) => {
325 self.pointer_local = [p[0] - rect[0], p[1] - rect[1]];
326 if self.scrubbing {
327 actions.push(KeyframesAction::ScrubFrame(self.x_to_time(self.pointer_local[0]).round()));
328 } else if let Some((sp, tr, sy)) = self.panning {
329 let dx = f64::from((self.pointer_local[0] - sp[0]) / (plot[2] - plot[0]).max(1.0));
330 let dt = dx * (tr[1] - tr[0]);
331 self.t_range = [tr[0] - dt, tr[1] - dt];
332 self.scroll_y = (sy - (self.pointer_local[1] - sp[1])).max(0.0);
333 } else if self.retime_drag.is_some() {
334 if self.apply_retime_drag(comp) {
335 actions.push(KeyframesAction::KeyframesEdited);
336 }
337 } else if let Some((_, ref mut cur)) = self.box_select {
338 *cur = self.pointer_local;
339 } else {
340 self.hovered_key = self.hit_key(comp, self.pointer_local);
341 }
342 }
343 ui::Event::Button { button, pressed, .. } => {
344 if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) {
345 if pressed {
346 self.panning = Some((self.pointer_local, self.t_range, self.scroll_y));
347 } else {
348 self.panning = None;
349 }
350 } else if button == MouseButton::Left {
351 if pressed {
352 // Sidebar header "All / Sel" toggle pill
353 if self.pointer_local[0] >= SIDEBAR_W - 48.0
354 && self.pointer_local[0] <= SIDEBAR_W - 6.0
355 && self.pointer_local[1] >= 4.0
356 && self.pointer_local[1] <= RULER_H - 4.0
357 {
358 self.selected_only = !self.selected_only;
359 self.scroll_y = 0.0;
360 self.sync_tracks(comp, selected_node);
361 } else if self.pointer_local[0] < SIDEBAR_W && self.pointer_local[1] >= self.tracks_top() {
362 let ri = ((self.pointer_local[1] - self.tracks_top() + self.scroll_y) / ROW_H).floor() as isize;
363 if ri >= 0 && (ri as usize) < self.rows.len() {
364 match &self.rows[ri as usize] {
365 TrackRow::NodeHeader { node_id, .. } => {
366 let id = *node_id;
367 if self.pointer_local[0] < 24.0 {
368 if !self.collapsed_nodes.remove(&id) {
369 self.collapsed_nodes.insert(id);
370 }
371 self.sync_tracks(comp, selected_node);
372 } else {
373 actions.push(KeyframesAction::SelectNode(id));
374 }
375 }
376 TrackRow::Channel { node_id, .. } => {
377 actions.push(KeyframesAction::SelectNode(*node_id));
378 }
379 }
380 }
381 } else if self.pointer_local[0] >= SIDEBAR_W && self.pointer_local[1] < RULER_H {
382 self.scrubbing = true;
383 actions.push(KeyframesAction::ScrubFrame(self.x_to_time(self.pointer_local[0]).round()));
384 } else if let Some(hit) = self.hit_key(comp, self.pointer_local) {
385 if modifiers.shift_key() {
386 if !self.selected_keys.remove(&hit) {
387 self.selected_keys.insert(hit);
388 }
389 } else if !self.selected_keys.contains(&hit) {
390 self.selected_keys.clear();
391 self.selected_keys.insert(hit);
392 }
393 self.begin_retime_drag(comp);
394 } else if let Some((sname, idxs)) = self.hit_span_bar(comp, self.pointer_local) {
395 if !modifiers.shift_key() {
396 self.selected_keys.clear();
397 }
398 for ki in idxs {
399 self.selected_keys.insert(DopeKeyRef { spline: sname.clone(), key_idx: ki });
400 }
401 self.begin_retime_drag(comp);
402 } else if self.pointer_local[0] >= SIDEBAR_W {
403 if !modifiers.shift_key() {
404 self.selected_keys.clear();
405 }
406 self.box_select = Some((self.pointer_local, self.pointer_local));
407 }
408 } else {
409 self.scrubbing = false;
410 if self.finish_retime_drag(comp, history) {
411 actions.push(KeyframesAction::KeyframesEdited);
412 }
413 if let Some((a, b)) = self.box_select.take() {
414 let x0 = a[0].min(b[0]);
415 let x1 = a[0].max(b[0]);
416 let y0 = a[1].min(b[1]);
417 let y1 = a[1].max(b[1]);
418 if (x1 - x0) > 4.0 || (y1 - y0) > 4.0 {
419 for (ri, row) in self.rows.iter().enumerate() {
420 let cy = self.row_y(ri) + ROW_H * 0.5;
421 if cy < y0 || cy > y1 {
422 continue;
423 }
424 if let TrackRow::Channel { spline, .. } = row {
425 if let Some(sp) = comp.splines.get(spline) {
426 for (ki, kf) in sp.keyframes.iter().enumerate() {
427 let kx = self.time_to_x(kf.time);
428 if kx >= x0 && kx <= x1 {
429 self.selected_keys.insert(DopeKeyRef {
430 spline: spline.clone(),
431 key_idx: ki,
432 });
433 }
434 }
435 }
436 }
437 }
438 }
439 }
440 }
441 }
442 }
443 ui::Event::Wheel(delta) => {
444 if self.pointer_local[0] < SIDEBAR_W || modifiers.shift_key() {
445 let max_scroll = (self.rows.len() as f32 * ROW_H - (self.size[1] - self.tracks_top() - FOOTER_H)).max(0.0);
446 self.scroll_y = (self.scroll_y - delta[1]).clamp(0.0, max_scroll);
447 } else {
448 let f = f64::from((1.0 - delta[1] * 0.0045).clamp(0.7, 1.4));
449 let p = self.x_to_time(self.pointer_local[0]);
450 let t0 = p - (p - self.t_range[0]) * f;
451 let t1 = p + (self.t_range[1] - p) * f;
452 if (t1 - t0) > 4.0 && (t1 - t0) < 100_000.0 {
453 self.t_range = [t0, t1];
454 }
455 }
456 }
457 ui::Event::KeyInput { physical, key, state: ElementState::Pressed, repeat: false, modifiers: kmod, .. } => {
458 if physical == PhysicalKey::Code(KeyCode::NumpadDecimal) {
459 self.fit_comp(comp);
460 } else {
461 self.handle_key(comp, history, &key, kmod, &mut actions);
462 }
463 }
464 ui::Event::Key { key, modifiers: kmod, .. } => {
465 self.handle_key(comp, history, &key, kmod, &mut actions);
466 }
467 _ => {}
468 }
469
470 actions
471 }
472
473 fn handle_key(
474 &mut self,
475 comp: &mut Comp,
476 history: &mut CompHistory,
477 key: &Key,
478 kmod: ModifiersState,
479 actions: &mut Vec<KeyframesAction>,
480 ) {
481 match key {
482 Key::Named(NamedKey::Delete | NamedKey::Backspace) => {
483 if self.delete_selected(comp, history) {
484 actions.push(KeyframesAction::KeyframesEdited);
485 }
486 }
487 Key::Character(c) => match c.to_ascii_lowercase().as_str() {
488 "f" | "." => self.fit_comp(comp),
489 "x" if !kmod.super_key() => {
490 if self.delete_selected(comp, history) {
491 actions.push(KeyframesAction::KeyframesEdited);
492 }
493 }
494 _ => {}
495 },
496 _ => {}
497 }
498 }
499
500 pub fn prepare_labels(&mut self) {
501 let font_sm = text::Font {
502 families: Arc::from([text::Family::Mono]),
503 size: 10.0,
504 weight: 500,
505 italic: false,
506 };
507 let font_row = text::Font {
508 families: Arc::from([text::Family::Sans]),
509 size: 11.0,
510 weight: 500,
511 italic: false,
512 };
513 let font_hdr = text::Font {
514 families: Arc::from([text::Family::Sans]),
515 size: 11.0,
516 weight: 600,
517 italic: false,
518 };
519 let make = |s: &str, font: &text::Font| {
520 let styles = [text::Style::new(font.clone())];
521 text::Paragraph {
522 text: s,
523 styles: &styles,
524 spans: &[],
525 replacements: &[],
526 width: None,
527 indent: 0.0,
528 line_height: 1.2,
529 align: text::Align::Left,
530 tab: 32.0,
531 }
532 .layout()
533 };
534
535 for (k, txt, f) in [
536 ("hdr:title", "Keyframes", &font_hdr),
537 ("hdr:all", "All", &font_sm),
538 ("hdr:sel", "Sel", &font_sm),
539 ("hdr:audio", "Audio", &font_row),
540 ("footer", "Drag keys/spans to retime · Ruler: Scrub · Wheel: Zoom · Del: Remove · F: Fit", &font_sm),
541 ] {
542 self.text_cache.entry(k.to_owned()).or_insert_with(|| make(txt, f));
543 }
544
545 for row in &self.rows {
546 match row {
547 TrackRow::NodeHeader { node_id, label, .. } => {
548 let glyph = if self.collapsed_nodes.contains(node_id) { "▸" } else { "▾" };
549 let text = format!("{glyph} {label}");
550 self.text_cache.entry(format!("nh:{text}")).or_insert_with(|| make(&text, &font_hdr));
551 }
552 TrackRow::Channel { label, .. } => {
553 self.text_cache.entry(format!("ch:{label}")).or_insert_with(|| make(label, &font_row));
554 }
555 }
556 }
557
558 let plot = self.plot_rect();
559 let max_ticks = f64::from(((plot[2] - plot[0]) / 56.0).max(2.0));
560 let t_step = nice_step((self.t_range[1] - self.t_range[0]) / max_ticks);
561 let t_start = (self.t_range[0] / t_step).floor() as i64;
562 let t_end = (self.t_range[1] / t_step).ceil() as i64;
563 for ti in t_start..=t_end {
564 let key = format!("t:{}", (ti as f64 * t_step).round() as i64);
565 self.text_cache.entry(key.clone()).or_insert_with(|| make(&key[2..], &font_sm));
566 }
567 }
568
569 pub fn paint<'a>(&'a self, comp: &'a Comp, current_frame: f64) -> Vec<Primitive<'a>> {
570 let mut out = Vec::with_capacity(512);
571 let [w, h] = self.size;
572 let plot = self.plot_rect();
573 let top = self.tracks_top();
574
575 // Sidebar + Ruler chrome
576 out.push(Primitive::Rect { rect: [0.0, 0.0, SIDEBAR_W, h], color: self.palette.sidebar });
577 out.push(Primitive::Rect { rect: [SIDEBAR_W, 0.0, w, RULER_H], color: self.palette.ruler });
578 out.push(Primitive::Segment { from: [SIDEBAR_W, 0.0], to: [SIDEBAR_W, h], width: 1.0, color: self.palette.rule });
579 out.push(Primitive::Segment { from: [0.0, RULER_H], to: [w, RULER_H], width: 1.0, color: self.palette.rule });
580
581 if let Some(tl) = self.text_cache.get("hdr:title") {
582 out.push(Primitive::Text {
583 text: tl as &dyn Glyphs,
584 origin: [10.0, 6.0],
585 clip: Some([8.0, 0.0, SIDEBAR_W - 52.0, RULER_H]),
586 ink: self.palette.text,
587 });
588 }
589 // "All / Sel" filter pill
590 let pill_rect = [SIDEBAR_W - 46.0, 4.0, SIDEBAR_W - 8.0, RULER_H - 4.0];
591 out.push(Primitive::RoundedRect {
592 rect: pill_rect,
593 radius: 4.0,
594 stroke: None,
595 color: if self.selected_only {
596 [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.28]
597 } else {
598 [self.palette.bg[0], self.palette.bg[1], self.palette.bg[2], 0.7]
599 },
600 });
601 out.push(Primitive::RoundedRect {
602 rect: pill_rect,
603 radius: 4.0,
604 stroke: Some(1.0),
605 color: if self.selected_only { self.palette.accent } else { self.palette.rule },
606 });
607 let mode_key = if self.selected_only { "hdr:sel" } else { "hdr:all" };
608 if let Some(ml) = self.text_cache.get(mode_key) {
609 out.push(Primitive::Text {
610 text: ml as &dyn Glyphs,
611 origin: [pill_rect[0] + 9.0, 7.0],
612 clip: Some(pill_rect),
613 ink: if self.selected_only { self.palette.text } else { self.palette.text_dim },
614 });
615 }
616
617 // Ruler frame ticks
618 let max_ticks = f64::from(((plot[2] - plot[0]) / 56.0).max(2.0));
619 let t_step = nice_step((self.t_range[1] - self.t_range[0]) / max_ticks);
620 let t_start = (self.t_range[0] / t_step).floor() as i64;
621 let t_end = (self.t_range[1] / t_step).ceil() as i64;
622 for ti in t_start..=t_end {
623 let t = ti as f64 * t_step;
624 let x = self.time_to_x(t);
625 if x < plot[0] || x > plot[2] {
626 continue;
627 }
628 out.push(Primitive::Segment { from: [x, RULER_H], to: [x, plot[3]], width: 1.0, color: self.palette.grid });
629 let key = format!("t:{}", t.round() as i64);
630 if let Some(tl) = self.text_cache.get(&key) {
631 out.push(Primitive::Text {
632 text: tl as &dyn Glyphs,
633 origin: [x + 3.0, 5.0],
634 clip: Some([plot[0], 0.0, plot[2], RULER_H]),
635 ink: self.palette.text_dim,
636 });
637 }
638 }
639
640 // Green RAM cache bar along bottom edge of ruler
641 for &(c0, c1) in &self.cached_ranges {
642 let x0 = self.time_to_x(c0 as f64).max(plot[0]);
643 let x1 = self.time_to_x((c1 + 1) as f64).min(plot[2]);
644 if x1 > x0 {
645 out.push(Primitive::Rect {
646 rect: [x0, RULER_H - 3.5, x1.max(x0 + 2.0), RULER_H - 0.5],
647 color: [0.22, 0.86, 0.48, 0.92],
648 });
649 }
650 }
651
652 // Dedicated Audio Waveform row when audio is present
653 if !self.audio_peaks.is_empty() {
654 let ay0 = RULER_H;
655 let ay1 = RULER_H + AUDIO_ROW_H;
656 out.push(Primitive::Rect { rect: [0.0, ay0, w, ay1], color: self.palette.row_alt });
657 out.push(Primitive::Segment { from: [0.0, ay1], to: [w, ay1], width: 1.0, color: self.palette.rule });
658 if let Some(al) = self.text_cache.get("hdr:audio") {
659 out.push(Primitive::Text {
660 text: al as &dyn Glyphs,
661 origin: [12.0, ay0 + 5.0],
662 clip: Some([8.0, ay0, SIDEBAR_W - 8.0, ay1]),
663 ink: [0.54, 0.80, 1.0, 0.95],
664 });
665 }
666 out.push(Primitive::PushClip { rect: [plot[0], ay0, plot[2], ay1], radius: 0.0 });
667 let mid_y = 0.5 * (ay0 + ay1);
668 let max_half = AUDIO_ROW_H * 0.42;
669 let a0 = self.audio_range[0];
670 let n = self.audio_peaks.len() as i64;
671 let f_vis0 = (self.t_range[0].floor() as i64).max(a0);
672 let f_vis1 = (self.t_range[1].ceil() as i64).min(a0 + n - 1);
673 let bar_step = ((plot[2] - plot[0]) / ((self.t_range[1] - self.t_range[0]).max(1.0) as f32)).max(1.5);
674 let stride = ((1.8 / bar_step).ceil() as i64).max(1);
675 let mut f = f_vis0;
676 while f <= f_vis1 {
677 let mut peak = 0.0_f32;
678 for off in 0..stride {
679 let idx = (f + off - a0) as usize;
680 if let Some(&v) = self.audio_peaks.get(idx) {
681 if v > peak { peak = v; }
682 }
683 }
684 if peak > 0.01 {
685 let x = self.time_to_x(f as f64);
686 let hh = (peak * max_half).max(1.0);
687 let bw = (bar_step * stride as f32 - 0.6).max(1.2);
688 out.push(Primitive::Rect {
689 rect: [x, mid_y - hh, x + bw, mid_y + hh],
690 color: [0.46, 0.74, 0.98, 0.55],
691 });
692 }
693 f += stride;
694 }
695 out.push(Primitive::PopClip);
696 }
697
698 // Render range subtle shading
699 let rx0 = self.time_to_x(comp.render_range[0] as f64);
700 let rx1 = self.time_to_x(comp.render_range[1] as f64);
701 out.push(Primitive::PushClip { rect: [plot[0], top, plot[2], plot[3]], radius: 0.0 });
702 if rx0 > plot[0] {
703 out.push(Primitive::Rect { rect: [plot[0], top, rx0.min(plot[2]), plot[3]], color: [0.0, 0.0, 0.0, 0.16] });
704 }
705 if rx1 < plot[2] {
706 out.push(Primitive::Rect { rect: [rx1.max(plot[0]), top, plot[2], plot[3]], color: [0.0, 0.0, 0.0, 0.16] });
707 }
708 out.push(Primitive::PopClip);
709
710 // Track rows (clipped to track area)
711 out.push(Primitive::PushClip { rect: [0.0, top, w, plot[3]], radius: 0.0 });
712 for (ri, row) in self.rows.iter().enumerate() {
713 let y0 = self.row_y(ri);
714 let y1 = y0 + ROW_H;
715 if y1 < top || y0 > plot[3] {
716 continue;
717 }
718 if ri % 2 == 1 {
719 out.push(Primitive::Rect { rect: [0.0, y0, w, y1], color: self.palette.row_alt });
720 }
721 out.push(Primitive::Segment { from: [0.0, y1], to: [w, y1], width: 1.0, color: self.palette.grid });
722
723 match row {
724 TrackRow::NodeHeader { node_id, label, splines } => {
725 let glyph = if self.collapsed_nodes.contains(node_id) { "▸" } else { "▾" };
726 let key = format!("nh:{glyph} {label}");
727 if let Some(tl) = self.text_cache.get(&key) {
728 out.push(Primitive::Text {
729 text: tl as &dyn Glyphs,
730 origin: [10.0, y0 + 4.0],
731 clip: Some([6.0, y0, SIDEBAR_W - 6.0, y1]),
732 ink: self.palette.text,
733 });
734 }
735 // Summary span + tick dots on node header row
736 let mut t_min = f64::INFINITY;
737 let mut t_max = f64::NEG_INFINITY;
738 for sname in splines {
739 if let Some(sp) = comp.splines.get(sname) {
740 for kf in &sp.keyframes {
741 t_min = t_min.min(kf.time);
742 t_max = t_max.max(kf.time);
743 }
744 }
745 }
746 if t_min.is_finite() {
747 let sx0 = self.time_to_x(t_min).max(plot[0]);
748 let sx1 = self.time_to_x(t_max).min(plot[2]);
749 if sx1 >= sx0 {
750 out.push(Primitive::RoundedRect {
751 rect: [sx0, y0 + 6.0, sx1.max(sx0 + 4.0), y1 - 6.0],
752 radius: 3.0,
753 stroke: None,
754 color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.22],
755 });
756 }
757 }
758 }
759 TrackRow::Channel { label, spline, color, .. } => {
760 out.push(Primitive::RoundedRect {
761 rect: [20.0, y0 + 7.0, 28.0, y0 + 15.0],
762 radius: 2.0,
763 stroke: None,
764 color: *color,
765 });
766 if let Some(tl) = self.text_cache.get(&format!("ch:{label}")) {
767 out.push(Primitive::Text {
768 text: tl as &dyn Glyphs,
769 origin: [34.0, y0 + 4.0],
770 clip: Some([32.0, y0, SIDEBAR_W - 6.0, y1]),
771 ink: self.palette.text_dim,
772 });
773 }
774
775 if let Some(sp) = comp.splines.get(spline) {
776 if sp.keyframes.len() >= 2 {
777 let sx0 = self.time_to_x(sp.keyframes.first().unwrap().time).max(plot[0]);
778 let sx1 = self.time_to_x(sp.keyframes.last().unwrap().time).min(plot[2]);
779 if sx1 > sx0 {
780 out.push(Primitive::RoundedRect {
781 rect: [sx0, y0 + 8.0, sx1, y1 - 8.0],
782 radius: 2.0,
783 stroke: None,
784 color: [color[0], color[1], color[2], 0.28],
785 });
786 }
787 }
788 let cy = y0 + ROW_H * 0.5;
789 for (ki, kf) in sp.keyframes.iter().enumerate() {
790 let kx = self.time_to_x(kf.time);
791 if kx < plot[0] - 8.0 || kx > plot[2] + 8.0 {
792 continue;
793 }
794 let kref = DopeKeyRef { spline: spline.clone(), key_idx: ki };
795 let sel = self.selected_keys.contains(&kref);
796 let hov = self.hovered_key.as_ref() == Some(&kref);
797 let r = if sel || hov { 5.0 } else { 4.0 };
798 out.push(Primitive::RoundedRect {
799 rect: [kx - r, cy - r, kx + r, cy + r],
800 radius: 1.5,
801 stroke: None,
802 color: if sel {
803 [1.0, 0.84, 0.24, 1.0]
804 } else if hov {
805 [1.0, 1.0, 1.0, 1.0]
806 } else {
807 *color
808 },
809 });
810 out.push(Primitive::RoundedRect {
811 rect: [kx - r, cy - r, kx + r, cy + r],
812 radius: 1.5,
813 stroke: Some(1.0),
814 color: [0.04, 0.04, 0.06, 0.9],
815 });
816 }
817 }
818 }
819 }
820 }
821
822 // Box select overlay
823 if let Some((a, b)) = self.box_select {
824 let x0 = a[0].min(b[0]);
825 let x1 = a[0].max(b[0]);
826 let y0 = a[1].min(b[1]);
827 let y1 = a[1].max(b[1]);
828 out.push(Primitive::RoundedRect {
829 rect: [x0, y0, x1, y1],
830 radius: 2.0,
831 stroke: None,
832 color: [self.palette.accent[0], self.palette.accent[1], self.palette.accent[2], 0.16],
833 });
834 out.push(Primitive::RoundedRect {
835 rect: [x0, y0, x1, y1],
836 radius: 2.0,
837 stroke: Some(1.2),
838 color: self.palette.accent,
839 });
840 }
841 out.push(Primitive::PopClip);
842
843 // Playhead vertical line
844 let px = self.time_to_x(current_frame);
845 if px >= plot[0] && px <= plot[2] {
846 out.push(Primitive::Segment {
847 from: [px, 0.0],
848 to: [px, plot[3]],
849 width: 1.6,
850 color: [0.96, 0.36, 0.34, 0.92],
851 });
852 }
853
854 // Footer bar
855 out.push(Primitive::Rect { rect: [SIDEBAR_W, h - FOOTER_H, w, h], color: self.palette.ruler });
856 if let Some(fl) = self.text_cache.get("footer") {
857 out.push(Primitive::Text {
858 text: fl as &dyn Glyphs,
859 origin: [SIDEBAR_W + 10.0, h - FOOTER_H + 5.0],
860 clip: Some([SIDEBAR_W + 6.0, h - FOOTER_H, w - 6.0, h]),
861 ink: self.palette.text_dim,
862 });
863 }
864
865 out
866 }
867}
868
869pub fn build_tracks(
870 comp: &Comp,
871 selected_node: Option<NodeId>,
872 selected_only: bool,
873 collapsed: &HashSet<NodeId>,
874) -> Vec<TrackRow> {
875 let mut rows = Vec::new();
876 let palette: &[[f32; 4]] = &[
877 [0.98, 0.44, 0.62, 1.0],
878 [0.36, 0.84, 0.96, 1.0],
879 [0.50, 0.92, 0.46, 1.0],
880 [0.98, 0.78, 0.28, 1.0],
881 [0.74, 0.56, 0.98, 1.0],
882 ];
883 let mut color_idx = 0usize;
884
885 let iter_ids: Vec<NodeId> = if selected_only {
886 selected_node.into_iter().collect()
887 } else {
888 comp.nodes.iter().map(|n| n.id).collect()
889 };
890
891 for id in iter_ids {
892 if id.0 >= comp.nodes.len() {
893 continue;
894 }
895 let channels: Vec<(String, String)> = comp
896 .node_splines(id)
897 .into_iter()
898 .filter(|(_, sname)| !sname.contains("LUTIn"))
899 .collect();
900 if channels.is_empty() {
901 continue;
902 }
903 let node = comp.node(id);
904 let spline_names: Vec<String> = channels.iter().map(|(_, s)| s.clone()).collect();
905 rows.push(TrackRow::NodeHeader {
906 node_id: id,
907 label: node.name.clone(),
908 splines: spline_names,
909 });
910 if !collapsed.contains(&id) {
911 for (label, spline) in channels {
912 let col = comp
913 .splines
914 .get(&spline)
915 .map(|sp| {
916 let [r, g, b] = sp.color;
917 if r as u16 + g as u16 + b as u16 > 120 {
918 [r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0]
919 } else {
920 palette[color_idx % palette.len()]
921 }
922 })
923 .unwrap_or_else(|| palette[color_idx % palette.len()]);
924 color_idx += 1;
925 rows.push(TrackRow::Channel {
926 node_id: id,
927 label,
928 spline,
929 color: col,
930 });
931 }
932 }
933 }
934 rows
935}
936
937pub fn retime_selected_keys(
938 comp: &mut Comp,
939 saved_splines: &HashMap<String, Vec<Keyframe>>,
940 selected: &HashSet<DopeKeyRef>,
941 dt: f64,
942) {
943 for (sname, orig) in saved_splines {
944 if let Some(sp) = comp.splines.get_mut(sname) {
945 sp.keyframes = orig.clone();
946 }
947 }
948 for kref in selected {
949 let Some(sp) = comp.splines.get_mut(&kref.spline) else { continue };
950 let Some(kf) = sp.keyframes.get_mut(kref.key_idx) else { continue };
951 kf.time += dt;
952 if let Some(lh) = &mut kf.lh {
953 lh[0] += dt;
954 }
955 if let Some(rh) = &mut kf.rh {
956 rh[0] += dt;
957 }
958 }
959 comp.revision += 1;
960}
961
962fn nice_step(raw: f64) -> f64 {
963 let raw = raw.max(1.0);
964 let pow = 10.0_f64.powf(raw.log10().floor());
965 let frac = raw / pow;
966 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 };
967 (nice * pow).max(1.0)
968}
969
970#[cfg(test)]
971mod tests {
972 use super::*;
973
974 fn sample_animated_comp() -> Comp {
975 let src = r#"Composition {
976 CurrentTime = 10,
977 RenderRange = { 0, 100 },
978 GlobalRange = { 0, 100 },
979 Tools = ordered() {
980 XF1 = Transform {
981 Inputs = {
982 Size = Input { SourceOp = "XF1Size", Source = "Value", },
983 },
984 },
985 XF1Size = BezierSpline {
986 SplineColor = { Red = 220, Green = 120, Blue = 80 },
987 KeyFrames = {
988 [10] = { 1.0, RH = { 20.0, 1.0 }, Flags = { Linear = false } },
989 [40] = { 2.0, LH = { 30.0, 2.0 }, Flags = { Linear = false } },
990 },
991 },
992 },
993 }"#;
994 Comp::from_fusion_str(src).expect("parse animated comp")
995 }
996
997 #[test]
998 fn build_tracks_lists_animated_nodes_and_channels() {
999 let comp = sample_animated_comp();
1000 let xf = comp.find_node("XF1").unwrap();
1001 let rows = build_tracks(&comp, Some(xf), false, &HashSet::new());
1002 assert_eq!(rows.len(), 2);
1003 assert!(matches!(&rows[0], TrackRow::NodeHeader { label, .. } if label == "XF1"));
1004 assert!(matches!(&rows[1], TrackRow::Channel { spline, .. } if spline == "XF1Size"));
1005
1006 let mut collapsed = HashSet::new();
1007 collapsed.insert(xf);
1008 let collapsed_rows = build_tracks(&comp, Some(xf), false, &collapsed);
1009 assert_eq!(collapsed_rows.len(), 1);
1010 }
1011
1012 #[test]
1013 fn retime_shifts_key_and_handles_together_with_undo() {
1014 let mut comp = sample_animated_comp();
1015 let mut history = CompHistory::new();
1016 let pre = comp.clone();
1017 let mut saved = HashMap::new();
1018 saved.insert("XF1Size".to_owned(), comp.splines["XF1Size"].keyframes.clone());
1019 let mut sel = HashSet::new();
1020 sel.insert(DopeKeyRef { spline: "XF1Size".to_owned(), key_idx: 1 });
1021
1022 retime_selected_keys(&mut comp, &saved, &sel, 15.0);
1023 history.push_snapshot(&pre, "Retime Keyframes");
1024
1025 let kf1 = &comp.splines["XF1Size"].keyframes[1];
1026 assert!((kf1.time - 55.0).abs() < 1e-6);
1027 assert!((kf1.lh.unwrap()[0] - 45.0).abs() < 1e-6, "left handle must shift with key");
1028
1029 assert!(history.undo(&mut comp));
1030 assert!((comp.splines["XF1Size"].keyframes[1].time - 40.0).abs() < 1e-6);
1031 }
1032}
crates/studio/src/main.rs+266-16
...@@ -3,12 +3,17 @@...@@ -3,12 +3,17 @@
33
4mod add_tool;4mod add_tool;
5mod inspector;5mod inspector;
6mod keyframes;
67
7use add_tool::{AddToolLauncher, ToolEntry};8use add_tool::{AddToolLauncher, ToolEntry};
8use dock::{Axis as DockAxis, Command, Dock, Event, GroupId, Node as DockNode, Part as DockPart, Place, Plus, Side, SplitId, Tab};9use dock::{Axis as DockAxis, Command, Dock, Event, GroupId, Node as DockNode, Part as DockPart, Place, Plus, Side, SplitId, Tab};
9use engine::{AudioPlayer, AudioTrack, CacheMode, Engine, ExportOptions, export_saver_png_sequence};10use engine::{
11 AudioPlayer, AudioTrack, CacheMode, DEFAULT_RAM_CACHE_MB, Engine, ExportOptions, PrefetchJob,
12 RamFrameCache, RamPrefetcher, export_saver_png_sequence,
13};
10use flow::{FlowAction, FlowView};14use flow::{FlowAction, FlowView};
11use inspector::{InspectorAction, InspectorState};15use inspector::{InspectorAction, InspectorState};
16use keyframes::{KeyframesAction, KeyframesView};
12use model::{Comp, CompHistory, NodeId, default_main_input_port};17use model::{Comp, CompHistory, NodeId, default_main_input_port};
13use spline::{SplineAction, SplineView};18use spline::{SplineAction, SplineView};
14use std::collections::HashMap;19use std::collections::HashMap;
...@@ -28,13 +33,14 @@ use winit::keyboard::{Key, KeyCode, NamedKey, PhysicalKey};...@@ -28,13 +33,14 @@ use winit::keyboard::{Key, KeyCode, NamedKey, PhysicalKey};
28use winit::window::{CursorIcon, Window, WindowId};33use winit::window::{CursorIcon, Window, WindowId};
2934
30const DEFAULT_COMP: &str = "/Volumes/Project/trees/fusion/20_falling.comp";35const DEFAULT_COMP: &str = "/Volumes/Project/trees/fusion/20_falling.comp";
31const PANES: &[&str] = &["Viewer 1", "Viewer 2", "Flow", "Spline", "Inspector"];36const PANES: &[&str] = &["Viewer 1", "Viewer 2", "Flow", "Spline", "Keyframes", "Inspector"];
3237
33fn viewer_pane_id(slot: usize) -> ui::Id { ui::Id::ROOT.child(("pane-viewer", slot)) }38fn viewer_pane_id(slot: usize) -> ui::Id { ui::Id::ROOT.child(("pane-viewer", slot)) }
34fn viewer_canvas_id(slot: usize) -> ui::Id { ui::Id::ROOT.child(("canvas-viewer", slot)) }39fn viewer_canvas_id(slot: usize) -> ui::Id { ui::Id::ROOT.child(("canvas-viewer", slot)) }
35fn flow_pane_id() -> ui::Id { ui::Id::ROOT.child("pane-flow") }40fn flow_pane_id() -> ui::Id { ui::Id::ROOT.child("pane-flow") }
36fn flow_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-flow") }41fn flow_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-flow") }
37fn spline_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-spline") }42fn spline_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-spline") }
43fn keyframes_canvas_id() -> ui::Id { ui::Id::ROOT.child("canvas-keyframes") }
38fn inspector_pane_id() -> ui::Id { ui::Id::ROOT.child("pane-inspector") }44fn inspector_pane_id() -> ui::Id { ui::Id::ROOT.child("pane-inspector") }
3945
40struct Cli {46struct Cli {
...@@ -44,6 +50,7 @@ struct Cli {...@@ -44,6 +50,7 @@ struct Cli {
44 select_node: Option<String>,50 select_node: Option<String>,
45 dual_viewer: bool,51 dual_viewer: bool,
46 open_add_tool: bool,52 open_add_tool: bool,
53 show_keyframes: bool,
47}54}
4855
49fn parse_cli() -> Cli {56fn parse_cli() -> Cli {
...@@ -54,6 +61,7 @@ fn parse_cli() -> Cli {...@@ -54,6 +61,7 @@ fn parse_cli() -> Cli {
54 let mut select_node = None;61 let mut select_node = None;
55 let mut dual_viewer = false;62 let mut dual_viewer = false;
56 let mut open_add_tool = false;63 let mut open_add_tool = false;
64 let mut show_keyframes = false;
57 let mut i = 1;65 let mut i = 1;
58 while i < args.len() {66 while i < args.len() {
59 match args[i].as_str() {67 match args[i].as_str() {
...@@ -77,6 +85,10 @@ fn parse_cli() -> Cli {...@@ -77,6 +85,10 @@ fn parse_cli() -> Cli {
77 open_add_tool = true;85 open_add_tool = true;
78 i += 1;86 i += 1;
79 }87 }
88 "--show-keyframes" => {
89 show_keyframes = true;
90 i += 1;
91 }
80 other if !other.starts_with("--") => {92 other if !other.starts_with("--") => {
81 comp_path = PathBuf::from(other);93 comp_path = PathBuf::from(other);
82 i += 1;94 i += 1;
...@@ -84,7 +96,7 @@ fn parse_cli() -> Cli {...@@ -84,7 +96,7 @@ fn parse_cli() -> Cli {
84 _ => i += 1,96 _ => i += 1,
85 }97 }
86 }98 }
87 Cli { comp_path, snapshot, frame, select_node, dual_viewer, open_add_tool }99 Cli { comp_path, snapshot, frame, select_node, dual_viewer, open_add_tool, show_keyframes }
88}100}
89101
90fn main() {102fn main() {
...@@ -116,8 +128,12 @@ struct Studio {...@@ -116,8 +128,12 @@ struct Studio {
116 viewers: [ViewerState; 2],128 viewers: [ViewerState; 2],
117 flow: FlowView,129 flow: FlowView,
118 spline: SplineView,130 spline: SplineView,
131 keyframes: KeyframesView,
119 inspector: InspectorState,132 inspector: InspectorState,
120 add_tool: AddToolLauncher,133 add_tool: AddToolLauncher,
134 ram_cache: RamFrameCache,
135 prefetcher: Option<RamPrefetcher>,
136 last_prefetch_sig: Option<(NodeId, i64, u64, u32, bool, bool)>,
121 renaming_node: Option<NodeId>,137 renaming_node: Option<NodeId>,
122 rename_buf: String,138 rename_buf: String,
123 rename_needs_focus: bool,139 rename_needs_focus: bool,
...@@ -133,6 +149,7 @@ impl Studio {...@@ -133,6 +149,7 @@ impl Studio {
133 init_frame: Option<f64>,149 init_frame: Option<f64>,
134 select_node: Option<&str>,150 select_node: Option<&str>,
135 dual_viewer: bool,151 dual_viewer: bool,
152 show_keyframes: bool,
136 enable_audio: bool,153 enable_audio: bool,
137 ) -> Self {154 ) -> Self {
138 let engine = Engine::new(renderer.device().clone(), renderer.queue().clone());155 let engine = Engine::new(renderer.device().clone(), renderer.queue().clone());
...@@ -187,7 +204,12 @@ impl Studio {...@@ -187,7 +204,12 @@ impl Studio {
187 },204 },
188 DockPart {205 DockPart {
189 share: 0.48,206 share: 0.48,
190 node: DockNode::Group { id: g_spline, tabs: vec!["Spline".to_owned()], preview: None, rest: Default::default() },207 node: DockNode::Group {
208 id: g_spline,
209 tabs: vec!["Spline".to_owned(), "Keyframes".to_owned()],
210 preview: None,
211 rest: Default::default(),
212 },
191 rest: Default::default(),213 rest: Default::default(),
192 },214 },
193 ],215 ],
...@@ -222,7 +244,10 @@ impl Studio {...@@ -222,7 +244,10 @@ impl Studio {
222 seen.active.insert(g_v2, "Viewer 2".to_owned());244 seen.active.insert(g_v2, "Viewer 2".to_owned());
223 }245 }
224 seen.active.insert(g_flow, "Flow".to_owned());246 seen.active.insert(g_flow, "Flow".to_owned());
225 seen.active.insert(g_spline, "Spline".to_owned());247 seen.active.insert(
248 g_spline,
249 if show_keyframes { "Keyframes" } else { "Spline" }.to_owned(),
250 );
226 seen.active.insert(g_inspector, "Inspector".to_owned());251 seen.active.insert(g_inspector, "Inspector".to_owned());
227 seen.focused = Some(g_flow);252 seen.focused = Some(g_flow);
228 let dock = Dock::new();253 let dock = Dock::new();
...@@ -253,8 +278,20 @@ impl Studio {...@@ -253,8 +278,20 @@ impl Studio {
253 let mut spline = SplineView::new(&ui_theme);278 let mut spline = SplineView::new(&ui_theme);
254 spline.set_target_node(&comp, default_sel);279 spline.set_target_node(&comp, default_sel);
255280
281 let mut keyframes = KeyframesView::new(&ui_theme);
282 keyframes.sync_tracks(&comp, default_sel);
283
284 v1.selected_node = default_sel;
285 v2.selected_node = default_sel;
286
256 let inspector = InspectorState::new(&ui_theme);287 let inspector = InspectorState::new(&ui_theme);
257 let add_tool = AddToolLauncher::new();288 let add_tool = AddToolLauncher::new();
289 let ram_cache = RamFrameCache::new(DEFAULT_RAM_CACHE_MB);
290 let prefetcher = if enable_audio {
291 Some(RamPrefetcher::new(ram_cache.clone(), engine.vram_budget_mb()))
292 } else {
293 None
294 };
258295
259 let (audio_player, audio_rx) = if enable_audio {296 let (audio_player, audio_rx) = if enable_audio {
260 let player = match AudioPlayer::new() {297 let player = match AudioPlayer::new() {
...@@ -290,8 +327,12 @@ impl Studio {...@@ -290,8 +327,12 @@ impl Studio {
290 viewers: [v1, v2],327 viewers: [v1, v2],
291 flow,328 flow,
292 spline,329 spline,
330 keyframes,
293 inspector,331 inspector,
294 add_tool,332 add_tool,
333 ram_cache,
334 prefetcher,
335 last_prefetch_sig: None,
295 renaming_node: None,336 renaming_node: None,
296 rename_buf: String::new(),337 rename_buf: String::new(),
297 rename_needs_focus: false,338 rename_needs_focus: false,
...@@ -315,6 +356,15 @@ impl Studio {...@@ -315,6 +356,15 @@ impl Studio {
315 track.duration_secs,356 track.duration_secs,
316 track.sample_rate357 track.sample_rate
317 );358 );
359 let peaks = track.waveform_peaks(
360 self.comp.fps,
361 self.comp.audio_offset,
362 self.comp.render_range[0],
363 self.comp.render_range[1],
364 );
365 self.viewers[0].audio_peaks = peaks.clone();
366 self.keyframes.audio_peaks = peaks;
367 self.keyframes.audio_range = self.comp.render_range;
318 let t = self.audio_time_secs();368 let t = self.audio_time_secs();
319 let playing = self.playback.playing;369 let playing = self.playback.playing;
320 if let Some(player) = &mut self.audio_player {370 if let Some(player) = &mut self.audio_player {
...@@ -362,12 +412,66 @@ impl Studio {...@@ -362,12 +412,66 @@ impl Studio {
362 } else {412 } else {
363 self.engine.bust_all_caches();413 self.engine.bust_all_caches();
364 }414 }
415 self.ram_cache.invalidate_other_revisions(self.comp.revision);
416 if let Some(pf) = &self.prefetcher {
417 pf.cancel();
418 }
419 self.last_prefetch_sig = None;
365 for v in &mut self.viewers {420 for v in &mut self.viewers {
366 v.cached_frames.clear();421 v.cached_frames.clear();
367 v.dirty = true;422 v.dirty = true;
368 }423 }
369 }424 }
370425
426 fn sync_ram_ranges_and_prefetch(&mut self) {
427 let sel = self.flow.primary;
428 for v in &mut self.viewers {
429 v.selected_node = sel;
430 }
431 if let Some(target) = self.viewers[0].viewed_node {
432 let ranges = self.ram_cache.cached_frame_ranges(
433 target,
434 self.comp.revision,
435 self.engine.proxy_scale,
436 self.engine.hiq,
437 self.engine.use_proxy_clips,
438 );
439 self.viewers[0].ram_cached_ranges = ranges.clone();
440 self.keyframes.cached_ranges = ranges;
441
442 if let Some(pf) = &mut self.prefetcher {
443 if self.engine.cache.mode == CacheMode::Enabled {
444 let cur_f = self.playback.current_frame.round() as i64;
445 let sig = (
446 target,
447 cur_f,
448 self.comp.revision,
449 self.engine.proxy_scale,
450 self.engine.hiq,
451 self.engine.use_proxy_clips,
452 );
453 if self.last_prefetch_sig != Some(sig) {
454 self.last_prefetch_sig = Some(sig);
455 self.ram_cache.invalidate_other_revisions(self.comp.revision);
456 pf.request_lookahead(PrefetchJob {
457 comp: self.comp.clone(),
458 target,
459 center_frame: cur_f,
460 range: self.comp.render_range,
461 lookahead: 24,
462 proxy_scale: self.engine.proxy_scale,
463 hiq: self.engine.hiq,
464 use_proxy_clips: self.engine.use_proxy_clips,
465 });
466 }
467 }
468 }
469 } else {
470 self.viewers[0].ram_cached_ranges.clear();
471 self.keyframes.cached_ranges.clear();
472 }
473 }
474
371 fn undo(&mut self) {475 fn undo(&mut self) {
372 let label = self.history.undo_label().unwrap_or("Edit").to_owned();476 let label = self.history.undo_label().unwrap_or("Edit").to_owned();
373 if self.history.undo(&mut self.comp) {477 if self.history.undo(&mut self.comp) {
...@@ -506,6 +610,16 @@ impl Studio {...@@ -506,6 +610,16 @@ impl Studio {
506 self.flow.primary = Some(id);610 self.flow.primary = Some(id);
507 }611 }
508 self.spline.set_target_node(&self.comp, default_sel);612 self.spline.set_target_node(&self.comp, default_sel);
613 self.keyframes.audio_peaks.clear();
614 self.keyframes.cached_ranges.clear();
615 self.keyframes.fit_comp(&self.comp);
616 self.keyframes.sync_tracks(&self.comp, default_sel);
617 self.viewers[0].audio_peaks.clear();
618 self.ram_cache.clear();
619 if let Some(pf) = &self.prefetcher {
620 pf.cancel();
621 }
622 self.last_prefetch_sig = None;
509 self.inspector.reset();623 self.inspector.reset();
510 self.renaming_node = None;624 self.renaming_node = None;
511625
...@@ -636,15 +750,24 @@ impl Studio {...@@ -636,15 +750,24 @@ impl Studio {
636 }750 }
637 }751 }
638752
753 self.sync_ram_ranges_and_prefetch();
639 let shown = self.dock.at(&mut self.layout, &mut self.seen, &String::clone).shown();754 let shown = self.dock.at(&mut self.layout, &mut self.seen, &String::clone).shown();
640 for (slot, pane_name) in [(0, "Viewer 1"), (1, "Viewer 2")] {755 for (slot, pane_name) in [(0, "Viewer 1"), (1, "Viewer 2")] {
641 if shown.contains(&pane_name.to_owned()) {756 if shown.contains(&pane_name.to_owned()) {
642 self.viewers[slot].ensure_rendered(&mut self.engine, &self.comp, self.playback.current_frame, self.scale);757 self.viewers[slot].ensure_rendered_with_ram(
758 &mut self.engine,
759 Some(&self.ram_cache),
760 &self.comp,
761 self.playback.current_frame,
762 self.scale,
763 );
643 self.viewers[slot].prepare_hud(&self.comp, &self.engine, &self.playback);764 self.viewers[slot].prepare_hud(&self.comp, &self.engine, &self.playback);
644 }765 }
645 }766 }
646 self.flow.prepare_labels(&self.comp);767 self.flow.prepare_labels(&self.comp);
647 self.spline.prepare_labels(&self.comp);768 self.spline.prepare_labels(&self.comp);
769 self.keyframes.sync_tracks(&self.comp, self.flow.primary);
770 self.keyframes.prepare_labels();
648771
649 self.ui.begin(self.size, self.scale, now);772 self.ui.begin(self.size, self.scale, now);
650773
...@@ -671,6 +794,7 @@ impl Studio {...@@ -671,6 +794,7 @@ impl Studio {
671 viewers,794 viewers,
672 flow,795 flow,
673 spline,796 spline,
797 keyframes,
674 inspector,798 inspector,
675 add_tool,799 add_tool,
676 renaming_node,800 renaming_node,
...@@ -684,6 +808,7 @@ impl Studio {...@@ -684,6 +808,7 @@ impl Studio {
684 let v2_bg = viewers[1].background();808 let v2_bg = viewers[1].background();
685 let flow_bg = flow.background();809 let flow_bg = flow.background();
686 let spline_bg = spline.background();810 let spline_bg = spline.background();
811 let keyframes_bg = keyframes.background();
687 let inspector_bg = inspector.background();812 let inspector_bg = inspector.background();
688 let mut viewer_actions: Vec<(usize, ViewerAction)> = Vec::new();813 let mut viewer_actions: Vec<(usize, ViewerAction)> = Vec::new();
689 let mut inspector_actions: Vec<InspectorAction> = Vec::new();814 let mut inspector_actions: Vec<InspectorAction> = Vec::new();
...@@ -709,6 +834,7 @@ impl Studio {...@@ -709,6 +834,7 @@ impl Studio {
709 "Viewer 2" => v2_bg,834 "Viewer 2" => v2_bg,
710 "Flow" => flow_bg,835 "Flow" => flow_bg,
711 "Spline" => spline_bg,836 "Spline" => spline_bg,
837 "Keyframes" => keyframes_bg,
712 "Inspector" => inspector_bg,838 "Inspector" => inspector_bg,
713 _ => flow_bg,839 _ => flow_bg,
714 };840 };
...@@ -836,6 +962,18 @@ impl Studio {...@@ -836,6 +962,18 @@ impl Studio {
836 ui.close();962 ui.close();
837 Some(id)963 Some(id)
838 }964 }
965 "Keyframes" => {
966 let id = ui.open_as(
967 keyframes_canvas_id(),
968 ui::Spec {
969 flags: ui::Flags::CUSTOM | ui::Flags::FOCUSABLE | ui::Flags::KEY_INPUT,
970 size: [ui::fill(), ui::fill()],
971 ..ui::Spec::default()
972 },
973 );
974 ui.close();
975 Some(id)
976 }
839 "Inspector" => {977 "Inspector" => {
840 let acts = inspector.build_ui(978 let acts = inspector.build_ui(
841 ui,979 ui,
...@@ -998,7 +1136,15 @@ impl Studio {...@@ -998,7 +1136,15 @@ impl Studio {
998 let mods = self.ui.modifiers();1136 let mods = self.ui.modifiers();
999 let mut acts = Vec::new();1137 let mut acts = Vec::new();
1000 for ev in sig.events {1138 for ev in sig.events {
1001 acts.extend(self.spline.input(&mut self.comp, self.playback.current_frame, ev, rect, ptr, mods));1139 acts.extend(self.spline.input_with_history(
1140 &mut self.comp,
1141 Some(&mut self.history),
1142 self.playback.current_frame,
1143 ev,
1144 rect,
1145 ptr,
1146 mods,
1147 ));
1002 }1148 }
1003 for a in acts {1149 for a in acts {
1004 match a {1150 match a {
...@@ -1023,11 +1169,58 @@ impl Studio {...@@ -1023,11 +1169,58 @@ impl Studio {
1023 }1169 }
1024 }1170 }
10251171
1172 if let Some(rect) = self.ui.laid_out(keyframes_canvas_id()) {
1173 self.keyframes.resize([rect[2] - rect[0], rect[3] - rect[1]]);
1174 let sig = self.ui.signal(keyframes_canvas_id());
1175 let ptr = self.ui.last_pointer();
1176 let mods = self.ui.modifiers();
1177 let mut acts = Vec::new();
1178 for ev in sig.events {
1179 acts.extend(self.keyframes.input(
1180 &mut self.comp,
1181 &mut self.history,
1182 self.flow.primary,
1183 ev,
1184 rect,
1185 ptr,
1186 mods,
1187 ));
1188 }
1189 for a in acts {
1190 match a {
1191 KeyframesAction::ScrubFrame(f) => {
1192 if self.playback.set_frame(&self.comp, f, now) {
1193 self.sync_audio(false, true);
1194 for v in &mut self.viewers {
1195 v.dirty = true;
1196 }
1197 }
1198 }
1199 KeyframesAction::SelectNode(id) => {
1200 self.flow.selected.clear();
1201 self.flow.selected.insert(id);
1202 self.flow.primary = Some(id);
1203 self.spline.set_target_node(&self.comp, Some(id));
1204 }
1205 KeyframesAction::KeyframesEdited => {
1206 self.invalidate_node(None);
1207 }
1208 }
1209 }
1210 }
1211
1026 // Immediately re-render any dirty visible viewer before painting this frame!1212 // Immediately re-render any dirty visible viewer before painting this frame!
1213 self.sync_ram_ranges_and_prefetch();
1027 let shown_now = self.dock.at(&mut self.layout, &mut self.seen, &String::clone).shown();1214 let shown_now = self.dock.at(&mut self.layout, &mut self.seen, &String::clone).shown();
1028 for (slot, pane_name) in [(0, "Viewer 1"), (1, "Viewer 2")] {1215 for (slot, pane_name) in [(0, "Viewer 1"), (1, "Viewer 2")] {
1029 if shown_now.contains(&pane_name.to_owned()) && self.viewers[slot].dirty {1216 if shown_now.contains(&pane_name.to_owned()) && self.viewers[slot].dirty {
1030 self.viewers[slot].ensure_rendered(&mut self.engine, &self.comp, self.playback.current_frame, self.scale);1217 self.viewers[slot].ensure_rendered_with_ram(
1218 &mut self.engine,
1219 Some(&self.ram_cache),
1220 &self.comp,
1221 self.playback.current_frame,
1222 self.scale,
1223 );
1031 self.viewers[slot].prepare_hud(&self.comp, &self.engine, &self.playback);1224 self.viewers[slot].prepare_hud(&self.comp, &self.engine, &self.playback);
1032 }1225 }
1033 }1226 }
...@@ -1061,6 +1254,8 @@ impl Studio {...@@ -1061,6 +1254,8 @@ impl Studio {
1061 }1254 }
1062 ViewerAction::BustFrame(f) => {1255 ViewerAction::BustFrame(f) => {
1063 self.engine.bust_frame(f);1256 self.engine.bust_frame(f);
1257 self.ram_cache.clear();
1258 self.last_prefetch_sig = None;
1064 for v in &mut self.viewers {1259 for v in &mut self.viewers {
1065 v.cached_frames.remove(&f);1260 v.cached_frames.remove(&f);
1066 v.dirty = true;1261 v.dirty = true;
...@@ -1070,6 +1265,8 @@ impl Studio {...@@ -1070,6 +1265,8 @@ impl Studio {
1070 if let Some(id) = self.flow.primary.or(self.viewers[slot].viewed_node) {1265 if let Some(id) = self.flow.primary.or(self.viewers[slot].viewed_node) {
1071 self.engine.bust_subtree(id);1266 self.engine.bust_subtree(id);
1072 }1267 }
1268 self.ram_cache.clear();
1269 self.last_prefetch_sig = None;
1073 for v in &mut self.viewers {1270 for v in &mut self.viewers {
1074 v.cached_frames.clear();1271 v.cached_frames.clear();
1075 v.dirty = true;1272 v.dirty = true;
...@@ -1077,6 +1274,8 @@ impl Studio {...@@ -1077,6 +1274,8 @@ impl Studio {
1077 }1274 }
1078 ViewerAction::BustGpu => {1275 ViewerAction::BustGpu => {
1079 self.engine.bust_gpu_cache();1276 self.engine.bust_gpu_cache();
1277 self.ram_cache.clear();
1278 self.last_prefetch_sig = None;
1080 for v in &mut self.viewers {1279 for v in &mut self.viewers {
1081 v.cached_frames.clear();1280 v.cached_frames.clear();
1082 v.dirty = true;1281 v.dirty = true;
...@@ -1084,6 +1283,8 @@ impl Studio {...@@ -1084,6 +1283,8 @@ impl Studio {
1084 }1283 }
1085 ViewerAction::BustAll => {1284 ViewerAction::BustAll => {
1086 self.engine.bust_all_caches();1285 self.engine.bust_all_caches();
1286 self.ram_cache.clear();
1287 self.last_prefetch_sig = None;
1087 for v in &mut self.viewers {1288 for v in &mut self.viewers {
1088 v.cached_frames.clear();1289 v.cached_frames.clear();
1089 v.dirty = true;1290 v.dirty = true;
...@@ -1119,6 +1320,11 @@ impl Studio {...@@ -1119,6 +1320,11 @@ impl Studio {
1119 ViewerAction::ClearViewers => {1320 ViewerAction::ClearViewers => {
1120 self.clear_viewers();1321 self.clear_viewers();
1121 }1322 }
1323 ViewerAction::GizmoEdited(edit) => {
1324 self.history.push_coalesced(&self.comp, edit.label, &edit.coalesce_key);
1325 self.comp.set_input_value(edit.node_id, edit.input, edit.value);
1326 self.invalidate_node(Some(edit.node_id));
1327 }
1122 }1328 }
1123 }1329 }
1124 }1330 }
...@@ -1126,7 +1332,7 @@ impl Studio {...@@ -1126,7 +1332,7 @@ impl Studio {
1126 fn paint(&mut self, target: &wgpu::TextureView, pixels: [u32; 2]) -> Result<(), Box<dyn Error>> {1332 fn paint(&mut self, target: &wgpu::TextureView, pixels: [u32; 2]) -> Result<(), Box<dyn Error>> {
1127 let scale = self.scale;1333 let scale = self.scale;
1128 let cur_f = self.playback.current_frame;1334 let cur_f = self.playback.current_frame;
1129 let Studio { ui, renderer, comp, viewers, flow, spline, .. } = self;1335 let Studio { ui, renderer, comp, viewers, flow, spline, keyframes, .. } = self;
11301336
1131 let mut custom_prims: HashMap<ui::Id, ([f32; 4], [f32; 2], Vec<draw::Primitive<'_>>)> = HashMap::new();1337 let mut custom_prims: HashMap<ui::Id, ([f32; 4], [f32; 2], Vec<draw::Primitive<'_>>)> = HashMap::new();
1132 for slot in [0usize, 1] {1338 for slot in [0usize, 1] {
...@@ -1141,6 +1347,9 @@ impl Studio {...@@ -1141,6 +1347,9 @@ impl Studio {
1141 if let Some(r) = ui.laid_out(spline_canvas_id()) {1347 if let Some(r) = ui.laid_out(spline_canvas_id()) {
1142 custom_prims.insert(spline_canvas_id(), (spline.background(), [r[0], r[1]], spline.paint(comp, cur_f)));1348 custom_prims.insert(spline_canvas_id(), (spline.background(), [r[0], r[1]], spline.paint(comp, cur_f)));
1143 }1349 }
1350 if let Some(r) = ui.laid_out(keyframes_canvas_id()) {
1351 custom_prims.insert(keyframes_canvas_id(), (keyframes.background(), [r[0], r[1]], keyframes.paint(comp, cur_f)));
1352 }
11441353
1145 let interface = ui.layers();1354 let interface = ui.layers();
1146 let layers: Vec<draw::Layer> = interface1355 let layers: Vec<draw::Layer> = interface
...@@ -1184,7 +1393,32 @@ fn run_snapshot(cli: &Cli, out_path: &Path) -> Result<(), Box<dyn Error>> {...@@ -1184,7 +1393,32 @@ fn run_snapshot(cli: &Cli, out_path: &Path) -> Result<(), Box<dyn Error>> {
1184 }))?;1393 }))?;
1185 let renderer = draw::Renderer::new(device, queue, wgpu::TextureFormat::Rgba8Unorm);1394 let renderer = draw::Renderer::new(device, queue, wgpu::TextureFormat::Rgba8Unorm);
11861395
1187 let mut studio = Studio::new(renderer, comp, cli.frame, cli.select_node.as_deref(), cli.dual_viewer, false);1396 let mut studio = Studio::new(
1397 renderer,
1398 comp,
1399 cli.frame,
1400 cli.select_node.as_deref(),
1401 cli.dual_viewer,
1402 cli.show_keyframes,
1403 false,
1404 );
1405 // Load audio waveform peaks if available so snapshot verifies the waveform overlay too
1406 if let Some(af) = studio.comp.audio_filename.clone() {
1407 let p = PathBuf::from(af);
1408 if p.exists() {
1409 if let Ok(track) = AudioTrack::load(&p) {
1410 let peaks = track.waveform_peaks(
1411 studio.comp.fps,
1412 studio.comp.audio_offset,
1413 studio.comp.render_range[0],
1414 studio.comp.render_range[1],
1415 );
1416 studio.viewers[0].audio_peaks = peaks.clone();
1417 studio.keyframes.audio_peaks = peaks;
1418 studio.keyframes.audio_range = studio.comp.render_range;
1419 }
1420 }
1421 }
1188 if cli.open_add_tool {1422 if cli.open_add_tool {
1189 studio.add_tool.open();1423 studio.add_tool.open();
1190 }1424 }
...@@ -1263,6 +1497,7 @@ fn run_window(cli: &Cli) -> Result<(), Box<dyn Error>> {...@@ -1263,6 +1497,7 @@ fn run_window(cli: &Cli) -> Result<(), Box<dyn Error>> {
1263 select_node: cli.select_node.clone(),1497 select_node: cli.select_node.clone(),
1264 dual_viewer: cli.dual_viewer,1498 dual_viewer: cli.dual_viewer,
1265 open_add_tool: cli.open_add_tool,1499 open_add_tool: cli.open_add_tool,
1500 show_keyframes: cli.show_keyframes,
1266 },1501 },
1267 host: None,1502 host: None,
1268 error: None,1503 error: None,
...@@ -1283,7 +1518,15 @@ impl WindowHost {...@@ -1283,7 +1518,15 @@ impl WindowHost {
1283 .with_inner_size(LogicalSize::new(1440.0, 900.0));1518 .with_inner_size(LogicalSize::new(1440.0, 900.0));
1284 let (window, access) = Accessibility::window(event_loop, attrs, [640.0, 420.0], proxy.clone(), ui::Id::ROOT)?;1519 let (window, access) = Accessibility::window(event_loop, attrs, [640.0, 420.0], proxy.clone(), ui::Id::ROOT)?;
1285 let (surface, renderer) = pollster::block_on(Surface::new(window.clone()))?;1520 let (surface, renderer) = pollster::block_on(Surface::new(window.clone()))?;
1286 let mut studio = Studio::new(renderer, comp, cli.frame, cli.select_node.as_deref(), cli.dual_viewer, true);1521 let mut studio = Studio::new(
1522 renderer,
1523 comp,
1524 cli.frame,
1525 cli.select_node.as_deref(),
1526 cli.dual_viewer,
1527 cli.show_keyframes,
1528 true,
1529 );
1287 studio.ui.window_focused = window.has_focus();1530 studio.ui.window_focused = window.has_focus();
1288 studio.ui.clipboard = Clipboard::system();1531 studio.ui.clipboard = Clipboard::system();
1289 window.request_redraw();1532 window.request_redraw();
...@@ -1523,11 +1766,18 @@ impl ApplicationHandler<UserEvent> for App {...@@ -1523,11 +1766,18 @@ impl ApplicationHandler<UserEvent> for App {
15231766
1524 fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {1767 fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
1525 if let Some(host) = &self.host {1768 if let Some(host) = &self.host {
1526 if host.studio.playback.playing && !host.occluded {1769 if !host.occluded {
1527 let wake = host.studio.playback.next_wake(&host.studio.comp);1770 if host.studio.playback.playing {
1528 event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + wake));1771 let wake = host.studio.playback.next_wake(&host.studio.comp);
1529 host.window.request_redraw();1772 event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + wake));
1530 return;1773 host.window.request_redraw();
1774 return;
1775 }
1776 if host.studio.prefetcher.as_ref().is_some_and(RamPrefetcher::is_busy) {
1777 event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(200)));
1778 host.window.request_redraw();
1779 return;
1780 }
1531 }1781 }
1532 }1782 }
1533 event_loop.set_control_flow(ControlFlow::Wait);1783 event_loop.set_control_flow(ControlFlow::Wait);
crates/viewer/src/gizmos.rs created+725
...@@ -0,0 +1,725 @@
1//! Interactive on-screen Viewer gizmos for selected Fusion nodes
2//! (`Transform`, `Merge`, `EllipseMask`, `RectangleMask`, `PolylineMask`).
3
4use draw::Primitive;
5use model::{Comp, ExprEngine, Node, NodeId, ParamValue};
6use std::f32::consts::TAU;
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum GizmoHandle {
10 Center,
11 AxisX,
12 AxisY,
13 Rotate,
14 Scale,
15 Width,
16 Height,
17}
18
19#[derive(Clone, Debug)]
20pub struct GizmoEdit {
21 pub node_id: NodeId,
22 pub input: &'static str,
23 pub value: ParamValue,
24 pub label: &'static str,
25 pub coalesce_key: String,
26}
27
28#[derive(Clone, Debug)]
29pub struct GizmoDrag {
30 pub node_id: NodeId,
31 pub handle: GizmoHandle,
32 pub start_local: [f32; 2],
33 pub start_center: [f64; 2],
34 pub start_size: f64,
35 pub start_angle: f64,
36 pub start_width: f64,
37 pub start_height: f64,
38 pub start_angle_ptr: f64,
39 pub start_dist_px: f32,
40}
41
42pub struct GizmoState {
43 pub enabled: bool,
44 pub hovered: Option<GizmoHandle>,
45 pub drag: Option<GizmoDrag>,
46 expr: ExprEngine,
47}
48
49impl Default for GizmoState {
50 fn default() -> Self {
51 Self::new()
52 }
53}
54
55impl GizmoState {
56 pub fn new() -> Self {
57 Self {
58 enabled: true,
59 hovered: None,
60 drag: None,
61 expr: ExprEngine::new(),
62 }
63 }
64
65 pub fn is_dragging(&self) -> bool {
66 self.drag.is_some()
67 }
68
69 pub fn supports_node(comp: &Comp, node_id: NodeId) -> bool {
70 if node_id.0 >= comp.nodes.len() {
71 return false;
72 }
73 matches!(
74 comp.node(node_id).kind.as_str(),
75 "Transform" | "Merge" | "EllipseMask" | "RectangleMask" | "PolylineMask"
76 )
77 }
78
79 /// Maps Fusion normalized coordinates (`[0..1]`, Y-up) to viewer-local screen pixels.
80 pub fn fu_to_local(fu: [f64; 2], img_rect: [f32; 4]) -> [f32; 2] {
81 let w = (img_rect[2] - img_rect[0]).max(1.0);
82 let h = (img_rect[3] - img_rect[1]).max(1.0);
83 [
84 img_rect[0] + fu[0] as f32 * w,
85 img_rect[3] - fu[1] as f32 * h,
86 ]
87 }
88
89 /// Maps viewer-local screen pixels to Fusion normalized coordinates (`[0..1]`, Y-up).
90 pub fn local_to_fu(pt: [f32; 2], img_rect: [f32; 4]) -> [f64; 2] {
91 let w = (img_rect[2] - img_rect[0]).max(1.0);
92 let h = (img_rect[3] - img_rect[1]).max(1.0);
93 [
94 f64::from((pt[0] - img_rect[0]) / w),
95 f64::from((img_rect[3] - pt[1]) / h),
96 ]
97 }
98
99 fn eval_node_params(&self, comp: &Comp, node: &Node, time: f64) -> NodeGizmoParams {
100 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
101 let size = comp.eval_number(node, "Size", time, 1.0, &self.expr);
102 let angle = comp.eval_number(node, "Angle", time, 0.0, &self.expr);
103 let width = comp.eval_number(node, "Width", time, 0.5, &self.expr);
104 let height = comp.eval_number(node, "Height", time, 0.5, &self.expr);
105 NodeGizmoParams { center, size, angle, width, height }
106 }
107
108 fn handle_positions(&self, comp: &Comp, node: &Node, time: f64, img_rect: [f32; 4]) -> Vec<(GizmoHandle, [f32; 2])> {
109 let p = self.eval_node_params(comp, node, time);
110 let c = Self::fu_to_local(p.center, img_rect);
111 let rad = (p.angle as f32).to_radians();
112 // Fusion CCW angle in Y-up => screen space (Y-down): +X dir is (cos, -sin), +Y dir is (-sin, -cos)
113 let ux = [rad.cos(), -rad.sin()];
114 let uy = [-rad.sin(), -rad.cos()];
115 let img_w = (img_rect[2] - img_rect[0]).max(1.0);
116 let img_h = (img_rect[3] - img_rect[1]).max(1.0);
117
118 match node.kind.as_str() {
119 "Transform" | "Merge" => {
120 let arm = 58.0_f32;
121 let ring_r = 46.0_f32;
122 let diag = (0.7071_f32) * (ring_r + 12.0);
123 vec![
124 (GizmoHandle::AxisX, [c[0] + ux[0] * arm, c[1] + ux[1] * arm]),
125 (GizmoHandle::AxisY, [c[0] + uy[0] * arm, c[1] + uy[1] * arm]),
126 (GizmoHandle::Rotate, [c[0] - uy[0] * ring_r, c[1] - uy[1] * ring_r]),
127 (
128 GizmoHandle::Scale,
129 [
130 c[0] + (ux[0] + uy[0]) * diag,
131 c[1] + (ux[1] + uy[1]) * diag,
132 ],
133 ),
134 (GizmoHandle::Center, c),
135 ]
136 }
137 "EllipseMask" | "RectangleMask" => {
138 let hw = (p.width.abs() as f32 * 0.5 * img_w).max(10.0);
139 let hh = if node.kind == "EllipseMask" {
140 // Fusion EllipseMask: both Width & Height are in frame-width units
141 (p.height.abs() as f32 * 0.5 * img_w).max(10.0)
142 } else {
143 // Fusion RectangleMask: Width in frame-width units, Height in frame-height units
144 (p.height.abs() as f32 * 0.5 * img_h).max(10.0)
145 };
146 vec![
147 (GizmoHandle::Width, [c[0] + ux[0] * hw, c[1] + ux[1] * hw]),
148 (GizmoHandle::Height, [c[0] + uy[0] * hh, c[1] + uy[1] * hh]),
149 (GizmoHandle::Rotate, [c[0] + ux[0] * (hw + 22.0), c[1] + ux[1] * (hw + 22.0)]),
150 (GizmoHandle::Center, c),
151 ]
152 }
153 "PolylineMask" => vec![(GizmoHandle::Center, c)],
154 _ => Vec::new(),
155 }
156 }
157
158 pub fn hit_test(
159 &self,
160 comp: &Comp,
161 node_id: NodeId,
162 time: f64,
163 img_rect: [f32; 4],
164 pointer_local: [f32; 2],
165 ) -> Option<GizmoHandle> {
166 if !self.enabled || !Self::supports_node(comp, node_id) {
167 return None;
168 }
169 let node = comp.node(node_id);
170 let handles = self.handle_positions(comp, node, time, img_rect);
171 let mut best: Option<(f32, GizmoHandle)> = None;
172 for (h, pos) in handles {
173 let d = hypot2(pointer_local, pos);
174 let tol = if h == GizmoHandle::Center { 13.0 } else { 11.0 };
175 if d <= tol && best.is_none_or(|(bd, _)| d < bd) {
176 best = Some((d, h));
177 }
178 }
179 best.map(|(_, h)| h)
180 }
181
182 pub fn update_hover(
183 &mut self,
184 comp: &Comp,
185 node_id: Option<NodeId>,
186 time: f64,
187 img_rect: [f32; 4],
188 pointer_local: [f32; 2],
189 ) {
190 self.hovered = node_id.and_then(|id| self.hit_test(comp, id, time, img_rect, pointer_local));
191 }
192
193 pub fn begin_drag(
194 &mut self,
195 comp: &Comp,
196 node_id: NodeId,
197 time: f64,
198 img_rect: [f32; 4],
199 pointer_local: [f32; 2],
200 ) -> bool {
201 let Some(handle) = self.hit_test(comp, node_id, time, img_rect, pointer_local) else {
202 return false;
203 };
204 let node = comp.node(node_id);
205 let p = self.eval_node_params(comp, node, time);
206 let c = Self::fu_to_local(p.center, img_rect);
207 let dx = f64::from(pointer_local[0] - c[0]);
208 let dy = f64::from(c[1] - pointer_local[1]); // Y-up
209 let start_angle_ptr = dy.atan2(dx).to_degrees();
210 let start_dist_px = hypot2(pointer_local, c).max(8.0);
211 self.drag = Some(GizmoDrag {
212 node_id,
213 handle,
214 start_local: pointer_local,
215 start_center: p.center,
216 start_size: p.size,
217 start_angle: p.angle,
218 start_width: p.width,
219 start_height: p.height,
220 start_angle_ptr,
221 start_dist_px,
222 });
223 true
224 }
225
226 pub fn update_drag(
227 &mut self,
228 comp: &Comp,
229 img_rect: [f32; 4],
230 pointer_local: [f32; 2],
231 fine: bool,
232 ) -> Option<GizmoEdit> {
233 let d = self.drag.as_ref()?;
234 if d.node_id.0 >= comp.nodes.len() {
235 return None;
236 }
237 let kind = comp.node(d.node_id).kind.as_str();
238 let img_w = f64::from((img_rect[2] - img_rect[0]).max(1.0));
239 let img_h = f64::from((img_rect[3] - img_rect[1]).max(1.0));
240 let sens = if fine { 0.2 } else { 1.0 };
241 let c = Self::fu_to_local(d.start_center, img_rect);
242 let dx_px = f64::from(pointer_local[0] - d.start_local[0]) * sens;
243 let dy_px = f64::from(d.start_local[1] - pointer_local[1]) * sens; // Y-up
244
245 match d.handle {
246 GizmoHandle::Center => {
247 let nx = d.start_center[0] + dx_px / img_w;
248 let ny = d.start_center[1] + dy_px / img_h;
249 Some(GizmoEdit {
250 node_id: d.node_id,
251 input: "Center",
252 value: ParamValue::Point([nx, ny]),
253 label: "Move Center",
254 coalesce_key: format!("gizmo:{}:Center", d.node_id.0),
255 })
256 }
257 GizmoHandle::AxisX => {
258 let nx = d.start_center[0] + dx_px / img_w;
259 Some(GizmoEdit {
260 node_id: d.node_id,
261 input: "Center",
262 value: ParamValue::Point([nx, d.start_center[1]]),
263 label: "Move Center X",
264 coalesce_key: format!("gizmo:{}:Center", d.node_id.0),
265 })
266 }
267 GizmoHandle::AxisY => {
268 let ny = d.start_center[1] + dy_px / img_h;
269 Some(GizmoEdit {
270 node_id: d.node_id,
271 input: "Center",
272 value: ParamValue::Point([d.start_center[0], ny]),
273 label: "Move Center Y",
274 coalesce_key: format!("gizmo:{}:Center", d.node_id.0),
275 })
276 }
277 GizmoHandle::Rotate => {
278 let rx = f64::from(pointer_local[0] - c[0]);
279 let ry = f64::from(c[1] - pointer_local[1]);
280 let cur_ang = ry.atan2(rx).to_degrees();
281 let mut delta = cur_ang - d.start_angle_ptr;
282 if delta > 180.0 { delta -= 360.0; }
283 if delta < -180.0 { delta += 360.0; }
284 let new_ang = d.start_angle + delta * sens;
285 Some(GizmoEdit {
286 node_id: d.node_id,
287 input: "Angle",
288 value: ParamValue::Number(new_ang),
289 label: "Rotate Gizmo",
290 coalesce_key: format!("gizmo:{}:Angle", d.node_id.0),
291 })
292 }
293 GizmoHandle::Scale => {
294 let cur_dist = hypot2(pointer_local, c).max(4.0);
295 let ratio = f64::from(cur_dist / d.start_dist_px);
296 let new_size = (d.start_size * (1.0 + (ratio - 1.0) * sens)).clamp(0.01, 20.0);
297 Some(GizmoEdit {
298 node_id: d.node_id,
299 input: "Size",
300 value: ParamValue::Number(new_size),
301 label: "Scale Gizmo",
302 coalesce_key: format!("gizmo:{}:Size", d.node_id.0),
303 })
304 }
305 GizmoHandle::Width => {
306 let rad = d.start_angle.to_radians();
307 let ux = [rad.cos(), -rad.sin()];
308 let rx = f64::from(pointer_local[0] - c[0]);
309 let ry = f64::from(pointer_local[1] - c[1]);
310 let proj = (rx * ux[0] + ry * ux[1]).abs();
311 let new_w = ((proj * 2.0) / img_w).clamp(0.005, 4.0);
312 Some(GizmoEdit {
313 node_id: d.node_id,
314 input: "Width",
315 value: ParamValue::Number(new_w),
316 label: "Resize Mask Width",
317 coalesce_key: format!("gizmo:{}:Width", d.node_id.0),
318 })
319 }
320 GizmoHandle::Height => {
321 let rad = d.start_angle.to_radians();
322 let uy = [-rad.sin(), -rad.cos()];
323 let rx = f64::from(pointer_local[0] - c[0]);
324 let ry = f64::from(pointer_local[1] - c[1]);
325 let proj = (rx * uy[0] + ry * uy[1]).abs();
326 let denom = if kind == "EllipseMask" { img_w } else { img_h };
327 let new_h = ((proj * 2.0) / denom).clamp(0.005, 4.0);
328 Some(GizmoEdit {
329 node_id: d.node_id,
330 input: "Height",
331 value: ParamValue::Number(new_h),
332 label: "Resize Mask Height",
333 coalesce_key: format!("gizmo:{}:Height", d.node_id.0),
334 })
335 }
336 }
337 }
338
339 pub fn end_drag(&mut self) {
340 self.drag = None;
341 }
342
343 pub fn paint<'a>(
344 &self,
345 comp: &Comp,
346 node_id: NodeId,
347 time: f64,
348 img_rect: [f32; 4],
349 vis_rect: [f32; 4],
350 ) -> Vec<Primitive<'a>> {
351 let mut out = Vec::new();
352 if !self.enabled || !Self::supports_node(comp, node_id) {
353 return out;
354 }
355 let node = comp.node(node_id);
356 let p = self.eval_node_params(comp, node, time);
357 let c = Self::fu_to_local(p.center, img_rect);
358 let rad = (p.angle as f32).to_radians();
359 let ux = [rad.cos(), -rad.sin()];
360 let uy = [-rad.sin(), -rad.cos()];
361 let img_w = (img_rect[2] - img_rect[0]).max(1.0);
362 let img_h = (img_rect[3] - img_rect[1]).max(1.0);
363 let active_h = self.drag.as_ref().map(|d| d.handle).or(self.hovered);
364
365 out.push(Primitive::PushClip { rect: vis_rect, radius: 0.0 });
366
367 match node.kind.as_str() {
368 "Transform" | "Merge" => {
369 let arm = 58.0_f32;
370 let ring_r = 46.0_f32;
371 let diag = 0.7071_f32 * (ring_r + 12.0);
372
373 // Subtle rotation ring (28 segments)
374 let ring_col = if active_h == Some(GizmoHandle::Rotate) {
375 [1.0, 0.85, 0.30, 0.95]
376 } else {
377 [0.72, 0.78, 0.96, 0.45]
378 };
379 const SEGS: usize = 28;
380 for i in 0..SEGS {
381 let a0 = (i as f32 / SEGS as f32) * TAU;
382 let a1 = ((i + 1) as f32 / SEGS as f32) * TAU;
383 out.push(Primitive::Segment {
384 from: [c[0] + a0.cos() * ring_r, c[1] + a0.sin() * ring_r],
385 to: [c[0] + a1.cos() * ring_r, c[1] + a1.sin() * ring_r],
386 width: 1.2,
387 color: ring_col,
388 });
389 }
390
391 // X axis arrow (coral red)
392 let px = [c[0] + ux[0] * arm, c[1] + ux[1] * arm];
393 let col_x = if active_h == Some(GizmoHandle::AxisX) {
394 [1.0, 0.50, 0.48, 1.0]
395 } else {
396 [0.95, 0.34, 0.34, 0.92]
397 };
398 out.push(Primitive::Segment { from: c, to: px, width: 1.8, color: col_x });
399 push_handle_dot(&mut out, px, 4.5, col_x, active_h == Some(GizmoHandle::AxisX));
400
401 // Y axis arrow (emerald green)
402 let py = [c[0] + uy[0] * arm, c[1] + uy[1] * arm];
403 let col_y = if active_h == Some(GizmoHandle::AxisY) {
404 [0.48, 1.0, 0.64, 1.0]
405 } else {
406 [0.30, 0.88, 0.48, 0.92]
407 };
408 out.push(Primitive::Segment { from: c, to: py, width: 1.8, color: col_y });
409 push_handle_dot(&mut out, py, 4.5, col_y, active_h == Some(GizmoHandle::AxisY));
410
411 // Rotation knob on bottom of ring
412 let pr = [c[0] - uy[0] * ring_r, c[1] - uy[1] * ring_r];
413 push_handle_dot(
414 &mut out,
415 pr,
416 4.5,
417 [0.58, 0.74, 1.0, 0.95],
418 active_h == Some(GizmoHandle::Rotate),
419 );
420
421 // Scale square handle (NE)
422 let ps = [c[0] + (ux[0] + uy[0]) * diag, c[1] + (ux[1] + uy[1]) * diag];
423 out.push(Primitive::Segment {
424 from: c,
425 to: ps,
426 width: 1.0,
427 color: [0.96, 0.80, 0.32, 0.45],
428 });
429 push_handle_square(
430 &mut out,
431 ps,
432 4.5,
433 [0.98, 0.80, 0.30, 0.95],
434 active_h == Some(GizmoHandle::Scale),
435 );
436
437 // Center crosshair
438 push_center_crosshair(&mut out, c, active_h == Some(GizmoHandle::Center));
439 }
440 "EllipseMask" => {
441 let hw = (p.width.abs() as f32 * 0.5 * img_w).max(4.0);
442 let hh = (p.height.abs() as f32 * 0.5 * img_w).max(4.0);
443 let outline_col = [0.30, 0.92, 0.62, 0.88];
444 const SEGS: usize = 40;
445 for i in 0..SEGS {
446 let a0 = (i as f32 / SEGS as f32) * TAU;
447 let a1 = ((i + 1) as f32 / SEGS as f32) * TAU;
448 let p0 = [
449 c[0] + ux[0] * (a0.cos() * hw) + uy[0] * (a0.sin() * hh),
450 c[1] + ux[1] * (a0.cos() * hw) + uy[1] * (a0.sin() * hh),
451 ];
452 let p1 = [
453 c[0] + ux[0] * (a1.cos() * hw) + uy[0] * (a1.sin() * hh),
454 c[1] + ux[1] * (a1.cos() * hw) + uy[1] * (a1.sin() * hh),
455 ];
456 out.push(Primitive::Segment { from: p0, to: p1, width: 1.5, color: outline_col });
457 }
458 let pw = [c[0] + ux[0] * hw, c[1] + ux[1] * hw];
459 let ph = [c[0] + uy[0] * hh, c[1] + uy[1] * hh];
460 let pr = [c[0] + ux[0] * (hw + 22.0), c[1] + ux[1] * (hw + 22.0)];
461 out.push(Primitive::Segment { from: pw, to: pr, width: 1.1, color: [0.60, 0.80, 1.0, 0.6] });
462 push_handle_square(&mut out, pw, 4.2, outline_col, active_h == Some(GizmoHandle::Width));
463 push_handle_square(&mut out, ph, 4.2, outline_col, active_h == Some(GizmoHandle::Height));
464 push_handle_dot(&mut out, pr, 4.2, [0.58, 0.74, 1.0, 0.95], active_h == Some(GizmoHandle::Rotate));
465 push_center_crosshair(&mut out, c, active_h == Some(GizmoHandle::Center));
466 }
467 "RectangleMask" => {
468 let hw = (p.width.abs() as f32 * 0.5 * img_w).max(4.0);
469 let hh = (p.height.abs() as f32 * 0.5 * img_h).max(4.0);
470 let outline_col = [0.30, 0.92, 0.62, 0.88];
471 let corners = [
472 [c[0] - ux[0] * hw - uy[0] * hh, c[1] - ux[1] * hw - uy[1] * hh],
473 [c[0] + ux[0] * hw - uy[0] * hh, c[1] + ux[1] * hw - uy[1] * hh],
474 [c[0] + ux[0] * hw + uy[0] * hh, c[1] + ux[1] * hw + uy[1] * hh],
475 [c[0] - ux[0] * hw + uy[0] * hh, c[1] - ux[1] * hw + uy[1] * hh],
476 ];
477 for i in 0..4 {
478 out.push(Primitive::Segment {
479 from: corners[i],
480 to: corners[(i + 1) % 4],
481 width: 1.5,
482 color: outline_col,
483 });
484 }
485 let pw = [c[0] + ux[0] * hw, c[1] + ux[1] * hw];
486 let ph = [c[0] + uy[0] * hh, c[1] + uy[1] * hh];
487 let pr = [c[0] + ux[0] * (hw + 22.0), c[1] + ux[1] * (hw + 22.0)];
488 out.push(Primitive::Segment { from: pw, to: pr, width: 1.1, color: [0.60, 0.80, 1.0, 0.6] });
489 push_handle_square(&mut out, pw, 4.2, outline_col, active_h == Some(GizmoHandle::Width));
490 push_handle_square(&mut out, ph, 4.2, outline_col, active_h == Some(GizmoHandle::Height));
491 push_handle_dot(&mut out, pr, 4.2, [0.58, 0.74, 1.0, 0.95], active_h == Some(GizmoHandle::Rotate));
492 push_center_crosshair(&mut out, c, active_h == Some(GizmoHandle::Center));
493 }
494 "PolylineMask" => {
495 let pts = extract_polyline_points(comp, node, time);
496 let poly_col = [0.34, 0.88, 0.98, 0.90];
497 let handle_col = [0.88, 0.56, 0.98, 0.75];
498 if pts.len() >= 2 {
499 for i in 0..pts.len() {
500 let a = &pts[i];
501 let b = &pts[(i + 1) % pts.len()];
502 let p0 = Self::fu_to_local([p.center[0] + a.x, p.center[1] + a.y], img_rect);
503 let p1 = Self::fu_to_local([p.center[0] + a.x + a.rx, p.center[1] + a.y + a.ry], img_rect);
504 let p2 = Self::fu_to_local([p.center[0] + b.x + b.lx, p.center[1] + b.y + b.ly], img_rect);
505 let p3 = Self::fu_to_local([p.center[0] + b.x, p.center[1] + b.y], img_rect);
506 let curved = a.rx.abs() + a.ry.abs() + b.lx.abs() + b.ly.abs() > 1e-5;
507 if curved {
508 let mut prev = p0;
509 for s in 1..=10 {
510 let t = s as f32 / 10.0;
511 let u = 1.0 - t;
512 let cur = [
513 u * u * u * p0[0] + 3.0 * u * u * t * p1[0] + 3.0 * u * t * t * p2[0] + t * t * t * p3[0],
514 u * u * u * p0[1] + 3.0 * u * u * t * p1[1] + 3.0 * u * t * t * p2[1] + t * t * t * p3[1],
515 ];
516 out.push(Primitive::Segment { from: prev, to: cur, width: 1.5, color: poly_col });
517 prev = cur;
518 }
519 } else {
520 out.push(Primitive::Segment { from: p0, to: p3, width: 1.5, color: poly_col });
521 }
522 if a.rx.abs() + a.ry.abs() > 1e-4 {
523 out.push(Primitive::Segment { from: p0, to: p1, width: 1.0, color: handle_col });
524 push_handle_dot(&mut out, p1, 2.8, handle_col, false);
525 }
526 if a.lx.abs() + a.ly.abs() > 1e-4 {
527 let pl = Self::fu_to_local([p.center[0] + a.x + a.lx, p.center[1] + a.y + a.ly], img_rect);
528 out.push(Primitive::Segment { from: p0, to: pl, width: 1.0, color: handle_col });
529 push_handle_dot(&mut out, pl, 2.8, handle_col, false);
530 }
531 push_handle_square(&mut out, p0, 3.4, poly_col, false);
532 }
533 }
534 push_center_crosshair(&mut out, c, active_h == Some(GizmoHandle::Center));
535 }
536 _ => {}
537 }
538
539 out.push(Primitive::PopClip);
540 out
541 }
542}
543
544struct NodeGizmoParams {
545 center: [f64; 2],
546 size: f64,
547 angle: f64,
548 width: f64,
549 height: f64,
550}
551
552fn extract_polyline_points(comp: &Comp, node: &Node, time: f64) -> Vec<model::PolyPoint> {
553 if let Some(src) = node.connected_node("Polyline") {
554 if let Some(pts) = comp.eval_polyline_spline(src, time) {
555 return pts;
556 }
557 if let Some(pp) = comp.poly_paths.get(src) {
558 return pp.points.clone();
559 }
560 }
561 if let Some(pl_tbl) = node
562 .raw
563 .get_table("Inputs")
564 .and_then(|i| i.get_table("Polyline").or_else(|| i.get_table("PolyLine")))
565 .and_then(|p| p.get_table("Value"))
566 {
567 return model::PolyPath::parse_polyline_table(pl_tbl).1;
568 }
569 Vec::new()
570}
571
572fn push_center_crosshair(out: &mut Vec<Primitive<'_>>, c: [f32; 2], hot: bool) {
573 let col = if hot { [1.0, 0.90, 0.35, 1.0] } else { [0.96, 0.96, 0.98, 0.92] };
574 let r = if hot { 8.0 } else { 6.5 };
575 out.push(Primitive::Segment { from: [c[0] - r, c[1]], to: [c[0] + r, c[1]], width: 1.6, color: col });
576 out.push(Primitive::Segment { from: [c[0], c[1] - r], to: [c[0], c[1] + r], width: 1.6, color: col });
577 out.push(Primitive::RoundedRect {
578 rect: [c[0] - 4.5, c[1] - 4.5, c[0] + 4.5, c[1] + 4.5],
579 radius: 4.5,
580 stroke: Some(1.4),
581 color: col,
582 });
583}
584
585fn push_handle_dot(out: &mut Vec<Primitive<'_>>, p: [f32; 2], r: f32, col: [f32; 4], hot: bool) {
586 let rad = if hot { r + 1.5 } else { r };
587 out.push(Primitive::RoundedRect {
588 rect: [p[0] - rad, p[1] - rad, p[0] + rad, p[1] + rad],
589 radius: rad,
590 stroke: None,
591 color: if hot { [1.0, 1.0, 1.0, 1.0] } else { col },
592 });
593 out.push(Primitive::RoundedRect {
594 rect: [p[0] - rad, p[1] - rad, p[0] + rad, p[1] + rad],
595 radius: rad,
596 stroke: Some(1.1),
597 color: [0.05, 0.05, 0.08, 0.9],
598 });
599}
600
601fn push_handle_square(out: &mut Vec<Primitive<'_>>, p: [f32; 2], r: f32, col: [f32; 4], hot: bool) {
602 let rad = if hot { r + 1.4 } else { r };
603 out.push(Primitive::RoundedRect {
604 rect: [p[0] - rad, p[1] - rad, p[0] + rad, p[1] + rad],
605 radius: 1.5,
606 stroke: None,
607 color: if hot { [1.0, 1.0, 1.0, 1.0] } else { col },
608 });
609 out.push(Primitive::RoundedRect {
610 rect: [p[0] - rad, p[1] - rad, p[0] + rad, p[1] + rad],
611 radius: 1.5,
612 stroke: Some(1.1),
613 color: [0.05, 0.05, 0.08, 0.9],
614 });
615}
616
617fn hypot2(a: [f32; 2], b: [f32; 2]) -> f32 {
618 ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)).sqrt()
619}
620
621#[cfg(test)]
622mod tests {
623 use super::*;
624
625 fn sample_gizmo_comp() -> Comp {
626 let src = r#"Composition {
627 CurrentTime = 0,
628 RenderRange = { 0, 100 },
629 GlobalRange = { 0, 100 },
630 Tools = ordered() {
631 XF1 = Transform {
632 Inputs = {
633 Center = Input { Value = { 0.5, 0.5 }, },
634 Size = Input { Value = 1.0, },
635 Angle = Input { Value = 0.0, },
636 },
637 },
638 Ell1 = EllipseMask {
639 Inputs = {
640 Center = Input { Value = { 0.5, 0.5 }, },
641 Width = Input { Value = 0.4, },
642 Height = Input { Value = 0.2, },
643 Angle = Input { Value = 0.0, },
644 },
645 },
646 Rect1 = RectangleMask {
647 Inputs = {
648 Center = Input { Value = { 0.5, 0.5 }, },
649 Width = Input { Value = 0.5, },
650 Height = Input { Value = 0.5, },
651 },
652 },
653 },
654 }"#;
655 Comp::from_fusion_str(src).expect("parse gizmo test comp")
656 }
657
658 #[test]
659 fn fu_to_local_roundtrip_is_exact() {
660 let rect = [100.0, 50.0, 900.0, 500.0]; // 800x450
661 let fu = [0.25, 0.75];
662 let local = GizmoState::fu_to_local(fu, rect);
663 assert!((local[0] - 300.0).abs() < 1e-4);
664 assert!((local[1] - 162.5).abs() < 1e-4);
665 let back = GizmoState::local_to_fu(local, rect);
666 assert!((back[0] - fu[0]).abs() < 1e-5);
667 assert!((back[1] - fu[1]).abs() < 1e-5);
668 }
669
670 #[test]
671 fn transform_gizmo_hit_and_drag_updates_center_and_size() {
672 let comp = sample_gizmo_comp();
673 let xf = comp.find_node("XF1").unwrap();
674 let rect = [0.0, 0.0, 800.0, 450.0];
675 let mut gz = GizmoState::new();
676
677 // Hit center at (400, 225)
678 assert_eq!(gz.hit_test(&comp, xf, 0.0, rect, [400.0, 225.0]), Some(GizmoHandle::Center));
679 assert!(gz.begin_drag(&comp, xf, 0.0, rect, [400.0, 225.0]));
680 let edit = gz.update_drag(&comp, rect, [480.0, 180.0], false).unwrap();
681 assert_eq!(edit.input, "Center");
682 if let ParamValue::Point([x, y]) = edit.value {
683 assert!((x - 0.6).abs() < 1e-4);
684 assert!((y - 0.6).abs() < 1e-4);
685 } else {
686 panic!("expected Point");
687 }
688 gz.end_drag();
689
690 // Hit X-axis handle at (458, 225)
691 assert_eq!(gz.hit_test(&comp, xf, 0.0, rect, [458.0, 225.0]), Some(GizmoHandle::AxisX));
692 assert!(gz.begin_drag(&comp, xf, 0.0, rect, [458.0, 225.0]));
693 let edit_x = gz.update_drag(&comp, rect, [538.0, 100.0], false).unwrap();
694 if let ParamValue::Point([x, y]) = edit_x.value {
695 assert!((x - 0.6).abs() < 1e-4);
696 assert!((y - 0.5).abs() < 1e-4, "AxisX must keep Y locked");
697 } else {
698 panic!("expected Point");
699 }
700 }
701
702 #[test]
703 fn ellipse_and_rectangle_mask_gizmos_respect_fusion_units() {
704 let comp = sample_gizmo_comp();
705 let ell = comp.find_node("Ell1").unwrap();
706 let rect_node = comp.find_node("Rect1").unwrap();
707 let img = [0.0, 0.0, 800.0, 400.0]; // 2:1 aspect
708 let mut gz = GizmoState::new();
709
710 // EllipseMask Height=0.2 in frame-width units -> half_h = 0.1 * 800 = 80px above center (400, 200) -> (400, 120)
711 assert_eq!(gz.hit_test(&comp, ell, 0.0, img, [400.0, 120.0]), Some(GizmoHandle::Height));
712 assert!(gz.begin_drag(&comp, ell, 0.0, img, [400.0, 120.0]));
713 let edit = gz.update_drag(&comp, img, [400.0, 80.0], false).unwrap();
714 assert_eq!(edit.input, "Height");
715 if let ParamValue::Number(h) = edit.value {
716 assert!((h - 0.3).abs() < 1e-4, "expected 0.3, got {h}");
717 } else {
718 panic!("expected Number");
719 }
720 gz.end_drag();
721
722 // RectangleMask Height=0.5 in frame-height units -> half_h = 0.25 * 400 = 100px above center (400, 200) -> (400, 100)
723 assert_eq!(gz.hit_test(&comp, rect_node, 0.0, img, [400.0, 100.0]), Some(GizmoHandle::Height));
724 }
725}
crates/viewer/src/lib.rs+103-2
...@@ -6,8 +6,12 @@...@@ -6,8 +6,12 @@
6//! - Proxy scaling (1:1, 1:2, 1:4) with identical framing & proportions6//! - Proxy scaling (1:1, 1:2, 1:4) with identical framing & proportions
7//! - Surgical cache-busting controls + live GPU telemetry + `Cmd+F` / Numpad `.` fit-to-view.7//! - Surgical cache-busting controls + live GPU telemetry + `Cmd+F` / Numpad `.` fit-to-view.
88
9pub mod gizmos;
10
11pub use gizmos::{GizmoEdit, GizmoHandle, GizmoState};
12
9use draw::{Glyphs, Primitive, RasterImage};13use draw::{Glyphs, Primitive, RasterImage};
10use engine::{CacheMode, DisplaySettings, Engine, EvalStats};14use engine::{CacheMode, DisplaySettings, Engine, EvalStats, RamFrameCache, RamFrameKey};
11use model::{Comp, NodeId};15use model::{Comp, NodeId};
12use std::collections::HashSet;16use std::collections::HashSet;
13use std::sync::Arc;17use std::sync::Arc;
...@@ -141,6 +145,7 @@ pub enum ViewerAction {...@@ -141,6 +145,7 @@ pub enum ViewerAction {
141 SetProxy(u32),145 SetProxy(u32),
142 ToggleHiQ,146 ToggleHiQ,
143 ClearViewers,147 ClearViewers,
148 GizmoEdited(GizmoEdit),
144}149}
145150
146#[derive(Clone, Copy, Debug)]151#[derive(Clone, Copy, Debug)]
...@@ -180,6 +185,10 @@ pub struct ViewerState {...@@ -180,6 +185,10 @@ pub struct ViewerState {
180 pub size: [f32; 2],185 pub size: [f32; 2],
181 pub last_stats: EvalStats,186 pub last_stats: EvalStats,
182 pub cached_frames: HashSet<i64>,187 pub cached_frames: HashSet<i64>,
188 pub ram_cached_ranges: Vec<(i64, i64)>,
189 pub audio_peaks: Vec<f32>,
190 pub selected_node: Option<NodeId>,
191 pub gizmos: GizmoState,
183 pub dirty: bool,192 pub dirty: bool,
184 pub palette: ViewerPalette,193 pub palette: ViewerPalette,
185 last_revision: u64,194 last_revision: u64,
...@@ -207,6 +216,10 @@ impl ViewerState {...@@ -207,6 +216,10 @@ impl ViewerState {
207 size: [800.0, 500.0],216 size: [800.0, 500.0],
208 last_stats: EvalStats::default(),217 last_stats: EvalStats::default(),
209 cached_frames: HashSet::new(),218 cached_frames: HashSet::new(),
219 ram_cached_ranges: Vec::new(),
220 audio_peaks: Vec::new(),
221 selected_node: None,
222 gizmos: GizmoState::new(),
210 dirty: true,223 dirty: true,
211 palette: ViewerPalette::from_ui(theme),224 palette: ViewerPalette::from_ui(theme),
212 last_revision: 0,225 last_revision: 0,
...@@ -310,6 +323,17 @@ impl ViewerState {...@@ -310,6 +323,17 @@ impl ViewerState {
310 }323 }
311324
312 pub fn ensure_rendered(&mut self, engine: &mut Engine, comp: &Comp, current_frame: f64, dpi_scale: f32) {325 pub fn ensure_rendered(&mut self, engine: &mut Engine, comp: &Comp, current_frame: f64, dpi_scale: f32) {
326 self.ensure_rendered_with_ram(engine, None, comp, current_frame, dpi_scale);
327 }
328
329 pub fn ensure_rendered_with_ram(
330 &mut self,
331 engine: &mut Engine,
332 ram_cache: Option<&RamFrameCache>,
333 comp: &Comp,
334 current_frame: f64,
335 dpi_scale: f32,
336 ) {
313 let Some(target) = self.viewed_node else {337 let Some(target) = self.viewed_node else {
314 return;338 return;
315 };339 };
...@@ -360,7 +384,25 @@ impl ViewerState {...@@ -360,7 +384,25 @@ impl ViewerState {
360 if let Some(tex) = &self.output_tex {384 if let Some(tex) = &self.output_tex {
361 let mut disp = self.display;385 let mut disp = self.display;
362 disp.uv_rect = uv_rect;386 disp.uv_rect = uv_rect;
363 self.last_stats = engine.render_into_viewer(comp, target, current_frame, tex, disp);387 let ram_hit = if engine.cache.mode == CacheMode::Enabled {
388 ram_cache.and_then(|rc| {
389 rc.get(RamFrameKey {
390 target,
391 frame: frame_i,
392 revision: comp.revision,
393 proxy_scale: engine.proxy_scale,
394 hiq: engine.hiq,
395 use_proxy_clips: engine.use_proxy_clips,
396 })
397 })
398 } else {
399 None
400 };
401 if let Some(frame) = ram_hit {
402 self.last_stats = engine.render_ram_frame_into_viewer(&frame, tex, disp);
403 } else {
404 self.last_stats = engine.render_into_viewer(comp, target, current_frame, tex, disp);
405 }
364 if engine.cache.mode == CacheMode::Enabled {406 if engine.cache.mode == CacheMode::Enabled {
365 self.cached_frames.insert(frame_i);407 self.cached_frames.insert(frame_i);
366 }408 }
...@@ -511,6 +553,9 @@ impl ViewerState {...@@ -511,6 +553,9 @@ impl ViewerState {
511 if tool_btn(ui, ("fit", self.slot), "Fit", self.fit_mode).clicked {553 if tool_btn(ui, ("fit", self.slot), "Fit", self.fit_mode).clicked {
512 self.fit();554 self.fit();
513 }555 }
556 if tool_btn(ui, ("gizmo", self.slot), "Gizmo", self.gizmos.enabled).clicked {
557 self.gizmos.enabled = !self.gizmos.enabled;
558 }
514559
515 if self.slot == 0 {560 if self.slot == 0 {
516 let bypass_lbl = match engine.cache.mode {561 let bypass_lbl = match engine.cache.mode {
...@@ -624,6 +669,11 @@ impl ViewerState {...@@ -624,6 +669,11 @@ impl ViewerState {
624 self.pointer_local = [p[0] - rect[0], p[1] - rect[1]];669 self.pointer_local = [p[0] - rect[0], p[1] - rect[1]];
625 if self.scrubbing {670 if self.scrubbing {
626 actions.push(ViewerAction::SetFrame(self.frame_at_x(comp, self.pointer_local[0])));671 actions.push(ViewerAction::SetFrame(self.frame_at_x(comp, self.pointer_local[0])));
672 } else if self.gizmos.is_dragging() {
673 let (img_rect, _, _, _) = self.image_layout(comp);
674 if let Some(edit) = self.gizmos.update_drag(comp, img_rect, self.pointer_local, modifiers.shift_key()) {
675 actions.push(ViewerAction::GizmoEdited(edit));
676 }
627 } else if let Some((sp, span)) = self.panning {677 } else if let Some((sp, span)) = self.panning {
628 self.fit_mode = false;678 self.fit_mode = false;
629 self.pan = [679 self.pan = [
...@@ -631,6 +681,9 @@ impl ViewerState {...@@ -631,6 +681,9 @@ impl ViewerState {
631 span[1] + (self.pointer_local[1] - sp[1]),681 span[1] + (self.pointer_local[1] - sp[1]),
632 ];682 ];
633 self.dirty = true;683 self.dirty = true;
684 } else {
685 let (img_rect, _, _, _) = self.image_layout(comp);
686 self.gizmos.update_hover(comp, self.selected_node, clock.current_frame, img_rect, self.pointer_local);
634 }687 }
635 }688 }
636 ui::Event::Button { button, pressed, .. } => {689 ui::Event::Button { button, pressed, .. } => {
...@@ -651,9 +704,13 @@ impl ViewerState {...@@ -651,9 +704,13 @@ impl ViewerState {
651 if self.pointer_local[1] >= scrub[1] - 6.0 {704 if self.pointer_local[1] >= scrub[1] - 6.0 {
652 self.scrubbing = true;705 self.scrubbing = true;
653 actions.push(ViewerAction::SetFrame(self.frame_at_x(comp, self.pointer_local[0])));706 actions.push(ViewerAction::SetFrame(self.frame_at_x(comp, self.pointer_local[0])));
707 } else if let Some(sel) = self.selected_node {
708 let (img_rect, _, _, _) = self.image_layout(comp);
709 self.gizmos.begin_drag(comp, sel, clock.current_frame, img_rect, self.pointer_local);
654 }710 }
655 } else {711 } else {
656 self.scrubbing = false;712 self.scrubbing = false;
713 self.gizmos.end_drag();
657 }714 }
658 }715 }
659 }716 }
...@@ -709,6 +766,9 @@ impl ViewerState {...@@ -709,6 +766,9 @@ impl ViewerState {
709 stroke: Some(1.0),766 stroke: Some(1.0),
710 color: self.palette.border,767 color: self.palette.border,
711 });768 });
769 if let Some(sel) = self.selected_node {
770 out.extend(self.gizmos.paint(comp, sel, current_frame, full_rect, vis));
771 }
712 }772 }
713 }773 }
714 }774 }
...@@ -735,6 +795,47 @@ impl ViewerState {...@@ -735,6 +795,47 @@ impl ViewerState {
735 let span = (r1 - r0).max(1.0);795 let span = (r1 - r0).max(1.0);
736 let bar_w = (sr[2] - sr[0]).max(1.0);796 let bar_w = (sr[2] - sr[0]).max(1.0);
737 let tick_w = (bar_w / span as f32).max(2.0);797 let tick_w = (bar_w / span as f32).max(2.0);
798
799 // Audio waveform overlay across the timeline scrubber
800 if !self.audio_peaks.is_empty() && bar_w > 16.0 {
801 let max_bars = (bar_w / 3.0).floor().clamp(8.0, 480.0) as usize;
802 let n = self.audio_peaks.len();
803 let mid_y = 0.5 * (sr[1] + sr[3] - 3.0);
804 let max_half = ((sr[3] - sr[1] - 5.0) * 0.5).max(1.5);
805 let step_w = bar_w / max_bars as f32;
806 for b in 0..max_bars {
807 let i0 = (b * n) / max_bars;
808 let i1 = (((b + 1) * n) / max_bars).max(i0 + 1).min(n);
809 let mut peak = 0.0_f32;
810 for &v in &self.audio_peaks[i0..i1] {
811 if v > peak { peak = v; }
812 }
813 if peak > 0.015 {
814 let h = (peak * max_half).max(1.0);
815 let x = sr[0] + b as f32 * step_w;
816 out.push(Primitive::Rect {
817 rect: [x, mid_y - h, (x + (step_w - 0.8).max(1.0)).min(sr[2]), mid_y + h],
818 color: [0.46, 0.72, 0.96, 0.36],
819 });
820 }
821 }
822 }
823
824 // Green RAM cache ranges along the bottom of the scrubber
825 for &(c0, c1) in &self.ram_cached_ranges {
826 let f0 = (c0 as f64).max(r0);
827 let f1 = (c1 as f64).min(r1);
828 if f1 < f0 {
829 continue;
830 }
831 let x0 = sr[0] + ((f0 - r0) / span) as f32 * bar_w;
832 let x1 = (sr[0] + ((f1 - r0) / span) as f32 * bar_w + tick_w).min(sr[2]);
833 out.push(Primitive::Rect {
834 rect: [x0, sr[3] - 4.0, x1.max(x0 + 2.0), sr[3] - 1.0],
835 color: [0.22, 0.86, 0.48, 0.92],
836 });
837 }
838 // Individual GPU-cached frames from this session
738 for &cf in &self.cached_frames {839 for &cf in &self.cached_frames {
739 if (cf as f64) >= r0 && (cf as f64) <= r1 {840 if (cf as f64) >= r0 && (cf as f64) <= r1 {
740 let frac = ((cf as f64 - r0) / span) as f32;841 let frac = ((cf as f64 - r0) / span) as f32;