diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/anim/player.zig | 410 | ||||
| -rw-r--r-- | src/anim/root.zig | 1043 | ||||
| -rw-r--r-- | src/anim/typst.zig | 66 |
3 files changed, 1519 insertions, 0 deletions
diff --git a/src/anim/player.zig b/src/anim/player.zig new file mode 100644 index 0000000..bac5178 --- /dev/null +++ b/src/anim/player.zig @@ -0,0 +1,410 @@ +//! 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"); +const geom = vector.geom; + +pub const name = if (@hasDecl(scene_file, "name")) scene_file.name else "anim"; +/// The scene's frame, in scene units: what shows at camera zoom 1. +pub const width = 1280; +pub const height = 720; + +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 { + /// 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. + render_ns: f32 = 0, + shapes: usize = 0, +}; + +const Built = struct { drawing: vector.Drawing, bounds: geom.Rect }; + +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; +} + +/// 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); + 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}); + 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 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(anim.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; + 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.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); +} diff --git a/src/anim/root.zig b/src/anim/root.zig new file mode 100644 index 0000000..00e9362 --- /dev/null +++ b/src/anim/root.zig @@ -0,0 +1,1043 @@ +//! manim-style animation, written as code. A scene is one file, of one of +//! two kinds, drawn by the same player. +//! +//! **Compiled** (`Scene`): `construct` runs once, at comptime, recording +//! objects and plays, which become keyframes per object (a `from` pose, a +//! `to` pose, a time span and an easing). The whole timeline is data before +//! the first frame, and drawing an instant is a lookup and a `tween.lerp`. +//! Updaters (`always`) add motion on top. +//! +//! pub const scene = anim.Scene(construct); +//! +//! fn construct(s: *anim.Builder) void { +//! const title = s.typst("= Hello", .{ .y = -200 }); +//! s.play(.{title.write()}, .{}); +//! s.always(title, bob, .{20}); +//! s.play(.{anim.camera(.{ .zoom = 1.5 })}, .{ .ease = anim.ease.outBack }); +//! } +//! +//! fn bob(now: anim.Now, height: f32) anim.Pose { +//! var p = now.pose; +//! p.y += height * @sin(now.t * 3); +//! return p; +//! } +//! +//! **Live** (`Live`): `frame` runs every frame, at runtime, with the time +//! and the input. The same calls add objects and play animations, but each +//! `play` takes effect at once, against `s.t`, so the code after it can read +//! and change what shows: updaters are plain code, and a scene can follow +//! the mouse or any runtime data. Its Typst sources sit in a namespace, for +//! the build to find. +//! +//! pub const typst = struct { +//! pub const title = "= Hello"; +//! }; +//! pub const scene = anim.Live(frame, typst); +//! +//! fn frame(s: *anim.Frame) void { +//! const title = s.typst(typst.title, .{ .y = -200 }); +//! s.play(.{title.write()}, .{}); +//! s.pause(); +//! s.pose(title).x = s.pointer[0]; +//! } +//! +//! Both are functions of time (and a live one, of the input too), so +//! scrubbing, seeking and hot reload are free. +//! +//! Animations, as methods of an object handle: `write`, `create`, +//! `fadeIn`, `fadeOut`, `transformInto` (morph), `move`, `scaleTo`, +//! `rotate`, `indicate`; and `camera`, `Value.to`. `play` runs a tuple of +//! them together, with options `.seconds`, `.ease` (any `fn (f32) f32`, +//! `ease.smooth` by default) and `.lag`. `wait` moves time on; `pause` +//! holds the player there until a click, like a slide. Typst is compiled +//! at build time (`sb.addScene`), from the scene's `typst_sources`. +//! +//! **Custom objects** (`s.custom(&data, .{ .x = 100 })`) are drawn by the +//! scene's own code, with `sketch.Frame` commands, in their place among +//! the others: same camera, same pose, same animations (see `Placed`). +const std = @import("std"); +const sk = @import("sketch"); +const vector = @import("vector"); +const tween = sk.tween; +const Drawing = vector.Drawing; + +pub const ease = tween.ease; + +// manim's palette. +pub const blue: u32 = 0x58c4dd; +pub const teal: u32 = 0x5cd0b3; +pub const green: u32 = 0x83c167; +pub const yellow: u32 = 0xf7d96f; +pub const gold: u32 = 0xf0ac5f; +pub const red: u32 = 0xfc6255; +pub const maroon: u32 = 0xc55f73; +pub const purple: u32 = 0x9a72ac; +pub const white: u32 = 0xece6e2; +pub const background: u32 = 0x1c1c1f; + +/// Where an object is and how much of it shows. Every field interpolates. +pub const Pose = struct { + x: f32 = 0, + y: f32 = 0, + scale: f32 = 1, + rotation: f32 = 0, + opacity: f32 = 1, + visible: bool = false, + /// Write/create progress: 0 nothing, 1 complete. + drawn: f32 = 1, + reveal: Reveal = .write, + /// Morph progress into `into`. + morph: f32 = 0, + into: u16 = none, + /// Indicate's glow. + highlight: f32 = 0, + + pub const none = std.math.maxInt(u16); + pub const Reveal = enum { write, create }; +}; + +pub const Camera = struct { + x: f32 = 0, + y: f32 = 0, + zoom: f32 = 1, + rotation: f32 = 0, +}; + +pub const Ease = *const fn (f32) f32; + +pub fn Key(comptime P: type) type { + return struct { + start: f32, + end: f32, + ease: Ease, + lag: f32 = 0, + from: P, + to: P, + + pub fn at(k: @This(), t: f32) P { + return tween.lerp(k.from, k.to, k.ease(tween.progress(t, k.start, k.end))); + } + }; +} + +// --------------------------------------------------------------------------- +// Objects + +pub const Source = union(enum) { + svg: []const u8, + /// Typst source, compiled to SVG at build time. + typst: []const u8, + rect: struct { w: f32, h: f32, radius: f32 = 0 }, + circle: struct { r: f32 }, + line: struct { dx: f32, dy: f32, arrow: bool = false }, + polygon: []const [2]f32, + /// Drawn by the scene's own code (`custom`). + custom: Custom, +}; + +/// An object the scene draws itself with 2D commands (`f.fill`, `sk.draw`, +/// `f.text`): runtime data as a table, a memory grid, a code panel. It is +/// an object like the others: posed, animated and ordered among them. +/// `draw` runs while the frame is painted, when the object shows +/// (`visible`, `opacity` above 0); `ctx` must live until then (a live +/// scene's `s.arena` does). +pub const Custom = struct { + draw: *const fn (ctx: *const anyopaque, f: *sk.Frame, at: Placed) void, + ctx: *const anyopaque, +}; + +/// What a custom object's `draw` gets: where it stands at this instant. +pub const Placed = struct { + /// Scene time, in seconds. + t: f32, + /// The object's pose now. `x`, `y`, `scale` and `rotation` are in `xf` + /// already; `opacity` is for `draw` to honour (`pen` and `text` do), + /// and so are `drawn` (0 to 1 as a `write` or `create` plays: reveal + /// what you like by it) and `highlight` (`indicate`). + pose: Pose, + /// The object's units (its origin where the pose puts it, y down) to + /// canvas pixels: the camera, then the pose. + xf: sk.math.Affine, + /// Canvas pixels per unit of the object: for text sizes. + scale: f32, + /// Scene units to canvas pixels: the camera alone. + stage: sk.math.Affine, + /// Every `Value` of the scene, now. + values: []const f32, + + pub fn value(p: Placed, v: Value) f32 { + return p.values[@backingInt(v)]; + } + + /// `base` in the object's units and at its opacity, for `sk.draw`: + /// `sk.draw.rect(f, r, at.pen(.{ .fill = .white }))`. + pub fn pen(p: Placed, base: sk.draw.Pen) sk.draw.Pen { + var out = base.transformed(p.xf); + if (out.fill) |c| out.fill = p.faded(c); + if (out.stroke) |c| out.stroke = p.faded(c); + return out; + } + + /// `f.text` in the object's units and at its opacity: `x, y` is the + /// line's top left, scale 1 a 13-unit font. Text does not turn: a + /// rotated object's text moves with it and stays level. + pub fn text(p: Placed, f: *sk.Frame, x: f32, y: f32, scale: f32, bytes: []const u8, ink: sk.Color) void { + const at = p.xf.apply(.{ x, y }); + f.text(at[0], at[1], scale * p.scale, bytes, p.faded(ink)); + } + + /// The width and line height `text` covers, in the object's units. + pub fn textSize(p: Placed, f: *sk.Frame, scale: f32, bytes: []const u8) [2]f32 { + const size = f.host.textSize(scale * p.scale, bytes); + return .{ size[0] / p.scale, size[1] / p.scale }; + } + + /// `ink` at the pose's opacity. + pub fn faded(p: Placed, ink: sk.Color) sk.Color { + return ink.alphaFloat(@as(f32, @floatFromInt(ink.a)) / 255 * p.pose.opacity); + } +}; + +pub const Object = struct { + source: Source, + pose: Pose, + /// Styling for primitives; SVGs keep their own. + fill: ?u32 = null, + stroke: ?u32 = null, + width: f32 = 4, + + /// Identifies what the object looks like (not where it is), to cache + /// its drawing by. + pub fn id(o: Object) u64 { + var h: std.hash.Wyhash = .init(0); + h.update(@tagName(o.source)); + switch (o.source) { + .svg, .typst => |text| h.update(text), + .polygon => |points| h.update(std.mem.sliceAsBytes(points)), + .rect => |r| h.update(std.mem.asBytes(&[_]f32{ r.w, r.h, r.radius })), + .circle => |c| h.update(std.mem.asBytes(&c.r)), + .line => |l| h.update(std.mem.asBytes(&[_]f32{ l.dx, l.dy, @floatFromInt(@intFromBool(l.arrow)) })), + .custom => |c| h.update(std.mem.asBytes(&[_]usize{ @intFromPtr(c.draw), @intFromPtr(c.ctx) })), + } + h.update(std.mem.asBytes(&[_]u64{ o.fill orelse 1 << 32, o.stroke orelse 1 << 32 })); + h.update(std.mem.asBytes(&o.width)); + return h.final(); + } +}; + +/// Pose fields to animate towards; the others stay as they are. +pub const Target = struct { + x: ?f32 = null, + y: ?f32 = null, + scale: ?f32 = null, + rotation: ?f32 = null, + opacity: ?f32 = null, + + fn of(fields: anytype) Target { + var t: Target = .{}; + inline for (@typeInfo(@TypeOf(fields)).@"struct".field_names) |name| @field(t, name) = @field(fields, name); + return t; + } + fn apply(t: Target, p: *Pose) void { + inline for (@typeInfo(Target).@"struct".field_names) |name| if (@field(t, name)) |v| { + @field(p, name) = v; + }; + } +}; + +pub const CameraTarget = struct { + x: ?f32 = null, + y: ?f32 = null, + zoom: ?f32 = null, + rotation: ?f32 = null, +}; + +/// A handle to an object added to a scene. +pub const Obj = enum(u16) { + _, + + pub fn write(o: Obj) Animation { + return .{ .write = o }; + } + pub fn create(o: Obj) Animation { + return .{ .create = o }; + } + pub fn fadeIn(o: Obj) Animation { + return .{ .fade_in = o }; + } + pub fn fadeOut(o: Obj) Animation { + return .{ .fade_out = o }; + } + /// Morphs into `other`, which takes over when done. + pub fn transformInto(o: Obj, other: Obj) Animation { + return .{ .transform = .{ .from = o, .to = other } }; + } + /// Towards any of `x`, `y`, `scale`, `rotation`, `opacity`. + pub fn move(o: Obj, to: anytype) Animation { + return .{ .move = .{ .obj = o, .to = .of(to) } }; + } + pub fn scaleTo(o: Obj, scale: f32) Animation { + return .{ .move = .{ .obj = o, .to = .{ .scale = scale } } }; + } + /// By `radians`, from wherever it is. + pub fn rotate(o: Obj, radians: f32) Animation { + return .{ .rotate = .{ .obj = o, .by = radians } }; + } + pub fn indicate(o: Obj) Animation { + return .{ .indicate = o }; + } +}; + +/// A number animated along the timeline, for updaters (or live code) to read. +pub const Value = enum(u16) { + _, + + pub fn to(v: Value, target: f32) Animation { + return .{ .value = .{ .value = v, .to = target } }; + } +}; + +/// Moves the camera towards any of `x`, `y`, `zoom`, `rotation`. +pub fn camera(to: anytype) Animation { + var t: CameraTarget = .{}; + inline for (@typeInfo(@TypeOf(to)).@"struct".field_names) |name| @field(t, name) = @field(to, name); + return .{ .camera = t }; +} + +pub const Animation = union(enum) { + write: Obj, + create: Obj, + fade_in: Obj, + fade_out: Obj, + transform: struct { from: Obj, to: Obj }, + move: struct { obj: Obj, to: Target }, + rotate: struct { obj: Obj, by: f32 }, + indicate: Obj, + camera: CameraTarget, + value: struct { value: Value, to: f32 }, +}; + +/// What an updater sees each frame. +pub const Now = struct { + /// Scene time, in seconds. + t: f32, + /// The object's pose from the timeline (and earlier updaters). + pose: Pose, + values: []const f32, + + pub fn value(n: Now, v: Value) f32 { + return n.values[@backingInt(v)]; + } +}; + +pub const Updater = struct { + obj: Obj, + /// From this time on. + since: f32, + update: *const fn (Now) Pose, +}; + +// --------------------------------------------------------------------------- +// Playing animations, the same for both kinds of scene + +const Play = struct { + start: f32, + seconds: f32, + ease: Ease, + lag: f32, + animations: []const Animation, + + /// `play`'s options: `.seconds` (1, or 2 with a write in it), `.ease` + /// (`ease.smooth`) and `.lag` (0.08). + fn of(start: f32, animations: []const Animation, options: anytype) Play { + const O = @TypeOf(options); + var seconds: f32 = 1; + for (animations) |a| if (a == .write) { + seconds = 2; + }; + if (@hasField(O, "seconds")) seconds = options.seconds; + return .{ + .start = start, + .seconds = seconds, + .ease = if (@hasField(O, "ease")) options.ease else ease.smooth, + .lag = if (@hasField(O, "lag")) options.lag else 0.08, + .animations = animations, + }; + } + + fn key(p: Play, comptime P: type, from: P, to: P, with: ?Ease) Key(P) { + return .{ .start = p.start, .end = p.start + p.seconds, .ease = with orelse p.ease, .lag = p.lag, .from = from, .to = to }; + } +}; + +/// Animations as an array, from a tuple or an array. +fn list(animations: anytype) [count(@TypeOf(animations))]Animation { + var out: [count(@TypeOf(animations))]Animation = undefined; + inline for (animations, 0..) |a, i| out[i] = a; + return out; +} + +fn count(comptime T: type) usize { + return switch (@typeInfo(T)) { + .array => |a| a.len, + else => @typeInfo(T).@"struct".field_names.len, + }; +} + +/// What a play does to one object: the pose it starts from and ends on. +const Change = struct { obj: u16, from: Pose, to: Pose, ease: ?Ease = null }; + +/// The changes `animations`, played together, make to objects standing in +/// their `settled` poses. `buf` needs two per animation. +fn changes(buf: []Change, settled: []const Pose, animations: []const Animation) []Change { + var n: usize = 0; + for (animations) |a| switch (a) { + .write, .create => |o| { + const c = touch(buf, &n, settled, o); + c.from.visible = true; + c.from.drawn = 0; + if (c.from.opacity <= 0) c.from.opacity = 1; + c.from.reveal = if (a == .write) .write else .create; + c.to = c.from; + c.to.drawn = 1; + }, + .fade_in => |o| { + const c = touch(buf, &n, settled, o); + c.from.visible = true; + c.from.drawn = 1; + c.from.opacity = 0; + c.to = c.from; + c.to.opacity = 1; + }, + .fade_out => |o| { + const c = touch(buf, &n, settled, o); + c.to.opacity = 0; + c.to.visible = false; + }, + .transform => |t| { + const c = touch(buf, &n, settled, t.from); + c.from.into = @backingInt(t.to); + c.from.morph = 0; + c.to = c.from; + c.to.morph = 1; + c.to.visible = false; + const d = touch(buf, &n, settled, t.to); + d.from.visible = false; + d.to = d.from; + d.to.visible = true; + d.to.drawn = 1; + d.to.opacity = 1; + }, + .move => |m| m.to.apply(&touch(buf, &n, settled, m.obj).to), + .rotate => |r| touch(buf, &n, settled, r.obj).to.rotation += r.by, + .indicate => |o| { + const c = touch(buf, &n, settled, o); + c.to.scale *= 1.2; + c.to.highlight = 1; + c.ease = ease.thereAndBack; + }, + .camera, .value => {}, + }; + return buf[0..n]; +} + +fn touch(buf: []Change, n: *usize, settled: []const Pose, o: Obj) *Change { + const i = @backingInt(o); + for (buf[0..n.*]) |*c| if (c.obj == i) return c; + buf[n.*] = .{ .obj = i, .from = settled[i], .to = settled[i] }; + n.* += 1; + return &buf[n.* - 1]; +} + +/// Where `animations` leave a camera standing at `view`, if they move it. +fn aim(view: Camera, animations: []const Animation) ?Camera { + var out: ?Camera = null; + for (animations) |a| if (a == .camera) { + var c = out orelse view; + inline for (@typeInfo(CameraTarget).@"struct".field_names) |name| if (@field(a.camera, name)) |v| { + @field(c, name) = v; + }; + out = c; + }; + return out; +} + +/// Adding objects, the same for both kinds of scene (anything with `add`). +const adding = struct { + /// An SVG document, placed by `at`'s fields: `x`, `y`, `scale`, + /// `rotation`, `opacity`, `visible`. + fn svg(s: anytype, bytes: []const u8, at: anytype) Obj { + return s.add(.{ .source = .{ .svg = bytes }, .pose = tween.toward(Pose{}, at, 1) }); + } + /// Typst markup (after the scene's `typst_preamble`), placed like `svg`. + fn typst(s: anytype, source: []const u8, at: anytype) Obj { + return s.add(.{ .source = .{ .typst = source }, .pose = tween.toward(Pose{}, at, 1) }); + } + /// Primitives take their size, `fill`, `stroke`, `width`, and the pose + /// fields, in one literal. + fn rect(s: anytype, spec: anytype) Obj { + return s.add(primitive(.{ .rect = .{ .w = spec.w, .h = spec.h, .radius = number(spec, "radius", 0) } }, spec)); + } + fn circle(s: anytype, spec: anytype) Obj { + return s.add(primitive(.{ .circle = .{ .r = spec.r } }, spec)); + } + fn line(s: anytype, spec: anytype) Obj { + return s.add(primitive(.{ .line = .{ .dx = spec.dx, .dy = spec.dy } }, spec)); + } + fn arrow(s: anytype, spec: anytype) Obj { + return s.add(primitive(.{ .line = .{ .dx = spec.dx, .dy = spec.dy, .arrow = true } }, spec)); + } + /// `.points` is a slice of `[2]f32`, kept by reference. + fn polygon(s: anytype, spec: anytype) Obj { + return s.add(primitive(.{ .polygon = spec.points }, spec)); + } + /// An object drawn by `data.draw(f, placed)` (`f: *sk.Frame`, `placed: + /// Placed`), placed like `svg`. `data` is a pointer, kept: in a live + /// scene to something in `s.arena`, which the code after the plays may + /// still change; in a compiled one to a constant. + fn custom(s: anytype, data: anytype, at: anytype) Obj { + const T = @typeInfo(@TypeOf(data)).pointer.child; + const erased = struct { + fn draw(ctx: *const anyopaque, f: *sk.Frame, placed: Placed) void { + @as(*const T, @ptrCast(@alignCast(ctx))).draw(f, placed); + } + }; + return s.add(.{ .source = .{ .custom = .{ .draw = erased.draw, .ctx = data } }, .pose = tween.toward(Pose{}, at, 1) }); + } +}; + +fn primitive(source: Source, spec: anytype) Object { + var pose: Pose = .{}; + inline for (.{ "x", "y", "scale", "rotation", "opacity", "visible" }) |name| { + if (@hasField(@TypeOf(spec), name)) @field(pose, name) = @field(spec, name); + } + return .{ + .source = source, + .pose = pose, + .fill = if (@hasField(@TypeOf(spec), "fill")) spec.fill else null, + .stroke = if (@hasField(@TypeOf(spec), "stroke")) spec.stroke else null, + .width = number(spec, "width", 4), + }; +} + +fn number(spec: anytype, comptime name: []const u8, default: f32) f32 { + return if (@hasField(@TypeOf(spec), name)) @field(spec, name) else default; +} + +// --------------------------------------------------------------------------- +// Compiled scenes + +/// What `construct` receives. Every method runs at comptime. +pub const Builder = struct { + objects: []const Object = &.{}, + values: []const f32 = &.{}, + plays: []const Play = &.{}, + updaters: []const Updater = &.{}, + stops: []const f32 = &.{}, + /// Where the next play starts. + cursor: f32 = 0, + + pub fn add(b: *Builder, o: Object) Obj { + b.objects = b.objects ++ .{o}; + return @fromBackingInt(@intCast(b.objects.len - 1)); + } + pub const svg = adding.svg; + pub const typst = adding.typst; + pub const rect = adding.rect; + pub const circle = adding.circle; + pub const line = adding.line; + pub const arrow = adding.arrow; + pub const polygon = adding.polygon; + pub const custom = adding.custom; + + pub fn value(b: *Builder, initial: f32) Value { + b.values = b.values ++ .{initial}; + return @fromBackingInt(@intCast(b.values.len - 1)); + } + + /// Runs `animations` (a tuple or an array) together, then moves time + /// past them. + pub fn play(b: *Builder, animations: anytype, options: anytype) void { + const all = list(animations); + const p = Play.of(b.cursor, &all, options); + b.plays = b.plays ++ .{p}; + b.cursor += p.seconds; + } + + pub fn wait(b: *Builder, seconds: f32) void { + b.cursor += seconds; + } + + /// The player holds here until a click. + pub fn pause(b: *Builder) void { + b.stops = b.stops ++ .{b.cursor}; + } + + /// From now on, every frame, `o`'s pose is `update(now, args...)`: + /// `args` (a tuple) is bound here, like a closure's captures, so an + /// updater can follow other objects or read values. + pub fn always(b: *Builder, o: Obj, comptime update: anytype, comptime args: anytype) void { + const bound = struct { + fn call(now: Now) Pose { + return @call(.auto, update, .{now} ++ args); + } + }; + b.updaters = b.updaters ++ .{Updater{ .obj = o, .since = b.cursor, .update = bound.call }}; + } +}; + +/// Runs `construct` at comptime and compiles what it recorded. +pub fn Scene(comptime construct: fn (*Builder) void) type { + @setEvalBranchQuota(10_000_000); + const recorded = comptime blk: { + var b: Builder = .{}; + construct(&b); + break :blk b; + }; + const n = recorded.objects.len; + + // Play the timeline once, at comptime, recording keyframes. + const compiled = comptime blk: { + var poses: [n]Pose = undefined; + for (&poses, recorded.objects) |*p, o| p.* = o.pose; + var values: [recorded.values.len]f32 = recorded.values[0..recorded.values.len].*; + var view: Camera = .{}; + var keys: [n][]const Key(Pose) = @splat(&.{}); + var value_keys: [recorded.values.len][]const Key(f32) = @splat(&.{}); + var camera_keys: []const Key(Camera) = &.{}; + var marks: []const f32 = &.{}; + for (recorded.plays) |play| { + var buf: [2 * play.animations.len]Change = undefined; + for (changes(&buf, &poses, play.animations)) |c| { + const k = play.key(Pose, c.from, c.to, c.ease); + keys[c.obj] = keys[c.obj] ++ .{k}; + poses[c.obj] = k.at(k.end); + } + for (play.animations) |a| if (a == .value) { + const i = @backingInt(a.value.value); + value_keys[i] = value_keys[i] ++ .{play.key(f32, values[i], a.value.to, null)}; + values[i] = a.value.to; + }; + if (aim(view, play.animations)) |to| { + camera_keys = camera_keys ++ .{play.key(Camera, view, to, null)}; + view = to; + } + marks = marks ++ .{play.start}; + } + break :blk .{ .keys = keys, .value_keys = value_keys, .camera_keys = camera_keys, .marks = marks }; + }; + const frozen_objects = recorded.objects[0..n].*; + const frozen_values = recorded.values[0..recorded.values.len].*; + const frozen_updaters = recorded.updaters[0..recorded.updaters.len].*; + const frozen_stops = recorded.stops[0..recorded.stops.len].*; + const frozen_keys = compiled.keys; + const frozen_value_keys = compiled.value_keys; + const frozen_camera_keys = compiled.camera_keys[0..compiled.camera_keys.len].*; + const frozen_marks = compiled.marks[0..compiled.marks.len].*; + const typst_list = comptime blk: { + var out: []const []const u8 = &.{}; + for (recorded.objects) |o| if (o.source == .typst) { + out = out ++ .{o.source.typst}; + }; + break :blk out[0..out.len].*; + }; + + return struct { + pub const objects: []const Object = &frozen_objects; + pub const initial_values: []const f32 = &frozen_values; + pub const updaters: []const Updater = &frozen_updaters; + pub const keys: [n][]const Key(Pose) = frozen_keys; + pub const value_keys = frozen_value_keys; + pub const camera_keys: []const Key(Camera) = &frozen_camera_keys; + /// Start times of every play, for chapter-style seeking. + pub const marks: []const f32 = &frozen_marks; + pub const stops: []const f32 = &frozen_stops; + pub const duration: f32 = recorded.cursor; + /// Every Typst source, for the build step that compiles them. + pub const typst_sources: []const []const u8 = &typst_list; + + /// The scene at `now`, for the player. + pub fn shot(arena: std.mem.Allocator, now: Instant) !Shot { + const poses = try arena.alloc(Pose, n); + const morphs = try arena.alloc(Morph, n); + for (poses, morphs, 0..) |*p, *m, i| { + p.* = pose(i, now.t); + if (p.into != Pose.none) if (key(i, now.t)) |k| { + m.* = .{ .from = k.from, .to = pose(p.into, k.end) }; + }; + } + return .{ .objects = objects, .poses = poses, .morphs = morphs, .values = try arena.dupe(f32, &values(now.t)), .camera = view(now.t), .duration = duration, .marks = marks, .stops = stops }; + } + + /// The key shaping object `i` at `t`: the last one to have started. + pub fn key(i: usize, t: f32) ?Key(Pose) { + return latest(Pose, keys[i], t); + } + + /// Every value at `t`. + pub fn values(t: f32) [frozen_values.len]f32 { + var out = frozen_values; + for (&out, value_keys) |*v, own| if (latest(f32, own, t)) |k| { + v.* = k.at(t); + }; + return out; + } + + /// Where object `i` is at `t`: the timeline, then its updaters. + pub fn pose(i: usize, t: f32) Pose { + var p = if (key(i, t)) |k| k.at(t) else objects[i].pose; + if (updaters.len > 0) { + const now_values = values(t); + for (updaters) |u| if (@backingInt(u.obj) == i and t >= u.since) { + p = u.update(.{ .t = t, .pose = p, .values = &now_values }); + }; + } + return p; + } + + /// The camera at `t`. + pub fn view(t: f32) Camera { + return if (latest(Camera, camera_keys, t)) |k| k.at(t) else .{}; + } + }; +} + +fn latest(comptime P: type, keys: []const Key(P), t: f32) ?Key(P) { + var found: ?Key(P) = null; + for (keys) |k| { + if (k.start > t) break; + found = k; + } + return found; +} + +/// The drawing of an object, centered on its origin, in pixels at scale 1. +/// `compiled` has `find(source) ?[]const u8` for Typst objects' SVGs. +pub fn build(arena: std.mem.Allocator, o: Object, compiled: anytype) !Drawing { + const document: ?[]const u8 = switch (o.source) { + .svg => |bytes| bytes, + .typst => |source| compiled.find(source) orelse return error.TypstNotCompiled, + .custom => return error.CustomHasNoDrawing, + else => null, + }; + if (document) |bytes| { + { + const d = try vector.svg.parse(arena, bytes); + // Keep the SVG's pixel size (Typst's points are 4/3 px), centered. + const s = if (d.view.w > 0) d.width / d.view.w else 1; + const c = d.view.center(); + const shapes = try arena.dupe(Drawing.Shape, d.shapes); + for (shapes) |*shape| shape.transform = vector.geom.Affine.scale(s, s).mul(.translate(-c[0], -c[1])).mul(shape.transform); + var out = d; + out.shapes = shapes; + out.view = .{ .x = -d.view.w * s / 2, .y = -d.view.h * s / 2, .w = d.view.w * s, .h = d.view.h * s }; + return out; + } + } + var b: Drawing.Builder = .init(arena); + var style: Drawing.Style = .{ + .fill = if (o.fill) |c| .{ .color = color(c) } else .none, + .stroke = if (o.stroke) |c| .{ .color = color(c) } else .none, + .stroke_width = o.width, + .cap = .round, + .join = .round, + }; + switch (o.source) { + .rect => |r| try b.rect(.{ .x = -r.w / 2, .y = -r.h / 2, .w = r.w, .h = r.h }, r.radius), + .circle => |c| try b.ellipse(.{ 0, 0 }, c.r, c.r), + .polygon => |pts| { + var points: [64]vector.geom.Vec = undefined; + for (pts[0..@min(pts.len, 64)], 0..) |p, i| points[i] = p; + try b.polyline(points[0..@min(pts.len, 64)], true); + }, + .line => |l| { + const a: vector.geom.Vec = .{ -l.dx / 2, -l.dy / 2 }; + const z: vector.geom.Vec = .{ l.dx / 2, l.dy / 2 }; + try b.lineTo(a, z); + try b.closeSubpath(false); + if (l.arrow) { + try b.endShape(.identity, style); + // The head, filled in the stroke color. + const dir = vector.geom.normalize(z - a); + const n = vector.geom.perp(dir); + const head = @max(o.width * 3, 12); + const back = z - dir * vector.geom.splat(head); + try b.polyline(&.{ z + dir * vector.geom.splat(o.width), back + n * vector.geom.splat(head / 2), back - n * vector.geom.splat(head / 2) }, true); + style.fill = style.stroke; + style.stroke = .none; + } + }, + .svg, .typst, .custom => unreachable, + } + try b.endShape(.identity, style); + const r = @max(extent(o.source), 1); + return b.finish(.{ .x = -r, .y = -r, .w = 2 * r, .h = 2 * r }, 2 * r, 2 * r); +} + +fn extent(s: Source) f32 { + return switch (s) { + .rect => |r| @max(r.w, r.h) / 2, + .circle => |c| c.r, + .line => |l| @max(@abs(l.dx), @abs(l.dy)) / 2, + .polygon => |pts| blk: { + var m: f32 = 0; + for (pts) |p| m = @max(m, @max(@abs(p[0]), @abs(p[1]))); + break :blk m; + }, + .svg, .typst, .custom => 0, + }; +} + +/// `0xRRGGBB`, or `0xRRGGBBAA` when above 24 bits. +pub fn color(c: u32) Drawing.Color { + const rgba: u32 = if (c > 0xffffff) c else (c << 8) | 0xff; + return .{ + @as(f32, @floatFromInt(rgba >> 24)) / 255, + @as(f32, @floatFromInt((rgba >> 16) & 0xff)) / 255, + @as(f32, @floatFromInt((rgba >> 8) & 0xff)) / 255, + @as(f32, @floatFromInt(rgba & 0xff)) / 255, + }; +} + +// --------------------------------------------------------------------------- +// Live scenes + +/// A live scene: `frame` runs every frame, at runtime, and the scene is +/// whatever it builds. `typst` is a namespace whose declarations are the +/// Typst sources `frame` uses, for the build to compile. +pub fn Live(comptime frame: fn (*Frame) void, comptime typst: type) type { + const decls = @typeInfo(typst).@"struct".decl_names; + var sources: [decls.len][]const u8 = undefined; + for (&sources, decls) |*s, name| s.* = @field(typst, name); + const frozen_sources = sources; + return struct { + pub const typst_sources: []const []const u8 = &frozen_sources; + + /// The scene at `now`, for the player: `frame`, run once. + pub fn shot(arena: std.mem.Allocator, now: Instant) !Shot { + var s: Frame = .{ .t = now.t, .clock = now.clock, .in = now.in, .pointer = now.pointer, .arena = arena }; + frame(&s); + const values = try arena.alloc(f32, s.values.items.len); + for (values, s.values.items) |*v, own| v.* = own.shown; + return .{ .objects = s.objects.items, .poses = s.shown.items, .morphs = s.morphs.items, .values = values, .camera = s.view, .duration = s.cursor, .marks = s.marks.items, .stops = s.stops.items }; + } + }; +} + +/// What a live scene's `frame` gets: the time, the input, and the same calls +/// as `Builder`, which take effect at `t` right away. +pub const Frame = struct { + /// Scene time, in seconds. + t: f32, + /// Seconds on the wall clock, which runs on while the player pauses: + /// for motion that should not stop. + clock: f32, + in: *const sk.Input, + /// The mouse, in scene units from the canvas center (before the scene's + /// own camera). + pointer: [2]f32, + /// Lives for this frame. + arena: std.mem.Allocator, + /// Where the next play starts. + cursor: f32 = 0, + objects: std.ArrayList(Object) = .empty, + /// Each object's pose after every play so far, and as it shows at `t`. + settled: std.ArrayList(Pose) = .empty, + shown: std.ArrayList(Pose) = .empty, + morphs: std.ArrayList(Morph) = .empty, + values: std.ArrayList(struct { settled: f32, shown: f32 }) = .empty, + settled_view: Camera = .{}, + view: Camera = .{}, + marks: std.ArrayList(f32) = .empty, + stops: std.ArrayList(f32) = .empty, + + pub fn add(s: *Frame, o: Object) Obj { + s.push(&s.objects, o); + s.push(&s.settled, o.pose); + s.push(&s.shown, o.pose); + s.push(&s.morphs, undefined); + return @fromBackingInt(@intCast(s.objects.items.len - 1)); + } + pub const svg = adding.svg; + pub const typst = adding.typst; + pub const rect = adding.rect; + pub const circle = adding.circle; + pub const line = adding.line; + pub const arrow = adding.arrow; + pub const polygon = adding.polygon; + pub const custom = adding.custom; + + pub fn value(s: *Frame, initial: f32) Value { + s.push(&s.values, .{ .settled = initial, .shown = initial }); + return @fromBackingInt(@intCast(s.values.items.len - 1)); + } + + /// Value `v` at `t`. + pub fn get(s: *const Frame, v: Value) f32 { + return s.values.items[@backingInt(v)].shown; + } + + /// How `o` shows at `t`, to change in place. Code runs in order: a later + /// play that has started by `t` sets it again. + pub fn pose(s: *Frame, o: Obj) *Pose { + return &s.shown.items[@backingInt(o)]; + } + + /// The camera at `t`, to change in place, like `pose`. + pub fn camera(s: *Frame) *Camera { + return &s.view; + } + + /// Runs `animations` (a tuple or an array) together from the cursor, as + /// they stand at `t`, then moves the cursor past them. + pub fn play(s: *Frame, animations: anytype, options: anytype) void { + const all = list(animations); + const p = Play.of(s.cursor, &all, options); + const started = s.t >= p.start; + var buf: [2 * all.len]Change = undefined; + const touched = changes(&buf, s.settled.items, &all); + for (touched) |c| { + const k = p.key(Pose, c.from, c.to, c.ease); + s.settled.items[c.obj] = k.at(k.end); + if (started) s.shown.items[c.obj] = k.at(s.t); + } + // A morph ends where its target settles. + if (started) for (touched) |c| if (c.from.into != Pose.none) { + s.morphs.items[c.obj] = .{ .from = c.from, .to = s.settled.items[c.from.into] }; + }; + for (all) |a| if (a == .value) { + const v = &s.values.items[@backingInt(a.value.value)]; + const k = p.key(f32, v.settled, a.value.to, null); + v.settled = a.value.to; + if (started) v.shown = k.at(s.t); + }; + if (aim(s.settled_view, &all)) |to| { + const k = p.key(Camera, s.settled_view, to, null); + s.settled_view = to; + if (started) s.view = k.at(s.t); + } + s.push(&s.marks, p.start); + s.cursor += p.seconds; + } + + pub fn wait(s: *Frame, seconds: f32) void { + s.cursor += seconds; + } + + /// The player holds here until a click, like a slide. + pub fn pause(s: *Frame) void { + s.push(&s.stops, s.cursor); + } + + /// `data` in the arena, to change until the frame ends: what a custom + /// object draws. + pub fn new(s: *Frame, data: anytype) *@TypeOf(data) { + const kept = s.arena.create(@TypeOf(data)) catch @panic("anim: out of memory"); + kept.* = data; + return kept; + } + + /// Keeps scene code free of error handling: the frame arena running out + /// is fatal anyway. + fn push(s: *Frame, items: anytype, item: @TypeOf(items.items[0])) void { + items.append(s.arena, item) catch @panic("anim: out of memory"); + } +}; + +// --------------------------------------------------------------------------- +// Both kinds, to the player + +/// What a scene is asked for, each frame. +pub const Instant = struct { + /// Scene time, in seconds. + t: f32, + clock: f32 = 0, + in: *const sk.Input = &no_input, + pointer: [2]f32 = .{ 0, 0 }, + + const no_input: sk.Input = .{}; +}; + +/// A scene at one instant: what the player draws. +pub const Shot = struct { + objects: []const Object, + poses: []const Pose, + /// For each object morphing (`pose.into`): the pose its morph started + /// from, and where its target ends up. + morphs: []const Morph, + /// Every `Value`, by handle. + values: []const f32, + camera: Camera, + duration: f32, + /// Start times of every play, for chapter-style seeking. + marks: []const f32, + /// Where the player holds until a click (`pause`). + stops: []const f32, +}; + +pub const Morph = struct { from: Pose, to: Pose }; + +// --------------------------------------------------------------------------- + +fn testScene(s: *Builder) void { + const a = s.circle(.{ .r = 10, .fill = blue }); + const b = s.rect(.{ .w = 20, .h = 20, .x = 100 }); + const k = s.value(0); + s.play(.{a.create()}, .{}); + s.wait(0.5); + s.play(.{ a.move(.{ .x = 50 }), camera(.{ .zoom = 2 }), k.to(10) }, .{ .seconds = 2 }); + s.always(b, follow, .{k}); + s.play(.{a.transformInto(b)}, .{}); +} + +fn follow(now: Now, k: Value) Pose { + var p = now.pose; + p.y = now.value(k); + return p; +} + +test "construct records a timeline that compiles to settling keyframes" { + const S = Scene(testScene); + try std.testing.expectEqual(@as(f32, 4.5), S.duration); + try std.testing.expectEqual(@as(f32, 1), S.pose(0, 1).drawn); + try std.testing.expectApproxEqAbs(@as(f32, 25), S.pose(0, 2.5).x, 1e-3); + try std.testing.expectEqual(@as(f32, 2), S.view(10).zoom); + try std.testing.expectApproxEqAbs(@as(f32, 5), S.values(2.5)[0], 1e-3); + // The updater only runs from where it was added. + try std.testing.expectEqual(@as(f32, 0), S.pose(1, 1).y); + try std.testing.expectEqual(@as(f32, 10), S.pose(1, 4).y); + const mid = S.pose(0, 4.0); + try std.testing.expect(mid.visible and mid.morph > 0 and mid.into == 1); + try std.testing.expect(!S.pose(0, 4.5).visible); + try std.testing.expect(S.pose(1, 4.5).visible); + try std.testing.expectEqual(@as(usize, 3), S.marks.len); +} + +/// `testScene`, live: the updater is a line of code after the plays. +fn liveScene(s: *Frame) void { + const a = s.circle(.{ .r = 10, .fill = blue }); + const b = s.rect(.{ .w = 20, .h = 20, .x = 100 }); + const k = s.value(0); + s.play(.{a.create()}, .{}); + s.wait(0.5); + s.play(.{ a.move(.{ .x = 50 }), camera(.{ .zoom = 2 }), k.to(10) }, .{ .seconds = 2 }); + const since = s.cursor; + s.play(.{a.transformInto(b)}, .{}); + if (s.t >= since) s.pose(b).y = s.get(k); +} + +test "a live scene shows what the compiled one does, at every instant" { + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + const compiled = Scene(testScene); + const live = Live(liveScene, struct {}); + for ([_]f32{ 0, 0.5, 1, 1.7, 2.5, 3.5, 4, 4.5, 9 }) |t| { + const a = try compiled.shot(arena.allocator(), .{ .t = t }); + const b = try live.shot(arena.allocator(), .{ .t = t }); + try std.testing.expectEqualSlices(Pose, a.poses, b.poses); + try std.testing.expectEqualSlices(f32, a.values, b.values); + try std.testing.expectEqual(a.camera, b.camera); + try std.testing.expectEqual(a.duration, b.duration); + try std.testing.expectEqualSlices(f32, a.marks, b.marks); + } +} diff --git a/src/anim/typst.zig b/src/anim/typst.zig new file mode 100644 index 0000000..d9df734 --- /dev/null +++ b/src/anim/typst.zig @@ -0,0 +1,66 @@ +//! Build-time Typst for a scene file. `sb.addTypst` builds a small generator +//! around this file that imports the scene, whose `construct` has already +//! run at comptime and listed its Typst objects (`scene.typst_sources`), +//! compiles each with the `typst` CLI after the scene's `typst_preamble`, +//! and writes a module the player uses to find the SVGs by source: +//! +//! typst.find(source) ?[]const u8 +const std = @import("std"); + +/// Used when the scene declares no `typst_preamble`. +pub const default_preamble = + \\#set page(width: auto, height: auto, margin: 3pt, fill: none) +; + +pub fn generate(comptime SceneFile: type, comptime sources: []const []const u8, gpa: std.mem.Allocator, io: std.Io, out_path: []const u8, cache_path: []const u8) !void { + const preamble: []const u8 = if (@hasDecl(SceneFile, "typst_preamble")) SceneFile.typst_preamble else default_preamble; + const cwd = std.Io.Dir.cwd(); + var out = try cwd.createDirPathOpen(io, out_path, .{}); + defer out.close(io); + var cache = try cwd.createDirPathOpen(io, cache_path, .{}); + defer cache.close(io); + + var table: std.ArrayList(u8) = .empty; + var seen: std.AutoHashMapUnmanaged(u64, void) = .empty; + for (sources) |source| { + const key = std.hash.Wyhash.hash(0, source); + if ((try seen.getOrPut(gpa, key)).found_existing) continue; + const name = try std.fmt.allocPrint(gpa, "{x:0>16}.svg", .{key}); + // Cached by preamble and source together. + const cache_name = try std.fmt.allocPrint(gpa, "{x:0>16}-{s}", .{ std.hash.Wyhash.hash(0, preamble), name }); + const svg = cache.readFileAlloc(io, cache_name, gpa, .limited(64 << 20)) catch try compile(gpa, io, cache, cache_name, preamble, source); + try out.writeFile(io, .{ .sub_path = name, .data = svg }); + try table.print(gpa, " .{{ 0x{x:0>16}, @embedFile(\"{s}\") }},\n", .{ key, name }); + } + const module = try std.fmt.allocPrint(gpa, + \\//! Generated by sketchbook's src/anim/typst.zig: the scene's Typst objects, as SVG. + \\const std = @import("std"); + \\ + \\const table = [_]struct {{ u64, []const u8 }}{{ + \\{s}}}; + \\ + \\/// The SVG compiled from Typst `source`, if the scene declared it. + \\pub fn find(source: []const u8) ?[]const u8 {{ + \\ const key = std.hash.Wyhash.hash(0, source); + \\ for (table) |entry| if (entry[0] == key) return entry[1]; + \\ return null; + \\}} + \\ + , .{table.items}); + try out.writeFile(io, .{ .sub_path = "typst.zig", .data = module }); +} + +/// Runs `typst compile` on `preamble ++ source` and caches the SVG. +fn compile(gpa: std.mem.Allocator, io: std.Io, cache: std.Io.Dir, name: []const u8, preamble: []const u8, source: []const u8) ![]const u8 { + const typ = try std.fmt.allocPrint(gpa, "{s}.typ", .{name}); + try cache.writeFile(io, .{ .sub_path = typ, .data = try std.mem.concat(gpa, u8, &.{ preamble, "\n", source, "\n" }) }); + const result = try std.process.run(gpa, io, .{ + .argv = &.{ "typst", "compile", "--format", "svg", typ, name }, + .cwd = .{ .dir = cache }, + }); + if (result.term != .exited or result.term.exited != 0) { + std.debug.print("typst failed on:\n{s}\n{s}\n", .{ source, result.stderr }); + return error.TypstFailed; + } + return cache.readFileAlloc(io, name, gpa, .limited(64 << 20)); +} |
