summaryrefslogtreecommitdiff
path: root/src/host/gfx.zig
blob: 16148a668b14f2e5ac756feebb0130bce2d8d63a (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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
//! Images and drawing. Textures have host lifetime; sketches hold handles.
const std = @import("std");
const c = @import("c");
const abi = @import("abi");

pub const Images = struct {
    gpa: std.mem.Allocator,
    renderer: *c.SDL_Renderer,
    /// Handle `n` is `entries[n - 1]`.
    entries: std.ArrayList(Entry) = .empty,
    paths: std.StringHashMapUnmanaged(abi.Image) = .empty,

    const Entry = struct {
        texture: ?*c.SDL_Texture = null,
        w: u32 = 0,
        h: u32 = 0,
    };

    pub fn deinit(self: *Images) void {
        for (self.entries.items) |entry| if (entry.texture) |t| c.SDL_DestroyTexture(t);
        self.entries.deinit(self.gpa);
        var keys = self.paths.keyIterator();
        while (keys.next()) |key| self.gpa.free(key.*);
        self.paths.deinit(self.gpa);
    }

    pub fn load(self: *Images, path: []const u8) abi.Image {
        if (self.paths.get(path)) |image| return image;
        var buf: [std.fs.max_path_bytes]u8 = undefined;
        const z = std.mem.printSentinel(&buf, "{s}", .{path}, 0) catch return .none;
        const surface = c.SDL_LoadPNG(z.ptr);
        if (surface == null) std.log.warn("image {s}: {s}", .{ path, c.SDL_GetError() });
        const image = self.add(surface);
        const key = self.gpa.dupe(u8, path) catch return image;
        self.paths.put(self.gpa, key, image) catch self.gpa.free(key);
        return image;
    }

    pub fn decode(self: *Images, png: []const u8) abi.Image {
        const io = c.SDL_IOFromConstMem(png.ptr, png.len) orelse return .none;
        return self.add(c.SDL_LoadPNG_IO(io, true));
    }

    pub fn new(self: *Images, w: u32, h: u32) abi.Image {
        const texture = c.SDL_CreateTexture(self.renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_STREAMING, @intCast(w), @intCast(h));
        if (texture) |t| setup(t);
        return self.append(.{ .texture = texture, .w = w, .h = h });
    }

    /// Makes `image` show a GPU render target (GPU renderer only).
    pub fn wrap(self: *Images, image: abi.Image, gpu_texture: *anyopaque, w: u32, h: u32) !void {
        const entry = self.get(image) orelse return error.UnknownImage;
        const props = c.SDL_CreateProperties();
        defer c.SDL_DestroyProperties(props);
        _ = c.SDL_SetPointerProperty(props, c.SDL_PROP_TEXTURE_CREATE_GPU_TEXTURE_POINTER, gpu_texture);
        _ = c.SDL_SetNumberProperty(props, c.SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, c.SDL_PIXELFORMAT_ABGR8888);
        _ = c.SDL_SetNumberProperty(props, c.SDL_PROP_TEXTURE_CREATE_WIDTH_NUMBER, w);
        _ = c.SDL_SetNumberProperty(props, c.SDL_PROP_TEXTURE_CREATE_HEIGHT_NUMBER, h);
        const texture = c.SDL_CreateTextureWithProperties(self.renderer, props) orelse return error.WrapTexture;
        // Rendered output: smooth scaling, and already premultiplied.
        _ = c.SDL_SetTextureScaleMode(texture, c.SDL_SCALEMODE_LINEAR);
        _ = c.SDL_SetTextureBlendMode(texture, c.SDL_BLENDMODE_BLEND_PREMULTIPLIED);
        if (entry.texture) |old| c.SDL_DestroyTexture(old);
        entry.* = .{ .texture = texture, .w = w, .h = h };
    }

    /// Stops showing a wrapped render target, before the target goes away.
    pub fn unwrap(self: *Images, image: abi.Image) void {
        const entry = self.get(image) orelse return;
        if (entry.texture) |t| c.SDL_DestroyTexture(t);
        entry.texture = null;
    }

    pub fn free(self: *Images, image: abi.Image) void {
        const entry = self.get(image) orelse return;
        if (entry.texture) |t| c.SDL_DestroyTexture(t);
        entry.* = .{};
    }

    pub fn size(self: *Images, image: abi.Image) [2]u32 {
        const entry = self.get(image) orelse return .{ 0, 0 };
        return .{ entry.w, entry.h };
    }

    pub fn get(self: *Images, image: abi.Image) ?*Entry {
        const index = @backingInt(image);
        if (index == 0 or index > self.entries.items.len) return null;
        return &self.entries.items[index - 1];
    }

    /// Takes ownership of `surface`, which may be null (a missing image).
    fn add(self: *Images, surface: ?*c.SDL_Surface) abi.Image {
        const s = surface orelse return self.append(.{});
        defer c.SDL_DestroySurface(s);
        const texture = c.SDL_CreateTextureFromSurface(self.renderer, s);
        if (texture) |t| setup(t);
        return self.append(.{ .texture = texture, .w = @intCast(s.*.w), .h = @intCast(s.*.h) });
    }

    fn append(self: *Images, entry: Entry) abi.Image {
        self.entries.append(self.gpa, entry) catch return .none;
        return @fromBackingInt(@intCast(self.entries.items.len));
    }

    fn setup(texture: *c.SDL_Texture) void {
        _ = c.SDL_SetTextureScaleMode(texture, c.SDL_SCALEMODE_NEAREST);
        _ = c.SDL_SetTextureBlendMode(texture, c.SDL_BLENDMODE_BLEND);
    }
};

/// Draws one graphics command. Other commands are not graphics: ignored.
pub fn draw(renderer: *c.SDL_Renderer, images: *Images, command: abi.Command) void {
    switch (command) {
        .clear => |color| {
            if (@import("builtin").os.tag == .linux) c.sk_text_begin_frame(renderer);
            setColor(renderer, color);
            _ = c.SDL_RenderClear(renderer);
        },
        .rect => |r| {
            setColor(renderer, r.color);
            _ = c.SDL_RenderFillRect(renderer, &frect(r.dst));
        },
        .image => |img| {
            const entry = images.get(img.image);
            const texture = if (entry) |e| e.texture else null;
            const t = texture orelse return missing(renderer, img.dst);
            _ = c.SDL_SetTextureColorMod(t, img.tint.r, img.tint.g, img.tint.b);
            _ = c.SDL_SetTextureAlphaMod(t, img.tint.a);
            const src = frect(img.src);
            _ = c.SDL_RenderTexture(renderer, t, if (img.src.w > 0) &src else null, &frect(img.dst));
        },
        .text => |text| drawText(renderer, text.x, text.y, text.scale, text.bytes, text.color),
        .clip => |clip| {
            if (clip) |r| {
                const rect: c.SDL_Rect = .{ .x = @intFromFloat(r.x), .y = @intFromFloat(r.y), .w = @intFromFloat(r.w), .h = @intFromFloat(r.h) };
                _ = c.SDL_SetRenderClipRect(renderer, &rect);
            } else _ = c.SDL_SetRenderClipRect(renderer, null);
        },
        .pixels => |p| {
            const entry = images.get(p.image) orelse return;
            const texture = entry.texture orelse return;
            if (p.w != entry.w or p.h != entry.h or p.rgba.len < @as(usize, p.w) * p.h * 4) return;
            _ = c.SDL_SetTextureBlendMode(texture, if (p.premultiplied) c.SDL_BLENDMODE_BLEND_PREMULTIPLIED else c.SDL_BLENDMODE_BLEND);
            _ = c.SDL_UpdateTexture(texture, null, p.rgba.ptr, @intCast(p.w * 4));
        },
        else => {},
    }
}

/// Native shaped text on Linux, using a 13px monospace face at scale 1.
/// Other targets retain SDL's built-in 8x8 fallback. Coordinates are line-box tops.
pub fn drawText(renderer: *c.SDL_Renderer, x: f32, y: f32, scale: f32, bytes: []const u8, color: abi.Color) void {
    if (@import("builtin").os.tag == .linux and c.sk_text_draw(renderer, x, y, scale, bytes.ptr, bytes.len, color.r, color.g, color.b, color.a)) return;
    var buf: [1024]u8 = undefined;
    const len = @min(std.mem.indexOfScalar(u8, bytes, 0) orelse bytes.len, buf.len - 1);
    @memcpy(buf[0..len], bytes[0..len]);
    buf[len] = 0;
    setColor(renderer, color);
    var sx: f32 = 1;
    var sy: f32 = 1;
    _ = c.SDL_GetRenderScale(renderer, &sx, &sy);
    const s = @max(scale, 1);
    // The clip rect scales with the renderer: shrink it to match, to the
    // whole pixels around it (so it may let up to `s - 1` pixels more through).
    var clip: c.SDL_Rect = undefined;
    const clipped = c.SDL_RenderClipEnabled(renderer) and c.SDL_GetRenderClipRect(renderer, &clip);
    _ = c.SDL_SetRenderScale(renderer, sx * s, sy * s);
    if (clipped and s != 1) {
        const x0 = @floor(@as(f32, @floatFromInt(clip.x)) / s);
        const y0 = @floor(@as(f32, @floatFromInt(clip.y)) / s);
        const x1 = @ceil(@as(f32, @floatFromInt(clip.x + clip.w)) / s);
        const y1 = @ceil(@as(f32, @floatFromInt(clip.y + clip.h)) / s);
        const scaled: c.SDL_Rect = .{ .x = @intFromFloat(x0), .y = @intFromFloat(y0), .w = @intFromFloat(x1 - x0), .h = @intFromFloat(y1 - y0) };
        _ = c.SDL_SetRenderClipRect(renderer, &scaled);
    }
    _ = c.SDL_RenderDebugText(renderer, x / s, y / s, &buf);
    _ = c.SDL_SetRenderScale(renderer, sx, sy);
    if (clipped and s != 1) _ = c.SDL_SetRenderClipRect(renderer, &clip);
}

fn missing(renderer: *c.SDL_Renderer, dst: abi.Rect) void {
    setColor(renderer, .{ .r = 110, .g = 30, .b = 70 });
    _ = c.SDL_RenderFillRect(renderer, &frect(dst));
    drawText(renderer, dst.x + 4, dst.y + 4, 1, "missing image", .{ .r = 255, .g = 210, .b = 240 });
}

fn setColor(renderer: *c.SDL_Renderer, color: abi.Color) void {
    _ = c.SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);
}

fn frect(r: abi.Rect) c.SDL_FRect {
    return .{ .x = r.x, .y = r.y, .w = r.w, .h = r.h };
}