summaryrefslogtreecommitdiff
path: root/src/glsl.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/glsl.zig')
-rw-r--r--src/glsl.zig158
1 files changed, 158 insertions, 0 deletions
diff --git a/src/glsl.zig b/src/glsl.zig
new file mode 100644
index 0000000..995985b
--- /dev/null
+++ b/src/glsl.zig
@@ -0,0 +1,158 @@
+//! GLSL declarations from Zig structs, so shaders and the code that feeds
+//! them share one definition: the Zig one. `Sketchbook.addGlslLayouts` builds a
+//! small generator around this file for the types it is given; each type
+//! says how it appears in GLSL with a `glsl` tag:
+//!
+//! pub const Viewport = extern struct {
+//! size: [2]f32,
+//! pad: [2]f32 = .{ 0, 0 },
+//! pub const glsl = .{ .uniform = .{ .set = 1, .instance = "viewport" } };
+//! };
+//!
+//! becomes `Viewport.glsl`:
+//!
+//! layout(set = 1, binding = 0, std140) uniform Viewport {
+//! vec2 size;
+//! vec2 pad;
+//! } viewport;
+//!
+//! Tags: `.vertex` (one `layout(location = N) in` per field, in the order
+//! `abi.gpu.attributes` uses), `.{ .uniform = .{ .set, .binding = 0,
+//! .instance } }` (SDL_GPU's SPIR-V sets: 1 vertex, 3 fragment), `.plain`
+//! (a `struct`, for nesting).
+const std = @import("std");
+
+/// `T`'s declaration, as GLSL source.
+pub fn source(comptime T: type, comptime name: []const u8) []const u8 {
+ comptime {
+ @setEvalBranchQuota(100_000);
+ const tag = T.glsl;
+ const fields = @typeInfo(T).@"struct".fields;
+ var out: []const u8 = "// Generated from the Zig struct " ++ @typeName(T) ++ "; do not edit.\n";
+ if (@TypeOf(tag) == @TypeOf(.enum_literal) and tag == .vertex) {
+ for (fields, 0..) |f, i| out = out ++ std.fmt.comptimePrint("layout(location = {d}) in {s} {s};\n", .{ i, typeName(f.type, .vertex), f.name });
+ } else if (@TypeOf(tag) == @TypeOf(.enum_literal) and tag == .plain) {
+ out = out ++ "struct " ++ name ++ " {\n" ++ members(T) ++ "};\n";
+ } else if (@hasField(@TypeOf(tag), "uniform")) {
+ const u = tag.uniform;
+ assertStd140(T);
+ const binding = if (@hasField(@TypeOf(u), "binding")) u.binding else 0;
+ out = out ++ std.fmt.comptimePrint("layout(set = {d}, binding = {d}, std140) uniform {s} {{\n", .{ u.set, binding, name }) ++ members(T) ++ "} " ++ u.instance ++ ";\n";
+ } else @compileError(@typeName(T) ++ ".glsl must be .vertex, .plain or .{ .uniform = ... }");
+ return out;
+ }
+}
+
+fn members(comptime T: type) []const u8 {
+ comptime {
+ var out: []const u8 = "";
+ for (@typeInfo(T).@"struct".fields) |f| {
+ const array_of_composites = switch (@typeInfo(f.type)) {
+ .array => |a| @typeInfo(a.child) == .array or @typeInfo(a.child) == .@"struct",
+ else => false,
+ };
+ out = out ++ if (array_of_composites)
+ std.fmt.comptimePrint(" {s} {s}[{d}];\n", .{ typeName(@typeInfo(f.type).array.child, .uniform), f.name, @typeInfo(f.type).array.len })
+ else
+ std.fmt.comptimePrint(" {s} {s};\n", .{ typeName(f.type, .uniform), f.name });
+ }
+ return out;
+ }
+}
+
+fn typeName(comptime T: type, comptime use: enum { vertex, uniform }) []const u8 {
+ if (T == f32) return "float";
+ if (T == u32) return "uint";
+ if (T == i32) return "int";
+ if (use == .vertex and (T == [4]u8 or T == @Vector(4, u8))) return "vec4";
+ return switch (@typeInfo(T)) {
+ .array => |a| vector(a.len, a.child),
+ .vector => |v| vector(v.len, v.child),
+ .@"struct" => @typeName(T)[if (std.mem.lastIndexOfScalar(u8, @typeName(T), '.')) |dot| dot + 1 else 0..],
+ else => @compileError("no GLSL type for " ++ @typeName(T)),
+ };
+}
+
+fn vector(comptime len: usize, comptime child: type) []const u8 {
+ const prefix = if (child == f32) "" else if (child == u32) "u" else if (child == i32) "i" else @compileError("no GLSL vector of " ++ @typeName(child));
+ return std.fmt.comptimePrint("{s}vec{d}", .{ prefix, len });
+}
+
+/// The type at `path` (dot-separated declarations) inside `root`.
+pub fn resolve(comptime root: type, comptime path: []const u8) type {
+ comptime {
+ var t = root;
+ var it = std.mem.tokenizeScalar(u8, path, '.');
+ while (it.next()) |name| t = @field(t, name);
+ return t;
+ }
+}
+
+/// Writes `<Name>.glsl` for each type path into `dir`.
+pub fn generate(comptime root: type, comptime paths: []const []const u8, io: std.Io, dir: std.Io.Dir) !void {
+ inline for (paths) |path| {
+ const T = resolve(root, path);
+ const name = comptime path[if (std.mem.lastIndexOfScalar(u8, path, '.')) |dot| dot + 1 else 0..];
+ try dir.writeFile(io, .{ .sub_path = name ++ ".glsl", .data = comptime source(T, name) });
+ }
+}
+
+/// Fails to compile unless `U` lays out exactly as a std140 uniform block
+/// with the same members in GLSL: scalars at 4 bytes, `vec2` at 8,
+/// `vec3`/`vec4` at 16, arrays and nested structs at 16 with 16-byte strides.
+pub fn assertStd140(comptime U: type) void {
+ comptime {
+ if (@typeInfo(U).@"struct".layout != .@"extern") @compileError(@typeName(U) ++ " must be extern to be a uniform block");
+ for (@typeInfo(U).@"struct".fields) |f| {
+ const want = std140Align(f.type);
+ if (@offsetOf(U, f.name) % want != 0) @compileError(std.fmt.comptimePrint("{s}.{s} sits at {d}; std140 wants a multiple of {d}", .{ @typeName(U), f.name, @offsetOf(U, f.name), want }));
+ }
+ if (@sizeOf(U) % 16 != 0) @compileError(@typeName(U) ++ " must be a multiple of 16 bytes");
+ }
+}
+
+fn std140Align(comptime T: type) usize {
+ return switch (@typeInfo(T)) {
+ .float, .int => 4,
+ .bool => @compileError("GLSL bools are 4 bytes: use u32"),
+ .vector => |v| if (v.len == 2) 8 else 16,
+ .array => |a| blk: {
+ if (@typeInfo(a.child) == .float or @typeInfo(a.child) == .int) {
+ // `[2]f32` stands for a vec2, `[3]`/`[4]f32` for vec3/vec4.
+ if (a.len == 2) break :blk 8;
+ if (a.len == 3 or a.len == 4) break :blk 16;
+ @compileError("std140 arrays of scalars have a 16-byte stride: use [N][4]f32");
+ }
+ if (@sizeOf(a.child) % 16 != 0) @compileError("std140 array elements are 16-byte strided");
+ break :blk 16;
+ },
+ .@"struct" => blk: {
+ assertStd140(T);
+ break :blk 16;
+ },
+ else => @compileError("no std140 layout for " ++ @typeName(T)),
+ };
+}
+
+test "uniform blocks and vertex inputs from structs" {
+ const Root = struct {
+ pub const Paint = extern struct {
+ color: [4]f32,
+ size: [2]f32,
+ pad: [2]f32,
+ stops: [4][4]f32,
+ pub const glsl = .{ .uniform = .{ .set = 3, .instance = "paint" } };
+ };
+ pub const Vertex = extern struct {
+ position: [2]f32,
+ tint: [4]u8,
+ pub const glsl = .vertex;
+ };
+ };
+ const paint = comptime source(resolve(Root, "Paint"), "Paint");
+ try std.testing.expect(std.mem.indexOf(u8, paint, "layout(set = 3, binding = 0, std140) uniform Paint {") != null);
+ try std.testing.expect(std.mem.indexOf(u8, paint, " vec4 stops[4];") != null);
+ try std.testing.expect(std.mem.indexOf(u8, paint, "} paint;") != null);
+ const vertex = comptime source(Root.Vertex, "Vertex");
+ try std.testing.expect(std.mem.indexOf(u8, vertex, "layout(location = 1) in vec4 tint;") != null);
+}