Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Enhance cursor and zoom interpolation, add screen motion blur

Richie McIlroyc91f08cd3e1f
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index c4471b56e..f12d16c94 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -3,10 +3,10 @@ use cap_fail::fail;
use cap_project::CursorMoveEvent;
use cap_project::cursor::SHORT_CURSOR_SHAPE_DEBOUNCE_MS;
use cap_project::{
- CameraShape, CursorClickEvent, InstantRecordingMeta, MultipleSegments, Platform,
- ProjectConfiguration, RecordingMeta, RecordingMetaInner, SharingMeta, StudioRecordingMeta,
- StudioRecordingStatus, TimelineConfiguration, TimelineSegment, UploadMeta, ZoomMode,
- ZoomSegment, cursor::CursorEvents,
+ CameraShape, CursorClickEvent, GlideDirection, InstantRecordingMeta, MultipleSegments,
+ Platform, ProjectConfiguration, RecordingMeta, RecordingMetaInner, SharingMeta,
+ StudioRecordingMeta, StudioRecordingStatus, TimelineConfiguration, TimelineSegment, UploadMeta,
+ ZoomMode, ZoomSegment, cursor::CursorEvents,
};
use cap_recording::feeds::camera::CameraFeedLock;
#[cfg(target_os = "macos")]
@@ -1760,24 +1760,26 @@ fn generate_zoom_segments_from_clicks_impl(
mut moves: Vec<CursorMoveEvent>,
max_duration: f64,
) -> Vec<ZoomSegment> {
- const STOP_PADDING_SECONDS: f64 = 0.8;
- const CLICK_PRE_PADDING: f64 = 0.6;
- const CLICK_POST_PADDING: f64 = 1.6;
- const MOVEMENT_PRE_PADDING: f64 = 0.4;
- const MOVEMENT_POST_PADDING: f64 = 1.2;
- const MERGE_GAP_THRESHOLD: f64 = 0.6;
- const MIN_SEGMENT_DURATION: f64 = 1.3;
- const MOVEMENT_WINDOW_SECONDS: f64 = 1.2;
- const MOVEMENT_EVENT_DISTANCE_THRESHOLD: f64 = 0.025;
- const MOVEMENT_WINDOW_DISTANCE_THRESHOLD: f64 = 0.1;
+ const STOP_PADDING_SECONDS: f64 = 0.5;
+ const CLICK_GROUP_TIME_THRESHOLD_SECS: f64 = 2.5;
+ const CLICK_GROUP_SPATIAL_THRESHOLD: f64 = 0.15;
+ const CLICK_PRE_PADDING: f64 = 0.4;
+ const CLICK_POST_PADDING: f64 = 1.8;
+ const MOVEMENT_PRE_PADDING: f64 = 0.3;
+ const MOVEMENT_POST_PADDING: f64 = 1.5;
+ const MERGE_GAP_THRESHOLD: f64 = 0.8;
+ const MIN_SEGMENT_DURATION: f64 = 1.0;
+ const MOVEMENT_WINDOW_SECONDS: f64 = 1.5;
+ const MOVEMENT_EVENT_DISTANCE_THRESHOLD: f64 = 0.02;
+ const MOVEMENT_WINDOW_DISTANCE_THRESHOLD: f64 = 0.08;
const AUTO_ZOOM_AMOUNT: f64 = 1.5;
+ const SHAKE_FILTER_THRESHOLD: f64 = 0.33;
+ const SHAKE_FILTER_WINDOW_MS: f64 = 150.0;
if max_duration <= 0.0 {
return Vec::new();
}
- // We trim the tail of the recording to avoid using the final
- // "stop recording" click as a zoom target.
let activity_end_limit = if max_duration > STOP_PADDING_SECONDS {
max_duration - STOP_PADDING_SECONDS
} else {
@@ -1799,7 +1801,6 @@ fn generate_zoom_segments_from_clicks_impl(
.unwrap_or(std::cmp::Ordering::Equal)
});
- // Remove trailing click-down events that are too close to the end.
while let Some(index) = clicks.iter().rposition(|c| c.down) {
let time_secs = clicks[index].time_ms / 1000.0;
if time_secs > activity_end_limit {
@@ -1809,16 +1810,78 @@ fn generate_zoom_segments_from_clicks_impl(
}
}
+ let click_positions: HashMap<usize, (f64, f64)> = clicks
+ .iter()
+ .enumerate()
+ .filter(|(_, c)| c.down)
+ .filter_map(|(idx, click)| {
+ let click_time = click.time_ms;
+ moves
+ .iter()
+ .filter(|m| m.time_ms <= click_time)
+ .last()
+ .map(|m| (idx, (m.x, m.y)))
+ })
+ .collect();
+
+ let mut click_groups: Vec<Vec<usize>> = Vec::new();
+ let down_clicks: Vec<(usize, &CursorClickEvent)> = clicks
+ .iter()
+ .enumerate()
+ .filter(|(_, c)| c.down && c.time_ms / 1000.0 < activity_end_limit)
+ .collect();
+
+ for (idx, click) in &down_clicks {
+ let click_time = click.time_ms / 1000.0;
+ let click_pos = click_positions.get(idx);
+
+ let mut found_group = false;
+ for group in click_groups.iter_mut() {
+ let can_join = group.iter().any(|&group_idx| {
+ let group_click = &clicks[group_idx];
+ let group_time = group_click.time_ms / 1000.0;
+ let time_close = (click_time - group_time).abs() < CLICK_GROUP_TIME_THRESHOLD_SECS;
+
+ let spatial_close = match (click_pos, click_positions.get(&group_idx)) {
+ (Some((x1, y1)), Some((x2, y2))) => {
+ let dx = x1 - x2;
+ let dy = y1 - y2;
+ (dx * dx + dy * dy).sqrt() < CLICK_GROUP_SPATIAL_THRESHOLD
+ }
+ _ => true,
+ };
+
+ time_close && spatial_close
+ });
+
+ if can_join {
+ group.push(*idx);
+ found_group = true;
+ break;
+ }
+ }
+
+ if !found_group {
+ click_groups.push(vec![*idx]);
+ }
+ }
+
let mut intervals: Vec<(f64, f64)> = Vec::new();
- for click in clicks.into_iter().filter(|c| c.down) {
- let time = click.time_ms / 1000.0;
- if time >= activity_end_limit {
+ for group in click_groups {
+ if group.is_empty() {
continue;
}
- let start = (time - CLICK_PRE_PADDING).max(0.0);
- let end = (time + CLICK_POST_PADDING).min(activity_end_limit);
+ let times: Vec<f64> = group
+ .iter()
+ .map(|&idx| clicks[idx].time_ms / 1000.0)
+ .collect();
+ let group_start = times.iter().cloned().fold(f64::INFINITY, f64::min);
+ let group_end = times.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
+
+ let start = (group_start - CLICK_PRE_PADDING).max(0.0);
+ let end = (group_end + CLICK_POST_PADDING).min(activity_end_limit);
if end > start {
intervals.push((start, end));
@@ -1828,6 +1891,7 @@ fn generate_zoom_segments_from_clicks_impl(
let mut last_move_by_cursor: HashMap<String, (f64, f64, f64)> = HashMap::new();
let mut distance_window: VecDeque<(f64, f64)> = VecDeque::new();
let mut window_distance = 0.0_f64;
+ let mut shake_window: VecDeque<(f64, f64, f64)> = VecDeque::new();
for mv in moves.iter() {
let time = mv.time_ms / 1000.0;
@@ -1849,6 +1913,40 @@ fn generate_zoom_segments_from_clicks_impl(
continue;
}
+ shake_window.push_back((mv.time_ms, mv.x, mv.y));
+ while let Some(&(old_time, _, _)) = shake_window.front() {
+ if mv.time_ms - old_time > SHAKE_FILTER_WINDOW_MS {
+ shake_window.pop_front();
+ } else {
+ break;
+ }
+ }
+
+ if shake_window.len() >= 3 {
+ let positions: Vec<(f64, f64)> =
+ shake_window.iter().map(|(_, x, y)| (*x, *y)).collect();
+ let mut direction_changes = 0;
+ for i in 1..positions.len() - 1 {
+ let dx1 = positions[i].0 - positions[i - 1].0;
+ let dy1 = positions[i].1 - positions[i - 1].1;
+ let dx2 = positions[i + 1].0 - positions[i].0;
+ let dy2 = positions[i + 1].1 - positions[i].1;
+
+ if (dx1 * dx2 + dy1 * dy2) < 0.0 {
+ direction_changes += 1;
+ }
+ }
+
+ let total_dist: f64 = positions
+ .windows(2)
+ .map(|w| ((w[1].0 - w[0].0).powi(2) + (w[1].1 - w[0].1).powi(2)).sqrt())
+ .sum();
+
+ if direction_changes >= 2 && total_dist < SHAKE_FILTER_THRESHOLD * 3.0 {
+ continue;
+ }
+ }
+
distance_window.push_back((time, distance));
window_distance += distance;
@@ -1910,6 +2008,10 @@ fn generate_zoom_segments_from_clicks_impl(
end,
amount: AUTO_ZOOM_AMOUNT,
mode: ZoomMode::Auto,
+ glide_direction: GlideDirection::None,
+ glide_speed: 0.5,
+ instant_animation: false,
+ edge_snap_ratio: 0.25,
})
})
.collect()
diff --git a/bash.exe.stackdump b/bash.exe.stackdump
deleted file mode 100644
index 9c9810c04..000000000
--- a/bash.exe.stackdump
+++ /dev/null
@@ -1,28 +0,0 @@
-Stack trace:
-Frame Function Args
-0007FFFFB360 00021005FE8E (000210285F68, 00021026AB6E, 000000000000, 0007FFFFA260) msys-2.0.dll+0x1FE8E
-0007FFFFB360 0002100467F9 (000000000000, 000000000000, 000000000000, 0007FFFFB638) msys-2.0.dll+0x67F9
-0007FFFFB360 000210046832 (000210286019, 0007FFFFB218, 000000000000, 000000000000) msys-2.0.dll+0x6832
-0007FFFFB360 000210068CF6 (000000000000, 000000000000, 000000000000, 000000000000) msys-2.0.dll+0x28CF6
-0007FFFFB360 000210068E24 (0007FFFFB370, 000000000000, 000000000000, 000000000000) msys-2.0.dll+0x28E24
-0007FFFFB640 00021006A225 (0007FFFFB370, 000000000000, 000000000000, 000000000000) msys-2.0.dll+0x2A225
-End of stack trace
-Loaded modules:
-000100400000 bash.exe
-7FFE664C0000 ntdll.dll
-7FFE65400000 KERNEL32.DLL
-7FFE63610000 KERNELBASE.dll
-7FFE64260000 USER32.dll
-000210040000 msys-2.0.dll
-7FFE64180000 win32u.dll
-7FFE64EE0000 GDI32.dll
-7FFE63B60000 gdi32full.dll
-7FFE641B0000 msvcp_win.dll
-7FFE63A10000 ucrtbase.dll
-7FFE657E0000 advapi32.dll
-7FFE648D0000 msvcrt.dll
-7FFE65A90000 sechost.dll
-7FFE64DC0000 RPCRT4.dll
-7FFE62C40000 CRYPTBASE.DLL
-7FFE64040000 bcryptPrimitives.dll
-7FFE65600000 IMM32.DLL
diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs
index b81a2da76..0d8c04129 100644
--- a/crates/editor/src/playback.rs
+++ b/crates/editor/src/playback.rs
@@ -4,7 +4,10 @@ use cap_audio::{LatencyCorrectionConfig, LatencyCorrector, default_output_latenc
use cap_media::MediaError;
use cap_media_info::AudioInfo;
use cap_project::{ProjectConfiguration, XY};
-use cap_rendering::{DecodedSegmentFrames, ProjectUniforms, RenderVideoConstants};
+use cap_rendering::{
+ DecodedSegmentFrames, ProjectUniforms, RenderVideoConstants, ZoomFocusInterpolator,
+ spring_mass_damper::SpringMassDamperSimulationConfig,
+};
#[cfg(not(target_os = "windows"))]
use cpal::{BufferSize, SupportedBufferSize};
use cpal::{
@@ -636,6 +639,20 @@ impl Playback {
);
}
+ let cursor_smoothing =
+ (!cached_project.cursor.raw).then_some(SpringMassDamperSimulationConfig {
+ tension: cached_project.cursor.tension,
+ mass: cached_project.cursor.mass,
+ friction: cached_project.cursor.friction,
+ });
+
+ let zoom_focus_interpolator = ZoomFocusInterpolator::new(
+ &segment_media.cursor,
+ cursor_smoothing,
+ cached_project.screen_movement_spring,
+ duration,
+ );
+
let uniforms = ProjectUniforms::new(
&self.render_constants,
&cached_project,
@@ -644,6 +661,8 @@ impl Playback {
resolution_base,
&segment_media.cursor,
&segment_frames,
+ duration,
+ &zoom_focus_interpolator,
);
self.renderer
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index f3883914e..f2f49fbea 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -304,6 +304,8 @@ pub struct Camera {
pub shape: CameraShape,
#[serde(alias = "rounding_type")]
pub rounding_type: CornerStyle,
+ #[serde(default = "Camera::default_scale_during_zoom")]
+ pub scale_during_zoom: f32,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Type, Default)]
@@ -322,6 +324,10 @@ impl Camera {
fn default_rounding() -> f32 {
100.0
}
+
+ fn default_scale_during_zoom() -> f32 {
+ 0.7
+ }
}
impl Default for Camera {
@@ -341,6 +347,7 @@ impl Default for Camera {
}),
shape: CameraShape::Square,
rounding_type: CornerStyle::default(),
+ scale_during_zoom: Self::default_scale_during_zoom(),
}
}
}
@@ -412,18 +419,54 @@ pub struct CursorSmoothingPreset {
pub friction: f32,
}
+#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct ClickSpringConfig {
+ pub tension: f32,
+ pub mass: f32,
+ pub friction: f32,
+}
+
+impl Default for ClickSpringConfig {
+ fn default() -> Self {
+ Self {
+ tension: 700.0,
+ mass: 1.0,
+ friction: 30.0,
+ }
+ }
+}
+
+#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct ScreenMovementSpring {
+ pub stiffness: f32,
+ pub damping: f32,
+ pub mass: f32,
+}
+
+impl Default for ScreenMovementSpring {
+ fn default() -> Self {
+ Self {
+ stiffness: 200.0,
+ damping: 40.0,
+ mass: 2.25,
+ }
+ }
+}
+
impl CursorAnimationStyle {
pub fn preset(self) -> Option<CursorSmoothingPreset> {
match self {
Self::Slow => Some(CursorSmoothingPreset {
- tension: 65.0,
- mass: 1.8,
- friction: 16.0,
+ tension: 200.0,
+ mass: 2.25,
+ friction: 40.0,
}),
Self::Mellow => Some(CursorSmoothingPreset {
- tension: 120.0,
- mass: 1.1,
- friction: 18.0,
+ tension: 470.0,
+ mass: 3.0,
+ friction: 70.0,
}),
Self::Custom => None,
}
@@ -445,6 +488,14 @@ pub struct CursorConfiguration {
pub raw: bool,
pub motion_blur: f32,
pub use_svg: bool,
+ #[serde(default = "CursorConfiguration::default_rotation_amount")]
+ pub rotation_amount: f32,
+ #[serde(default)]
+ pub base_rotation: f32,
+ #[serde(default)]
+ pub click_spring: Option<ClickSpringConfig>,
+ #[serde(default)]
+ pub stop_movement_in_last_seconds: Option<f32>,
}
impl Default for CursorConfiguration {
@@ -454,15 +505,19 @@ impl Default for CursorConfiguration {
hide: false,
hide_when_idle: false,
hide_when_idle_delay: Self::default_hide_when_idle_delay(),
- size: 100,
+ size: 150,
r#type: CursorType::default(),
animation_style,
- tension: 65.0,
- mass: 1.8,
- friction: 16.0,
- raw: true,
+ tension: 470.0,
+ mass: 3.0,
+ friction: 70.0,
+ raw: false,
motion_blur: 0.5,
use_svg: true,
+ rotation_amount: Self::default_rotation_amount(),
+ base_rotation: 0.0,
+ click_spring: None,
+ stop_movement_in_last_seconds: None,
};
if let Some(preset) = animation_style.preset() {
@@ -479,9 +534,17 @@ impl CursorConfiguration {
2.0
}
+ fn default_rotation_amount() -> f32 {
+ 0.5
+ }
+
pub fn cursor_type(&self) -> &CursorType {
&self.r#type
}
+
+ pub fn click_spring_config(&self) -> ClickSpringConfig {
+ self.click_spring.unwrap_or_default()
+ }
}
#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
@@ -515,6 +578,17 @@ impl TimelineSegment {
}
}
+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq, Copy)]
+#[serde(rename_all = "kebab-case")]
+pub enum GlideDirection {
+ #[default]
+ None,
+ Left,
+ Right,
+ Up,
+ Down,
+}
+
#[derive(Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ZoomSegment {
@@ -522,6 +596,24 @@ pub struct ZoomSegment {
pub end: f64,
pub amount: f64,
pub mode: ZoomMode,
+ #[serde(default)]
+ pub glide_direction: GlideDirection,
+ #[serde(default = "ZoomSegment::default_glide_speed")]
+ pub glide_speed: f64,
+ #[serde(default)]
+ pub instant_animation: bool,
+ #[serde(default = "ZoomSegment::default_edge_snap_ratio")]
+ pub edge_snap_ratio: f64,
+}
+
+impl ZoomSegment {
+ fn default_glide_speed() -> f64 {
+ 0.5
+ }
+
+ fn default_edge_snap_ratio() -> f64 {
+ 0.25
+ }
}
#[derive(Type, Serialize, Deserialize, Clone, Debug)]
@@ -995,6 +1087,10 @@ pub struct ProjectConfiguration {
pub annotations: Vec<Annotation>,
#[serde(skip_serializing)]
pub hidden_text_segments: Vec<usize>,
+ #[serde(default = "ProjectConfiguration::default_screen_motion_blur")]
+ pub screen_motion_blur: f32,
+ #[serde(default)]
+ pub screen_movement_spring: ScreenMovementSpring,
}
fn camera_config_needs_migration(value: &Value) -> bool {
@@ -1009,6 +1105,10 @@ fn camera_config_needs_migration(value: &Value) -> bool {
}
impl ProjectConfiguration {
+ fn default_screen_motion_blur() -> f32 {
+ 0.5
+ }
+
pub fn validate(&self) -> Result<(), AnnotationValidationError> {
for annotation in &self.annotations {
annotation.validate()?;
diff --git a/crates/rendering/src/cursor_interpolation.rs b/crates/rendering/src/cursor_interpolation.rs
index 9482050d2..74bd7646c 100644
--- a/crates/rendering/src/cursor_interpolation.rs
+++ b/crates/rendering/src/cursor_interpolation.rs
@@ -1,6 +1,6 @@
use std::borrow::Cow;
-use cap_project::{CursorClickEvent, CursorEvents, CursorMoveEvent, XY};
+use cap_project::{ClickSpringConfig, CursorClickEvent, CursorEvents, CursorMoveEvent, XY};
use crate::{
Coord, RawDisplayUVSpace,
@@ -9,6 +9,8 @@ use crate::{
const CLICK_REACTION_WINDOW_MS: f64 = 160.0;
const MIN_MASS: f32 = 0.1;
+const SHAKE_THRESHOLD_UV: f64 = 0.015;
+const SHAKE_DETECTION_WINDOW_MS: f64 = 100.0;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum SpringProfile {
@@ -24,11 +26,26 @@ struct CursorSpringPresets {
}
impl CursorSpringPresets {
- fn new(base: SpringMassDamperSimulationConfig) -> Self {
+ fn new(
+ base: SpringMassDamperSimulationConfig,
+ click_spring: Option<ClickSpringConfig>,
+ ) -> Self {
+ let snappy = click_spring
+ .map(|c| SpringMassDamperSimulationConfig {
+ tension: c.tension,
+ mass: c.mass,
+ friction: c.friction,
+ })
+ .unwrap_or(SpringMassDamperSimulationConfig {
+ tension: 700.0,
+ mass: 1.0,
+ friction: 30.0,
+ });
+
Self {
default: base,
- snappy: scale_config(base, 1.65, 0.65, 1.25),
- drag: scale_config(base, 1.25, 0.85, 1.1),
+ snappy,
+ drag: scale_config(base, 0.8, 1.2, 1.3),
}
}
@@ -112,6 +129,15 @@ pub fn interpolate_cursor(
cursor: &CursorEvents,
time_secs: f32,
smoothing: Option<SpringMassDamperSimulationConfig>,
+) -> Option<InterpolatedCursorPosition> {
+ interpolate_cursor_with_click_spring(cursor, time_secs, smoothing, None)
+}
+
+pub fn interpolate_cursor_with_click_spring(
+ cursor: &CursorEvents,
+ time_secs: f32,
+ smoothing: Option<SpringMassDamperSimulationConfig>,
+ click_spring: Option<ClickSpringConfig>,
) -> Option<InterpolatedCursorPosition> {
let time_ms = (time_secs * 1000.0) as f64;
@@ -146,8 +172,14 @@ pub fn interpolate_cursor(
}
if let Some(smoothing_config) = smoothing {
- let prepared_moves = densify_cursor_moves(&cursor.moves);
- let events = get_smoothed_cursor_events(cursor, prepared_moves.as_ref(), smoothing_config);
+ let filtered_moves = filter_cursor_shake(&cursor.moves);
+ let prepared_moves = densify_cursor_moves(filtered_moves.as_ref());
+ let events = get_smoothed_cursor_events_with_click_spring(
+ cursor,
+ prepared_moves.as_ref(),
+ smoothing_config,
+ click_spring,
+ );
interpolate_smoothed_position(&events, time_secs as f64, smoothing_config)
} else {
let (pos, cursor_id, velocity) = cursor.moves.windows(2).find_map(|chunk| {
@@ -178,37 +210,45 @@ pub fn interpolate_cursor(
}
}
+#[allow(dead_code)]
fn get_smoothed_cursor_events(
cursor: &CursorEvents,
moves: &[CursorMoveEvent],
smoothing_config: SpringMassDamperSimulationConfig,
+) -> Vec<SmoothedCursorEvent> {
+ get_smoothed_cursor_events_with_click_spring(cursor, moves, smoothing_config, None)
+}
+
+fn get_smoothed_cursor_events_with_click_spring(
+ cursor: &CursorEvents,
+ moves: &[CursorMoveEvent],
+ smoothing_config: SpringMassDamperSimulationConfig,
+ click_spring: Option<ClickSpringConfig>,
) -> Vec<SmoothedCursorEvent> {
let mut last_time = 0.0;
let mut events = vec![];
let mut sim = SpringMassDamperSimulation::new(smoothing_config);
- let presets = CursorSpringPresets::new(smoothing_config);
+ let presets = CursorSpringPresets::new(smoothing_config, click_spring);
let mut context = CursorSpringContext::new(&cursor.clicks);
sim.set_position(XY::new(moves[0].x, moves[0].y).map(|v| v as f32));
sim.set_velocity(XY::new(0.0, 0.0));
+ sim.set_target_position(sim.position);
if moves[0].time_ms > 0.0 {
events.push(SmoothedCursorEvent {
time: 0.0,
- target_position: sim.position,
+ target_position: sim.target_position,
position: sim.position,
velocity: sim.velocity,
cursor_id: moves[0].cursor_id.clone(),
})
}
- for (i, m) in moves.iter().enumerate() {
- let target_position = moves
- .get(i + 1)
- .map(|e| XY::new(e.x, e.y).map(|v| v as f32))
- .unwrap_or(sim.target_position);
+ for m in moves.iter() {
+ let target_position = XY::new(m.x, m.y).map(|v| v as f32);
sim.set_target_position(target_position);
context.advance_to(m.time_ms);
@@ -219,10 +259,15 @@ fn get_smoothed_cursor_events(
last_time = m.time_ms as f32;
+ let clamped_position = XY::new(
+ sim.position.x.clamp(0.0, 1.0),
+ sim.position.y.clamp(0.0, 1.0),
+ );
+
events.push(SmoothedCursorEvent {
time: m.time_ms as f32,
target_position,
- position: sim.position,
+ position: clamped_position,
velocity: sim.velocity,
cursor_id: m.cursor_id.clone(),
});
@@ -265,8 +310,13 @@ fn interpolate_smoothed_position(
}
};
+ let clamped_position = XY::new(
+ sim.position.x.clamp(0.0, 1.0) as f64,
+ sim.position.y.clamp(0.0, 1.0) as f64,
+ );
+
Some(InterpolatedCursorPosition {
- position: Coord::new(sim.position.map(|v| v as f64)),
+ position: Coord::new(clamped_position),
velocity: sim.velocity,
cursor_id,
})
@@ -277,6 +327,64 @@ const GAP_INTERPOLATION_THRESHOLD_MS: f64 = CURSOR_FRAME_DURATION_MS * 4.0;
const MIN_CURSOR_TRAVEL_FOR_INTERPOLATION: f64 = 0.02;
const MAX_INTERPOLATED_STEPS: usize = 120;
+fn filter_cursor_shake<'a>(moves: &'a [CursorMoveEvent]) -> Cow<'a, [CursorMoveEvent]> {
+ if moves.len() < 3 {
+ return Cow::Borrowed(moves);
+ }
+
+ let mut filtered = Vec::with_capacity(moves.len());
+ filtered.push(moves[0].clone());
+
+ let mut i = 1;
+ while i < moves.len() - 1 {
+ let prev = filtered.last().unwrap();
+ let curr = &moves[i];
+ let next = &moves[i + 1];
+
+ if curr.cursor_id != prev.cursor_id || curr.cursor_id != next.cursor_id {
+ filtered.push(curr.clone());
+ i += 1;
+ continue;
+ }
+
+ let time_window = next.time_ms - prev.time_ms;
+ if time_window > SHAKE_DETECTION_WINDOW_MS {
+ filtered.push(curr.clone());
+ i += 1;
+ continue;
+ }
+
+ let dir_to_curr = (curr.x - prev.x, curr.y - prev.y);
+ let dir_to_next = (next.x - curr.x, next.y - curr.y);
+
+ let dot = dir_to_curr.0 * dir_to_next.0 + dir_to_curr.1 * dir_to_next.1;
+ let is_reversal = dot < 0.0;
+
+ let displacement_curr = (dir_to_curr.0.powi(2) + dir_to_curr.1.powi(2)).sqrt();
+ let displacement_next = (dir_to_next.0.powi(2) + dir_to_next.1.powi(2)).sqrt();
+ let is_small_movement =
+ displacement_curr < SHAKE_THRESHOLD_UV && displacement_next < SHAKE_THRESHOLD_UV;
+
+ if is_reversal && is_small_movement {
+ i += 1;
+ continue;
+ }
+
+ filtered.push(curr.clone());
+ i += 1;
+ }
+
+ if moves.len() > 1 {
+ filtered.push(moves.last().unwrap().clone());
+ }
+
+ if filtered.len() == moves.len() {
+ return Cow::Borrowed(moves);
+ }
+
+ Cow::Owned(filtered)
+}
+
fn densify_cursor_moves<'a>(moves: &'a [CursorMoveEvent]) -> Cow<'a, [CursorMoveEvent]> {
if moves.len() < 2 {
return Cow::Borrowed(moves);
diff --git a/crates/rendering/src/decoder/multi_position.rs b/crates/rendering/src/decoder/multi_position.rs
index 698dcb2a4..f9aac22c8 100644
--- a/crates/rendering/src/decoder/multi_position.rs
+++ b/crates/rendering/src/decoder/multi_position.rs
@@ -4,8 +4,31 @@ use tokio::runtime::Handle as TokioHandle;
use cap_video_decode::avassetreader::KeyframeIndex;
-pub const MAX_DECODER_POOL_SIZE: usize = 3;
-pub const REPOSITION_THRESHOLD_SECS: f32 = 2.5;
+pub const BASE_DECODER_POOL_SIZE: usize = 5;
+pub const MAX_DECODER_POOL_SIZE: usize = 8;
+pub const BASE_REPOSITION_THRESHOLD_SECS: f32 = 5.0;
+pub const LONG_VIDEO_THRESHOLD_SECS: f64 = 600.0;
+pub const VERY_LONG_VIDEO_THRESHOLD_SECS: f64 = 1800.0;
+
+pub fn calculate_optimal_pool_size(duration_secs: f64) -> usize {
+ if duration_secs >= VERY_LONG_VIDEO_THRESHOLD_SECS {
+ MAX_DECODER_POOL_SIZE
+ } else if duration_secs >= LONG_VIDEO_THRESHOLD_SECS {
+ BASE_DECODER_POOL_SIZE + 2
+ } else {
+ BASE_DECODER_POOL_SIZE
+ }
+}
+
+pub fn calculate_reposition_threshold(duration_secs: f64) -> f32 {
+ if duration_secs >= VERY_LONG_VIDEO_THRESHOLD_SECS {
+ 10.0
+ } else if duration_secs >= LONG_VIDEO_THRESHOLD_SECS {
+ 7.0
+ } else {
+ BASE_REPOSITION_THRESHOLD_SECS
+ }
+}
pub struct DecoderPosition {
pub id: usize,
@@ -43,11 +66,15 @@ pub struct DecoderPoolManager {
positions: Vec<DecoderPosition>,
access_history: BTreeMap<u32, u64>,
total_accesses: u64,
+ reposition_threshold: f32,
+ optimal_pool_size: usize,
}
impl DecoderPoolManager {
pub fn new(config: MultiPositionDecoderConfig) -> Self {
- let initial_positions = Self::calculate_initial_positions(&config);
+ let optimal_pool_size = calculate_optimal_pool_size(config.duration_secs);
+ let reposition_threshold = calculate_reposition_threshold(config.duration_secs);
+ let initial_positions = Self::calculate_initial_positions(&config, optimal_pool_size);
let positions: Vec<DecoderPosition> = initial_positions
.into_iter()
@@ -55,26 +82,38 @@ impl DecoderPoolManager {
.map(|(id, pos)| DecoderPosition::new(id, pos))
.collect();
+ tracing::info!(
+ duration_secs = config.duration_secs,
+ optimal_pool_size = optimal_pool_size,
+ reposition_threshold = reposition_threshold,
+ "Configured decoder pool for video duration"
+ );
+
Self {
config,
positions,
access_history: BTreeMap::new(),
total_accesses: 0,
+ reposition_threshold,
+ optimal_pool_size,
}
}
- fn calculate_initial_positions(config: &MultiPositionDecoderConfig) -> Vec<f32> {
+ fn calculate_initial_positions(
+ config: &MultiPositionDecoderConfig,
+ pool_size: usize,
+ ) -> Vec<f32> {
if let Some(ref kf_index) = config.keyframe_index {
- let strategic = kf_index.get_strategic_positions(MAX_DECODER_POOL_SIZE);
+ let strategic = kf_index.get_strategic_positions(pool_size);
strategic.into_iter().map(|t| t as f32).collect()
} else {
let duration = config.duration_secs as f32;
if duration <= 0.0 {
vec![0.0]
} else {
- (0..MAX_DECODER_POOL_SIZE)
+ (0..pool_size)
.map(|i| {
- let frac = i as f32 / MAX_DECODER_POOL_SIZE as f32;
+ let frac = i as f32 / pool_size as f32;
(duration * frac).min(duration)
})
.collect()
@@ -82,6 +121,14 @@ impl DecoderPoolManager {
}
}
+ pub fn optimal_pool_size(&self) -> usize {
+ self.optimal_pool_size
+ }
+
+ pub fn reposition_threshold(&self) -> f32 {
+ self.reposition_threshold
+ }
+
pub fn find_best_decoder_for_time(&mut self, requested_time: f32) -> (usize, f32, bool) {
self.total_accesses += 1;
@@ -95,7 +142,7 @@ impl DecoderPoolManager {
for position in &self.positions {
let distance = (position.position_secs - requested_time).abs();
let is_usable = position.position_secs <= requested_time
- && (requested_time - position.position_secs) < REPOSITION_THRESHOLD_SECS;
+ && (requested_time - position.position_secs) < self.reposition_threshold;
if is_usable && distance < best_distance {
best_distance = distance;
@@ -145,13 +192,13 @@ impl DecoderPoolManager {
let top_hotspots: Vec<f32> = hotspots
.into_iter()
- .take(MAX_DECODER_POOL_SIZE)
+ .take(self.optimal_pool_size)
.map(|(frame, _)| frame as f32 / self.config.fps as f32)
.collect();
- if top_hotspots.len() < MAX_DECODER_POOL_SIZE {
+ if top_hotspots.len() < self.optimal_pool_size {
let mut result = top_hotspots;
- let remaining = MAX_DECODER_POOL_SIZE - result.len();
+ let remaining = self.optimal_pool_size - result.len();
let duration = self.config.duration_secs as f32;
for i in 0..remaining {
let frac = (i + 1) as f32 / (remaining + 1) as f32;
@@ -178,11 +225,13 @@ pub struct ScrubDetector {
request_rate: f64,
is_scrubbing: bool,
scrub_start_time: Option<std::time::Instant>,
+ last_frame_delta: u32,
}
impl ScrubDetector {
- const SCRUB_THRESHOLD_RATE: f64 = 5.0;
- const SCRUB_COOLDOWN_MS: u64 = 150;
+ const SCRUB_FRAME_JUMP_THRESHOLD: u32 = 5;
+ const SCRUB_COOLDOWN_MS: u64 = 100;
+ const SEQUENTIAL_PLAYBACK_THRESHOLD: u32 = 2;
pub fn new() -> Self {
Self {
@@ -191,6 +240,7 @@ impl ScrubDetector {
request_rate: 0.0,
is_scrubbing: false,
scrub_start_time: None,
+ last_frame_delta: 0,
}
}
@@ -200,13 +250,15 @@ impl ScrubDetector {
let elapsed_secs = elapsed.as_secs_f64().max(0.001);
let frame_delta = frame.abs_diff(self.last_frame);
+ self.last_frame_delta = frame_delta;
let instantaneous_rate = frame_delta as f64 / elapsed_secs;
self.request_rate = self.request_rate * 0.7 + instantaneous_rate * 0.3;
- let _was_scrubbing = self.is_scrubbing;
-
- if self.request_rate > Self::SCRUB_THRESHOLD_RATE && frame_delta > 1 {
+ if frame_delta <= Self::SEQUENTIAL_PLAYBACK_THRESHOLD {
+ self.is_scrubbing = false;
+ self.scrub_start_time = None;
+ } else if frame_delta >= Self::SCRUB_FRAME_JUMP_THRESHOLD {
self.is_scrubbing = true;
if self.scrub_start_time.is_none() {
self.scrub_start_time = Some(now);
@@ -226,6 +278,18 @@ impl ScrubDetector {
self.is_scrubbing
}
+ pub fn request_rate(&self) -> f64 {
+ self.request_rate
+ }
+
+ pub fn last_frame(&self) -> u32 {
+ self.last_frame
+ }
+
+ pub fn last_frame_delta(&self) -> u32 {
+ self.last_frame_delta
+ }
+
pub fn scrub_duration(&self) -> Option<std::time::Duration> {
self.scrub_start_time.map(|start| start.elapsed())
}
@@ -236,3 +300,72 @@ impl Default for ScrubDetector {
Self::new()
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_calculate_optimal_pool_size_short_video() {
+ assert_eq!(calculate_optimal_pool_size(60.0), BASE_DECODER_POOL_SIZE);
+ assert_eq!(calculate_optimal_pool_size(300.0), BASE_DECODER_POOL_SIZE);
+ assert_eq!(calculate_optimal_pool_size(599.0), BASE_DECODER_POOL_SIZE);
+ }
+
+ #[test]
+ fn test_calculate_optimal_pool_size_long_video() {
+ assert_eq!(
+ calculate_optimal_pool_size(600.0),
+ BASE_DECODER_POOL_SIZE + 2
+ );
+ assert_eq!(
+ calculate_optimal_pool_size(1200.0),
+ BASE_DECODER_POOL_SIZE + 2
+ );
+ assert_eq!(
+ calculate_optimal_pool_size(1799.0),
+ BASE_DECODER_POOL_SIZE + 2
+ );
+ }
+
+ #[test]
+ fn test_calculate_optimal_pool_size_very_long_video() {
+ assert_eq!(calculate_optimal_pool_size(1800.0), MAX_DECODER_POOL_SIZE);
+ assert_eq!(calculate_optimal_pool_size(3600.0), MAX_DECODER_POOL_SIZE);
+ assert_eq!(calculate_optimal_pool_size(7200.0), MAX_DECODER_POOL_SIZE);
+ }
+
+ #[test]
+ fn test_calculate_reposition_threshold_short_video() {
+ assert_eq!(
+ calculate_reposition_threshold(60.0),
+ BASE_REPOSITION_THRESHOLD_SECS
+ );
+ assert_eq!(
+ calculate_reposition_threshold(300.0),
+ BASE_REPOSITION_THRESHOLD_SECS
+ );
+ }
+
+ #[test]
+ fn test_calculate_reposition_threshold_long_video() {
+ assert_eq!(calculate_reposition_threshold(600.0), 7.0);
+ assert_eq!(calculate_reposition_threshold(1200.0), 7.0);
+ }
+
+ #[test]
+ fn test_calculate_reposition_threshold_very_long_video() {
+ assert_eq!(calculate_reposition_threshold(1800.0), 10.0);
+ assert_eq!(calculate_reposition_threshold(3600.0), 10.0);
+ }
+
+ #[test]
+ fn test_55_minute_video_gets_max_decoders() {
+ let duration_55_min = 55.0 * 60.0;
+ assert_eq!(
+ calculate_optimal_pool_size(duration_55_min),
+ MAX_DECODER_POOL_SIZE
+ );
+ assert_eq!(calculate_reposition_threshold(duration_55_min), 10.0);
+ }
+}
diff --git a/crates/rendering/src/layers/cursor.rs b/crates/rendering/src/layers/cursor.rs
index 10274197e..4ed98b0dd 100644
--- a/crates/rendering/src/layers/cursor.rs
+++ b/crates/rendering/src/layers/cursor.rs
@@ -22,6 +22,7 @@ const CURSOR_MIN_MOTION_PX: f32 = 1.0;
const CURSOR_BASELINE_FPS: f32 = 60.0;
const CURSOR_MULTIPLIER: f32 = 3.0;
const CURSOR_MAX_STRENGTH: f32 = 5.0;
+const VELOCITY_BLEND_RATIO: f32 = 0.7;
/// The size to render the svg to.
static SVG_CURSOR_RASTERIZED_HEIGHT: u32 = 200;
@@ -268,21 +269,35 @@ impl CursorLayer {
let cursor_strength = (uniforms.motion_blur_amount * CURSOR_MULTIPLIER * fps_scale)
.clamp(0.0, CURSOR_MAX_STRENGTH);
let parent_motion = uniforms.display_parent_motion_px;
- let child_motion = uniforms
- .prev_cursor
- .as_ref()
- .filter(|prev| prev.cursor_id == interpolated_cursor.cursor_id)
- .map(|prev| {
- let delta_uv = XY::new(
- (interpolated_cursor.position.coord.x - prev.position.coord.x) as f32,
- (interpolated_cursor.position.coord.y - prev.position.coord.y) as f32,
- );
- XY::new(
- delta_uv.x * screen_size.x as f32,
- delta_uv.y * screen_size.y as f32,
- )
- })
- .unwrap_or_else(|| XY::new(0.0, 0.0));
+ let child_motion = {
+ let delta_motion = uniforms
+ .prev_cursor
+ .as_ref()
+ .filter(|prev| prev.cursor_id == interpolated_cursor.cursor_id)
+ .map(|prev| {
+ let delta_uv = XY::new(
+ (interpolated_cursor.position.coord.x - prev.position.coord.x) as f32,
+ (interpolated_cursor.position.coord.y - prev.position.coord.y) as f32,
+ );
+ XY::new(
+ delta_uv.x * screen_size.x as f32,
+ delta_uv.y * screen_size.y as f32,
+ )
+ })
+ .unwrap_or_else(|| XY::new(0.0, 0.0));
+
+ let spring_velocity = XY::new(
+ interpolated_cursor.velocity.x * screen_size.x as f32 / fps,
+ interpolated_cursor.velocity.y * screen_size.y as f32 / fps,
+ );
+
+ XY::new(
+ delta_motion.x * (1.0 - VELOCITY_BLEND_RATIO)
+ + spring_velocity.x * VELOCITY_BLEND_RATIO,
+ delta_motion.y * (1.0 - VELOCITY_BLEND_RATIO)
+ + spring_velocity.y * VELOCITY_BLEND_RATIO,
+ )
+ };
let combined_motion_px = if cursor_strength <= f32::EPSILON {
XY::new(0.0, 0.0)
@@ -478,6 +493,12 @@ impl CursorLayer {
effective_strength,
cursor_opacity,
],
+ rotation_params: [
+ uniforms.project.cursor.rotation_amount,
+ uniforms.project.cursor.base_rotation,
+ 0.0,
+ 0.0,
+ ],
};
constants.queue.write_buffer(
@@ -535,6 +556,7 @@ pub struct CursorUniforms {
output_size: [f32; 4],
screen_bounds: [f32; 4],
motion_vector_strength: [f32; 4],
+ rotation_params: [f32; 4],
}
fn compute_cursor_idle_opacity(
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 52d5687ea..bd98ec812 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -34,10 +34,11 @@ mod layers;
mod mask;
mod project_recordings;
mod scene;
-mod spring_mass_damper;
+pub mod spring_mass_damper;
mod text;
pub mod yuv_converter;
mod zoom;
+pub mod zoom_focus_interpolation;
pub use coord::*;
pub use decoder::{DecodedFrame, DecoderStatus, DecoderType, PixelFormat};
@@ -48,6 +49,7 @@ use mask::interpolate_masks;
use scene::*;
use text::{PreparedText, prepare_texts};
use zoom::*;
+pub use zoom_focus_interpolation::ZoomFocusInterpolator;
const STANDARD_CURSOR_HEIGHT: f32 = 75.0;
@@ -260,6 +262,27 @@ pub async fn render_video_to_channel(
let total_frames = (fps as f64 * duration).ceil() as u32;
+ let cursor_smoothing =
+ (!project.cursor.raw).then_some(spring_mass_damper::SpringMassDamperSimulationConfig {
+ tension: project.cursor.tension,
+ mass: project.cursor.mass,
+ friction: project.cursor.friction,
+ });
+
+ let zoom_focus_interpolators: Vec<ZoomFocusInterpolator> = render_segments
+ .iter()
+ .map(|segment| {
+ let mut interp = ZoomFocusInterpolator::new(
+ &segment.cursor,
+ cursor_smoothing,
+ project.screen_movement_spring,
+ duration,
+ );
+ interp.precompute();
+ interp
+ })
+ .collect();
+
let mut frame_number = 0;
let mut frame_renderer = FrameRenderer::new(constants);
@@ -272,7 +295,7 @@ pub async fn render_video_to_channel(
let mut last_successful_frame: Option<RenderedFrame> = None;
let mut consecutive_failures = 0u32;
- const MAX_CONSECUTIVE_FAILURES: u32 = 30;
+ const MAX_CONSECUTIVE_FAILURES: u32 = 200;
loop {
if frame_number >= total_frames {
@@ -299,11 +322,12 @@ pub async fn render_video_to_channel(
let mut segment_frames = None;
let mut retry_count = 0;
- const MAX_RETRIES: u32 = 3;
+ const MAX_RETRIES: u32 = 5;
while segment_frames.is_none() && retry_count < MAX_RETRIES {
if retry_count > 0 {
- tokio::time::sleep(std::time::Duration::from_millis(50 * retry_count as u64)).await;
+ tokio::time::sleep(std::time::Duration::from_millis(100 * retry_count as u64))
+ .await;
}
segment_frames = render_segment
@@ -331,6 +355,8 @@ pub async fn render_video_to_channel(
let frame = if let Some(segment_frames) = segment_frames {
consecutive_failures = 0;
+ let zoom_focus_interp = &zoom_focus_interpolators[segment.recording_clip as usize];
+
let uniforms = ProjectUniforms::new(
constants,
project,
@@ -339,6 +365,8 @@ pub async fn render_video_to_channel(
resolution_base,
&render_segment.cursor,
&segment_frames,
+ duration,
+ zoom_focus_interp,
);
match frame_renderer
@@ -1059,10 +1087,11 @@ impl ProjectUniforms {
zoom: &InterpolatedZoom,
scene: &InterpolatedScene,
base_size: f32,
- zoom_size: f32,
+ scale_during_zoom: f32,
) -> f32 {
let t = zoom.t as f32;
- let lerp = t * zoom_size * base_size + (1.0 - t) * base_size;
+ let zoomed_size = base_size * scale_during_zoom;
+ let lerp = t * zoomed_size + (1.0 - t) * base_size;
lerp * scene.camera_scale as f32
}
@@ -1080,6 +1109,7 @@ impl ProjectUniforms {
resolve_motion_descriptor(&analysis, base_amount, CAMERA_MULTIPLIER, CAMERA_MULTIPLIER)
}
+ #[allow(dead_code)]
fn auto_zoom_focus(
cursor_events: &CursorEvents,
time_secs: f32,
@@ -1186,6 +1216,8 @@ impl ProjectUniforms {
resolution_base: XY<u32>,
cursor_events: &CursorEvents,
segment_frames: &DecodedSegmentFrames,
+ total_duration: f64,
+ zoom_focus_interpolator: &ZoomFocusInterpolator,
) -> Self {
let options = &constants.options;
let output_size = Self::get_output_size(options, project, resolution_base);
@@ -1198,9 +1230,28 @@ impl ProjectUniforms {
};
let current_recording_time = segment_frames.recording_time;
let prev_recording_time = (segment_frames.recording_time - 1.0 / fps_f32).max(0.0);
- let user_motion_blur = project.cursor.motion_blur.clamp(0.0, 1.0);
+
+ let cursor_stop_time = project
+ .cursor
+ .stop_movement_in_last_seconds
+ .map(|seconds| (total_duration - seconds as f64).max(0.0) as f32);
+
+ let cursor_time_for_interp = if let Some(stop_time) = cursor_stop_time {
+ current_recording_time.min(stop_time)
+ } else {
+ current_recording_time
+ };
+
+ let prev_cursor_time_for_interp = if let Some(stop_time) = cursor_stop_time {
+ prev_recording_time.min(stop_time)
+ } else {
+ prev_recording_time
+ };
+
+ let cursor_motion_blur = project.cursor.motion_blur.clamp(0.0, 1.0);
+ let screen_motion_blur = project.screen_motion_blur.clamp(0.0, 1.0);
let has_previous = frame_number > 0;
- let normalized_motion = normalized_motion_amount(user_motion_blur, fps_f32);
+ let normalized_screen_motion = normalized_motion_amount(screen_motion_blur, fps_f32);
let crop = Self::get_crop(options, project);
@@ -1211,10 +1262,10 @@ impl ProjectUniforms {
});
let interpolated_cursor =
- interpolate_cursor(cursor_events, current_recording_time, cursor_smoothing);
+ interpolate_cursor(cursor_events, cursor_time_for_interp, cursor_smoothing);
let prev_interpolated_cursor =
- interpolate_cursor(cursor_events, prev_recording_time, cursor_smoothing);
+ interpolate_cursor(cursor_events, prev_cursor_time_for_interp, cursor_smoothing);
let zoom_segments = project
.timeline
@@ -1228,28 +1279,28 @@ impl ProjectUniforms {
.map(|t| t.scene_segments.as_slice())
.unwrap_or(&[]);
- let zoom_focus = Self::auto_zoom_focus(
- cursor_events,
- current_recording_time,
- cursor_smoothing,
- interpolated_cursor.clone(),
- );
+ let zoom_focus = zoom_focus_interpolator.interpolate(current_recording_time);
- let prev_zoom_focus = Self::auto_zoom_focus(
- cursor_events,
- prev_recording_time,
- cursor_smoothing,
- prev_interpolated_cursor.clone(),
- );
+ let prev_zoom_focus = zoom_focus_interpolator.interpolate(prev_recording_time);
+
+ let actual_cursor_coord = interpolated_cursor
+ .as_ref()
+ .map(|c| Coord::<RawDisplayUVSpace>::new(c.position.coord));
+
+ let prev_actual_cursor_coord = prev_interpolated_cursor
+ .as_ref()
+ .map(|c| Coord::<RawDisplayUVSpace>::new(c.position.coord));
- let zoom = InterpolatedZoom::new(
+ let zoom = InterpolatedZoom::new_with_cursor(
SegmentsCursor::new(frame_time as f64, zoom_segments),
zoom_focus,
+ actual_cursor_coord,
);
- let prev_zoom = InterpolatedZoom::new(
+ let prev_zoom = InterpolatedZoom::new_with_cursor(
SegmentsCursor::new(prev_frame_time as f64, zoom_segments),
prev_zoom_focus,
+ prev_actual_cursor_coord,
);
let scene =
@@ -1288,7 +1339,7 @@ impl ProjectUniforms {
MotionBounds::new(start, end),
MotionBounds::new(prev_start, prev_end),
has_previous,
- normalized_motion,
+ normalized_screen_motion,
scene_blur_strength,
);
let descriptor = display_motion.descriptor;
@@ -1375,15 +1426,12 @@ impl ProjectUniforms {
let camera_padding = CAMERA_PADDING * resolution_scale;
let base_size = project.camera.size / 100.0;
- let zoom_size = project
- .camera
- .zoom_size
- .unwrap_or(cap_project::Camera::default_zoom_size())
- / 100.0;
+ let scale_during_zoom = project.camera.scale_during_zoom;
- let zoomed_size = Self::camera_zoom_factor(&zoom, &scene, base_size, zoom_size);
+ let zoomed_size =
+ Self::camera_zoom_factor(&zoom, &scene, base_size, scale_during_zoom);
let prev_zoomed_size =
- Self::camera_zoom_factor(&prev_zoom, &prev_scene, base_size, zoom_size);
+ Self::camera_zoom_factor(&prev_zoom, &prev_scene, base_size, scale_during_zoom);
let aspect = frame_size[0] / frame_size[1];
let camera_size_for = |scale: f32| match project.camera.shape {
@@ -1460,7 +1508,7 @@ impl ProjectUniforms {
current_bounds,
prev_bounds,
has_previous,
- normalized_motion,
+ normalized_screen_motion,
);
let crop_bounds = match project.camera.shape {
@@ -1644,7 +1692,7 @@ impl ProjectUniforms {
frame_number,
prev_cursor: prev_interpolated_cursor,
display_parent_motion_px: display_motion_parent,
- motion_blur_amount: user_motion_blur,
+ motion_blur_amount: cursor_motion_blur,
masks,
texts,
}
diff --git a/crates/rendering/src/shaders/cursor.wgsl b/crates/rendering/src/shaders/cursor.wgsl
index 2b058c537..1e880b27b 100644
--- a/crates/rendering/src/shaders/cursor.wgsl
+++ b/crates/rendering/src/shaders/cursor.wgsl
@@ -8,6 +8,7 @@ struct Uniforms {
output_size: vec4<f32>,
screen_bounds: vec4<f32>,
motion_vector_strength: vec4<f32>,
+ rotation_params: vec4<f32>,
};
@group(0) @binding(0)
@@ -19,6 +20,19 @@ var t_cursor: texture_2d<f32>;
@group(0) @binding(2)
var s_cursor: sampler;
+const MAX_ROTATION_RADIANS: f32 = 0.25;
+const ROTATION_VELOCITY_SCALE: f32 = 0.003;
+
+fn rotate_point(p: vec2<f32>, center: vec2<f32>, angle: f32) -> vec2<f32> {
+ let cos_a = cos(angle);
+ let sin_a = sin(angle);
+ let translated = p - center;
+ return vec2<f32>(
+ translated.x * cos_a - translated.y * sin_a,
+ translated.x * sin_a + translated.y * cos_a
+ ) + center;
+}
+
@vertex
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
var positions = array<vec2<f32>, 4>(
@@ -39,12 +53,21 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
let screen_pos = uniforms.position_size.xy;
let cursor_size = uniforms.position_size.zw;
- // Calculate final position - centered around cursor position
- // Flip the Y coordinate by subtracting from output height
+ let rotation_amount = uniforms.rotation_params.x;
+ let base_rotation = uniforms.rotation_params.y;
+
+ let motion_x = uniforms.motion_vector_strength.x;
+ let normalized_velocity = clamp(motion_x * ROTATION_VELOCITY_SCALE, -1.0, 1.0);
+ let velocity_rotation = normalized_velocity * MAX_ROTATION_RADIANS * rotation_amount;
+ let rotation_angle = velocity_rotation + base_rotation;
+
+ let pivot = vec2<f32>(0.0, 0.0);
+ let rotated_pos = rotate_point(pos, pivot, rotation_angle);
+
var adjusted_pos = screen_pos;
- adjusted_pos.y = uniforms.output_size.y - adjusted_pos.y; // Flip Y coordinate
+ adjusted_pos.y = uniforms.output_size.y - adjusted_pos.y;
- let final_pos = ((pos * cursor_size) + adjusted_pos) / uniforms.output_size.xy * 2.0 - 1.0;
+ let final_pos = ((rotated_pos * cursor_size) + adjusted_pos) / uniforms.output_size.xy * 2.0 - 1.0;
var output: VertexOutput;
output.position = vec4<f32>(final_pos, 0.0, 1.0);
@@ -54,41 +77,60 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
@fragment
fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
- // Increase samples for higher quality blur
- let num_samples = 20;
- let base_sample = textureSample(t_cursor, s_cursor, input.uv);
- var color_sum = base_sample;
- var weight_sum = 1.0;
-
- // Calculate velocity magnitude for adaptive blur strength
let motion_vec = uniforms.motion_vector_strength.xy;
let blur_strength = uniforms.motion_vector_strength.z;
let opacity = uniforms.motion_vector_strength.w;
let motion_len = length(motion_vec);
- if (motion_len < 1e-4 || blur_strength < 0.001) {
+ if (motion_len < 0.5 || blur_strength < 0.001) {
return textureSample(t_cursor, s_cursor, input.uv) * opacity;
}
- let direction = motion_vec / motion_len;
- let max_offset = motion_len;
+ let cursor_size = uniforms.position_size.zw;
+ let blur_offset_uv = motion_vec * 0.45 / cursor_size;
+ let blur_len = length(blur_offset_uv);
- for (var i = 1; i < num_samples; i++) {
+ if (blur_len < 0.005) {
+ return textureSample(t_cursor, s_cursor, input.uv) * opacity;
+ }
+
+ let num_samples = 24;
+ var color_sum = vec4<f32>(0.0);
+ var alpha_sum = 0.0;
+ var weight_sum = 0.0;
+
+ let blur_center = 0.3;
+ let blur_spread = 2.5;
+
+ for (var i = 0; i < num_samples; i++) {
let t = f32(i) / f32(num_samples - 1);
- let eased = smoothstep(0.0, 1.0, t);
- let offset = direction * (max_offset * blur_strength) * eased;
- let sample_uv = input.uv + offset / uniforms.output_size.xy;
+ let centered_t = t - blur_center;
+ let sample_offset = blur_offset_uv * centered_t;
+ let sample_uv = input.uv + sample_offset;
- // Sample with bilinear filtering
- let sample = textureSample(t_cursor, s_cursor, sample_uv);
+ let gauss_t = centered_t * blur_spread;
+ var weight = exp(-gauss_t * gauss_t);
- // Accumulate weighted sample
- let weight = 1.0 - t * 0.75;
- color_sum += sample * weight;
+ if (centered_t > 0.0) {
+ weight *= 1.0 + centered_t * 0.3;
+ }
+
+ let sample_color = textureSample(t_cursor, s_cursor, sample_uv);
+ let premul_rgb = sample_color.rgb * sample_color.a;
+ color_sum += vec4<f32>(premul_rgb * weight, 0.0);
+ alpha_sum += sample_color.a * weight;
weight_sum += weight;
}
- var final_color = color_sum / weight_sum;
+ let avg_alpha = alpha_sum / max(weight_sum, 0.001);
+ var final_color: vec4<f32>;
+ if (avg_alpha > 0.001) {
+ let final_rgb = color_sum.rgb / max(alpha_sum, 0.001);
+ final_color = vec4<f32>(final_rgb, avg_alpha);
+ } else {
+ final_color = vec4<f32>(0.0);
+ }
+
final_color *= opacity;
return final_color;
}
diff --git a/crates/rendering/src/spring_mass_damper.rs b/crates/rendering/src/spring_mass_damper.rs
index c4c1e2ee4..bfcf81c5b 100644
--- a/crates/rendering/src/spring_mass_damper.rs
+++ b/crates/rendering/src/spring_mass_damper.rs
@@ -16,7 +16,59 @@ pub struct SpringMassDamperSimulation {
pub target_position: XY<f32>,
}
-const SIMULATION_TICK_MS: f32 = 1000.0 / 60.0;
+const REST_VELOCITY_THRESHOLD: f32 = 0.0001;
+const REST_DISPLACEMENT_THRESHOLD: f32 = 0.00001;
+
+fn solve_spring_1d(displacement: f32, velocity: f32, t: f32, omega0: f32, zeta: f32) -> (f32, f32) {
+ if zeta < 1.0 - 1e-6 {
+ let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
+ let decay = (-zeta * omega0 * t).exp();
+ let cos_term = (omega_d * t).cos();
+ let sin_term = (omega_d * t).sin();
+
+ let a = displacement;
+ let b = (velocity + displacement * zeta * omega0) / omega_d.max(1e-6);
+
+ let new_disp = decay * (a * cos_term + b * sin_term);
+ let new_vel = decay
+ * ((b * omega_d - a * zeta * omega0) * cos_term
+ - (a * omega_d + b * zeta * omega0) * sin_term);
+
+ (new_disp, new_vel)
+ } else if zeta > 1.0 + 1e-6 {
+ let sqrt_term = (zeta * zeta - 1.0).sqrt();
+ let s1 = -omega0 * (zeta - sqrt_term);
+ let s2 = -omega0 * (zeta + sqrt_term);
+ let denom = s1 - s2;
+
+ if denom.abs() < 1e-10 {
+ let decay = (-omega0 * t).exp();
+ let new_disp = decay * (displacement + (velocity + displacement * omega0) * t);
+ let new_vel = decay * (velocity - omega0 * displacement);
+ (new_disp, new_vel)
+ } else {
+ let c1 = (velocity - displacement * s2) / denom;
+ let c2 = displacement - c1;
+
+ let e1 = (s1 * t).exp();
+ let e2 = (s2 * t).exp();
+
+ let new_disp = c1 * e1 + c2 * e2;
+ let new_vel = c1 * s1 * e1 + c2 * s2 * e2;
+
+ (new_disp, new_vel)
+ }
+ } else {
+ let decay = (-omega0 * t).exp();
+ let a = displacement;
+ let b = velocity + displacement * omega0;
+
+ let new_disp = decay * (a + b * t);
+ let new_vel = decay * (b - omega0 * (a + b * t));
+
+ (new_disp, new_vel)
+ }
+}
impl SpringMassDamperSimulation {
pub fn new(config: SpringMassDamperSimulationConfig) -> Self {
@@ -51,24 +103,32 @@ impl SpringMassDamperSimulation {
return self.position;
}
- let mut remaining = dt_ms;
+ let t = dt_ms / 1000.0;
+ let mass = self.mass.max(0.001);
+ let stiffness = self.tension;
+ let damping = self.friction;
- while remaining > 0.0 {
- let step_ms = remaining.min(SIMULATION_TICK_MS);
- let tick = step_ms / 1000.0;
- let d = self.target_position - self.position;
- let spring_force = d * self.tension;
+ let omega0 = (stiffness / mass).sqrt();
+ let zeta = damping / (2.0 * (stiffness * mass).sqrt());
- let damping_force = self.velocity * -self.friction;
+ let disp_x = self.position.x - self.target_position.x;
+ let disp_y = self.position.y - self.target_position.y;
- let total_force = spring_force + damping_force;
+ let (new_disp_x, new_vel_x) = solve_spring_1d(disp_x, self.velocity.x, t, omega0, zeta);
+ let (new_disp_y, new_vel_y) = solve_spring_1d(disp_y, self.velocity.y, t, omega0, zeta);
- let accel = total_force / self.mass.max(0.001);
+ self.position = XY::new(
+ self.target_position.x + new_disp_x,
+ self.target_position.y + new_disp_y,
+ );
+ self.velocity = XY::new(new_vel_x, new_vel_y);
- self.velocity = self.velocity + accel * tick;
- self.position = self.position + self.velocity * tick;
+ let disp_mag = (new_disp_x * new_disp_x + new_disp_y * new_disp_y).sqrt();
+ let vel_mag = (new_vel_x * new_vel_x + new_vel_y * new_vel_y).sqrt();
- remaining -= step_ms;
+ if disp_mag < REST_DISPLACEMENT_THRESHOLD && vel_mag < REST_VELOCITY_THRESHOLD {
+ self.position = self.target_position;
+ self.velocity = XY::new(0.0, 0.0);
}
self.position
diff --git a/crates/rendering/src/zoom.rs b/crates/rendering/src/zoom.rs
index 47f59a9fd..2ae4c33ba 100644
--- a/crates/rendering/src/zoom.rs
+++ b/crates/rendering/src/zoom.rs
@@ -4,6 +4,10 @@ use crate::{Coord, RawDisplayUVSpace};
pub const ZOOM_DURATION: f64 = 1.0;
+const SCREEN_SPRING_STIFFNESS: f64 = 200.0;
+const SCREEN_SPRING_DAMPING: f64 = 40.0;
+const SCREEN_SPRING_MASS: f64 = 2.25;
+
#[derive(Debug, Clone, Copy)]
pub struct SegmentsCursor<'a> {
time: f64,
@@ -52,24 +56,151 @@ pub struct SegmentBounds {
}
impl SegmentBounds {
- fn from_segment(segment: &ZoomSegment, interpolated_cursor: Coord<RawDisplayUVSpace>) -> Self {
- let position = match segment.mode {
- cap_project::ZoomMode::Auto => (interpolated_cursor.x, interpolated_cursor.y),
+ pub fn from_segment_with_cursor_constraint(
+ segment: &ZoomSegment,
+ zoom_focus: Coord<RawDisplayUVSpace>,
+ actual_cursor: Option<Coord<RawDisplayUVSpace>>,
+ ) -> Self {
+ let is_auto_mode = matches!(segment.mode, cap_project::ZoomMode::Auto);
+
+ let focus_pos = match segment.mode {
+ cap_project::ZoomMode::Auto => (zoom_focus.x, zoom_focus.y),
cap_project::ZoomMode::Manual { x, y } => (x as f64, y as f64),
};
- let scaled_center = [position.0 * segment.amount, position.1 * segment.amount];
- let center_diff = [scaled_center[0] - position.0, scaled_center[1] - position.1];
+ let (effective_zoom, viewport_center) = if is_auto_mode {
+ if let Some(cursor) = actual_cursor {
+ Self::calculate_zoom_and_center_for_cursor(
+ focus_pos,
+ (cursor.x, cursor.y),
+ segment.amount,
+ segment.edge_snap_ratio,
+ )
+ } else {
+ let center = Self::calculate_follow_center(
+ focus_pos,
+ segment.amount,
+ segment.edge_snap_ratio,
+ );
+ (segment.amount, center)
+ }
+ } else {
+ (segment.amount, focus_pos)
+ };
+
+ let scaled_center = [
+ viewport_center.0 * effective_zoom,
+ viewport_center.1 * effective_zoom,
+ ];
+ let center_diff = [
+ scaled_center[0] - viewport_center.0,
+ scaled_center[1] - viewport_center.1,
+ ];
SegmentBounds::new(
XY::new(0.0 - center_diff[0], 0.0 - center_diff[1]),
XY::new(
- segment.amount - center_diff[0],
- segment.amount - center_diff[1],
+ effective_zoom - center_diff[0],
+ effective_zoom - center_diff[1],
),
)
}
+ fn calculate_follow_center(
+ cursor_pos: (f64, f64),
+ zoom_amount: f64,
+ _edge_snap_ratio: f64,
+ ) -> (f64, f64) {
+ let viewport_half = 0.5 / zoom_amount;
+
+ let min_center = viewport_half;
+ let max_center = 1.0 - viewport_half;
+
+ (
+ cursor_pos.0.clamp(min_center, max_center),
+ cursor_pos.1.clamp(min_center, max_center),
+ )
+ }
+
+ fn calculate_zoom_and_center_for_cursor(
+ focus_pos: (f64, f64),
+ cursor_pos: (f64, f64),
+ target_zoom: f64,
+ _edge_snap_ratio: f64,
+ ) -> (f64, (f64, f64)) {
+ let viewport_half = 0.5 / target_zoom;
+ let min_center = viewport_half;
+ let max_center = 1.0 - viewport_half;
+
+ let mut center = (
+ focus_pos.0.clamp(min_center, max_center),
+ focus_pos.1.clamp(min_center, max_center),
+ );
+
+ let viewport_left = center.0 - viewport_half;
+ let viewport_right = center.0 + viewport_half;
+ let viewport_top = center.1 - viewport_half;
+ let viewport_bottom = center.1 + viewport_half;
+
+ let cursor_visible = cursor_pos.0 >= viewport_left
+ && cursor_pos.0 <= viewport_right
+ && cursor_pos.1 >= viewport_top
+ && cursor_pos.1 <= viewport_bottom;
+
+ if cursor_visible {
+ return (target_zoom, center);
+ }
+
+ if cursor_pos.0 < viewport_left {
+ center.0 = (cursor_pos.0 + viewport_half).clamp(min_center, max_center);
+ } else if cursor_pos.0 > viewport_right {
+ center.0 = (cursor_pos.0 - viewport_half).clamp(min_center, max_center);
+ }
+
+ if cursor_pos.1 < viewport_top {
+ center.1 = (cursor_pos.1 + viewport_half).clamp(min_center, max_center);
+ } else if cursor_pos.1 > viewport_bottom {
+ center.1 = (cursor_pos.1 - viewport_half).clamp(min_center, max_center);
+ }
+
+ let new_viewport_left = center.0 - viewport_half;
+ let new_viewport_right = center.0 + viewport_half;
+ let new_viewport_top = center.1 - viewport_half;
+ let new_viewport_bottom = center.1 + viewport_half;
+
+ let cursor_still_visible = cursor_pos.0 >= new_viewport_left
+ && cursor_pos.0 <= new_viewport_right
+ && cursor_pos.1 >= new_viewport_top
+ && cursor_pos.1 <= new_viewport_bottom;
+
+ if cursor_still_visible {
+ return (target_zoom, center);
+ }
+
+ let required_zoom = Self::minimum_zoom_to_show_cursor(cursor_pos);
+ let effective_zoom = target_zoom.min(required_zoom).max(1.0);
+
+ let new_viewport_half = 0.5 / effective_zoom;
+ let new_min_center = new_viewport_half;
+ let new_max_center = 1.0 - new_viewport_half;
+
+ let final_center = (
+ cursor_pos.0.clamp(new_min_center, new_max_center),
+ cursor_pos.1.clamp(new_min_center, new_max_center),
+ );
+
+ (effective_zoom, final_center)
+ }
+
+ fn minimum_zoom_to_show_cursor(cursor_pos: (f64, f64)) -> f64 {
+ let dist_from_edge_x = cursor_pos.0.min(1.0 - cursor_pos.0).max(0.001);
+ let dist_from_edge_y = cursor_pos.1.min(1.0 - cursor_pos.1).max(0.001);
+
+ let min_dist = dist_from_edge_x.min(dist_from_edge_y);
+
+ (0.5 / min_dist).max(1.0)
+ }
+
pub fn new(top_left: XY<f64>, bottom_right: XY<f64>) -> Self {
Self {
top_left,
@@ -89,27 +220,104 @@ pub struct InterpolatedZoom {
pub bounds: SegmentBounds,
}
+fn spring_ease(t: f32) -> f32 {
+ if t <= 0.0 {
+ return 0.0;
+ }
+ if t >= 1.0 {
+ return 1.0;
+ }
+
+ let omega0 = (SCREEN_SPRING_STIFFNESS / SCREEN_SPRING_MASS).sqrt() as f32;
+ let zeta = (SCREEN_SPRING_DAMPING
+ / (2.0 * (SCREEN_SPRING_STIFFNESS * SCREEN_SPRING_MASS).sqrt())) as f32;
+
+ if zeta < 1.0 {
+ let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
+ let decay = (-zeta * omega0 * t).exp();
+ 1.0 - decay * ((omega_d * t).cos() + (zeta * omega0 / omega_d) * (omega_d * t).sin())
+ } else {
+ let decay = (-omega0 * t).exp();
+ 1.0 - decay * (1.0 + omega0 * t)
+ }
+}
+
+fn spring_ease_out(t: f32) -> f32 {
+ if t <= 0.0 {
+ return 0.0;
+ }
+ if t >= 1.0 {
+ return 1.0;
+ }
+
+ let omega0 = (SCREEN_SPRING_STIFFNESS / SCREEN_SPRING_MASS).sqrt() as f32 * 0.9;
+ let zeta = (SCREEN_SPRING_DAMPING
+ / (2.0 * (SCREEN_SPRING_STIFFNESS * SCREEN_SPRING_MASS).sqrt())) as f32
+ * 1.15;
+
+ if zeta < 1.0 {
+ let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
+ let decay = (-zeta * omega0 * t).exp();
+ 1.0 - decay * ((omega_d * t).cos() + (zeta * omega0 / omega_d) * (omega_d * t).sin())
+ } else {
+ let decay = (-omega0 * t).exp();
+ 1.0 - decay * (1.0 + omega0 * t)
+ }
+}
+
+fn instant_ease(t: f32) -> f32 {
+ if t <= 0.0 { 0.0 } else { 1.0 }
+}
+
impl InterpolatedZoom {
pub fn new(cursor: SegmentsCursor, interpolated_cursor: Coord<RawDisplayUVSpace>) -> Self {
- let ease_in = bezier_easing::bezier_easing(0.1, 0.0, 0.3, 1.0).unwrap();
- let ease_out = bezier_easing::bezier_easing(0.5, 0.0, 0.5, 1.0).unwrap();
+ Self::new_with_cursor(cursor, interpolated_cursor, None)
+ }
- Self::new_with_easing(cursor, interpolated_cursor, ease_in, ease_out)
+ pub fn new_with_cursor(
+ cursor: SegmentsCursor,
+ zoom_focus: Coord<RawDisplayUVSpace>,
+ actual_cursor: Option<Coord<RawDisplayUVSpace>>,
+ ) -> Self {
+ let use_instant = cursor.segment.map(|s| s.instant_animation).unwrap_or(false);
+ if use_instant {
+ Self::new_with_easing_and_cursor(
+ cursor,
+ zoom_focus,
+ actual_cursor,
+ instant_ease,
+ instant_ease,
+ )
+ } else {
+ Self::new_with_easing_and_cursor(
+ cursor,
+ zoom_focus,
+ actual_cursor,
+ spring_ease,
+ spring_ease_out,
+ )
+ }
}
- // the multiplier applied to the display width/height
pub fn display_amount(&self) -> f64 {
(self.bounds.bottom_right - self.bounds.top_left).x
}
- pub(self) fn new_with_easing(
+ fn new_with_easing_and_cursor(
cursor: SegmentsCursor,
- interpolated_cursor: Coord<RawDisplayUVSpace>,
- ease_in: impl Fn(f32) -> f32,
- ease_out: impl Fn(f32) -> f32,
+ zoom_focus: Coord<RawDisplayUVSpace>,
+ actual_cursor: Option<Coord<RawDisplayUVSpace>>,
+ ease_in: impl Fn(f32) -> f32 + Copy,
+ ease_out: impl Fn(f32) -> f32 + Copy,
) -> InterpolatedZoom {
let default = SegmentBounds::default();
- match (cursor.prev_segment, cursor.segment) {
+ let is_auto_mode = cursor
+ .segment
+ .or(cursor.prev_segment)
+ .map(|s| matches!(s.mode, cap_project::ZoomMode::Auto))
+ .unwrap_or(false);
+
+ let result = match (cursor.prev_segment, cursor.segment) {
(Some(prev_segment), None) => {
let zoom_t =
ease_out(t_clamp((cursor.time - prev_segment.end) / ZOOM_DURATION) as f32)
@@ -119,7 +327,11 @@ impl InterpolatedZoom {
t: 1.0 - zoom_t,
bounds: {
let prev_segment_bounds =
- SegmentBounds::from_segment(prev_segment, interpolated_cursor);
+ SegmentBounds::from_segment_with_cursor_constraint(
+ prev_segment,
+ zoom_focus,
+ actual_cursor,
+ );
SegmentBounds::new(
prev_segment_bounds.top_left * (1.0 - zoom_t)
@@ -137,8 +349,11 @@ impl InterpolatedZoom {
Self {
t,
bounds: {
- let segment_bounds =
- SegmentBounds::from_segment(segment, interpolated_cursor);
+ let segment_bounds = SegmentBounds::from_segment_with_cursor_constraint(
+ segment,
+ zoom_focus,
+ actual_cursor,
+ );
SegmentBounds::new(
default.top_left * (1.0 - t) + segment_bounds.top_left * t,
@@ -148,14 +363,20 @@ impl InterpolatedZoom {
}
}
(Some(prev_segment), Some(segment)) => {
- let prev_segment_bounds =
- SegmentBounds::from_segment(prev_segment, interpolated_cursor);
- let segment_bounds = SegmentBounds::from_segment(segment, interpolated_cursor);
+ let prev_segment_bounds = SegmentBounds::from_segment_with_cursor_constraint(
+ prev_segment,
+ zoom_focus,
+ actual_cursor,
+ );
+ let segment_bounds = SegmentBounds::from_segment_with_cursor_constraint(
+ segment,
+ zoom_focus,
+ actual_cursor,
+ );
let zoom_t =
ease_in(t_clamp((cursor.time - segment.start) / ZOOM_DURATION) as f32) as f64;
- // no gap
if segment.start == prev_segment.end {
Self {
t: 1.0,
@@ -166,15 +387,11 @@ impl InterpolatedZoom {
+ segment_bounds.bottom_right * zoom_t,
),
}
- }
- // small gap
- else if segment.start - prev_segment.end < ZOOM_DURATION {
- // handling this is a bit funny, since we're not zooming in from 0 but rather
- // from the previous value that the zoom out got interrupted at by the current segment
-
- let min = InterpolatedZoom::new_with_easing(
+ } else if segment.start - prev_segment.end < ZOOM_DURATION {
+ let min = InterpolatedZoom::new_with_easing_and_cursor(
SegmentsCursor::new(segment.start, cursor.segments),
- interpolated_cursor,
+ zoom_focus,
+ actual_cursor,
ease_in,
ease_out,
);
@@ -191,9 +408,7 @@ impl InterpolatedZoom {
)
},
}
- }
- // entirely separate
- else {
+ } else {
Self {
t: zoom_t,
bounds: SegmentBounds::new(
@@ -208,6 +423,133 @@ impl InterpolatedZoom {
t: 0.0,
bounds: default,
},
+ };
+
+ if is_auto_mode {
+ if let Some(cursor_coord) = actual_cursor {
+ return result.ensure_cursor_visible((cursor_coord.x, cursor_coord.y));
+ }
+ }
+
+ result
+ }
+}
+
+impl InterpolatedZoom {
+ fn ensure_cursor_visible(self, cursor_pos: (f64, f64)) -> Self {
+ let current_zoom = self.bounds.bottom_right.x - self.bounds.top_left.x;
+
+ if current_zoom <= 1.001 {
+ return self;
+ }
+
+ let viewport_size = 1.0 / current_zoom;
+ let viewport_left = -self.bounds.top_left.x / current_zoom;
+ let viewport_right = viewport_left + viewport_size;
+ let viewport_top = -self.bounds.top_left.y / current_zoom;
+ let viewport_bottom = viewport_top + viewport_size;
+
+ let margin_ratio = 0.15;
+ let margin = viewport_size * margin_ratio;
+
+ let inner_left = viewport_left + margin;
+ let inner_right = viewport_right - margin;
+ let inner_top = viewport_top + margin;
+ let inner_bottom = viewport_bottom - margin;
+
+ let cursor_in_safe_zone = cursor_pos.0 >= inner_left
+ && cursor_pos.0 <= inner_right
+ && cursor_pos.1 >= inner_top
+ && cursor_pos.1 <= inner_bottom;
+
+ if cursor_in_safe_zone {
+ return self;
+ }
+
+ let target_margin = viewport_size * margin_ratio;
+
+ let mut new_viewport_left = viewport_left;
+ let mut new_viewport_top = viewport_top;
+
+ if cursor_pos.0 < inner_left {
+ new_viewport_left = cursor_pos.0 - target_margin;
+ } else if cursor_pos.0 > inner_right {
+ new_viewport_left = cursor_pos.0 - viewport_size + target_margin;
+ }
+
+ if cursor_pos.1 < inner_top {
+ new_viewport_top = cursor_pos.1 - target_margin;
+ } else if cursor_pos.1 > inner_bottom {
+ new_viewport_top = cursor_pos.1 - viewport_size + target_margin;
+ }
+
+ new_viewport_left = new_viewport_left.clamp(0.0, 1.0 - viewport_size);
+ new_viewport_top = new_viewport_top.clamp(0.0, 1.0 - viewport_size);
+
+ let new_viewport_right = new_viewport_left + viewport_size;
+ let new_viewport_bottom = new_viewport_top + viewport_size;
+
+ let cursor_now_visible = cursor_pos.0 >= new_viewport_left
+ && cursor_pos.0 <= new_viewport_right
+ && cursor_pos.1 >= new_viewport_top
+ && cursor_pos.1 <= new_viewport_bottom;
+
+ if cursor_now_visible {
+ let new_top_left_x = -new_viewport_left * current_zoom;
+ let new_top_left_y = -new_viewport_top * current_zoom;
+
+ return Self {
+ t: self.t,
+ bounds: SegmentBounds::new(
+ XY::new(new_top_left_x, new_top_left_y),
+ XY::new(new_top_left_x + current_zoom, new_top_left_y + current_zoom),
+ ),
+ };
+ }
+
+ let required_margin = 0.1;
+ let dist_from_left = (cursor_pos.0 - required_margin).max(0.0);
+ let dist_from_right = (1.0 - cursor_pos.0 - required_margin).max(0.0);
+ let dist_from_top = (cursor_pos.1 - required_margin).max(0.0);
+ let dist_from_bottom = (1.0 - cursor_pos.1 - required_margin).max(0.0);
+
+ let effective_dist_x = dist_from_left.min(dist_from_right).max(0.001);
+ let effective_dist_y = dist_from_top.min(dist_from_bottom).max(0.001);
+
+ let max_zoom_x = 0.5 / effective_dist_x;
+ let max_zoom_y = 0.5 / effective_dist_y;
+
+ let max_zoom_for_cursor = max_zoom_x.min(max_zoom_y).max(1.0);
+ let new_zoom = current_zoom.min(max_zoom_for_cursor);
+
+ let new_viewport_size = 1.0 / new_zoom;
+ let new_margin = new_viewport_size * margin_ratio;
+
+ let final_viewport_left = if cursor_pos.0 - new_margin <= 0.0 {
+ 0.0
+ } else if cursor_pos.0 + new_margin >= 1.0 {
+ 1.0 - new_viewport_size
+ } else {
+ (cursor_pos.0 - new_viewport_size / 2.0).clamp(0.0, 1.0 - new_viewport_size)
+ };
+
+ let final_viewport_top = if cursor_pos.1 - new_margin <= 0.0 {
+ 0.0
+ } else if cursor_pos.1 + new_margin >= 1.0 {
+ 1.0 - new_viewport_size
+ } else {
+ (cursor_pos.1 - new_viewport_size / 2.0).clamp(0.0, 1.0 - new_viewport_size)
+ };
+
+ let new_top_left_x = -final_viewport_left * new_zoom;
+ let new_top_left_y = -final_viewport_top * new_zoom;
+
+ Self {
+ t: self.t,
+ bounds: SegmentBounds::new(
+ XY::new(new_top_left_x, new_top_left_y),
+ XY::new(new_top_left_x + new_zoom, new_top_left_y + new_zoom),
+ ),
}
}
}
@@ -218,7 +560,7 @@ fn t_clamp(v: f64) -> f64 {
#[cfg(test)]
mod test {
- use cap_project::ZoomMode;
+ use cap_project::{GlideDirection, ZoomMode, ZoomSegment};
use super::*;
@@ -245,8 +587,13 @@ mod test {
}
fn test_interp((time, segments): (f64, &[ZoomSegment]), expected: InterpolatedZoom) {
- let actual =
- InterpolatedZoom::new_with_easing(c(time, segments), Default::default(), |t| t, |t| t);
+ let actual = InterpolatedZoom::new_with_easing_and_cursor(
+ c(time, segments),
+ Default::default(),
+ None,
+ |t| t,
+ |t| t,
+ );
assert_f64_near!(actual.t, expected.t, "t");
@@ -259,14 +606,25 @@ mod test {
assert_f64_near!(a.bottom_right.y, e.bottom_right.y, "bounds.bottom_right.y");
}
+ fn test_segment(start: f64, end: f64, amount: f64, x: f64, y: f64) -> ZoomSegment {
+ ZoomSegment {
+ start,
+ end,
+ amount,
+ mode: ZoomMode::Manual {
+ x: x as f32,
+ y: y as f32,
+ },
+ glide_direction: GlideDirection::default(),
+ glide_speed: 0.05,
+ instant_animation: false,
+ edge_snap_ratio: 0.075,
+ }
+ }
+
#[test]
fn one_segment() {
- let segments = vec![ZoomSegment {
- start: 2.0,
- end: 4.0,
- amount: 2.0,
- mode: ZoomMode::Manual { x: 0.5, y: 0.5 },
- }];
+ let segments = vec![test_segment(2.0, 4.0, 2.0, 0.5, 0.5)];
test_interp(
(0.0, &segments),
@@ -336,18 +694,8 @@ mod test {
#[test]
fn two_segments_no_gap() {
let segments = vec![
- ZoomSegment {
- start: 2.0,
- end: 4.0,
- amount: 2.0,
- mode: ZoomMode::Manual { x: 0.0, y: 0.0 },
- },
- ZoomSegment {
- start: 4.0,
- end: 6.0,
- amount: 4.0,
- mode: ZoomMode::Manual { x: 0.5, y: 0.5 },
- },
+ test_segment(2.0, 4.0, 2.0, 0.0, 0.0),
+ test_segment(4.0, 6.0, 4.0, 0.5, 0.5),
];
test_interp(
@@ -383,18 +731,8 @@ mod test {
#[test]
fn two_segments_small_gap() {
let segments = vec![
- ZoomSegment {
- start: 2.0,
- end: 4.0,
- amount: 2.0,
- mode: ZoomMode::Manual { x: 0.5, y: 0.5 },
- },
- ZoomSegment {
- start: 4.0 + ZOOM_DURATION * 0.75,
- end: 6.0,
- amount: 4.0,
- mode: ZoomMode::Manual { x: 0.5, y: 0.5 },
- },
+ test_segment(2.0, 4.0, 2.0, 0.5, 0.5),
+ test_segment(4.0 + ZOOM_DURATION * 0.75, 6.0, 4.0, 0.5, 0.5),
];
test_interp(
@@ -437,18 +775,8 @@ mod test {
#[test]
fn two_segments_large_gap() {
let segments = vec![
- ZoomSegment {
- start: 2.0,
- end: 4.0,
- amount: 2.0,
- mode: ZoomMode::Manual { x: 0.5, y: 0.5 },
- },
- ZoomSegment {
- start: 7.0,
- end: 9.0,
- amount: 4.0,
- mode: ZoomMode::Manual { x: 0.0, y: 0.0 },
- },
+ test_segment(2.0, 4.0, 2.0, 0.5, 0.5),
+ test_segment(7.0, 9.0, 4.0, 0.0, 0.0),
];
test_interp(
@@ -494,4 +822,105 @@ mod test {
},
);
}
+
+ fn cursor_is_visible_in_zoom(zoom: &InterpolatedZoom, cursor_pos: (f64, f64)) -> bool {
+ let current_zoom = zoom.bounds.bottom_right.x - zoom.bounds.top_left.x;
+ if current_zoom <= 1.001 {
+ return cursor_pos.0 >= 0.0
+ && cursor_pos.0 <= 1.0
+ && cursor_pos.1 >= 0.0
+ && cursor_pos.1 <= 1.0;
+ }
+
+ let viewport_size = 1.0 / current_zoom;
+ let viewport_left = -zoom.bounds.top_left.x / current_zoom;
+ let viewport_right = viewport_left + viewport_size;
+ let viewport_top = -zoom.bounds.top_left.y / current_zoom;
+ let viewport_bottom = viewport_top + viewport_size;
+
+ let margin = 1e-9;
+ cursor_pos.0 >= viewport_left - margin
+ && cursor_pos.0 <= viewport_right + margin
+ && cursor_pos.1 >= viewport_top + margin
+ && cursor_pos.1 <= viewport_bottom + margin
+ }
+
+ #[test]
+ fn ensure_cursor_visible_keeps_cursor_in_view() {
+ let zoom = InterpolatedZoom {
+ t: 1.0,
+ bounds: SegmentBounds::new(XY::new(-0.5, -0.5), XY::new(1.5, 1.5)),
+ };
+
+ let cursor_outside_right = (0.9, 0.5);
+ let result = zoom.ensure_cursor_visible(cursor_outside_right);
+ assert!(
+ cursor_is_visible_in_zoom(&result, cursor_outside_right),
+ "Cursor should be visible after ensure_cursor_visible"
+ );
+
+ let cursor_outside_bottom = (0.5, 0.9);
+ let result = zoom.ensure_cursor_visible(cursor_outside_bottom);
+ assert!(
+ cursor_is_visible_in_zoom(&result, cursor_outside_bottom),
+ "Cursor should be visible after ensure_cursor_visible"
+ );
+
+ let cursor_outside_corner = (0.9, 0.9);
+ let result = zoom.ensure_cursor_visible(cursor_outside_corner);
+ assert!(
+ cursor_is_visible_in_zoom(&result, cursor_outside_corner),
+ "Cursor should be visible after ensure_cursor_visible"
+ );
+
+ let cursor_at_edge = (0.95, 0.95);
+ let result = zoom.ensure_cursor_visible(cursor_at_edge);
+ assert!(
+ cursor_is_visible_in_zoom(&result, cursor_at_edge),
+ "Cursor at edge should be visible after ensure_cursor_visible"
+ );
+ }
+
+ #[test]
+ fn ensure_cursor_visible_handles_extreme_positions() {
+ let zoom = InterpolatedZoom {
+ t: 1.0,
+ bounds: SegmentBounds::new(XY::new(-0.5, -0.5), XY::new(1.5, 1.5)),
+ };
+
+ let test_positions = [
+ (0.05, 0.5),
+ (0.95, 0.5),
+ (0.5, 0.05),
+ (0.5, 0.95),
+ (0.05, 0.05),
+ (0.95, 0.95),
+ (0.05, 0.95),
+ (0.95, 0.05),
+ ];
+
+ for cursor_pos in test_positions {
+ let result = zoom.ensure_cursor_visible(cursor_pos);
+ assert!(
+ cursor_is_visible_in_zoom(&result, cursor_pos),
+ "Cursor at {:?} should be visible",
+ cursor_pos
+ );
+ }
+ }
+
+ #[test]
+ fn ensure_cursor_visible_handles_interpolated_bounds() {
+ let zoom = InterpolatedZoom {
+ t: 0.5,
+ bounds: SegmentBounds::new(XY::new(-0.25, -0.25), XY::new(1.25, 1.25)),
+ };
+
+ let cursor_pos = (0.85, 0.85);
+ let result = zoom.ensure_cursor_visible(cursor_pos);
+ assert!(
+ cursor_is_visible_in_zoom(&result, cursor_pos),
+ "Cursor should be visible in interpolated zoom state"
+ );
+ }
}
diff --git a/crates/rendering/src/zoom_focus_interpolation.rs b/crates/rendering/src/zoom_focus_interpolation.rs
new file mode 100644
index 000000000..7a1c983b4
--- /dev/null
+++ b/crates/rendering/src/zoom_focus_interpolation.rs
@@ -0,0 +1,200 @@
+use cap_project::{CursorEvents, ScreenMovementSpring, XY, ZoomSegment};
+
+use crate::{
+ Coord, RawDisplayUVSpace,
+ cursor_interpolation::interpolate_cursor,
+ spring_mass_damper::{SpringMassDamperSimulation, SpringMassDamperSimulationConfig},
+};
+
+const SAMPLE_INTERVAL_MS: f64 = 8.0;
+
+#[derive(Clone)]
+struct SmoothedFocusEvent {
+ time: f64,
+ position: XY<f32>,
+}
+
+pub struct ZoomFocusInterpolator {
+ events: Option<Vec<SmoothedFocusEvent>>,
+ cursor_events: CursorEvents,
+ cursor_smoothing: Option<SpringMassDamperSimulationConfig>,
+ screen_spring: ScreenMovementSpring,
+ duration_secs: f64,
+}
+
+impl ZoomFocusInterpolator {
+ pub fn new(
+ cursor_events: &CursorEvents,
+ cursor_smoothing: Option<SpringMassDamperSimulationConfig>,
+ screen_spring: ScreenMovementSpring,
+ duration_secs: f64,
+ ) -> Self {
+ Self {
+ events: None,
+ cursor_events: cursor_events.clone(),
+ cursor_smoothing,
+ screen_spring,
+ duration_secs,
+ }
+ }
+
+ pub fn precompute(&mut self) {
+ if self.events.is_some() {
+ return;
+ }
+
+ if self.cursor_events.moves.is_empty() {
+ self.events = Some(vec![]);
+ return;
+ }
+
+ let spring_config = SpringMassDamperSimulationConfig {
+ tension: self.screen_spring.stiffness,
+ mass: self.screen_spring.mass,
+ friction: self.screen_spring.damping,
+ };
+
+ let mut sim = SpringMassDamperSimulation::new(spring_config);
+
+ let first_cursor = interpolate_cursor(&self.cursor_events, 0.0, self.cursor_smoothing);
+ let initial_pos = first_cursor
+ .map(|c| XY::new(c.position.coord.x as f32, c.position.coord.y as f32))
+ .unwrap_or(XY::new(0.5, 0.5));
+
+ sim.set_position(initial_pos);
+ sim.set_velocity(XY::new(0.0, 0.0));
+ sim.set_target_position(initial_pos);
+
+ let mut events = vec![SmoothedFocusEvent {
+ time: 0.0,
+ position: initial_pos,
+ }];
+
+ let duration_ms = self.duration_secs * 1000.0;
+ let mut current_time_ms = 0.0;
+
+ while current_time_ms < duration_ms {
+ current_time_ms += SAMPLE_INTERVAL_MS;
+ let time_secs = (current_time_ms / 1000.0) as f32;
+
+ if let Some(cursor) =
+ interpolate_cursor(&self.cursor_events, time_secs, self.cursor_smoothing)
+ {
+ let target = XY::new(
+ cursor.position.coord.x as f32,
+ cursor.position.coord.y as f32,
+ );
+ sim.set_target_position(target);
+ }
+
+ sim.run(SAMPLE_INTERVAL_MS as f32);
+
+ events.push(SmoothedFocusEvent {
+ time: current_time_ms,
+ position: XY::new(
+ sim.position.x.clamp(0.0, 1.0),
+ sim.position.y.clamp(0.0, 1.0),
+ ),
+ });
+ }
+
+ self.events = Some(events);
+ }
+
+ pub fn interpolate(&self, time_secs: f32) -> Coord<RawDisplayUVSpace> {
+ let time_ms = (time_secs * 1000.0) as f64;
+
+ if self.cursor_events.moves.is_empty() {
+ return Coord::new(XY::new(0.5, 0.5));
+ }
+
+ if let Some(ref events) = self.events {
+ self.interpolate_from_events(events, time_ms)
+ } else {
+ self.interpolate_direct(time_secs)
+ }
+ }
+
+ fn interpolate_direct(&self, time_secs: f32) -> Coord<RawDisplayUVSpace> {
+ if let Some(cursor) =
+ interpolate_cursor(&self.cursor_events, time_secs, self.cursor_smoothing)
+ {
+ Coord::new(XY::new(
+ cursor.position.coord.x.clamp(0.0, 1.0),
+ cursor.position.coord.y.clamp(0.0, 1.0),
+ ))
+ } else {
+ Coord::new(XY::new(0.5, 0.5))
+ }
+ }
+
+ fn interpolate_from_events(
+ &self,
+ events: &[SmoothedFocusEvent],
+ time_ms: f64,
+ ) -> Coord<RawDisplayUVSpace> {
+ if events.is_empty() {
+ return Coord::new(XY::new(0.5, 0.5));
+ }
+
+ if time_ms <= events[0].time {
+ let pos = events[0].position;
+ return Coord::new(XY::new(pos.x as f64, pos.y as f64));
+ }
+
+ if let Some(last) = events.last() {
+ if time_ms >= last.time {
+ return Coord::new(XY::new(last.position.x as f64, last.position.y as f64));
+ }
+ }
+
+ let idx = events
+ .binary_search_by(|e| {
+ e.time
+ .partial_cmp(&time_ms)
+ .unwrap_or(std::cmp::Ordering::Less)
+ })
+ .unwrap_or_else(|i| i.saturating_sub(1));
+
+ let curr = &events[idx];
+ let next = events.get(idx + 1).unwrap_or(curr);
+
+ if (next.time - curr.time).abs() < f64::EPSILON {
+ return Coord::new(XY::new(curr.position.x as f64, curr.position.y as f64));
+ }
+
+ let t = ((time_ms - curr.time) / (next.time - curr.time)).clamp(0.0, 1.0) as f32;
+
+ let lerped = XY::new(
+ curr.position.x + (next.position.x - curr.position.x) * t,
+ curr.position.y + (next.position.y - curr.position.y) * t,
+ );
+
+ Coord::new(XY::new(lerped.x as f64, lerped.y as f64))
+ }
+}
+
+#[allow(dead_code)]
+pub fn apply_edge_snap_to_focus(
+ focus: Coord<RawDisplayUVSpace>,
+ segment: &ZoomSegment,
+) -> Coord<RawDisplayUVSpace> {
+ let position = (focus.x, focus.y);
+ let zoom_amount = segment.amount;
+ let edge_snap_ratio = segment.edge_snap_ratio;
+
+ let viewport_half = 0.5 / zoom_amount;
+ let snap_threshold = edge_snap_ratio / zoom_amount;
+
+ let snap_axis = |pos: f64| -> f64 {
+ if pos < snap_threshold {
+ viewport_half
+ } else if pos > 1.0 - snap_threshold {
+ 1.0 - viewport_half
+ } else {
+ pos.clamp(viewport_half, 1.0 - viewport_half)
+ }
+ };
+
+ Coord::new(XY::new(snap_axis(position.0), snap_axis(position.1)))
+}