diff options
| author | Gabriel Schneider <[email protected]> | 2026-09-25 21:47:58 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-09-25 21:48:16 -0300 |
| commit | 9c33714591a2147f7e5879e77212ca9886d0c967 (patch) | |
| tree | d250be9d9bc365d7894d49455c0f6376966b58be /src/sketch | |
| download | sketchbook-9c33714591a2147f7e5879e77212ca9886d0c967.tar.gz sketchbook-9c33714591a2147f7e5879e77212ca9886d0c967.zip | |
Put the game first: lib/sketchbook, sketches/vecanim
The root is the game. The platform library moves to lib/sketchbook (with
serve_web.py, which serves any sketch's web build, as a tool of it), and
vecanim to sketches/vecanim, still its own package on the same library.
Diffstat (limited to 'src/sketch')
| -rw-r--r-- | src/sketch/camera.zig | 60 | ||||
| -rw-r--r-- | src/sketch/root.zig | 215 | ||||
| -rw-r--r-- | src/sketch/shape.zig | 209 | ||||
| -rw-r--r-- | src/sketch/tween.zig | 133 | ||||
| -rw-r--r-- | src/sketch/web.zig | 201 |
5 files changed, 818 insertions, 0 deletions
diff --git a/src/sketch/camera.zig b/src/sketch/camera.zig new file mode 100644 index 0000000..460fc8a --- /dev/null +++ b/src/sketch/camera.zig @@ -0,0 +1,60 @@ +//! A 2D camera maps world points to canvas pixels. Zoom keeps the world point +//! underneath the pointer stationary; panning is measured in screen pixels. +//! Points and rects are duck-typed (see `shape.zig`) and come back in the +//! caller's own type. +const std = @import("std"); +const shape = @import("shape.zig"); + +pub const Camera = struct { + x: f32 = 0, + y: f32 = 0, + zoom: f32 = 1, + + pub fn toScreen(self: Camera, world: anytype) shape.Out(@TypeOf(world)) { + const T = shape.Out(@TypeOf(world)); + const x = self.x + shape.get(world, "x") * self.zoom; + const y = self.y + shape.get(world, "y") * self.zoom; + return if (comptime shape.isRect(T)) + shape.make(T, x, y, shape.get(world, "w") * self.zoom, shape.get(world, "h") * self.zoom) + else + shape.point(T, x, y); + } + pub fn toWorld(self: Camera, screen: anytype) shape.Out(@TypeOf(screen)) { + const T = shape.Out(@TypeOf(screen)); + const x = (shape.get(screen, "x") - self.x) / self.zoom; + const y = (shape.get(screen, "y") - self.y) / self.zoom; + return if (comptime shape.isRect(T)) + shape.make(T, x, y, shape.get(screen, "w") / self.zoom, shape.get(screen, "h") / self.zoom) + else + shape.point(T, x, y); + } + pub fn pan(self: *Camera, delta: anytype) void { + self.x += shape.get(delta, "x"); + self.y += shape.get(delta, "y"); + } + /// Zoom by `1.2^wheel` around `screen`, clamped to `[min, max]`. + pub fn zoomAt(self: *Camera, screen: anytype, wheel: f32, limits: struct { min: f32 = 0.04, max: f32 = 12 }) void { + if (!std.math.isFinite(wheel)) return; + const sx = shape.get(screen, "x"); + const sy = shape.get(screen, "y"); + const wx = (sx - self.x) / self.zoom; + const wy = (sy - self.y) / self.zoom; + self.zoom = std.math.clamp(self.zoom * std.math.pow(f32, 1.2, std.math.clamp(wheel, -40, 40)), limits.min, limits.max); + self.x = sx - wx * self.zoom; + self.y = sy - wy * self.zoom; + } +}; + +test "zooming keeps the point under the cursor fixed, in any shape" { + var camera: Camera = .{ .x = 10, .y = 20, .zoom = 0.5 }; + const P = struct { x: f32, y: f32 }; + const before = camera.toWorld(P{ .x = 300, .y = 200 }); + camera.zoomAt(@Vector(2, f32){ 300, 200 }, 3, .{}); + const after = camera.toWorld(P{ .x = 300, .y = 200 }); + try std.testing.expectApproxEqAbs(before.x, after.x, 1e-3); + try std.testing.expectApproxEqAbs(before.y, after.y, 1e-3); + const r = camera.toScreen([4]f32{ 0, 0, 10, 10 }); + try std.testing.expectApproxEqAbs(camera.zoom * 10, r[2], 1e-4); + // Literals come back as f32 points. + try std.testing.expectEqual(shape.Point{ .x = 12, .y = 21 }, (Camera{ .x = 10, .y = 20 }).toScreen(.{ .x = 2, .y = 1 })); +} diff --git a/src/sketch/root.zig b/src/sketch/root.zig new file mode 100644 index 0000000..316a886 --- /dev/null +++ b/src/sketch/root.zig @@ -0,0 +1,215 @@ +//! The sketch library: compiled into every app and reloaded with it. +//! +//! An app is an ordinary Zig module. Every declaration is optional: +//! +//! pub const name = "my sketch"; +//! pub const width = 960; +//! pub const height = 600; +//! pub const State = struct { ... }; // persisted and snapshotted: no pointers +//! pub const Session = struct { ... }; // survives reloads, never saved +//! pub const commands = .{"hello"}; // console completions +//! pub fn init(state: *State, host: sk.Host) void +//! pub fn update(state: *State, in: *const sk.Input) void +//! pub fn draw(state: *const State, session: *Session, f: *sk.Frame) void +//! pub fn command(state: *State, session: *Session, c: *sk.Console, line: []const u8) !bool +//! +//! `update` must be deterministic: the host replays recorded input through it. +//! `draw` presents state as pictures and sound, and may only change `Session`. +//! Geometry and colors are duck-typed: see `shape`. +const std = @import("std"); +pub const abi = @import("abi"); +pub const shape = @import("shape.zig"); +pub const Key = abi.Key; +pub const Camera = @import("camera.zig").Camera; +pub const tween = @import("tween.zig"); +pub const web = @import("web.zig"); + +pub const Rect = abi.Rect; +pub const Color = abi.Color; +pub const Event = abi.Event; +pub const Input = abi.Input; +pub const Mode = abi.Mode; +pub const Host = abi.Host; +pub const Image = abi.Image; +pub const Audio = abi.Audio; +pub const Cursor = abi.Cursor; +pub const Voice = abi.Voice; + +/// What `draw` receives: input, host services, allocators and the command list. +pub const Frame = struct { + ctx: *const abi.Context, + in: *const Input, + host: Host, + /// Frame lifetime. + arena: std.mem.Allocator, + /// Session lifetime; survives reloads. + gpa: std.mem.Allocator, + + pub fn init(ctx: *const abi.Context) Frame { + return .{ .ctx = ctx, .in = ctx.input, .host = ctx.host, .arena = ctx.arena, .gpa = ctx.gpa }; + } + + pub fn emit(f: *Frame, command: abi.Command) void { + f.ctx.commands.append(f.arena, command) catch f.host.log("frame arena full: command dropped"); + } + + pub fn clear(f: *Frame, color: anytype) void { + f.emit(.{ .clear = shape.color(color) }); + } + pub fn fill(f: *Frame, r: anytype, color: anytype) void { + f.emit(.{ .rect = .{ .dst = shape.rect(r), .color = shape.color(color) } }); + } + /// `options` may set `.src` (a rect within the image) and `.tint` (a color). + pub fn image(f: *Frame, img: Image, dst: anytype, options: anytype) void { + const O = @TypeOf(options); + f.emit(.{ .image = .{ + .image = img, + .dst = shape.rect(dst), + .src = if (@hasField(O, "src")) shape.rect(options.src) else .{}, + .tint = if (@hasField(O, "tint")) shape.color(options.tint) else .white, + } }); + } + /// `bytes` must live until the frame is consumed: literals, `arena` and + /// session memory all do. + pub fn text(f: *Frame, x: f32, y: f32, scale: f32, bytes: []const u8, color: anytype) void { + f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = shape.color(color), .bytes = bytes } }); + } + pub fn print(f: *Frame, x: f32, y: f32, scale: f32, color: anytype, comptime fmt: []const u8, args: anytype) void { + f.text(x, y, scale, f.format(fmt, args), color); + } + /// Formats into the frame arena. + pub fn format(f: *Frame, comptime fmt: []const u8, args: anytype) []const u8 { + return std.fmt.allocPrint(f.arena, fmt, args) catch "?"; + } + /// A rect, or `null` to stop clipping. + pub fn clip(f: *Frame, r: anytype) void { + f.emit(.{ .clip = if (@TypeOf(r) == @TypeOf(null)) null else shape.rect(r) }); + } + pub fn canvas(f: *Frame, w: u32, h: u32) void { + f.emit(.{ .canvas = .{ .w = w, .h = h } }); + } + pub fn cursor(f: *Frame, kind: Cursor) void { + f.emit(.{ .cursor = kind }); + } + pub fn voice(f: *Frame, v: Voice) void { + f.emit(.{ .voice = v }); + } + pub fn audio(f: *Frame, key: u32, samples: []const f32, options: struct { clear: bool = false }) void { + f.emit(.{ .audio = .{ .key = key, .samples = samples, .clear = options.clear } }); + } + pub fn pixels(f: *Frame, img: Image, w: u32, h: u32, rgba: []const u8, options: struct { premultiplied: bool = false }) void { + f.emit(.{ .pixels = .{ .image = img, .w = w, .h = h, .rgba = rgba, .premultiplied = options.premultiplied } }); + } + /// Runs GPU work described as data (see `abi.gpu`) into `pass.image`. + pub fn gpu(f: *Frame, pass: abi.gpu.Pass) void { + f.emit(.{ .gpu = pass }); + } + pub fn quit(f: *Frame) void { + f.emit(.quit); + } +}; + +/// What `command` receives: somewhere to answer, and the current input. +pub const Console = struct { + host: Host, + in: *const Input, + + pub fn log(c: *Console, message: []const u8) void { + c.host.log(message); + } + pub fn print(c: *Console, comptime fmt: []const u8, args: anytype) void { + c.host.print(fmt, args); + } +}; + +/// The entry points of `App`, for a host that links it statically. +pub fn sketch(comptime App: type) abi.Sketch { + const G = Glue(App); + return .{ .info = G.info, .defaults = G.defaults, .init = G.init, .update = G.update, .draw = G.draw, .command = G.command }; +} + +/// Exports `App` under `abi.Sketch.symbols`, for a hot-reloaded library. +pub fn exportSketch(comptime App: type) void { + const G = Glue(App); + const names = abi.Sketch.symbols; + @export(&G.info, .{ .name = names.info }); + @export(&G.defaults, .{ .name = names.defaults }); + @export(&G.init, .{ .name = names.init }); + @export(&G.update, .{ .name = names.update }); + @export(&G.draw, .{ .name = names.draw }); + @export(&G.command, .{ .name = names.command }); +} + +pub fn Glue(comptime App: type) type { + return struct { + pub const State = if (@hasDecl(App, "State")) App.State else struct {}; + pub const Session = if (@hasDecl(App, "Session")) App.Session else struct {}; + + pub const description: abi.Info = .{ + .abi = abi.hash, + .name = if (@hasDecl(App, "name")) App.name else "sketch", + .width = if (@hasDecl(App, "width")) App.width else 960, + .height = if (@hasDecl(App, "height")) App.height else 600, + .state = abi.layout.of(State, .forbidden), + .session = abi.layout.of(Session, .host_only), + .commands = if (@hasDecl(App, "commands")) &App.commands else &.{}, + }; + + fn state(ptr: [*]u8) *State { + return @ptrCast(@alignCast(ptr)); + } + fn session(ptr: [*]u8) *Session { + return @ptrCast(@alignCast(ptr)); + } + fn arity(comptime func: anytype) usize { + return @typeInfo(@TypeOf(func)).@"fn".params.len; + } + + pub fn info() callconv(.c) *const abi.Info { + return &description; + } + pub fn defaults(which: abi.Memory, ptr: [*]u8) callconv(.c) void { + switch (which) { + .state => state(ptr).* = .{}, + .session => session(ptr).* = .{}, + } + } + pub fn init(ctx: *const abi.Context, s: [*]u8) callconv(.c) void { + if (!@hasDecl(App, "init")) return; + switch (comptime arity(App.init)) { + 1 => App.init(state(s)), + else => App.init(state(s), ctx.host), + } + } + pub fn update(ctx: *const abi.Context, s: [*]u8) callconv(.c) void { + if (@hasDecl(App, "update")) App.update(state(s), ctx.input); + } + pub fn draw(ctx: *const abi.Context, s: [*]const u8, ss: [*]u8) callconv(.c) void { + if (!@hasDecl(App, "draw")) return; + var f: Frame = .init(ctx); + const current: *const State = @ptrCast(@alignCast(s)); + switch (comptime arity(App.draw)) { + 2 => App.draw(current, &f), + else => App.draw(current, session(ss), &f), + } + } + pub fn command(ctx: *const abi.Context, s: [*]u8, ss: [*]u8, line: *const []const u8) callconv(.c) bool { + if (!@hasDecl(App, "command")) return false; + var c: Console = .{ .host = ctx.host, .in = ctx.input }; + return switch (comptime arity(App.command)) { + 3 => App.command(state(s), &c, line.*), + else => App.command(state(s), session(ss), &c, line.*), + } catch |err| { + c.print("{t}. Type help for usage.", .{err}); + return true; + }; + } + }; +} + +test { + _ = abi.layout; + _ = shape; + _ = @import("camera.zig"); + _ = tween; +} diff --git a/src/sketch/shape.zig b/src/sketch/shape.zig new file mode 100644 index 0000000..9bd4cee --- /dev/null +++ b/src/sketch/shape.zig @@ -0,0 +1,209 @@ +//! Duck-typed geometry. A point is anything with `x` and `y`, a rect anything +//! that also has `w` and `h` (or `width`/`height`), in any int or float type; +//! `@Vector`s and arrays of two or four elements work too. Functions return +//! the caller's own type where they build one, so sketches keep their data in +//! whatever shape suits them and never convert to library types. +const std = @import("std"); +const abi = @import("abi"); + +/// Anything with an `x` and a `y`: fields, or a 2+ element vector or array. +pub fn isPoint(comptime T: type) bool { + return switch (@typeInfo(T)) { + .vector => |v| v.len >= 2 and isNumber(v.child), + .array => |a| a.len >= 2 and isNumber(a.child), + .@"struct" => @hasField(T, "x") and @hasField(T, "y"), + .pointer => |p| p.size == .one and isPoint(p.child), + else => false, + }; +} + +/// A point that also has a size: `w`/`h` or `width`/`height`, or 4 elements. +pub fn isRect(comptime T: type) bool { + return isPoint(T) and switch (@typeInfo(T)) { + .vector => |v| v.len >= 4, + .array => |a| a.len >= 4, + .@"struct" => (@hasField(T, "w") and @hasField(T, "h")) or (@hasField(T, "width") and @hasField(T, "height")), + .pointer => |p| isRect(p.child), + else => false, + }; +} + +/// `r`, `g`, `b` (optionally `a`) fields, or a `0xRRGGBB` integer. +pub fn isColor(comptime T: type) bool { + return switch (@typeInfo(T)) { + .int, .comptime_int => true, + .@"struct" => @hasField(T, "r") and @hasField(T, "g") and @hasField(T, "b"), + .pointer => |p| p.size == .one and isColor(p.child), + else => false, + }; +} + +fn isNumber(comptime T: type) bool { + return switch (@typeInfo(T)) { + .int, .float, .comptime_int, .comptime_float => true, + else => false, + }; +} + +pub const Point = struct { x: f32 = 0, y: f32 = 0 }; + +/// The type to build results in for inputs shaped like `T`: `T` itself, or +/// for anonymous literals (whose fields are comptime-only) an f32 `Point` or +/// `abi.Rect`. +pub fn Out(comptime T: type) type { + if (@typeInfo(T) != .@"struct") return T; + for (@typeInfo(T).@"struct".fields) |field| switch (@typeInfo(field.type)) { + .comptime_int, .comptime_float => return if (isRect(T)) abi.Rect else Point, + else => {}, + }; + return T; +} + +/// Component `name` of a point- or rect-like value, as f32. +pub fn get(value: anytype, comptime name: []const u8) f32 { + const T = @TypeOf(value); + return switch (@typeInfo(T)) { + .vector, .array => num(value[comptime index(name)]), + .@"struct" => if (@hasField(T, name)) + num(@field(value, name)) + else if (comptime std.mem.eql(u8, name, "w") and @hasField(T, "width")) + num(value.width) + else if (comptime std.mem.eql(u8, name, "h") and @hasField(T, "height")) + num(value.height) + else + @compileError(@typeName(T) ++ " has no field '" ++ name ++ "'"), + .pointer => get(value.*, name), + else => @compileError("expected a point or rect, found " ++ @typeName(T)), + }; +} + +/// A value of type `T` with the given components, converted to `T`'s fields. +pub fn make(comptime T: type, x: f32, y: f32, w: f32, h: f32) T { + switch (@typeInfo(T)) { + .vector => |v| return if (v.len == 2) .{ cast(v.child, x), cast(v.child, y) } else .{ cast(v.child, x), cast(v.child, y), cast(v.child, w), cast(v.child, h) }, + .array => |a| return if (a.len == 2) .{ cast(a.child, x), cast(a.child, y) } else .{ cast(a.child, x), cast(a.child, y), cast(a.child, w), cast(a.child, h) }, + .@"struct" => { + var result: T = undefined; + inline for (@typeInfo(T).@"struct".fields) |field| { + @field(result, field.name) = if (comptime eql(field.name, "x")) + cast(field.type, x) + else if (comptime eql(field.name, "y")) + cast(field.type, y) + else if (comptime eql(field.name, "w") or eql(field.name, "width")) + cast(field.type, w) + else if (comptime eql(field.name, "h") or eql(field.name, "height")) + cast(field.type, h) + else if (field.defaultValue()) |default| + default + else + @compileError(@typeName(T) ++ "." ++ field.name ++ " has no default"); + } + return result; + }, + else => @compileError("cannot build a point or rect of type " ++ @typeName(T)), + } +} + +pub fn point(comptime T: type, x: f32, y: f32) T { + return make(T, x, y, 0, 0); +} + +pub fn rect(value: anytype) abi.Rect { + comptime if (!isRect(@TypeOf(value))) @compileError("expected a rect (x, y, w, h), found " ++ @typeName(@TypeOf(value))); + return .{ .x = get(value, "x"), .y = get(value, "y"), .w = get(value, "w"), .h = get(value, "h") }; +} + +pub fn contains(r: anytype, p: anytype) bool { + const x = get(p, "x"); + const y = get(p, "y"); + const rx = get(r, "x"); + const ry = get(r, "y"); + return x >= rx and y >= ry and x < rx + get(r, "w") and y < ry + get(r, "h"); +} + +/// `r` shrunk by `d` on every side, in `r`'s own type. +pub fn inset(r: anytype, d: f32) Out(@TypeOf(r)) { + return make(Out(@TypeOf(r)), get(r, "x") + d, get(r, "y") + d, get(r, "w") - 2 * d, get(r, "h") - 2 * d); +} + +/// `r` moved by the point `by`, in `r`'s own type. +pub fn offset(r: anytype, by: anytype) Out(@TypeOf(r)) { + const has_size = comptime isRect(@TypeOf(r)); + return make(Out(@TypeOf(r)), get(r, "x") + get(by, "x"), get(r, "y") + get(by, "y"), if (has_size) get(r, "w") else 0, if (has_size) get(r, "h") else 0); +} + +/// Anything with `r`, `g`, `b` (and optionally `a`) in 0..255 or 0..1 floats, +/// or a `0xRRGGBB` integer. +pub fn color(value: anytype) abi.Color { + const T = @TypeOf(value); + comptime if (!isColor(T)) @compileError("expected a color (r, g, b[, a]) or 0xRRGGBB, found " ++ @typeName(T)); + if (T == abi.Color) return value; + return switch (@typeInfo(T)) { + .int, .comptime_int => abi.Color.hex(@intCast(value)), + .@"struct" => .{ + .r = channel(value.r), + .g = channel(value.g), + .b = channel(value.b), + .a = if (@hasField(T, "a")) channel(value.a) else 255, + }, + .pointer => color(value.*), + else => @compileError("expected a color, found " ++ @typeName(T)), + }; +} + +fn channel(v: anytype) u8 { + return switch (@typeInfo(@TypeOf(v))) { + .float, .comptime_float => @intFromFloat(std.math.clamp(v, 0, 1) * 255 + 0.5), + else => @intCast(std.math.clamp(v, 0, 255)), + }; +} + +fn index(comptime name: []const u8) usize { + if (eql(name, "x")) return 0; + if (eql(name, "y")) return 1; + if (eql(name, "w")) return 2; + if (eql(name, "h")) return 3; + @compileError("no component " ++ name); +} + +fn num(v: anytype) f32 { + return switch (@typeInfo(@TypeOf(v))) { + .int, .comptime_int => @floatFromInt(v), + .float, .comptime_float => @floatCast(v), + else => @compileError("not a number: " ++ @typeName(@TypeOf(v))), + }; +} + +fn cast(comptime T: type, v: f32) T { + return switch (@typeInfo(T)) { + .int => @intFromFloat(@round(v)), + .float => @floatCast(v), + else => @compileError("not a number type: " ++ @typeName(T)), + }; +} + +fn eql(a: []const u8, b: []const u8) bool { + return std.mem.eql(u8, a, b); +} + +test "shapes are recognized by their data" { + try std.testing.expect(isPoint(struct { x: u8, y: u8 })); + try std.testing.expect(!isRect(struct { x: u8, y: u8 })); + try std.testing.expect(!isRect(struct { w: u8, h: u8 })); + try std.testing.expect(isRect(struct { x: f32, y: f32, width: f32, height: f32 })); + try std.testing.expect(isRect(@Vector(4, i16))); + try std.testing.expect(!isPoint([2][]const u8)); + try std.testing.expect(isColor(struct { r: f32, g: f32, b: f32 })); +} + +test "any shape with the right fields works and keeps its type" { + const P = struct { x: i32, y: i32, label: u8 = 7 }; + const R = struct { x: f64, y: f64, width: f64, height: f64 }; + try std.testing.expect(contains(R{ .x = 0, .y = 0, .width = 10, .height = 5 }, P{ .x = 3, .y = 4 })); + try std.testing.expect(!contains(@Vector(4, f32){ 0, 0, 10, 5 }, [2]f32{ 3, 6 })); + const moved = offset(P{ .x = 1, .y = 2 }, @Vector(2, f32){ 2, 3 }); + try std.testing.expectEqual(P{ .x = 3, .y = 5 }, moved); + try std.testing.expectEqual(abi.Rect{ .x = 1, .y = 1, .w = 8, .h = 3 }, rect(inset(R{ .x = 0, .y = 0, .width = 10, .height = 5 }, 1))); + try std.testing.expectEqual(abi.Color{ .r = 255, .g = 0, .b = 128 }, color(0xff0080)); + try std.testing.expectEqual(abi.Color{ .r = 255, .g = 128, .b = 0, .a = 255 }, color(.{ .r = 1.0, .g = 0.5, .b = 0.0 })); +} diff --git a/src/sketch/tween.zig b/src/sketch/tween.zig new file mode 100644 index 0000000..d3b53a1 --- /dev/null +++ b/src/sketch/tween.zig @@ -0,0 +1,133 @@ +//! Interpolation over plain data. `lerp` works field by field on any struct, +//! array, vector or number: numbers blend, and everything else (bools, enums, +//! unions) switches to `b` once `t` reaches 1. Pair it with an easing: +//! +//! camera = tween.lerp(from, to, tween.ease.inOutCubic(t)); +const std = @import("std"); + +pub fn lerp(a: anytype, b: @TypeOf(a), t: f32) @TypeOf(a) { + const T = @TypeOf(a); + return switch (@typeInfo(T)) { + .float => a + (b - a) * @as(T, @floatCast(t)), + .comptime_float => a + (b - a) * t, + .int => @intFromFloat(@round(@as(f64, @floatFromInt(a)) + (@as(f64, @floatFromInt(b)) - @as(f64, @floatFromInt(a))) * t)), + .vector => |v| if (@typeInfo(v.child) == .float) + a + (b - a) * @as(T, @splat(@floatCast(t))) + else blk: { + var out: T = undefined; + inline for (0..v.len) |i| out[i] = lerp(a[i], b[i], t); + break :blk out; + }, + .array => blk: { + var out: T = undefined; + for (&out, a, b) |*o, x, y| o.* = lerp(x, y, t); + break :blk out; + }, + .@"struct" => |s| blk: { + var out: T = undefined; + inline for (s.fields) |field| @field(out, field.name) = lerp(@field(a, field.name), @field(b, field.name), t); + break :blk out; + }, + else => if (t >= 1) b else a, + }; +} + +/// Like `lerp`, but only the fields named in `names` (a tuple of enum +/// literals, `.{ .x, .zoom }`) move; every other field stays as in `a`. +pub fn lerpFields(a: anytype, b: @TypeOf(a), t: f32, comptime names: anytype) @TypeOf(a) { + var out = a; + inline for (names) |name| { + const field = @tagName(name); + @field(out, field) = lerp(@field(a, field), @field(b, field), t); + } + return out; +} + +/// Moves the fields that `target` names toward its values: the literal is +/// the list, so `toward(sprite, .{ .x = 100, .alpha = 0 }, t)` animates just +/// those two, converting each value to the field's own type. +pub fn toward(a: anytype, target: anytype, t: f32) @TypeOf(a) { + const T = @TypeOf(a); + var out = a; + inline for (@typeInfo(@TypeOf(target)).@"struct".fields) |field| { + if (!@hasField(T, field.name)) @compileError(@typeName(T) ++ " has no field '" ++ field.name ++ "' to animate"); + const F = @FieldType(T, field.name); + const goal: F = switch (@typeInfo(F)) { + .@"struct" => toward(@field(a, field.name), @field(target, field.name), 1), + else => @field(target, field.name), + }; + @field(out, field.name) = lerp(@field(a, field.name), goal, t); + } + return out; +} + +/// Where `t` sits between `start` and `end`, clamped to 0..1. +pub fn progress(t: f32, start: f32, end: f32) f32 { + if (end <= start) return if (t >= end) 1 else 0; + return std.math.clamp((t - start) / (end - start), 0, 1); +} + +/// Easing curves, 0 to 1 over 0 to 1. Plain functions, so any `fn (f32) f32` +/// can stand in for one. +pub const ease = struct { + pub fn linear(t: f32) f32 { + return t; + } + pub fn inQuad(t: f32) f32 { + return t * t; + } + pub fn outQuad(t: f32) f32 { + return 1 - (1 - t) * (1 - t); + } + pub fn inOutQuad(t: f32) f32 { + return if (t < 0.5) 2 * t * t else 1 - std.math.pow(f32, -2 * t + 2, 2) / 2; + } + pub fn inCubic(t: f32) f32 { + return t * t * t; + } + pub fn outCubic(t: f32) f32 { + return 1 - std.math.pow(f32, 1 - t, 3); + } + pub fn inOutCubic(t: f32) f32 { + return if (t < 0.5) 4 * t * t * t else 1 - std.math.pow(f32, -2 * t + 2, 3) / 2; + } + pub fn inOutSine(t: f32) f32 { + return -(@cos(std.math.pi * t) - 1) / 2; + } + pub fn outBack(t: f32) f32 { + const c1 = 1.70158; + const c3 = c1 + 1; + return 1 + c3 * std.math.pow(f32, t - 1, 3) + c1 * std.math.pow(f32, t - 1, 2); + } + pub fn outElastic(t: f32) f32 { + if (t <= 0 or t >= 1) return std.math.clamp(t, 0, 1); + return std.math.pow(f32, 2, -10 * t) * @sin((t * 10 - 0.75) * (2 * std.math.pi / 3.0)) + 1; + } + /// manim's default: smooth start and stop. + pub fn smooth(t: f32) f32 { + const s = std.math.clamp(t, 0, 1); + return s * s * s * (s * (s * 6 - 15) + 10); + } + /// Out and back again, for pulses. + pub fn thereAndBack(t: f32) f32 { + return smooth(if (t < 0.5) 2 * t else 2 * (1 - t)); + } +}; + +test "comptime field lists pick what animates" { + const Sprite = struct { x: f32 = 0, y: f32 = 0, alpha: f32 = 1, frame: u8 = 3, pos: struct { u: f32 = 0 } = .{} }; + const a: Sprite = .{}; + const b: Sprite = .{ .x = 10, .y = 10, .alpha = 0 }; + try std.testing.expectEqual(Sprite{ .x = 5, .y = 0, .alpha = 0.5 }, lerpFields(a, b, 0.5, .{ .x, .alpha })); + try std.testing.expectEqual(Sprite{ .x = 50, .alpha = 0.5, .frame = 3, .pos = .{ .u = 2 } }, toward(a, .{ .x = 100, .alpha = 0, .pos = .{ .u = 4 } }, 0.5)); +} + +test "lerp walks plain data field by field" { + const Camera = struct { x: f32, y: f32, zoom: f32 = 1, mode: enum { free, locked } = .free }; + const mid = lerp(Camera{ .x = 0, .y = 10 }, Camera{ .x = 10, .y = 20, .zoom = 3, .mode = .locked }, 0.5); + try std.testing.expectEqual(Camera{ .x = 5, .y = 15, .zoom = 2, .mode = .free }, mid); + try std.testing.expectEqual(@Vector(2, f32){ 1, 2 }, lerp(@Vector(2, f32){ 0, 0 }, .{ 2, 4 }, 0.5)); + try std.testing.expectEqual([2]i32{ 5, -5 }, lerp([2]i32{ 0, 0 }, .{ 10, -10 }, 0.5)); + try std.testing.expectEqual(@as(f32, 1), ease.smooth(1)); + try std.testing.expectEqual(@as(f32, 0.5), progress(1.5, 1, 2)); +} diff --git a/src/sketch/web.zig b/src/sketch/web.zig new file mode 100644 index 0000000..7246c0d --- /dev/null +++ b/src/sketch/web.zig @@ -0,0 +1,201 @@ +//! Runs a sketch in a browser. `web/host.js` forwards input and implements a +//! handful of drawing imports; state, `update` and `draw` are the same Zig as +//! on native. There is no console, timeline or persistence on the web. +const std = @import("std"); +const abi = @import("abi"); +const root = @import("root.zig"); + +const js = struct { + extern "host" fn log(ptr: [*]const u8, len: usize) void; + extern "host" fn loadImage(ptr: [*]const u8, len: usize) u32; + extern "host" fn imageWidth(image: u32) u32; + extern "host" fn imageHeight(image: u32) u32; + extern "host" fn newImage(w: u32, h: u32) u32; + extern "host" fn clock() f64; + extern "canvas" fn clear(r: u32, g: u32, b: u32, a: u32) void; + extern "canvas" fn fill(x: f32, y: f32, w: f32, h: f32, r: u32, g: u32, b: u32, a: u32) void; + extern "canvas" fn image(id: u32, x: f32, y: f32, w: f32, h: f32, sx: f32, sy: f32, sw: f32, sh: f32, alpha: u32) void; + extern "canvas" fn text(x: f32, y: f32, scale: f32, ptr: [*]const u8, len: usize, r: u32, g: u32, b: u32, a: u32) void; + extern "canvas" fn clip(enabled: u32, x: f32, y: f32, w: f32, h: f32) void; + extern "canvas" fn canvas(w: u32, h: u32) void; + extern "canvas" fn cursor(kind: u32) void; + extern "canvas" fn pixels(id: u32, w: u32, h: u32, ptr: [*]const u8, len: usize, premultiplied: u32) void; +}; + +/// Exports `App` for `web/host.js`: `sk_init`, `sk_event`, `sk_frame`, and +/// `sk_field` for tests to read state by path. +pub fn exportWeb(comptime App: type) void { + const D = Driver(App); + @export(&D.init, .{ .name = "sk_init" }); + @export(&D.event, .{ .name = "sk_event" }); + @export(&D.frame, .{ .name = "sk_frame" }); + @export(&D.buffer, .{ .name = "sk_buffer" }); + @export(&D.field, .{ .name = "sk_field" }); +} + +fn Driver(comptime App: type) type { + const G = root.Glue(App); + return struct { + var state: G.State = undefined; + var session: G.Session = undefined; + var events: [1024]abi.Event = undefined; + var event_count: usize = 0; + var input: abi.Input = .{}; + var commands: std.ArrayList(abi.Command) = .empty; + var arena: std.heap.ArenaAllocator = .init(std.heap.wasm_allocator); + var session_heap: std.heap.ArenaAllocator = .init(std.heap.wasm_allocator); + var last: u64 = 0; + var path: [256]u8 = undefined; + + fn context() abi.Context { + return .{ + .host = .{ .ctx = @ptrCast(&input), .vtable = &vtable }, + .input = &input, + .arena = arena.allocator(), + .gpa = session_heap.allocator(), + .commands = &commands, + }; + } + + fn init() callconv(.c) void { + G.defaults(.state, std.mem.asBytes(&state)); + G.defaults(.session, std.mem.asBytes(&session)); + input.width = G.description.width; + input.height = G.description.height; + js.canvas(G.description.width, G.description.height); + const ctx = context(); + G.init(&ctx, std.mem.asBytes(&state)); + } + + fn event(kind: u32, code: u32, x: f32, y: f32, value: u32) callconv(.c) void { + const k = std.enums.fromInt(abi.Event.Kind, kind) orelse return; + if (event_count == events.len) { + // Never leave a gesture armed when the queue overflows. + events[0] = .{ .kind = .cancel }; + event_count = 1; + } + events[event_count] = .{ .kind = k, .code = @intCast(code), .x = x, .y = y, .value = value }; + event_count += 1; + } + + fn frame(ms: f64) callconv(.c) void { + const now: u64 = @intFromFloat(@max(0, ms) * std.time.ns_per_ms); + const dt = if (last == 0) 0 else now -| last; + last = now; + if (event_count < events.len) { + events[event_count] = .{ .kind = .tick, .x = @floatCast(@as(f64, @floatFromInt(dt)) / std.time.ns_per_s) }; + event_count += 1; + } + for (events[0..event_count]) |*e| { + e.time = now; + input.track(e.*); + } + _ = arena.reset(.retain_capacity); + commands = .empty; + input.now = now; + input.dt = dt; + input.frame += 1; + input.events = events[0..event_count]; + const ctx = context(); + G.update(&ctx, std.mem.asBytes(&state)); + input.events = &.{}; + event_count = 0; + G.draw(&ctx, std.mem.asBytes(&state), std.mem.asBytes(&session)); + js.clip(0, 0, 0, 0, 0); + for (commands.items) |command| submit(command); + } + + fn submit(command: abi.Command) void { + switch (command) { + .clear => |v| js.clear(v.r, v.g, v.b, v.a), + .rect => |v| js.fill(v.dst.x, v.dst.y, v.dst.w, v.dst.h, v.color.r, v.color.g, v.color.b, v.color.a), + .image => |v| js.image(@intFromEnum(v.image), v.dst.x, v.dst.y, v.dst.w, v.dst.h, v.src.x, v.src.y, v.src.w, v.src.h, v.tint.a), + .text => |v| js.text(v.x, v.y, v.scale, v.bytes.ptr, v.bytes.len, v.color.r, v.color.g, v.color.b, v.color.a), + .clip => |v| if (v) |r| js.clip(1, r.x, r.y, r.w, r.h) else js.clip(0, 0, 0, 0, 0), + .canvas => |v| { + input.width = @floatFromInt(v.w); + input.height = @floatFromInt(v.h); + js.canvas(v.w, v.h); + }, + .cursor => |v| js.cursor(@intFromEnum(v)), + .pixels => |v| js.pixels(@intFromEnum(v.image), v.w, v.h, v.rgba.ptr, v.rgba.len, @intFromBool(v.premultiplied)), + // No sound or GPU passes on the web yet (Host.gpu says so); + // quitting a page means nothing. + .voice, .audio, .gpu, .quit => {}, + } + } + + fn buffer() callconv(.c) [*]u8 { + return &path; + } + + /// The state field at the path written into `sk_buffer`, as a number + /// (enums by value); NaN when there is no such scalar field. + fn field(len: usize) callconv(.c) f64 { + const name = path[0..@min(len, path.len)]; + const bytes = std.mem.asBytes(&state); + for (G.description.state.fields) |f| { + if (!std.mem.eql(u8, std.mem.span(f.path), name)) continue; + const raw = bytes[f.offset..][0..f.size]; + var value: u64 = 0; + for (raw[0..@min(raw.len, 8)], 0..) |b, i| value |= @as(u64, b) << @intCast(i * 8); + return switch (f.kind) { + .float => if (f.size == 4) @as(f32, @bitCast(@as(u32, @truncate(value)))) else @bitCast(value), + .int => blk: { + const shift: u6 = @intCast(64 - f.size * 8); + break :blk @floatFromInt(@as(i64, @bitCast(value << shift)) >> shift); + }, + .uint, .@"enum", .bool => @floatFromInt(value), + else => std.math.nan(f64), + }; + } + return std.math.nan(f64); + } + + const vtable: abi.Host.VTable = .{ + .log = log, + .loadImage = loadImage, + .decodeImage = unsupportedImage, + .newImage = newImage, + .freeImage = freeImage, + .gpu = gpu, + .imageSize = imageSize, + .loadSound = unsupportedSound, + .decodeSound = unsupportedSound, + .readFile = readFile, + .env = env, + .clock = clock, + }; + fn log(_: *anyopaque, message: []const u8) void { + js.log(message.ptr, message.len); + } + fn loadImage(_: *anyopaque, p: []const u8) abi.Image { + return @enumFromInt(js.loadImage(p.ptr, p.len)); + } + fn unsupportedImage(_: *anyopaque, _: []const u8) abi.Image { + return .none; + } + fn newImage(_: *anyopaque, w: u32, h: u32) abi.Image { + return @enumFromInt(js.newImage(w, h)); + } + fn freeImage(_: *anyopaque, _: abi.Image) void {} + fn gpu(_: *anyopaque) bool { + return false; + } + fn imageSize(_: *anyopaque, img: abi.Image) [2]u32 { + return .{ js.imageWidth(@intFromEnum(img)), js.imageHeight(@intFromEnum(img)) }; + } + fn unsupportedSound(_: *anyopaque, _: []const u8) abi.Audio { + return .none; + } + fn readFile(_: *anyopaque, _: []const u8) []const u8 { + return &.{}; + } + fn env(_: *anyopaque, _: []const u8) ?[]const u8 { + return null; + } + fn clock(_: *anyopaque) u64 { + return @intFromFloat(@max(js.clock(), 0) * std.time.ns_per_ms); + } + }; +} |
