start work on animation framework for custom shaders

This commit is contained in:
Kovid Goyal 2026-08-06 13:18:10 +05:30
parent 6a89fea569
commit 21772e43cd
No known key found for this signature in database
GPG key ID: 06BC317B515ACE7C
5 changed files with 214 additions and 39 deletions

51
kitty/animation-parse.h Normal file
View file

@ -0,0 +1,51 @@
/*
* animation-parse.h
* Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
*
* Distributed under terms of the GPL3 license.
*/
#pragma once
#include "data-types.h"
#include "animation.h"
// Populate an Animation from a Python EasingFunction NamedTuple
// (kitty.options.utils.EasingFunction). y_at_start/y_at_end are the output
// values at t=0 and t=1 respectively.
static void
add_easing_function(Animation *a, PyObject *e, double y_at_start, double y_at_end) {
#define G(name) RAII_PyObject(name, PyObject_GetAttrString(e, #name))
#define D(container, idx) PyFloat_AsDouble(PyTuple_GET_ITEM(container, idx))
#define EQ(x, val) (PyUnicode_CompareWithASCIIString((x), val) == 0)
G(type);
if (EQ(type, "cubic-bezier")) {
G(cubic_bezier_points);
add_cubic_bezier_animation(
a, y_at_start, y_at_end, D(cubic_bezier_points, 0), D(cubic_bezier_points, 1), D(cubic_bezier_points, 2), D(cubic_bezier_points, 3));
} else if (EQ(type, "linear")) {
G(linear_x);
G(linear_y);
size_t count = PyTuple_GET_SIZE(linear_x);
RAII_ALLOC(double, x, malloc(2 * sizeof(double) * count));
if (x) {
double *y = x + count;
for (size_t i = 0; i < count; i++) {
x[i] = D(linear_x, i);
y[i] = D(linear_y, i);
}
add_linear_animation(a, y_at_start, y_at_end, count, x, y);
}
} else if (EQ(type, "steps")) {
G(num_steps);
G(jump_type);
EasingStep jt = EASING_STEP_END;
if (EQ(jump_type, "start")) jt = EASING_STEP_START;
else if (EQ(jump_type, "none")) jt = EASING_STEP_NONE;
else if (EQ(jump_type, "both")) jt = EASING_STEP_BOTH;
add_steps_animation(a, y_at_start, y_at_end, PyLong_AsSize_t(num_steps), jt);
}
#undef EQ
#undef D
#undef G
}

View file

@ -280,6 +280,7 @@ NO_CURSOR_SHAPE: int
CURSOR_UNDERLINE: int
DECAWM: int
LNM: int
ANIMATION_SAMPLE_WAIT: int
BGIMAGE_PROGRAM: int
CELL_PROGRAM: int
PADDING_PROGRAM: int

View file

@ -9,6 +9,7 @@
#include "../state.h"
#include "../colors.h"
#include "../fonts.h"
#include "../animation-parse.h"
static inline float
PyFloat_AsFloat(PyObject *o) {
@ -249,43 +250,6 @@ window_logo_path(PyObject *src, Options *opts) {
#undef STR_SETTER
static void
add_easing_function(Animation *a, PyObject *e, double y_at_start, double y_at_end) {
#define G(name) RAII_PyObject(name, PyObject_GetAttrString(e, #name))
#define D(container, idx) PyFloat_AsDouble(PyTuple_GET_ITEM(container, idx))
#define EQ(x, val) (PyUnicode_CompareWithASCIIString((x), val) == 0)
G(type);
if (EQ(type, "cubic-bezier")) {
G(cubic_bezier_points);
add_cubic_bezier_animation(
a, y_at_start, y_at_end, D(cubic_bezier_points, 0), D(cubic_bezier_points, 1), D(cubic_bezier_points, 2), D(cubic_bezier_points, 3));
} else if (EQ(type, "linear")) {
G(linear_x);
G(linear_y);
size_t count = PyTuple_GET_SIZE(linear_x);
RAII_ALLOC(double, x, malloc(2 * sizeof(double) * count));
if (x) {
double *y = x + count;
for (size_t i = 0; i < count; i++) {
x[i] = D(linear_x, i);
y[i] = D(linear_y, i);
}
add_linear_animation(a, y_at_start, y_at_end, count, x, y);
}
} else if (EQ(type, "steps")) {
G(num_steps);
G(jump_type);
EasingStep jt = EASING_STEP_END;
if (EQ(jump_type, "start")) jt = EASING_STEP_START;
else if (EQ(jump_type, "none")) jt = EASING_STEP_NONE;
else if (EQ(jump_type, "both")) jt = EASING_STEP_BOTH;
add_steps_animation(a, y_at_start, y_at_end, PyLong_AsSize_t(num_steps), jt);
}
#undef EQ
#undef D
#undef G
}
#define parse_animation(duration, name, start, end) \
opts->duration = parse_s_double_to_monotonic_t(PyTuple_GET_ITEM(src, 0)); \
opts->animation.name = free_animation(opts->animation.name); \

View file

@ -11,6 +11,8 @@
#include "colors.h"
#include <stddef.h>
#include <string.h>
#include "animation.h"
#include "animation-parse.h"
#include "text-cache.h"
#include "tupleobject.h"
#include "window_logo.h"
@ -386,6 +388,17 @@ static ssize_t custom_end_vao_idx = -1;
typedef enum { CUSTOM_SHADER_TEXTURE_DEFAULT, CUSTOM_SHADER_TEXTURE_A, CUSTOM_SHADER_TEXTURE_B, CUSTOM_SHADER_TEXTURE_PERSIST } NamedTexture;
typedef enum {
SHADER_ANIM_EVENT_POINTER_LEFT_BUTTON_PRESS,
SHADER_ANIM_EVENT_OS_WINDOW_FOCUS_IN,
SHADER_ANIM_EVENT_OS_WINDOW_FOCUS_OUT,
SHADER_ANIM_EVENT_WINDOW_FOCUS_IN,
SHADER_ANIM_EVENT_WINDOW_FOCUS_OUT,
SHADER_ANIM_EVENT_TAB_CHANGE,
SHADER_ANIM_EVENT_BELL_IN_WINDOW,
NUM_SHADER_ANIM_EVENTS
} ShaderAnimationEvent;
typedef struct CustomShaderGroup {
struct {
float x, y;
@ -394,6 +407,11 @@ typedef struct CustomShaderGroup {
float w, h;
} viewport_size;
NamedTexture output_texture;
unsigned animation_start_events; // bitmask of ShaderAnimationEvent values; 0 = no animation
unsigned animation_end_events; // bitmask of events that stop the animation; 0 = none
monotonic_t animation_end_duration; // nanoseconds; 0 = no time limit
monotonic_t animation_step; // nanoseconds between animation samples
Animation *animation_curve; // parsed easing curve; NULL = no animation
} CustomShaderGroup;
typedef struct CustomShaderPipeline {
@ -401,6 +419,7 @@ typedef struct CustomShaderPipeline {
CustomShaderGroup groups[64];
size_t num_groups;
bool active;
unsigned all_animation_start_events; // union of animation_start_events across all groups
} CustomShaderPipeline;
static struct {
@ -2516,6 +2535,11 @@ pygpu_driver_version_string(PyObject *self UNUSED, PyObject *args UNUSED) {
return PyUnicode_FromString(global_state.gl_version ? gl_version_string() : "");
}
static void
free_custom_shader_pipeline(CustomShaderPipeline *p) {
for (size_t i = 0; i < p->num_groups; i++) p->groups[i].animation_curve = free_animation(p->groups[i].animation_curve);
}
static NamedTexture
named_texture_from_str(const char *s) {
if (strcmp(s, "a") == 0) return CUSTOM_SHADER_TEXTURE_A;
@ -2524,6 +2548,28 @@ named_texture_from_str(const char *s) {
return CUSTOM_SHADER_TEXTURE_DEFAULT;
}
static unsigned
shader_anim_event_bit(const char *s) {
if (strcmp(s, "pointer-left-button-press") == 0) return 1u << SHADER_ANIM_EVENT_POINTER_LEFT_BUTTON_PRESS;
if (strcmp(s, "os-window-focus-in") == 0) return 1u << SHADER_ANIM_EVENT_OS_WINDOW_FOCUS_IN;
if (strcmp(s, "os-window-focus-out") == 0) return 1u << SHADER_ANIM_EVENT_OS_WINDOW_FOCUS_OUT;
if (strcmp(s, "window-focus-in") == 0) return 1u << SHADER_ANIM_EVENT_WINDOW_FOCUS_IN;
if (strcmp(s, "window-focus-out") == 0) return 1u << SHADER_ANIM_EVENT_WINDOW_FOCUS_OUT;
if (strcmp(s, "tab-change") == 0) return 1u << SHADER_ANIM_EVENT_TAB_CHANGE;
if (strcmp(s, "bell-in-window") == 0) return 1u << SHADER_ANIM_EVENT_BELL_IN_WINDOW;
return 0;
}
static unsigned
parse_anim_event_sequence(PyObject *seq) {
unsigned mask = 0;
for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); i++) {
PyObject *item = PySequence_Fast_GET_ITEM(seq, i);
if (PyUnicode_Check(item)) mask |= shader_anim_event_bit(PyUnicode_AsUTF8(item));
}
return mask;
}
static bool
transfer_pipeline_to_struct(PyObject *pg, CustomShaderPipeline *p) {
#define is_seq(x) (x && (PyList_Check(x) || PyTuple_Check(x)))
@ -2568,7 +2614,26 @@ transfer_pipeline_to_struct(PyObject *pg, CustomShaderPipeline *p) {
}
PyObject *ot = PyDict_GetItemString(g, "output_texture");
if (ot && PyUnicode_Check(ot)) { cg->output_texture = named_texture_from_str(PyUnicode_AsUTF8(ot)); }
PyObject *astart = PyDict_GetItemString(g, "animation_start");
if (is_seq(astart)) cg->animation_start_events = parse_anim_event_sequence(astart);
PyObject *acurve = PyDict_GetItemString(g, "animation_curve");
if (acurve && PyObject_IsTrue(acurve)) {
if ((cg->animation_curve = alloc_animation()) != NULL) add_easing_function(cg->animation_curve, acurve, 0.0, 1.0);
}
PyObject *astep = PyDict_GetItemString(g, "animation_step");
cg->animation_step = (astep && PyLong_Check(astep)) ? (monotonic_t)PyLong_AsLong(astep) : ANIMATION_SAMPLE_WAIT;
PyObject *ae_events = PyDict_GetItemString(g, "animation_end_events");
if (is_seq(ae_events)) cg->animation_end_events = parse_anim_event_sequence(ae_events);
PyObject *ae_dur = PyDict_GetItemString(g, "animation_end_duration");
if (ae_dur && ae_dur != Py_None && PyLong_Check(ae_dur)) cg->animation_end_duration = (monotonic_t)PyLong_AsLong(ae_dur);
}
p->all_animation_start_events = 0;
for (size_t i = 0; i < p->num_groups; i++) p->all_animation_start_events |= p->groups[i].animation_start_events;
#undef is_seq
return true;
}
@ -2612,7 +2677,10 @@ compile_program(PyObject UNUSED *self, PyObject *args) {
}
Program *program = program_ptr(which);
if (!PyTuple_GET_SIZE(vertex_shaders)) {
if (which == CUSTOM_END_PROGRAM) { zero_at_ptr(&custom_shaders.end); }
if (which == CUSTOM_END_PROGRAM) {
free_custom_shader_pipeline(&custom_shaders.end);
zero_at_ptr(&custom_shaders.end);
}
if (program->id != 0) {
glDeleteProgram(program->id);
program->id = 0;
@ -2648,6 +2716,7 @@ compile_program(PyObject UNUSED *self, PyObject *args) {
}
#undef fail_compile
if (which == CUSTOM_END_PROGRAM) {
free_custom_shader_pipeline(&custom_shaders.end);
zero_at_ptr(&custom_shaders.end);
PyObject *pg = PyDict_GetItemString(metadata, "pipeline");
if (pg && !transfer_pipeline_to_struct(pg, &custom_shaders.end)) {
@ -2745,6 +2814,7 @@ cleanup_shader_resources_on_terminate(void) {
static void
finalize(void) {
default_visual_bell_animation = free_animation(default_visual_bell_animation);
free_custom_shader_pipeline(&custom_shaders.end);
free_program_layouts();
}
@ -2820,6 +2890,7 @@ init_shaders(PyObject *module) {
C(GL_UNSIGNED_INT);
C(GL_ARRAY_BUFFER);
C(GL_UNIFORM_BUFFER);
C(ANIMATION_SAMPLE_WAIT);
#undef C
if (PyModule_AddFunctions(module, module_methods) != 0) return false;

View file

@ -24,6 +24,7 @@ from typing import Any, Callable, Iterable, Iterator, Literal, NamedTuple, Typed
from kitty.constants import read_kitty_resource, shaders_dir, slangc
from kitty.fast_data_types import (
ANIMATION_SAMPLE_WAIT,
BGIMAGE_PROGRAM,
BLINK,
BLIT_PROGRAM,
@ -56,6 +57,7 @@ from kitty.fast_data_types import (
get_options,
)
from kitty.options.types import Options, defaults
from kitty.options.utils import EasingFunction
from kitty.types import run_once
from kitty.utils import lock_with_file, log_error, resolve_custom_file
@ -1095,6 +1097,56 @@ def is_valid_slot(x: str) -> TypeGuard[Slot]:
VALID_VAR_TYPES: frozenset[str] = frozenset({'uint', 'int', 'float', 'double', 'bool'})
SHADER_ANIMATION_EVENTS: frozenset[str] = frozenset({
'pointer-left-button-press',
'os-window-focus-in',
'os-window-focus-out',
'window-focus-in',
'window-focus-out',
'tab-change',
'bell-in-window',
})
def is_valid_animation_event(name: str) -> bool:
return name in SHADER_ANIMATION_EVENTS
def parse_animation_events(raw: str) -> tuple[str, ...]:
events = raw.split('|')
for e in events:
if not is_valid_animation_event(e):
raise ValueError(f'{e!r} is not a valid animation event name; valid names: {", ".join(sorted(SHADER_ANIMATION_EVENTS))}')
return tuple(events)
def parse_css_animation_curve(spec: str) -> EasingFunction:
_NAMED: dict[str, tuple[str, str]] = {
'ease-in-out': ('cubic-bezier', '0.42, 0, 0.58, 1'),
'linear': ('cubic-bezier', '0, 0, 1, 1'),
'ease': ('cubic-bezier', '0.25, 0.1, 0.25, 1'),
'ease-out': ('cubic-bezier', '0, 0, 0.58, 1'),
'ease-in': ('cubic-bezier', '0.42, 0, 1, 1'),
'step-start': ('steps', '1, start'),
'step-end': ('steps', '1, end'),
}
def make(func_name: str, params: str) -> EasingFunction:
if func_name == 'cubic-bezier':
return EasingFunction.cubic_bezier(params)
if func_name == 'linear':
return EasingFunction.linear(params)
if func_name == 'steps':
return EasingFunction.steps(params)
raise ValueError(f'{func_name!r} is not a valid easing function type')
spec = spec.strip()
if spec in _NAMED:
return make(*_NAMED[spec])
m = re.match(r'^([-a-zA-Z]+)\(([^)]+)\)$', spec)
if m:
return make(m.group(1), m.group(2))
raise ValueError(f'{spec!r} is not a recognized CSS animation curve')
@run_once
@ -1139,6 +1191,11 @@ class Group(TypedDict):
output_texture: NamedTexture
shaders: tuple[str, ...]
vars: dict[str, tuple[str, str]]
animation_start: tuple[str, ...] # empty = no animation
animation_curve: EasingFunction # parsed easing curve
animation_step: int # nanoseconds between animation samples
animation_end_events: tuple[str, ...] # events that stop the animation
animation_end_duration: int | None # nanoseconds; None = no time limit
class Pipeline(TypedDict):
@ -1166,7 +1223,12 @@ def parse_pipeline_definition(lines: Iterable[str], pipeline_name: str, pipeline
current_group = None
def init_group(*shaders: str) -> Group:
return {'viewport_pos': (0, 0), 'viewport_size': (1, 1), 'output_texture': NamedTexture.default, 'shaders': shaders, 'vars': {}}
return {
'viewport_pos': (0, 0), 'viewport_size': (1, 1), 'output_texture': NamedTexture.default,
'shaders': shaders, 'vars': {},
'animation_start': (), 'animation_curve': EasingFunction(),
'animation_step': ANIMATION_SAMPLE_WAIT, 'animation_end_events': (), 'animation_end_duration': None,
}
for line in lines:
line = line.strip()
@ -1204,6 +1266,32 @@ def parse_pipeline_definition(lines: Iterable[str], pipeline_name: str, pipeline
case 'var':
var_type, var_name, value = parse_var_directive(parts)
current_group['vars'][var_name] = (var_type, value)
case 'animation_start':
val = parts[1] if len(parts) > 1 else 'none'
current_group['animation_start'] = () if val == 'none' else parse_animation_events(val)
case 'animation_curve':
if len(parts) < 2:
raise ValueError('animation_curve requires a CSS curve name')
current_group['animation_curve'] = parse_css_animation_curve(' '.join(parts[1:]))
case 'animation_step':
if len(parts) < 2:
raise ValueError('animation_step requires a millisecond value')
current_group['animation_step'] = int(parts[1]) * 1_000_000
case 'animation_end':
val = parts[1] if len(parts) > 1 else 'never'
if val == 'never':
current_group['animation_end_events'] = ()
current_group['animation_end_duration'] = None
else:
end_events: list[str] = []
end_duration: int | None = None
for token in val.split('|'):
try:
end_duration = int(token) * 1_000_000
except ValueError:
end_events.extend(parse_animation_events(token))
current_group['animation_end_events'] = tuple(end_events)
current_group['animation_end_duration'] = end_duration
case 'endgroup':
commit_group()
case _: