From 6c4170a682ea3916039983c8dbe490710a110f55 Mon Sep 17 00:00:00 2001 From: Jonathan Lippincott Date: Sat, 12 Sep 2026 19:35:51 +0200 Subject: [PATCH] Add cursor trail motion blur custom shader --- .github/workflows/ci.py | 2 +- docs/custom-shaders.rst | 4 + kitty/cursor_trail.c | 14 ++ kitty/options/definition.py | 3 + kitty/options/types.py | 2 +- kitty/shaders.c | 6 + .../shaders/custom/cursor-trail-default.slang | 195 ++++++++++++++---- kitty/shaders/custom/demo.py | 1 + kitty/shaders/custom/types.slang | 5 +- kitty/shaders/slang.py | 2 +- kitty/state.h | 3 + kitty_tests/cursor_trail_test.zsh | 39 ++++ 12 files changed, 230 insertions(+), 46 deletions(-) create mode 100755 kitty_tests/cursor_trail_test.zsh diff --git a/.github/workflows/ci.py b/.github/workflows/ci.py index f60cc483a..73f5cf21f 100644 --- a/.github/workflows/ci.py +++ b/.github/workflows/ci.py @@ -349,7 +349,7 @@ def main() -> None: elif action == 'check_code_formatting': q = subprocess.check_output('gofmt -s -l tools kittens'.split()).decode() if q.strip(): - q = '\n'.join(filter(lambda x: not x.rstrip().endswith('_generated.go'), q.strip().splitlines())).strip() + q = '\n'.join(filter(lambda x: not x.rstrip().endswith(('_generated.go', '_generated_test.go')), q.strip().splitlines())).strip() if q: raise SystemExit(q) if subprocess.run(['ruff', 'format', '--check']).returncode != 0: diff --git a/docs/custom-shaders.rst b/docs/custom-shaders.rst index 692b854f5..54f2f09e4 100644 --- a/docs/custom-shaders.rst +++ b/docs/custom-shaders.rst @@ -29,6 +29,10 @@ Cursor trails You must have enabled cursor trails with something like ``cursor_trail 1`` in :file:`kitty.conf` for these shaders to take effect. +The bundled ``cursor-trail-default`` shader provides temporally supersampled motion +blur and spatial antialiasing. Enable it with :code:`custom_shaders cursor-trail-default`; +its compile-time rendering options are documented in the shader source. + .. include:: generated/custom-shaders-cursor-trails.rst Animated backgrounds diff --git a/kitty/cursor_trail.c b/kitty/cursor_trail.c index f82c0bf02..9263461bf 100644 --- a/kitty/cursor_trail.c +++ b/kitty/cursor_trail.c @@ -160,6 +160,12 @@ update_cursor_trail_needs_render(CursorTrail *ct, Window *w, ndc_coords g) { bool update_cursor_trail(CursorTrail *ct, Window *w, monotonic_t now, OSWindow *os_window) { + if (ct->has_previous_position) { + for (int i = 0; i < 4; i++) { + ct->previous_corner_x[i] = ct->corner_x[i]; + ct->previous_corner_y[i] = ct->corner_y[i]; + } + } ct->target_updated = false; ndc_coords g = { .xstart = gl_pos_x(w->render_data.geometry.left, os_window->viewport_width), @@ -179,6 +185,14 @@ update_cursor_trail(CursorTrail *ct, Window *w, monotonic_t now, OSWindow *os_wi bool needs_render_prev = ct->needs_render; update_cursor_trail_needs_render(ct, w, g); + if (!ct->has_previous_position) { + for (int i = 0; i < 4; i++) { + ct->previous_corner_x[i] = ct->corner_x[i]; + ct->previous_corner_y[i] = ct->corner_y[i]; + } + ct->has_previous_position = true; + } + ct->updated_at = now; // returning true here will cause the cells to be drawn diff --git a/kitty/options/definition.py b/kitty/options/definition.py index c5e3a4f14..048afdd35 100644 --- a/kitty/options/definition.py +++ b/kitty/options/definition.py @@ -459,6 +459,9 @@ for cursors that rapidly change their positions during UI updates in complex app See :opt:`cursor_trail_decay` to control the animation speed and :opt:`cursor_trail_start_threshold` to control when a cursor trail is started. You can also have different styles of trail by using the :opt:`custom_shaders` option, for example: :code:`custom_shaders cursor-trail-blaze`. +The bundled :code:`cursor-trail-default` shader provides temporally supersampled motion blur +and spatial antialiasing; enable it with :code:`custom_shaders cursor-trail-default` and see +the shader source for its compile-time options. """, ) diff --git a/kitty/options/types.py b/kitty/options/types.py index e35e9f1b3..51492b11d 100644 --- a/kitty/options/types.py +++ b/kitty/options/types.py @@ -1721,4 +1721,4 @@ all_colors = frozenset({ }) -secret_options = ('remote_control_password', 'file_transfer_confirmation_bypass') \ No newline at end of file +secret_options = ('remote_control_password', 'file_transfer_confirmation_bypass') diff --git a/kitty/shaders.c b/kitty/shaders.c index d1011bf24..806334ff1 100644 --- a/kitty/shaders.c +++ b/kitty/shaders.c @@ -2506,6 +2506,8 @@ run_custom_end_shader(OSWindow *os_window, float sx, float sy, monotonic_t now) float central_area[4]; float cursor_trail_corners_x[4]; float cursor_trail_corners_y[4]; + float cursor_trail_prev_corners_x[4]; + float cursor_trail_prev_corners_y[4]; float cursor_trail_edge[4]; float cursor_trail_prev_edge[4]; float cursor_color[4]; @@ -2585,6 +2587,10 @@ run_custom_end_shader(OSWindow *os_window, float sx, float sy, monotonic_t now) for (int i = 0; i < 4; i++) { d->cursor_trail_corners_x[i] = NDC_TO_UV(ct->corner_x[i]); d->cursor_trail_corners_y[i] = NDC_TO_UV(ct->corner_y[i]); + if (ct->has_previous_position) { + d->cursor_trail_prev_corners_x[i] = NDC_TO_UV(ct->previous_corner_x[i]); + d->cursor_trail_prev_corners_y[i] = NDC_TO_UV(ct->previous_corner_y[i]); + } } d->cursor_trail_edge[0] = NDC_TO_UV(ct->cursor_edge_x[0]); // left d->cursor_trail_edge[1] = NDC_TO_UV(ct->cursor_edge_x[1]); // right diff --git a/kitty/shaders/custom/cursor-trail-default.slang b/kitty/shaders/custom/cursor-trail-default.slang index 9a446d3aa..513f03176 100644 --- a/kitty/shaders/custom/cursor-trail-default.slang +++ b/kitty/shaders/custom/cursor-trail-default.slang @@ -2,57 +2,168 @@ // Copyright (C) 2026 Kovid Goyal // Distributed under terms of the GPLv3 license. // -// Custom cursor trail shader — replicates the built-in trail using the -// cursor_trail_* uniforms. Use as a starting point for custom effects. +// The default custom cursor trail. Set custom_shaders cursor-trail-default +// to use this shader instead of kitty's built-in cursor trail renderer. // -// Suggested pipeline config: -// startgroup -// animation_start cursor-trail-move -// animation_stop cursor-trail-stop -// shaders cursor-trail -// endgroup +// The options below are compile-time shader options. They can be changed +// here, or overridden from cursor-trail-default.pipeline with `var` lines. +// For example: +// var bool MOTION_BLUR true +// var int MOTION_BLUR_SAMPLES 64 // -// Note: animation_progress is not tied to the trail duration (which is -// an exponential decay of variable length). Use cursor_trail_color.a -// for opacity and the corner positions for geometry instead. +// MOTION_BLUR integrates the moving trail over time. ANTIALIASING integrates +// coverage over a regular subpixel grid. Both are enabled by default here; +// set either to false to disable that part of the effect. The sample counts +// are capped at 256 to keep accidental settings from producing an unusable +// shader. CONNECTED makes the blur terminate at the target cursor; when false +// it preserves kitty's original disconnected, lagging-cursor appearance. import kitty_custom_shader_types; -// Returns true when uv is inside the convex quad c0→c1→c2→c3 (clockwise, y-up). -// Corner order from cursor_trail_corners_*: 0=top-right, 1=bottom-right, 2=bottom-left, 3=top-left. -bool -inside_trail_quad(float2 uv, float2 c0, float2 c1, float2 c2, float2 c3) { - float2 e0 = c1 - c0; - float2 e1 = c2 - c1; - float2 e2 = c3 - c2; - float2 e3 = c0 - c3; - float s0 = e0.x * (uv.y - c0.y) - e0.y * (uv.x - c0.x); - float s1 = e1.x * (uv.y - c1.y) - e1.y * (uv.x - c1.x); - float s2 = e2.x * (uv.y - c2.y) - e2.y * (uv.x - c2.x); - float s3 = e3.x * (uv.y - c3.y) - e3.y * (uv.x - c3.x); - return s0 <= 0.0 && s1 <= 0.0 && s2 <= 0.0 && s3 <= 0.0; +// Integrate the trail between the previous and current animated positions. +static const bool MOTION_BLUR = true; +// Estimate pixel coverage using a regular grid of subpixel samples. +static const bool ANTIALIASING = true; +// Number of positions integrated per frame. Valid range is 1..256. +static const int MOTION_BLUR_SAMPLES = 64; +// Number of subpixel samples per frame. Valid range is 1..256. +static const int ANTIALIASING_SAMPLES = 16; +// If true, integrate to the target cursor rectangle; otherwise preserve the +// original disconnected, lagging-cursor shape. +static const bool CONNECTED = false; +// Opacity floor for the motion-blurred trail, in the range 0..1. +static const float MIN_OPACITY = 0.2; +// Fractions of the distance from the target over which the trail becomes +// white. The blend uses a smooth radial S-curve and reaches white at the end. +static const float TARGET_BLEND_START = 0.1; +static const float TARGET_BLEND_END = 0.02; + +// Corner order: top-right, bottom-right, bottom-left, top-left. +static bool +inside_triangle(float2 p, float2 a, float2 b, float2 c) { + float ab = (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x); + float bc = (c.x - b.x) * (p.y - b.y) - (c.y - b.y) * (p.x - b.x); + float ca = (a.x - c.x) * (p.y - c.y) - (a.y - c.y) * (p.x - c.x); + return ab <= 0.0 && bc <= 0.0 && ca <= 0.0; +} + +static float +trail_coverage(float2 p, float4 xs, float4 ys) { + float2 c0 = float2(xs.x, ys.x); + float2 c1 = float2(xs.y, ys.y); + float2 c2 = float2(xs.z, ys.z); + float2 c3 = float2(xs.w, ys.w); + // Match the GL_TRIANGLE_FAN used by kitty's original trail exactly. + return (inside_triangle(p, c0, c1, c2) || inside_triangle(p, c0, c2, c3)) ? 1.0 : 0.0; +} + +static bool +inside_rect(float2 p, float4 edge) { + return p.x >= edge.x && p.x <= edge.y && p.y >= edge.w && p.y <= edge.z; +} + +static float +distance_to_rect_pixels(float2 p, float4 edge, float2 pixel_dims) { + float2 lo = float2(edge.x, edge.w) * pixel_dims; + float2 hi = float2(edge.y, edge.z) * pixel_dims; + float2 px = p * pixel_dims; + float2 delta = max(max(lo - px, px - hi), float2(0.0)); + return length(delta); } public float4 fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) { + if (d.cursor_trail_color.a <= 0.0 || d.cursor_trail_state <= 0.0) return color; + + float2 pixel_dims = float2(d.viewport_size_pixels) * t.viewport.zw; + pixel_dims = max(pixel_dims, float2(1.0)); + float2 pixel_size = 1.0 / pixel_dims; + + const int temporal_samples = MOTION_BLUR ? min(max(MOTION_BLUR_SAMPLES, 1), 256) : 1; + const int spatial_samples = ANTIALIASING ? min(max(ANTIALIASING_SAMPLES, 1), 256) : 1; + const int grid_size = ANTIALIASING ? int(ceil(sqrt(float(spatial_samples)))) : 1; + + float4 end_x = d.cursor_trail_corners_x; + float4 end_y = d.cursor_trail_corners_y; + if (MOTION_BLUR && CONNECTED) { + // Connected mode ends at the target cursor rectangle. + end_x = float4(d.cursor_trail_edge.y, d.cursor_trail_edge.y, d.cursor_trail_edge.x, d.cursor_trail_edge.x); + end_y = float4(d.cursor_trail_edge.z, d.cursor_trail_edge.w, d.cursor_trail_edge.w, d.cursor_trail_edge.z); + } + + float4 start_x = MOTION_BLUR ? d.cursor_trail_prev_corners_x : end_x; + float4 start_y = MOTION_BLUR ? d.cursor_trail_prev_corners_y : end_y; + + // Custom end shaders run over the whole viewport. Reject pixels outside + // the swept trail before entering the expensive temporal/spatial loops. + float2 swept_min = float2(1.0, 1.0); + float2 swept_max = float2(0.0, 0.0); + for (int i = 0; i < 4; i++) { + float2 start = float2(start_x[i], start_y[i]); + float2 end = float2(end_x[i], end_y[i]); + swept_min = min(swept_min, min(start, end)); + swept_max = max(swept_max, max(start, end)); + } + swept_min -= pixel_size * 0.5; + swept_max += pixel_size * 0.5; + if (t.pos.x < swept_min.x || t.pos.x > swept_max.x || t.pos.y < swept_min.y || t.pos.y > swept_max.y) return color; + + float2 start_center = float2((start_x.x + start_x.y + start_x.z + start_x.w) * 0.25, (start_y.x + start_y.y + start_y.z + start_y.w) * 0.25); + float2 end_center = float2((end_x.x + end_x.y + end_x.z + end_x.w) * 0.25, (end_y.x + end_y.y + end_y.z + end_y.w) * 0.25); + float motion_distance = length((end_center - start_center) * pixel_dims); + + float blend_start = max(clamp(TARGET_BLEND_START, 0.0, 1.0), clamp(TARGET_BLEND_END, 0.0, 1.0)); + float blend_end = min(clamp(TARGET_BLEND_START, 0.0, 1.0), clamp(TARGET_BLEND_END, 0.0, 1.0)); + float start_radius = motion_distance * blend_start; + float end_radius = motion_distance * blend_end; + float target_blend = 0.0; + if (MOTION_BLUR && start_radius > end_radius && motion_distance > 0.0) { + float distance = distance_to_rect_pixels(t.pos, d.cursor_trail_edge, pixel_dims); + // Apply the radial blend before coverage so antialiased edges never + // become opaque merely because they are close to the target. + target_blend = 1.0 - smoothstep(end_radius, start_radius, distance); + } + + float coverage_sum = 0.0; + for (int ti = 0; ti < temporal_samples; ti++) { + float time = MOTION_BLUR ? (float(ti) + 0.5) / float(temporal_samples) : 1.0; + float4 xs = lerp(start_x, end_x, time); + float4 ys = lerp(start_y, end_y, time); + float2 sample_min = float2(1.0, 1.0); + float2 sample_max = float2(0.0, 0.0); + for (int ci = 0; ci < 4; ci++) { + float2 corner = float2(xs[ci], ys[ci]); + sample_min = min(sample_min, corner); + sample_max = max(sample_max, corner); + } + sample_min -= pixel_size * 0.5; + sample_max += pixel_size * 0.5; + if (t.pos.x < sample_min.x || t.pos.x > sample_max.x || t.pos.y < sample_min.y || t.pos.y > sample_max.y) continue; + + float sample_coverage = 0.0; + for (int si = 0; si < spatial_samples; si++) { + float2 sample_pos = t.pos; + if (ANTIALIASING) { + int sx = si % grid_size; + int sy = si / grid_size; + sample_pos += (float2(float(sx) + 0.5, float(sy) + 0.5) / float(grid_size) - 0.5) * pixel_size; + } + // Preserve the terminal-rendered cursor, including hollow and + // blinking cursor states. The trail never paints its rectangle. + if (d.cursor_color.a > 0.0 && inside_rect(sample_pos, d.cursor_trail_edge)) continue; + sample_coverage += trail_coverage(sample_pos, xs, ys); + } + coverage_sum += sample_coverage / float(spatial_samples); + } + float coverage = coverage_sum / float(temporal_samples); + if (coverage <= 0.0) return color; + float opacity = d.cursor_trail_color.a; - if (opacity <= 0.0) return color; - - float2 uv = t.pos; - - float2 c0 = float2(d.cursor_trail_corners_x.x, d.cursor_trail_corners_y.x); // top-right - float2 c1 = float2(d.cursor_trail_corners_x.y, d.cursor_trail_corners_y.y); // bottom-right - float2 c2 = float2(d.cursor_trail_corners_x.z, d.cursor_trail_corners_y.z); // bottom-left - float2 c3 = float2(d.cursor_trail_corners_x.w, d.cursor_trail_corners_y.w); // top-left - - if (!inside_trail_quad(uv, c0, c1, c2, c3)) return color; - - // Mask out the cursor's current rectangle so the real cursor renders cleanly on top. - // cursor_trail_edge: .x=left, .y=right, .z=top, .w=bottom (UV, y-up) - float inside_cursor = - step(d.cursor_trail_edge.x, uv.x) * step(uv.x, d.cursor_trail_edge.y) * step(d.cursor_trail_edge.w, uv.y) * step(uv.y, d.cursor_trail_edge.z); - opacity *= 1.0 - inside_cursor; - if (opacity <= 0.0) return color; - + if (MOTION_BLUR) { + float min_opacity = clamp(MIN_OPACITY, 0.0, 1.0); + opacity = min_opacity + (1.0 - min_opacity) * max(opacity, d.cursor_color.a); + opacity = lerp(opacity, 1.0, target_blend); + } + opacity = clamp(opacity * coverage, 0.0, 1.0); return float4(lerp(color.rgb, d.cursor_trail_color.rgb, opacity), color.a); } diff --git a/kitty/shaders/custom/demo.py b/kitty/shaders/custom/demo.py index dda1105f2..c63f63e80 100755 --- a/kitty/shaders/custom/demo.py +++ b/kitty/shaders/custom/demo.py @@ -146,6 +146,7 @@ metadata: dict[str, dict[str, Any]] = { 'pond-ripple': {'animate': pond_ripple, 'category': 'mouse', 'tagline': 'Clicking is like throwing stones in a pond.'}, 'spotlight': {'animate': spotlight, 'category': 'mouse', 'tagline': 'Spotlight your mouse pointer as it moves around.'}, # Cursor trail + 'cursor-trail-default': {'animate': cursor_trail, 'category': 'cursor-trail', 'tagline': 'A smooth, antialiased cursor trail with temporal motion blur.'}, 'cursor-trail-blaze': {'animate': cursor_trail, 'category': 'cursor-trail', 'tagline': 'Set your cursor on fire as it moves around.'}, 'cursor-trail-lightning': {'animate': cursor_trail, 'category': 'cursor-trail', 'tagline': 'Make your cursor shoot lightning as it moves around.'}, # Navigation diff --git a/kitty/shaders/custom/types.slang b/kitty/shaders/custom/types.slang index fc4f55163..d703bcc54 100644 --- a/kitty/shaders/custom/types.slang +++ b/kitty/shaders/custom/types.slang @@ -45,6 +45,10 @@ public struct KittyCustomShaderData { // animation_progress is NOT tied to trail duration; use cursor_trail_state.x for opacity instead. public float4 cursor_trail_corners_x; // UV x-coordinates of the 4 animated trail quad corners public float4 cursor_trail_corners_y; // UV y-coordinates of the 4 animated trail quad corners + // Previous-frame animated trail quad corners. These are available for + // custom shaders that perform temporal effects. + public float4 cursor_trail_prev_corners_x; + public float4 cursor_trail_prev_corners_y; // .x=left, .y=right, .z=top, .w=bottom UV edges of the current cursor rectangle public float4 cursor_trail_edge; // .x=left, .y=right, .z=top, .w=bottom UV edges of the cursor rectangle before the most recent move. @@ -58,7 +62,6 @@ public struct KittyCustomShaderData { // .rgb = trail color (falls back to cursor_color.rgb when cursor_trail_color option is "none"). // .a = trail opacity (0..1); zero when the trail is inactive. public float4 cursor_trail_color; - // the size in pixels of the full underlying viewport we are rendering too, // before applying any viewport transforms from the current group. // You can use t.viewport to derive the actual size and position of the diff --git a/kitty/shaders/slang.py b/kitty/shaders/slang.py index d87138011..81c80441f 100644 --- a/kitty/shaders/slang.py +++ b/kitty/shaders/slang.py @@ -216,7 +216,7 @@ class LoadShaderPrograms: self(allow_recompile=True) else: opts = self.get_options() - if opts.custom_shaders != self.custom_shaders or self.force_recompile_of_custom_shaders: + if tuple(opts.custom_shaders) != self.custom_shaders or self.force_recompile_of_custom_shaders: self.compile_custom_shaders(allow_recompile=True) def __call__(self, allow_recompile: bool = False) -> None: diff --git a/kitty/state.h b/kitty/state.h index 08aafba8b..f56a9e82e 100644 --- a/kitty/state.h +++ b/kitty/state.h @@ -434,10 +434,13 @@ typedef struct CursorTrail { float opacity; float corner_x[4]; float corner_y[4]; + float previous_corner_x[4]; + float previous_corner_y[4]; float cursor_edge_x[2]; float cursor_edge_y[2]; float prev_cursor_edge_x[2]; // cursor_edge_x before the most recent cursor move float prev_cursor_edge_y[2]; // cursor_edge_y before the most recent cursor move + bool has_previous_position; } CursorTrail; typedef struct Tab { diff --git a/kitty_tests/cursor_trail_test.zsh b/kitty_tests/cursor_trail_test.zsh new file mode 100755 index 000000000..024ad12e3 --- /dev/null +++ b/kitty_tests/cursor_trail_test.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# Exercise the animated cursor trail with frequent, large cursor jumps. +# +# Usage: +# kitty_tests/cursor_trail_test.zsh [iterations] [delay-in-seconds] [shape] +# +# Run this from inside a kitty window built from this checkout. + +iterations=${1:-250} +delay=${2:-0.06} +shape=${3:-} + +case "$shape" in + block) + printf '\033[2 q' + ;; + beam) + printf '\033[6 q' + ;; + underline) + printf '\033[4 q' + ;; + '') + ;; + *) + print -u2 "usage: $0 [iterations] [delay-in-seconds] [block|beam|underline]" + exit 2 + ;; +esac + +i=1 + +while (( i <= iterations )); do + y=$((2 + (i * 11 % 28))) + x=$((2 + (i * 23 % 110))) + printf '\033[%d;%dH' "$y" "$x" + sleep "$delay" + (( i++ )) +done