summaryrefslogtreecommitdiff
path: root/src/anim/Painter.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/anim/Painter.zig')
-rw-r--r--src/anim/Painter.zig256
1 files changed, 256 insertions, 0 deletions
diff --git a/src/anim/Painter.zig b/src/anim/Painter.zig
new file mode 100644
index 0000000..b5d492f
--- /dev/null
+++ b/src/anim/Painter.zig
@@ -0,0 +1,256 @@
+//! Draws a scene's `Shot` with the vector library, on the GPU (or the CPU),
+//! the scene's frame fitted into the canvas, and the canvas the room the
+//! host has: the window, or an export's `--size`. The player paints with
+//! one, and so does a sketch that runs a `Deck` itself: a `Painter` in its
+//! Session, and `paint` once a frame.
+const std = @import("std");
+const sk = @import("sketch");
+const vector = @import("vector");
+const anim = @import("root.zig");
+const geom = vector.geom;
+
+const Painter = @This();
+
+/// 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,
+/// Shapes drawn in the last frame.
+shapes: usize = 0,
+
+pub const Options = struct {
+ /// The viewer's own pan and zoom, on top of the scene's camera.
+ view: sk.Camera = .{},
+ backend: vector.Backend = .gpu,
+ /// Boxes, origins and axes, in scene units, with their numbers.
+ guides: bool = false,
+ /// The page (0xRRGGBB).
+ background: u32 = anim.background,
+};
+
+const Built = struct { drawing: vector.Drawing, bounds: geom.Rect };
+
+/// Sets the canvas to the window and draws `shot` on it. `svgs` has
+/// `find(source) ?[]const u8` for its Typst objects (`sb.addTypst`).
+pub fn paint(p: *Painter, f: *sk.Frame, shot: anim.Shot, svgs: anytype, options: Options) !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));
+ if (p.arena == null) p.arena = .init(f.session);
+ // A live scene may make new drawings every frame: start over now and then.
+ if (f.in.reloaded or p.drawings.count() > 1024) {
+ _ = p.arena.?.reset(.retain_capacity);
+ p.drawings = .empty;
+ }
+ // Use the host's GPU when it has one.
+ if (options.backend == .gpu and f.host.gpu()) try p.paintLayers(&p.gpu, f, shot, svgs, canvas, options) else try p.paintLayers(&p.cpu, f, shot, svgs, canvas, options);
+}
+
+/// Canvas pixels per scene unit: the scene's frame, fitted into `canvas`.
+pub fn fit(canvas: sk.Rect) f32 {
+ return @min(canvas.w / anim.width, canvas.h / anim.height);
+}
+
+/// Object `o`'s drawing, centered on its origin, and its bounds.
+fn built(p: *Painter, o: anim.Object, svgs: anytype) !Built {
+ const id = o.id();
+ if (p.drawings.get(id)) |b| return b;
+ const arena = p.arena.?.allocator();
+ const d = try anim.build(arena, o, svgs);
+ const b: Built = .{ .drawing = d, .bounds = d.bounds().rect() };
+ try p.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(view: sk.Camera, cam: anim.Camera, canvas: sk.Rect) geom.Affine {
+ const k = fit(canvas) * cam.zoom;
+ return geom.Affine.translate(view.x, view.y)
+ .mul(.scale(view.zoom, 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 paintLayers(p: *Painter, layers: anytype, f: *sk.Frame, shot: anim.Shot, svgs: anytype, canvas: sk.Rect, options: Options) !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(options.view, 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(options.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 = shot.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 p.built(o, svgs)).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 p.built(shot.objects[pose.into], svgs)).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 (options.guides) {
+ const r = open orelse try begun(layers, &used, f, canvas, .{ 0, 0, 0, 0 });
+ open = r;
+ try r.draw(try p.guides(f.scratch, shot, svgs, world, canvas), .identity, 1);
+ }
+ if (open) |r| r.present(f, canvas);
+ p.shapes = shapes;
+ if (options.guides) try p.labels(f, shot, svgs, 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(p: *Painter, arena: std.mem.Allocator, shot: anim.Shot, svgs: anytype, 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 p.built(o, svgs)).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(p: *Painter, f: *sk.Frame, shot: anim.Shot, svgs: anytype, 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 p.built(o, svgs)).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 });
+ }
+}