diff options
Diffstat (limited to 'src/anim/player.zig')
| -rw-r--r-- | src/anim/player.zig | 386 |
1 files changed, 86 insertions, 300 deletions
diff --git a/src/anim/player.zig b/src/anim/player.zig index 090b6cb..b329714 100644 --- a/src/anim/player.zig +++ b/src/anim/player.zig @@ -1,20 +1,26 @@ //! 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). +//! the vector library on the GPU (or the CPU, with B). Its state is an +//! `anim.Deck`, the playhead and the gates opened, and the viewer's own +//! settings; the picture is a function of them (and, for a live scene, of +//! the input). A scene that pauses is a talk, and steps: //! -//! space pause / play left/right previous / next play -//! click continue after a pause (`s.pause()` in the scene) +//! click, space, page down next step: open the pause the talk waits at, +//! or finish the step under way (in a scene with +//! no pause, space plays or pauses) +//! page up, backspace back a step: the picture before the last click +//! ] / [ next / previous slide (`s.slide()`), at rest +//! P play / pause left/right previous / next play //! ,/. step back / ahead home/end start / end //! up/down speed B GPU or CPU renderer -//! G guides: boxes, origins and axes, in scene units +//! L loop (not a talk) G guides: boxes, origins, axes //! 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. +//! once without controls, each pause held for the scene file's `hold` +//! seconds (1 without one), and the player quits at the end. const std = @import("std"); const sk = @import("sketch"); const vector = @import("vector"); @@ -23,71 +29,67 @@ const scene_file = @import("scene"); const scene = scene_file.scene; /// The scene's Typst sources, compiled at build time. const typst = @import("typst"); -const geom = vector.geom; 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; +/// Exported, how long each pause holds. +const hold: f32 = if (@hasDecl(scene_file, "hold")) scene_file.hold else 1; /// The scene's frame, in scene units: what shows at camera zoom 1. -pub const width = 1280; -pub const height = 720; +pub const width = anim.width; +pub const height = anim.height; pub const State = struct { - t: f32 = 0, - playing: bool = true, - speed: f32 = 1, + deck: anim.Deck = .{ .hold = hold }, 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. + /// Where the left button went down: a click, not a drag, steps. press: [2]f32 = .{ 0, 0 }, guides: bool = false, }; pub const Session = struct { - /// A renderer per run of vector objects between custom ones (`paint`). - gpu: std.ArrayList(vector.Renderer(.gpu)) = .empty, - cpu: std.ArrayList(vector.Renderer(.cpu)) = .empty, - /// Drawings by what they look like (`Object.id`), built on first use and - /// dropped on reload, since the code that builds them may have changed. - /// Their memory is the host's, kept across reloads. - arena: ?std.heap.ArenaAllocator = null, - drawings: std.AutoHashMapUnmanaged(u64, Built) = .empty, - /// Smoothed time to record a frame, and its shape count. + painter: anim.Painter = .{}, + /// Smoothed time to record a frame. render_ns: f32 = 0, - shapes: usize = 0, }; -const Built = struct { drawing: vector.Drawing, bounds: geom.Rect }; +/// A live scene's frame, or a compiled scene as a talk without gates. +const talk = if (@hasDecl(scene, "frame")) scene.frame else struct { + fn frame(s: *anim.Frame) void { + s.cursor = scene.duration; + } +}.frame; 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; + const d = &s.deck; + // A scene that waits somewhere is a talk: clicks and space step it. + const talking = d.gates > 0; + var ask: anim.Ask = .{}; + var mark: enum { none, previous, next } = .none; 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; + .key_down => if (e.flags & sk.Event.repeat == 0 or e.key() == .left or e.key() == .right or e.key() == .comma or e.key() == .period) switch (e.key()) { + .space => if (talking) { + ask.next = true; + } else { + d.playing = !d.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), + .page_down => ask.next = true, + .page_up, .backspace => ask.back = true, + .right_bracket => ask.next_slide = true, + .left_bracket => ask.back_slide = true, + .p => d.playing = !d.playing, + .home => ask.to = 0, + .end => ask.end = true, + .left => mark = .previous, + .right => mark = .next, + .comma => ask.to = @max((ask.to orelse d.t) - 1.0 / 30.0, 0), + .period => ask.to = @min((ask.to orelse d.t) + 1.0 / 30.0, d.duration), + .up => d.speed = @min(d.speed * 2, 8), + .down => d.speed = @max(d.speed / 2, 0.125), .b => s.backend = if (s.backend == .gpu) .cpu else .gpu, .g => s.guides = !s.guides, .l => s.looping = !s.looping, @@ -100,7 +102,7 @@ pub fn update(s: *State, in: *const sk.Input) void { }, .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); + if (s.dragging and click and talking) ask.next = true; s.dragging = false; }, .cancel => s.dragging = false, @@ -108,28 +110,26 @@ pub fn update(s: *State, in: *const sk.Input) void { .wheel => s.view.zoomAt(e, e.wheel(), .{ .min = 0.2, .max = 20 }), else => {}, }; + if (mark != .none) { + // The plays as the scene lays them now. + var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); + defer arena.deinit(); + if (shotNow(s, arena.allocator(), in, .{ 0, 0 })) |shot| { + ask.to = if (mark == .previous) previousMark(d.t, shot) else nextMark(d.t, shot); + } else |_| {} + } + // Played past the end: from the start again, or held there (a talk + // holds its last picture). + if (!in.exporting and d.t > d.duration + 1) { + if (s.looping and !talking) ask.to = 0 else d.t = d.duration; + } + d.update(in, ask, talk, .{}); } -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; +/// The scene at the deck's `t`: a live one through the deck, with its gates. +fn shotNow(s: *const State, arena: std.mem.Allocator, in: *const sk.Input, mouse: [2]f32) !anim.Shot { + if (@hasDecl(scene, "frame")) return s.deck.shot(arena, in, mouse, scene.frame, .{}); + return scene.shot(arena, .{ .t = s.deck.t, .in = in, .pointer = mouse }); } fn previousMark(t: f32, shot: anim.Shot) f32 { @@ -145,33 +145,22 @@ fn nextMark(t: f32, shot: anim.Shot) f32 { return shot.duration; } -/// Canvas pixels per scene unit: the scene's frame, fitted into `canvas`. -fn fit(canvas: sk.Rect) f32 { - return @min(canvas.w / width, canvas.h / height); -} - /// 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 = fit(canvas); + 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) }; - f.canvas(@intFromFloat(canvas.w), @intFromFloat(canvas.h)); const started = f.host.clock(); - const shot = scene.shot(f.scratch, .{ - .t = s.t, - .clock = @floatCast(@mod(@as(f64, @floatFromInt(f.in.now)) / std.time.ns_per_s, 3600)), - .in = f.in, - .pointer = pointer(s, f.in, canvas), - }) catch |err| return f.host.print("scene: {t}", .{err}); - render(s, ss, f, shot, canvas) catch |err| f.host.print("render: {t}", .{err}); + const shot = shotNow(s, f.scratch, f.in, 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(); + if (s.deck.t >= shot.duration) f.quit(); return; } const elapsed: f32 = @floatFromInt(f.host.clock() -| started); @@ -179,234 +168,31 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void { hud(s, ss, f, shot, canvas); } -fn render(s: *const State, ss: *Session, f: *sk.Frame, shot: anim.Shot, canvas: sk.Rect) !void { - if (ss.arena == null) ss.arena = .init(f.session); - // A live scene may make new drawings every frame: start over now and then. - if (f.in.reloaded or ss.drawings.count() > 1024) { - _ = ss.arena.?.reset(.retain_capacity); - ss.drawings = .empty; - } - // Use the host's GPU when it has one. - if (s.backend == .gpu and f.host.gpu()) try paint(s, ss, &ss.gpu, f, shot, canvas) else try paint(s, ss, &ss.cpu, f, shot, canvas); -} - -/// Object `o`'s drawing, centered on its origin, and its bounds. -fn built(ss: *Session, o: anim.Object) !Built { - const id = o.id(); - if (ss.drawings.get(id)) |b| return b; - const arena = ss.arena.?.allocator(); - const d = try anim.build(arena, o, typst); - const b: Built = .{ .drawing = d, .bounds = d.bounds().rect() }; - try ss.drawings.put(arena, id, b); - return b; -} - -/// Scene units to canvas pixels: the scene's camera, then the viewer's. -/// The scene's origin is the canvas center. -fn stage(s: *const State, cam: anim.Camera, canvas: sk.Rect) geom.Affine { - const k = fit(canvas) * cam.zoom; - return geom.Affine.translate(s.view.x, s.view.y) - .mul(.scale(s.view.zoom, s.view.zoom)) - .mul(.translate(canvas.w / 2, canvas.h / 2)) - .mul(.scale(k, k)) - .mul(.rotate(-cam.rotation)) - .mul(.translate(-cam.x, -cam.y)); -} - -/// The next of `layers`, begun: a renderer the size of the canvas. -fn begun(layers: anytype, used: *usize, f: *sk.Frame, canvas: sk.Rect, clear: vector.Drawing.Color) !*@TypeOf(layers.items[0]) { - if (used.* == layers.items.len) try layers.append(f.session, try .init(f.session, f.host, @intFromFloat(canvas.w), @intFromFloat(canvas.h))); - const r = &layers.items[used.*]; - used.* += 1; - r.begin(f, clear); - return r; -} - -/// Draws `shot` with the renderers in `layers` (either backend), objects -/// in the order they were added. Vector objects go into a renderer's image, -/// which is then drawn on the canvas; a custom object draws on the canvas -/// itself. So the vector objects before a custom one and those after it -/// are separate images, one renderer each: every GPU pass of a frame runs -/// before its first 2D command, and one image could only show the last. -fn paint(s: *const State, ss: *Session, layers: anytype, f: *sk.Frame, shot: anim.Shot, canvas: sk.Rect) !void { - if (layers.items.len > 0 and (layers.items[0].width() != @as(u32, @intFromFloat(canvas.w)) or layers.items[0].height() != @as(u32, @intFromFloat(canvas.h)))) { - for (layers.items) |*r| r.deinit(f.host); - layers.clearRetainingCapacity(); - } - const world = stage(s, shot.camera, canvas); - var used: usize = 0; - // The first layer is the background too. - var open: ?*@TypeOf(layers.items[0]) = try begun(layers, &used, f, canvas, anim.color(background)); - var shapes: usize = 0; - for (shot.objects, shot.poses, 0..) |o, pose, i| { - if (!pose.visible or pose.opacity <= 0) continue; - const m = world.mul(model(pose)); - if (o.source == .custom) { - if (open) |r| r.present(f, canvas); - open = null; - o.source.custom.draw(o.source.custom.ctx, f, .{ .t = s.t, .pose = pose, .xf = m, .scale = m.scaleFactor(), .stage = world, .values = shot.values }); - // It leaves no target, clip or blend behind. - f.target(.none); - f.blend(.alpha); - continue; - } - const r = open orelse try begun(layers, &used, f, canvas, .{ 0, 0, 0, 0 }); - open = r; - const d = (try built(ss, o)).drawing; - if (pose.into != anim.Pose.none and pose.morph > 0 and pose.morph < 1 and shot.objects[pose.into].source != .custom) { - // Morphing: from where this object began the transform to where - // its target will stand. - const morph = shot.morphs[i]; - const target = (try built(ss, shot.objects[pose.into])).drawing; - const between = try vector.morph.between(f.scratch, d, world.mul(model(morph.from)), target, world.mul(model(morph.to)), pose.morph); - try r.draw(between, .identity, pose.opacity); - shapes += between.shapes.len; - continue; - } - try reveal(r, d, m, pose, fit(canvas)); - shapes += d.shapes.len; - } - if (s.guides) { - const r = open orelse try begun(layers, &used, f, canvas, .{ 0, 0, 0, 0 }); - open = r; - try r.draw(try guides(ss, f.scratch, shot, world, canvas), .identity, 1); - } - if (open) |r| r.present(f, canvas); - ss.shapes = shapes; - if (s.guides) try labels(ss, f, shot, world); -} - -fn model(p: anim.Pose) geom.Affine { - return geom.Affine.translate(p.x, p.y).mul(.rotate(p.rotation)).mul(.scale(p.scale, p.scale)); -} - -/// manim's reveals, shape by shape with a stagger: Write traces each outline -/// then fills it; Create draws strokes along their length, then fills. -/// Outlines are `k` canvas pixels to the scene unit wide. -fn reveal(r: anytype, d: vector.Drawing, m: geom.Affine, pose: anim.Pose, k: f32) !void { - const n: f32 = @floatFromInt(d.shapes.len); - const lag: f32 = if (pose.drawn >= 1) 0 else 0.08; - const window = 1 / (1 + lag * @max(n - 1, 0)); - const glow = pose.highlight; - for (d.shapes, 0..) |shape, i| { - const local = std.math.clamp((pose.drawn - @as(f32, @floatFromInt(i)) * lag * window) / window, 0, 1); - if (local <= 0) continue; - var o: vector.Options = .{ .alpha = pose.opacity }; - switch (pose.reveal) { - .write => if (local < 1) { - o.trim = @min(local * 2, 1); - o.outline = .{ .width = 1.5 * k, .alpha = 1 - std.math.clamp(local * 2 - 1, 0, 1) }; - o.stroke = false; - // Fill arrives in the second half. - var fill = o; - fill.outline = null; - fill.alpha = pose.opacity * std.math.clamp(local * 2 - 1, 0, 1); - try r.drawShape(d, shape, m, fill); - o.fill = false; - }, - .create => if (local < 1) { - o.trim = local; - if (shape.style.stroke == .none) o.outline = .{ .width = 2 * k }; - var fill = o; - fill.stroke = false; - fill.outline = null; - fill.alpha = pose.opacity * std.math.clamp(local * 3 - 2, 0, 1); - try r.drawShape(d, shape, m, fill); - o.fill = false; - }, - } - try r.drawShape(d, shape, m, o); - if (glow > 0) { - // Indicate: a yellow glow over the shape. - var hot = shape; - hot.style.fill = if (shape.style.fill != .none) .{ .color = anim.color(anim.yellow) } else .none; - hot.style.stroke = if (shape.style.stroke != .none) .{ .color = anim.color(anim.yellow) } else .none; - try r.drawShape(d, hot, m, .{ .alpha = pose.opacity * glow }); - } - } -} - -/// Spacing of the guides' ticks, in scene units. -const tick = 100; - -fn guideStyle(c: u32, w: f32) vector.Drawing.Style { - return .{ .fill = .none, .stroke = .{ .color = anim.color(c) }, .stroke_width = w }; -} - -/// The scene's axes with ticks, and each visible object's bounding box (a -/// custom object has none) and origin, in canvas pixels. -fn guides(ss: *Session, arena: std.mem.Allocator, shot: anim.Shot, world: geom.Affine, canvas: sk.Rect) !vector.Drawing { - var b: vector.Drawing.Builder = .init(arena); - const far = 100 * tick; - try b.lineTo(world.apply(.{ -far, 0 }), world.apply(.{ far, 0 })); - try b.closeSubpath(false); - try b.endShape(.identity, guideStyle(anim.red, 1.5)); - try b.lineTo(world.apply(.{ 0, -far }), world.apply(.{ 0, far })); - try b.closeSubpath(false); - try b.endShape(.identity, guideStyle(anim.green, 1.5)); - var i: f32 = -20; - while (i <= 20) : (i += 1) { - const x = world.apply(.{ i * tick, 0 }); - const y = world.apply(.{ 0, i * tick }); - try b.lineTo(x - geom.Vec{ 0, 5 }, x + geom.Vec{ 0, 5 }); - try b.closeSubpath(false); - try b.lineTo(y - geom.Vec{ 5, 0 }, y + geom.Vec{ 5, 0 }); - try b.closeSubpath(false); - } - try b.endShape(.identity, guideStyle(0x8c8c8c, 1)); - - for (shot.objects, shot.poses) |o, pose| { - if (!pose.visible or pose.opacity <= 0) continue; - const m = world.mul(model(pose)); - if (o.source != .custom) { - const r = (try built(ss, o)).bounds; - try b.polyline(&.{ m.apply(.{ r.x, r.y }), m.apply(.{ r.x + r.w, r.y }), m.apply(.{ r.x + r.w, r.y + r.h }), m.apply(.{ r.x, r.y + r.h }) }, true); - } - // The object's origin: where its pose puts it. - const c = m.apply(.{ 0, 0 }); - try b.lineTo(c - geom.Vec{ 6, 0 }, c + geom.Vec{ 6, 0 }); - try b.closeSubpath(false); - try b.lineTo(c - geom.Vec{ 0, 6 }, c + geom.Vec{ 0, 6 }); - try b.closeSubpath(false); - } - try b.endShape(.identity, guideStyle(anim.yellow, 1)); - return b.finish(.{ .w = canvas.w, .h = canvas.h }, canvas.w, canvas.h); -} - -/// The guides' numbers: tick values, and each object's index and position. -fn labels(ss: *Session, f: *sk.Frame, shot: anim.Shot, world: geom.Affine) !void { - var i: f32 = -20; - while (i <= 20) : (i += 2) { - const x = world.apply(.{ i * tick, 0 }); - const y = world.apply(.{ 0, i * tick }); - f.print(x[0] + 3, x[1] + 8, 1, 0x8c8c8c, "{d}", .{i * tick}); - if (i != 0) f.print(y[0] + 8, y[1] - 3, 1, 0x8c8c8c, "{d}", .{i * tick}); - } - for (shot.objects, shot.poses, 0..) |o, pose, n| { - if (!pose.visible or pose.opacity <= 0) continue; - const r: geom.Rect = if (o.source == .custom) .{} else (try built(ss, o)).bounds; - const corner = world.mul(model(pose)).apply(.{ r.x, r.y }); - f.print(corner[0], corner[1] - 11, 1, anim.yellow, "#{d} {d:.0},{d:.0}", .{ n, pose.x, pose.y }); - } -} - 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; + const d = &s.deck; var play: usize = 0; - for (shot.marks, 1..) |m, i| if (m <= s.t) { + for (shot.marks, 1..) |m, i| if (m <= d.t) { play = i; }; + var buf: [64]u8 = undefined; + const steps = (if (d.slides > 0) + std.fmt.bufPrint(&buf, " slide {d}/{d} step {d}/{d}", .{ d.slide, d.slides, d.log.count(), d.gates }) + else if (d.gates > 0) + std.fmt.bufPrint(&buf, " step {d}/{d}", .{ d.log.count(), d.gates }) + else + std.fmt.bufPrint(&buf, "", .{})) catch ""; 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 ""; + const status = if (!d.playing) " paused" else if (d.waiting) " 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.shapes, s.speed, status, + f.print(12, h - 19, 1, 0xece6e2, "{d:5.2}s / {d:.2}s play {d}/{d}{s} {s} record {d:.3}ms {d} shapes speed x{d}{s}", .{ + d.t, shot.duration, play, shot.marks.len, steps, backend, ss.render_ns / 1e6, ss.painter.shapes, d.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.text(w - 400, h - 19, 1, "click space pgup [ ] P <- -> , . B G drag", 0x8c8c8c); f.cursor(.arrow); } |
