summaryrefslogtreecommitdiff
path: root/src/host/gfx.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/host/gfx.zig')
-rw-r--r--src/host/gfx.zig177
1 files changed, 177 insertions, 0 deletions
diff --git a/src/host/gfx.zig b/src/host/gfx.zig
new file mode 100644
index 0000000..e00d325
--- /dev/null
+++ b/src/host/gfx.zig
@@ -0,0 +1,177 @@
+//! 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.fmt.bufPrintZ(&buf, "{s}", .{path}) 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 = @intFromEnum(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 @enumFromInt(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| {
+ 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 => {},
+ }
+}
+
+/// SDL's built-in 8x8 font, `scale` times larger. Stops at the first NUL.
+pub fn drawText(renderer: *c.SDL_Renderer, x: f32, y: f32, scale: f32, bytes: []const u8, color: abi.Color) void {
+ 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);
+ _ = c.SDL_SetRenderScale(renderer, sx * s, sy * s);
+ _ = c.SDL_RenderDebugText(renderer, x / s, y / s, &buf);
+ _ = c.SDL_SetRenderScale(renderer, sx, sy);
+}
+
+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 };
+}