summaryrefslogtreecommitdiff
path: root/src/host/root.zig
blob: 637a3255c3e98f3a10b802d4f81e16ed260156e6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
//! The sketchbook host: runs a sketch linked in, or loaded from a library
//! that it hot-reloads whenever a build replaces it.
//!
//!     sketchbook [options] [LIBRARY]
//!       --state FILE         persistent state (default: <name>.state)
//!       --headless           offscreen video, silent audio
//!       --script FILE        play a script instead of reading devices
//!       --fresh              start from default state: no snapshots or recordings
//!       --define NAME=VALUE  substitute {NAME} in the script
const std = @import("std");
const c = @import("c");
const abi = @import("abi");
pub const Host = @import("Host.zig");
pub const memory = @import("memory.zig");
pub const fields = @import("fields.zig");
pub const script = @import("script.zig");
pub const timeline = @import("timeline.zig");

/// Entry point for both the generic host (`linked == null`) and apps that
/// link their sketch in.
pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void {
    const gpa = init.gpa;
    var options: Host.Options = .{};
    var script_path: ?[]const u8 = null;
    var defines: std.ArrayList([2][]const u8) = .empty;
    defer defines.deinit(gpa);

    var args = init.minimal.args.iterate();
    _ = args.skip();
    while (args.next()) |arg| {
        if (std.mem.eql(u8, arg, "--state")) {
            options.state = args.next() orelse fatal("--state needs a file");
        } else if (std.mem.eql(u8, arg, "--fresh")) {
            options.fresh = true;
        } else if (std.mem.eql(u8, arg, "--headless")) {
            options.headless = true;
        } else if (std.mem.eql(u8, arg, "--script")) {
            script_path = args.next() orelse fatal("--script needs a file");
        } else if (std.mem.eql(u8, arg, "--define")) {
            const pair = args.next() orelse fatal("--define needs NAME=VALUE");
            const eq = std.mem.indexOfScalar(u8, pair, '=') orelse fatal("--define needs NAME=VALUE");
            try defines.append(gpa, .{ pair[0..eq], pair[eq + 1 ..] });
        } else if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) {
            std.debug.print("{s}", .{usage});
            return;
        } else if (std.mem.startsWith(u8, arg, "-")) {
            fatal("unknown option (see --help)");
        } else {
            options.library = arg;
        }
    }
    if (linked == null and options.library == null) fatal("no sketch library given (see --help)");

    sdl_heap.install();
    {
        var host: Host = undefined;
        try host.init(gpa, init.io, init.environ_map, options, linked);
        defer host.deinit();
        if (script_path) |path| {
            const source = try std.Io.Dir.cwd().readFileAlloc(init.io, path, gpa, .limited(1 << 20));
            defer gpa.free(source);
            try script.run(&host, source, defines.items);
        } else try host.run();
    }
    if (sdl_heap.leaked()) return error.LeakedSdlMemory;
}

const usage =
    \\usage: sketchbook [options] [LIBRARY]
    \\  --state FILE         persistent state (default: sketch.state)
    \\  --headless           offscreen video, silent audio, no vsync
    \\  --script FILE        play a script instead of reading devices
    \\  --fresh              start from default state: no snapshots or recordings
    \\  --define NAME=VALUE  substitute {NAME} in the script
    \\
;

fn fatal(message: []const u8) noreturn {
    std.debug.print("sketchbook: {s}\n", .{message});
    std.process.exit(2);
}

/// SDL's allocations go through a leak-checking allocator of their own, so a
/// session that leaks SDL memory fails loudly at exit.
const sdl_heap = struct {
    var debug: std.heap.DebugAllocator(.{ .backing_allocator_zeroes = false }) = .{};
    const alignment: std.mem.Alignment = .of(std.c.max_align_t);
    const header = alignment.forward(@sizeOf(usize));

    fn install() void {
        _ = c.SDL_SetMemoryFunctions(malloc, calloc, realloc, free);
    }
    fn leaked() bool {
        return debug.deinit() == .leak;
    }
    fn block(size: usize) ?[*]u8 {
        const total = std.math.add(usize, header, size) catch return null;
        const base = debug.allocator().rawAlloc(total, alignment, @returnAddress()) orelse return null;
        @as(*usize, @ptrCast(@alignCast(base))).* = total;
        return base + header;
    }
    fn whole(mem: *anyopaque) []u8 {
        const base: [*]u8 = @as([*]u8, @ptrCast(mem)) - header;
        return base[0..@as(*const usize, @ptrCast(@alignCast(base))).*];
    }
    fn malloc(size: usize) callconv(.c) ?*anyopaque {
        return block(size);
    }
    fn calloc(n: usize, size: usize) callconv(.c) ?*anyopaque {
        const bytes = std.math.mul(usize, n, size) catch return null;
        const mem = block(bytes) orelse return null;
        @memset(mem[0..bytes], 0);
        return mem;
    }
    fn realloc(maybe: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque {
        const old = whole(maybe orelse return malloc(size));
        const total = std.math.add(usize, header, size) catch return null;
        if (debug.allocator().rawRemap(old, alignment, total, @returnAddress())) |base| {
            @as(*usize, @ptrCast(@alignCast(base))).* = total;
            return base + header;
        }
        const new = block(size) orelse return null;
        @memcpy(new[0..@min(size, old.len - header)], old[header..][0..@min(size, old.len - header)]);
        debug.allocator().rawFree(old, alignment, @returnAddress());
        return new;
    }
    fn free(maybe: ?*anyopaque) callconv(.c) void {
        debug.allocator().rawFree(whole(maybe orelse return), alignment, @returnAddress());
    }
};

test {
    _ = memory;
    _ = fields;
    _ = timeline;
    _ = @import("audio.zig");
    _ = @import("Console.zig");
}