Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
wip: Cursor easing
Richie McIlroy3c1b1d81d183
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsxindex 8f6bc663e..02cd3df98 100644--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx@@ -10,7 +10,11 @@ import { createWritableMemo } from "@solid-primitives/memo";import { createEventListenerMap } from "@solid-primitives/event-listener";import { produce } from "solid-js/store";-import type { BackgroundSource, CursorType } from "~/utils/tauri";+import type {+ BackgroundSource,+ CursorType,+ CursorAnimationStyle,+} from "~/utils/tauri";import { useEditorContext } from "./context";import {ComingSoonTooltip,@@ -36,6 +40,12 @@ const BACKGROUND_SOURCES_LIST = ["gradient",] satisfies Array<BackgroundSource["type"]>;+const CURSOR_ANIMATION_STYLES: Record<CursorAnimationStyle, string> = {+ slow: "Slow & Smooth",+ regular: "Regular",+ fast: "Fast & Responsive",+} as const;+export function ConfigSidebar() {const {selectedTab,@@ -522,40 +532,51 @@ export function ConfigSidebar() {step={1}/></Field>- <ComingSoonTooltip>- <Field name="Type" icon={<IconCapCursor />}>- <ul class="flex flex-row gap-2 text-gray-400">- <For- each={- [- { type: "pointer", icon: IconCapCursor },- { type: "circle", icon: IconCapCircle },- ] satisfies Array<{- icon: Component;- type: CursorType;- }>- }- >- {(item) => (- <li>- <button- disabled- type="button"- onClick={() => setProject("cursor", "type", item.type)}- data-selected={project.cursor.type === item.type}- class="border border-black-transparent-5 bg-gray-100 rounded-lg p-[0.625rem] text-gray-400 data-[selected='true']:text-gray-500 disabled:text-gray-300 focus-visible:outline-blue-300 focus-visible:outline outline-1 outline-offset-1"- >- <Dynamic- component={item.icon}- class="size-[1.75rem] mx-auto"- />- </button>- </li>- )}- </For>- </ul>- </Field>- </ComingSoonTooltip>+ <Field name="Animation Style" icon={<IconLucideRabbit />}>+ <RadioGroup+ defaultValue="regular"+ value={project.cursor.animationStyle}+ onChange={(value) => {+ console.log("Changing animation style to:", value);+ setProject(+ "cursor",+ "animationStyle",+ value as CursorAnimationStyle+ );+ }}+ class="flex flex-col gap-2"+ >+ {(+ Object.entries(CURSOR_ANIMATION_STYLES) as [+ CursorAnimationStyle,+ string+ ][]+ ).map(([value, label]) => (+ <RadioGroup.Item value={value} class="flex items-center">+ <RadioGroup.ItemInput class="peer sr-only" />+ <RadioGroup.ItemControl+ class={cx(+ "w-4 h-4 rounded-full border border-gray-300 mr-2",+ "relative after:absolute after:inset-0 after:m-auto after:block after:w-2 after:h-2 after:rounded-full",+ "after:transition-colors after:duration-200",+ "peer-checked:border-blue-500 peer-checked:after:bg-blue-400",+ "peer-focus-visible:ring-2 peer-focus-visible:ring-blue-400/50",+ "peer-disabled:opacity-50"+ )}+ />+ <span+ class={cx(+ "text-gray-500",+ "peer-checked:text-gray-900",+ "peer-disabled:opacity-50"+ )}+ >+ {label}+ </span>+ </RadioGroup.Item>+ ))}+ </RadioGroup>+ </Field></KTabs.Content><KTabs.Content value="hotkeys"><Field name="Hotkeys" icon={<IconCapHotkeys />}>diff --git a/apps/desktop/src/routes/editor/projectConfig.ts b/apps/desktop/src/routes/editor/projectConfig.tsindex 899c425d2..ca7465355 100644--- a/apps/desktop/src/routes/editor/projectConfig.ts+++ b/apps/desktop/src/routes/editor/projectConfig.ts@@ -26,10 +26,17 @@ export const DEFAULT_PROJECT_CONFIG: ProjectConfiguration = {rounding: 100,shadow: 50,size: 30,+ zoom_size: 20,},audio: { mute: false, improve: false },- cursor: { hideWhenIdle: false, size: 0, type: "pointer" },+ cursor: {+ hideWhenIdle: false,+ size: 0,+ type: "pointer",+ animationStyle: "regular" as const+ },hotkeys: { show: false },+ motionBlur: 0.2,};export const ASPECT_RATIOS = {diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 16a6f1b54..40fa7ccff 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -386,7 +386,8 @@ export type CaptureScreen = { id: number; name: string }export type CaptureWindow = { id: number; name: string; bounds: Bounds }export type Crop = { position: XY<number>; size: XY<number> }export type CurrentRecordingChanged = JsonValue<InProgressRecording | null>-export type CursorConfiguration = { hideWhenIdle: boolean; size: number; type: CursorType }+export type CursorAnimationStyle = "regular" | "slow" | "fast"+export type CursorConfiguration = { hideWhenIdle: boolean; size: number; type: CursorType; animationStyle: CursorAnimationStyle }export type CursorType = "pointer" | "circle"export type Display = { path: string }export type EditorStateChanged = { playhead_position: number }diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rsindex c3df56a83..2fd099f72 100644--- a/crates/project/src/configuration.rs+++ b/crates/project/src/configuration.rs@@ -225,12 +225,22 @@ pub enum CursorType {Circle,}+#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]+#[serde(rename_all = "camelCase")]+pub enum CursorAnimationStyle {+ #[default]+ Regular,+ Slow,+ Fast,+}+#[derive(Type, Serialize, Deserialize, Clone, Debug)]#[serde(rename_all = "camelCase")]pub struct CursorConfiguration {hide_when_idle: bool,pub size: u32,r#type: CursorType,+ pub animation_style: CursorAnimationStyle,}impl Default for CursorConfiguration {@@ -239,6 +249,7 @@ impl Default for CursorConfiguration {hide_when_idle: false,size: 100,r#type: CursorType::default(),+ animation_style: CursorAnimationStyle::Regular,}}}@@ -357,3 +368,11 @@ impl Default for ProjectConfiguration {}}}++pub const SLOW_SMOOTHING_SAMPLES: usize = 24;+pub const REGULAR_SMOOTHING_SAMPLES: usize = 16;+pub const FAST_SMOOTHING_SAMPLES: usize = 10;++pub const SLOW_VELOCITY_THRESHOLD: f64 = 0.003;+pub const REGULAR_VELOCITY_THRESHOLD: f64 = 0.008;+pub const FAST_VELOCITY_THRESHOLD: f64 = 0.015;diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex 8b8561b0d..981ca5040 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -12,8 +12,10 @@ use wgpu::util::DeviceExt;use wgpu::{CommandEncoder, COPY_BYTES_PER_ROW_ALIGNMENT};use cap_project::{- AspectRatio, BackgroundSource, CameraXPosition, CameraYPosition, Crop, CursorData,- CursorMoveEvent, ProjectConfiguration, XY,+ AspectRatio, BackgroundSource, CameraXPosition, CameraYPosition, Crop, CursorAnimationStyle,+ CursorData, CursorMoveEvent, ProjectConfiguration, FAST_SMOOTHING_SAMPLES,+ FAST_VELOCITY_THRESHOLD, REGULAR_SMOOTHING_SAMPLES, REGULAR_VELOCITY_THRESHOLD,+ SLOW_SMOOTHING_SAMPLES, SLOW_VELOCITY_THRESHOLD, XY,};use image::GenericImageView;@@ -476,7 +478,8 @@ impl ProjectUniforms {let options = &constants.options;let output_size = Self::get_output_size(options, project);- let cursor_position = interpolate_cursor_position(&constants.cursor, time);+ let cursor_position =+ interpolate_cursor_position(&constants.cursor, time, &project.cursor.animation_style);let zoom_keyframes = ZoomKeyframes::new(project);let current_zoom = zoom_keyframes.get_amount(time as f64);@@ -1046,12 +1049,20 @@ fn draw_cursor(encoder: &mut CommandEncoder,view: &wgpu::TextureView,) {- let Some(cursor_position) = interpolate_cursor_position(&constants.cursor, time) else {+ let Some(cursor_position) = interpolate_cursor_position(+ &constants.cursor,+ time,+ &uniforms.project.cursor.animation_style,+ ) else {return;};// Calculate previous position for velocity- let prev_position = interpolate_cursor_position(&constants.cursor, time - 1.0 / 30.0);+ let prev_position = interpolate_cursor_position(+ &constants.cursor,+ time - 1.0 / 30.0,+ &uniforms.project.cursor.animation_style,+ );// Calculate velocity in screen spacelet velocity = if let Some(prev_pos) = prev_position {@@ -1534,41 +1545,118 @@ impl AsyncVideoDecoderHandle {fn interpolate_cursor_position(cursor: &CursorData,time_secs: f32,+ animation_style: &CursorAnimationStyle,) -> Option<Coord<RawDisplayUVSpace>> {let time_ms = (time_secs * 1000.0) as f64;if cursor.moves.is_empty() {- None- } else {- let moves = &cursor.moves;+ return None;+ }- let mut position = 0;+ // Get style-specific parameters+ let (num_samples, velocity_threshold) = match animation_style {+ CursorAnimationStyle::Slow => (SLOW_SMOOTHING_SAMPLES, SLOW_VELOCITY_THRESHOLD),+ CursorAnimationStyle::Regular => (REGULAR_SMOOTHING_SAMPLES, REGULAR_VELOCITY_THRESHOLD),+ CursorAnimationStyle::Fast => (FAST_SMOOTHING_SAMPLES, FAST_VELOCITY_THRESHOLD),+ };- for (i, m) in moves.iter().enumerate() {- if m.process_time_ms < time_ms && m.process_time_ms > moves[position].process_time_ms {- position = i;- }- }+ // Find the closest move events around current time+ let mut closest_events: Vec<&CursorMoveEvent> = cursor+ .moves+ .iter()+ .filter(|m| (m.process_time_ms - time_ms).abs() <= 100.0) // Look at events within 100ms+ .collect();++ closest_events.sort_by(|a, b| {+ (a.process_time_ms - time_ms)+ .abs()+ .partial_cmp(&(b.process_time_ms - time_ms).abs())+ .unwrap()+ });- let m = &moves[position];- let next = moves.get(position + 1);+ // Take the nearest events up to num_samples+ let samples: Vec<(f64, f64, f64)> = closest_events+ .iter()+ .take(num_samples)+ .map(|m| (m.process_time_ms, m.x, m.y))+ .collect();++ if samples.is_empty() {+ // Fallback to nearest event if no samples in range+ let nearest = cursor+ .moves+ .iter()+ .min_by_key(|m| (m.process_time_ms - time_ms).abs() as i64)?;+ return Some(Coord::new(XY {+ x: nearest.x.clamp(0.0, 1.0),+ y: nearest.y.clamp(0.0, 1.0),+ }));+ }- let (x, y) = if let Some(next) = next {- let delta = next.process_time_ms - m.process_time_ms;- let progress = (time_ms - m.process_time_ms) / delta;- (- m.x + (next.x - m.x) * progress,- m.y + (next.y - m.y) * progress,- )+ // Calculate velocities between consecutive points+ let mut velocities = Vec::with_capacity(samples.len() - 1);+ for i in 0..samples.len() - 1 {+ let (t1, x1, y1) = samples[i];+ let (t2, x2, y2) = samples[i + 1];+ let dt = (t2 - t1).max(1.0); // Avoid division by zero+ let dx = x2 - x1;+ let dy = y2 - y1;+ let velocity = ((dx * dx + dy * dy) / (dt * dt)).sqrt();+ velocities.push(velocity);+ }++ // Apply adaptive smoothing based on velocities and time distance+ let mut x = 0.0;+ let mut y = 0.0;+ let mut total_weight = 0.0;++ for (i, &(t, px, py)) in samples.iter().enumerate() {+ // Time-based weight with style-specific falloff+ let time_diff = (t - time_ms).abs();+ let style_factor = match animation_style {+ CursorAnimationStyle::Slow => 0.0005,+ CursorAnimationStyle::Regular => 0.001,+ CursorAnimationStyle::Fast => 0.002,+ };+ let time_weight = 1.0 / (1.0 + time_diff * style_factor);++ // Velocity-based weight+ let velocity_weight = if i < velocities.len() {+ let vel = velocities[i];+ if vel > velocity_threshold {+ (velocity_threshold / vel).powf(match animation_style {+ CursorAnimationStyle::Slow => 1.5,+ CursorAnimationStyle::Regular => 1.0,+ CursorAnimationStyle::Fast => 0.5,+ })+ } else {+ 1.0+ }} else {- (m.x, m.y)+ 1.0};- Some(Coord::new(XY {- x: x.clamp(0.0, 1.0),- y: y.clamp(0.0, 1.0),- }))+ // Combine weights with style-specific emphasis+ let weight = match animation_style {+ CursorAnimationStyle::Slow => time_weight * velocity_weight.powf(1.5),+ CursorAnimationStyle::Regular => time_weight * velocity_weight,+ CursorAnimationStyle::Fast => time_weight * velocity_weight.powf(0.5),+ };++ x += px * weight;+ y += py * weight;+ total_weight += weight;+ }++ if total_weight > 0.0 {+ x /= total_weight;+ y /= total_weight;}++ Some(Coord::new(XY {+ x: x.clamp(0.0, 1.0),+ y: y.clamp(0.0, 1.0),+ }))}struct CursorPipeline {@@ -1708,7 +1796,7 @@ impl CursorPipeline {Self {bind_group_layout,- render_pipeline,+ render_pipeline: render_pipeline,}}}diff --git a/crates/rendering/src/shaders/cursor.wgsl b/crates/rendering/src/shaders/cursor.wgslindex 2e2b17e73..7935de49c 100644--- a/crates/rendering/src/shaders/cursor.wgsl+++ b/crates/rendering/src/shaders/cursor.wgsl@@ -66,39 +66,55 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {@fragmentfn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {- // Increase number of samples for smoother blur- let num_samples = 12;+ // Increase samples for higher quality blur+ let num_samples = 16;var color_sum = vec4<f32>(0.0);var weight_sum = 0.0;+ // Calculate velocity magnitude for adaptive blur strength+ let velocity_mag = length(uniforms.velocity);+ let adaptive_blur = uniforms.motion_blur_amount * smoothstep(0.0, 50.0, velocity_mag);+// Calculate blur direction from velocity- let velocity_dir = normalize(uniforms.velocity);+ var blur_dir = vec2<f32>(0.0);+ if (velocity_mag > 0.0) {+ blur_dir = uniforms.velocity / velocity_mag;+ }- // Increase the blur trail length- let blur_strength = uniforms.motion_blur_amount * 2.0;+ // Enhanced blur trail+ let max_blur_offset = 3.0 * adaptive_blur;- // Sample in both directions from the centerfor (var i = 0; i < num_samples; i++) {- // Adjusted sampling pattern for longer trails- let t = (f32(i) / f32(num_samples - 1)) * 2.0 - 1.0; // Range from -1 to 1- let weight = 1.0 - abs(t); // Higher weight in the center+ // Non-linear sampling for better blur distribution+ let t = pow(f32(i) / f32(num_samples - 1), 1.5) * 2.0 - 1.0;- // Calculate sample offset with increased range- let offset = velocity_dir * blur_strength * t;- let sample_uv = input.uv + offset * uniforms.velocity / uniforms.output_size.xy;+ // Gaussian-like weight distribution+ let weight = exp(-3.0 * t * t);- // Sample the texture+ // Calculate sample offset with velocity-based scaling+ let offset = blur_dir * max_blur_offset * t;+ let sample_uv = input.uv + offset / uniforms.output_size.xy;++ // Sample with bilinear filteringlet sample = textureSample(t_cursor, s_cursor, sample_uv);- // Accumulate weighted color including alpha+ // Accumulate weighted samplecolor_sum += sample * weight;weight_sum += weight;}- // Normalize by total weight- var final_color = vec4<f32>(0.0);- if (weight_sum > 0.0) {- final_color = color_sum / weight_sum;+ // Normalize the result+ var final_color = color_sum / weight_sum;++ // Enhance contrast slightly for fast movements+ if (velocity_mag > 30.0) {+ // Create new color with enhanced contrast instead of modifying components+ final_color = vec4<f32>(+ pow(final_color.r, 0.95),+ pow(final_color.g, 0.95),+ pow(final_color.b, 0.95),+ final_color.a+ );}return final_color;diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.tsindex bdb77a401..e0e49bf43 100644--- a/packages/ui-solid/src/auto-imports.d.ts+++ b/packages/ui-solid/src/auto-imports.d.ts@@ -59,6 +59,7 @@ declare global {const IconLucideFoler: typeof import("~icons/lucide/foler.jsx")["default"]const IconLucideLoaderCircle: typeof import('~icons/lucide/loader-circle.jsx')['default']const IconLucideMessageSquarePlus: typeof import('~icons/lucide/message-square-plus.jsx')['default']+ const IconLucideRabbit: typeof import('~icons/lucide/rabbit.jsx')['default']const IconLucideRewind: typeof import("~icons/lucide/rewind.jsx")["default"]const IconLucideSearch: typeof import('~icons/lucide/search.jsx')['default']const IconLucideSettings: typeof import("~icons/lucide/settings.jsx")["default"]