//! 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 /// for tests to read state by path, `sk_field` (a number) and `sk_tag` (an /// enum's tag name). 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" }); @export(&D.tag, .{ .name = "sk_tag" }); } 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]; input.started = input.frame == 1; 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. /// Writes the tag name of the enum field at the path in `buffer` over /// it, and returns its length; -1 when there is no such enum field. fn tag(len: usize) callconv(.c) i32 { const name = path[0..@min(len, path.len)]; for (G.description.state.fields) |f| { if (f.kind != .@"enum" or !std.mem.eql(u8, std.mem.span(f.path), name)) continue; const value: u64 = @intFromFloat(field(len)); var pairs = std.mem.tokenizeScalar(u8, std.mem.span(f.tags), ','); while (pairs.next()) |pair| { const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; if ((std.fmt.parseInt(u64, pair[eq + 1 ..], 10) catch continue) != value) continue; @memcpy(path[0..eq], pair[0..eq]); return @intCast(eq); } } return -1; } 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); } }; }