summaryrefslogtreecommitdiff
path: root/src/anim/player.zig
blob: c9f2169b803d6f88455864ddc9ebc8515fae5e8a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
//! The `anim` module's player: plays the scene file it is built around
//! (`sb.addScene`), compiled or live, as a manim-style animation drawn by
//! the vector library on the GPU (or the CPU, with B). Time is state;
//! everything else is a function of it (and, for a live scene, of the
//! input).
//!
//!   space  pause / play          left/right  previous / next play
//!   click  continue after a pause (`s.pause()` in the scene)
//!   ,/.    step back / ahead     home/end    start / end
//!   up/down speed                B           GPU or CPU renderer
//!   G      guides: boxes, origins and axes, in scene units
//!   drag, wheel: look around     R           reset the view
//!
//! The scene's frame, 1280x720 scene units around its origin, is fitted
//! into the canvas, and the canvas is the room the host has: the window, or
//! an export's `--size`. Exported (`in.exporting`), the scene plays through
//! once, without pauses or controls, and the player quits.
const std = @import("std");
const sk = @import("sketch");
const vector = @import("vector");
const anim = @import("anim");
const scene_file = @import("scene");
const scene = scene_file.scene;
/// The scene's Typst sources, compiled at build time.
const typst = @import("typst");

pub const name = if (@hasDecl(scene_file, "name")) scene_file.name else "anim";
/// The page: the scene file's `background` (0xRRGGBB), or manim's.
const background: u32 = if (@hasDecl(scene_file, "background")) scene_file.background else anim.background;
/// The scene's frame, in scene units: what shows at camera zoom 1.
pub const width = anim.width;
pub const height = anim.height;

pub const State = struct {
    t: f32 = 0,
    playing: bool = true,
    speed: f32 = 1,
    looping: bool = true,
    backend: vector.Backend = .gpu,
    /// The viewer's own pan and zoom, on top of the scene's camera.
    view: sk.Camera = .{},
    dragging: bool = false,
    /// Where the left button went down: a click, not a drag, continues.
    press: [2]f32 = .{ 0, 0 },
    guides: bool = false,
};

pub const Session = struct {
    painter: anim.Painter = .{},
    /// Smoothed time to record a frame.
    render_ns: f32 = 0,
};

pub fn update(s: *State, in: *const sk.Input) void {
    // The timeline as it stands: a live scene builds it as it runs.
    var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
    defer arena.deinit();
    const shot = scene.shot(arena.allocator(), .{ .t = s.t }) catch return;
    for (in.events) |e| switch (e.kind) {
        // Exported: nobody clicks, so straight through, once.
        .tick => if (in.exporting) {
            s.t += e.x;
        } else if (s.playing and !held(s.t, shot)) {
            const next = s.t + e.x * s.speed;
            s.t = stopBetween(s.t, next, shot) orelse next;
            if (s.t > shot.duration + 1) s.t = if (s.looping) 0 else shot.duration;
        },
        .key_down => if (e.flags & sk.Event.repeat == 0 or key(e) == .left or key(e) == .right or key(e) == .comma or key(e) == .period) switch (key(e)) {
            .space => if (s.playing and held(s.t, shot)) proceed(s) else {
                s.playing = !s.playing;
            },
            .home => s.t = 0,
            .end => s.t = shot.duration,
            .left => s.t = previousMark(s.t, shot),
            .right => s.t = nextMark(s.t, shot),
            .comma => s.t = @max(s.t - 1.0 / 30.0, 0),
            .period => s.t = @min(s.t + 1.0 / 30.0, shot.duration),
            .up => s.speed = @min(s.speed * 2, 8),
            .down => s.speed = @max(s.speed / 2, 0.125),
            .b => s.backend = if (s.backend == .gpu) .cpu else .gpu,
            .g => s.guides = !s.guides,
            .l => s.looping = !s.looping,
            .r => s.view = .{},
            else => {},
        },
        .mouse_down => if (e.code == 1) {
            s.dragging = true;
            s.press = .{ e.x, e.y };
        },
        .mouse_up => {
            const click = @abs(e.x - s.press[0]) + @abs(e.y - s.press[1]) < 4;
            if (s.dragging and click and held(s.t, shot)) proceed(s);
            s.dragging = false;
        },
        .cancel => s.dragging = false,
        .mouse_move => if (s.dragging) s.view.pan(.{ .x = e.x - in.mouse_x, .y = e.y - in.mouse_y }),
        .wheel => s.view.zoomAt(e, e.wheel(), .{ .min = 0.2, .max = 20 }),
        else => {},
    };
}

fn key(e: sk.Event) sk.Key {
    return @fromBackingInt(@intCast(@as(u8, @truncate(e.code))));
}

/// Waiting at a pause for a click.
fn held(t: f32, shot: anim.Shot) bool {
    for (shot.stops) |stop| if (stop == t) return true;
    return false;
}

/// The first pause in `(from, to]`.
fn stopBetween(from: f32, to: f32, shot: anim.Shot) ?f32 {
    for (shot.stops) |stop| if (stop > from and stop <= to) return stop;
    return null;
}

/// Past the pause the player waits at.
fn proceed(s: *State) void {
    s.t += 1e-3;
    s.playing = true;
}

fn previousMark(t: f32, shot: anim.Shot) f32 {
    var best: f32 = 0;
    for (shot.marks) |m| if (m < t - 0.25) {
        best = m;
    };
    return best;
}

fn nextMark(t: f32, shot: anim.Shot) f32 {
    for (shot.marks) |m| if (m > t + 0.01) return m;
    return shot.duration;
}

/// The mouse in scene units from the canvas center, before the scene's
/// camera: the viewer's pan and zoom undone.
fn pointer(s: *const State, in: *const sk.Input, canvas: sk.Rect) [2]f32 {
    const k = anim.Painter.fit(canvas);
    return .{ ((in.mouse_x - s.view.x) / s.view.zoom - canvas.w / 2) / k, ((in.mouse_y - s.view.y) / s.view.zoom - canvas.h / 2) / k };
}

pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
    // All the room there is: the window, or the size an export asks for.
    const canvas: sk.Rect = .{ .w = @max(@floor(f.in.window_width), 1), .h = @max(@floor(f.in.window_height), 1) };
    const started = f.host.clock();
    const shot = scene.shot(f.scratch, .{
        .t = s.t,
        .in = f.in,
        .pointer = pointer(s, f.in, canvas),
    }) catch |err| return f.host.print("scene: {t}", .{err});
    ss.painter.paint(f, shot, typst, .{ .view = s.view, .backend = s.backend, .guides = s.guides, .background = background }) catch |err| f.host.print("render: {t}", .{err});
    if (f.in.exporting) {
        // The frame that shows the end is the last.
        if (s.t >= shot.duration) f.quit();
        return;
    }
    const elapsed: f32 = @floatFromInt(f.host.clock() -| started);
    ss.render_ns = if (ss.render_ns == 0) elapsed else ss.render_ns * 0.9 + elapsed * 0.1;
    hud(s, ss, f, shot, canvas);
}

fn hud(s: *const State, ss: *const Session, f: *sk.Frame, shot: anim.Shot, canvas: sk.Rect) void {
    const w = canvas.w;
    const h = canvas.h;
    var play: usize = 0;
    for (shot.marks, 1..) |m, i| if (m <= s.t) {
        play = i;
    };
    const backend = if (s.backend == .gpu and f.host.gpu()) "GPU" else "CPU";
    const status = if (!s.playing) "  paused" else if (held(s.t, shot)) "  click to continue" else "";
    f.fill(sk.Rect{ .y = h - 28, .w = w, .h = 28 }, sk.Color{ .r = 0, .g = 0, .b = 0, .a = 150 });
    f.print(12, h - 19, 1, 0xece6e2, "{d:5.2}s / {d:.2}s  play {d}/{d}  {s}  record {d:.3}ms  {d} shapes  speed x{d}{s}", .{
        s.t, shot.duration, play, shot.marks.len, backend, ss.render_ns / 1e6, ss.painter.shapes, s.speed, status,
    });
    if (s.guides) {
        const p = pointer(s, f.in, canvas);
        f.print(w - 540, h - 19, 1, anim.yellow, "pointer {d:.0},{d:.0}", .{ p[0], p[1] });
    }
    f.text(w - 400, h - 19, 1, "space click <- -> , . B G drag wheel", 0x8c8c8c);
    f.cursor(.arrow);
}