summaryrefslogtreecommitdiff
path: root/src/gpu/scene.zig
blob: d5e1db597a3519cb29101c669fe29bc42f99efba (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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
//! Optional, self-contained GPU frames for embedders and remote views.
//! Version 1: "SGPU", u32 version, then Pass fields in declaration order.
//! Version 2 appends one fullscreen PostProcess sampling that pass's output.
//! Version 3 adds depth fields and an optional PostProcess after the pass.
//! Version 4 adds optional depth sampling to PostProcess.
//! Integers/enums/f32 are little endian; slices have a u32 count, optionals
//! and bools a byte (0 or 1). No pointers, native padding, or device handles.
//! Storage buffers are not part of this version: each frame stands alone.
const std = @import("std");
pub const abi = @import("abi");
pub const max_bytes = 4 << 20;
pub const Frame = struct { pass: abi.gpu.Pass, post: ?abi.gpu.PostProcess = null };

pub fn encode(w: *std.Io.Writer, pass: abi.gpu.Pass) !void {
    try validate(pass);
    try w.writeAll("SGPU");
    const version: u32 = if (pass.depth) 3 else 1;
    try w.writeInt(u32, version, .little);
    try put(w, pass, version);
    if (version == 3) try put(w, @as(?abi.gpu.PostProcess, null), version);
}

pub fn encodePostProcess(w: *std.Io.Writer, pass: abi.gpu.Pass, post: abi.gpu.PostProcess) !void {
    try validate(pass);
    try validatePostProcess(post);
    if (post.sample_depth and (!pass.depth or pass.samples != 1)) return error.BadScene;
    try w.writeAll("SGPU");
    const version: u32 = if (post.sample_depth) 4 else if (pass.depth) 3 else 2;
    try w.writeInt(u32, version, .little);
    try put(w, pass, version);
    if (version >= 3) try put(w, @as(?abi.gpu.PostProcess, post), version) else try put(w, post, version);
}

/// Allocations belong to the caller's frame arena. Never run unvalidated
/// wire data through a driver; this checks lengths, layouts and indices.
pub fn decode(arena: std.mem.Allocator, bytes: []const u8) !abi.gpu.Pass {
    const frame = try decodeFrame(arena, bytes);
    if (frame.post != null) return error.BadScene;
    return frame.pass;
}

pub fn decodeFrame(arena: std.mem.Allocator, bytes: []const u8) !Frame {
    if (bytes.len > max_bytes) return error.SceneTooLarge;
    var r: std.Io.Reader = .fixed(bytes);
    if (!std.mem.eql(u8, try r.take(4), "SGPU")) return error.BadScene;
    const version = try r.takeInt(u32, .little);
    if (version < 1 or version > 4) return error.BadScene;
    var budget: usize = max_bytes * 4;
    const pass = try get(abi.gpu.Pass, arena, &r, &budget, version);
    const post: ?abi.gpu.PostProcess = if (version >= 3) try get(?abi.gpu.PostProcess, arena, &r, &budget, version) else if (version == 2) try get(abi.gpu.PostProcess, arena, &r, &budget, version) else null;
    if (r.end != r.seek) return error.BadScene;
    try validate(pass);
    if (post) |p| {
        try validatePostProcess(p);
        if (p.sample_depth and (!pass.depth or pass.samples != 1)) return error.BadScene;
    }
    return .{ .pass = pass, .post = post };
}

fn depthField(comptime T: type, comptime name: []const u8) bool {
    return (T == abi.gpu.Pass and std.mem.eql(u8, name, "depth")) or
        (T == abi.gpu.Pipeline and (std.mem.eql(u8, name, "depth_test") or std.mem.eql(u8, name, "depth_write")));
}

fn absentField(comptime T: type, comptime name: []const u8, version: u32) bool {
    return (version < 3 and depthField(T, name)) or
        (version < 4 and T == abi.gpu.PostProcess and std.mem.eql(u8, name, "sample_depth"));
}

fn put(w: *std.Io.Writer, value: anytype, version: u32) anyerror!void {
    const T = @TypeOf(value);
    switch (@typeInfo(T)) {
        .int => try w.writeInt(T, value, .little),
        .float => try w.writeInt(u32, @bitCast(value), .little),
        .bool => try w.writeByte(@intFromBool(value)),
        .@"enum" => try w.writeInt(u32, @intCast(@backingInt(value)), .little),
        .optional => {
            try w.writeByte(@intFromBool(value != null));
            if (value) |v| try put(w, v, version);
        },
        .array => for (value) |v| try put(w, v, version),
        .pointer => {
            try w.writeInt(u32, @intCast(value.len), .little);
            for (value) |v| try put(w, v, version);
        },
        .@"struct" => |s| inline for (s.field_names) |name| {
            if (!absentField(T, name, version)) try put(w, @field(value, name), version);
        },
        else => @compileError("unsupported scene field"),
    }
}

fn get(comptime T: type, a: std.mem.Allocator, r: *std.Io.Reader, budget: *usize, version: u32) anyerror!T {
    switch (@typeInfo(T)) {
        .int => return r.takeInt(T, .little),
        .float => return @bitCast(try r.takeInt(u32, .little)),
        .bool => return switch (try r.takeByte()) {
            0 => false,
            1 => true,
            else => error.BadScene,
        },
        .@"enum" => |e| {
            const n = try r.takeInt(u32, .little);
            inline for (e.field_names, e.field_values) |name, value| if (n == value) return @field(T, name);
            return error.BadScene;
        },
        .optional => |o| return switch (try r.takeByte()) {
            0 => null,
            1 => try get(o.child, a, r, budget, version),
            else => error.BadScene,
        },
        .array => |ar| {
            var out: T = undefined;
            for (&out) |*v| v.* = try get(ar.child, a, r, budget, version);
            return out;
        },
        .pointer => |p| {
            const n = try r.takeInt(u32, .little);
            const size = std.math.mul(usize, n, @sizeOf(p.child)) catch return error.SceneTooLarge;
            if (size > budget.* or n > max_bytes) return error.SceneTooLarge;
            budget.* -= size;
            // SPIR-V must be word aligned, including after a wire decode.
            const out = try a.alignedAlloc(p.child, .fromByteUnits(@max(4, @alignOf(p.child))), n);
            for (out) |*v| v.* = try get(p.child, a, r, budget, version);
            return out;
        },
        .@"struct" => |s| {
            var out: T = undefined;
            inline for (s.field_names, s.field_types) |name, F| {
                @field(out, name) = if (absentField(T, name, version)) std.mem.zeroes(F) else try get(F, a, r, budget, version);
            }
            return out;
        },
        else => @compileError("unsupported scene field"),
    }
}

fn shader(s: abi.gpu.Shader) !void {
    if (s.code.len < 20 or s.code.len % 4 != 0 or std.mem.readInt(u32, s.code[0..4], .little) != 0x07230203 or s.uniform_buffers > 1 or s.storage_buffers != 0) return error.BadShader;
}

pub fn validatePostProcess(p: abi.gpu.PostProcess) !void {
    try shader(p.vertex);
    try shader(p.fragment);
    if (p.vertex.uniform_buffers != 0 or p.fragment_uniforms.len > 16384 or
        (p.fragment_uniforms.len > 0) != (p.fragment.uniform_buffers == 1)) return error.BadScene;
}

pub fn validate(p: abi.gpu.Pass) !void {
    if (p.image != .none or p.width == 0 or p.height == 0 or p.width > 4096 or p.height > 4096 or p.pipelines.len > 64 or p.draws.len > 4096 or (p.samples != 1 and p.samples != 2 and p.samples != 4 and p.samples != 8)) return error.BadScene;
    // Self-contained frames must not depend on an earlier view's contents.
    const clear = p.clear orelse return error.BadScene;
    for (clear) |v| if (!std.math.isFinite(v)) return error.BadScene;
    for (p.pipelines) |pipe| {
        if ((pipe.depth_test != null or pipe.depth_write) and !p.depth) return error.BadScene;
        try shader(pipe.vertex);
        try shader(pipe.fragment);
        if (pipe.attributes.len > 16 or pipe.stride > 4096) return error.BadScene;
        var locations: u32 = 0;
        for (pipe.attributes) |attr| {
            const size: u32 = switch (attr.format) {
                .float, .ubyte4_norm => 4,
                .float2 => 8,
                .float3 => 12,
                .float4 => 16,
            };
            if (attr.location >= 16 or attr.offset > pipe.stride or size > pipe.stride - attr.offset) return error.BadScene;
            const bit = @as(u32, 1) << @intCast(attr.location);
            if (locations & bit != 0) return error.BadScene;
            locations |= bit;
        }
    }
    var total: usize = 0;
    for (p.draws) |d| {
        if (d.pipeline >= p.pipelines.len or d.vertex_count > 1 << 20 or d.vertex_storage.len != 0 or d.fragment_storage.len != 0) return error.BadScene;
        const pipe = p.pipelines[d.pipeline];
        if (pipe.attributes.len != 0 and @as(u64, pipe.stride) * d.vertex_count > d.vertices.len) return error.BadScene;
        if (d.vertex_uniforms.len > 16384 or d.fragment_uniforms.len > 16384 or (d.vertex_uniforms.len > 0) != (pipe.vertex.uniform_buffers == 1) or (d.fragment_uniforms.len > 0) != (pipe.fragment.uniform_buffers == 1)) return error.BadScene;
        total += d.vertices.len;
        if (total > max_bytes) return error.SceneTooLarge;
        if (d.scissor) |r| inline for (.{ r.x, r.y, r.w, r.h }) |v| if (!std.math.isFinite(v) or v < 0 or v > 4096) return error.BadScene;
    }
}

test "GPU scene roundtrip, truncated and oversized inputs are refused" {
    const shader_bytes = std.mem.asBytes(&[_]u32{ 0x07230203, 0, 0, 0, 0 });
    const pipelines = [_]abi.gpu.Pipeline{.{ .vertex = .{ .code = shader_bytes }, .fragment = .{ .code = shader_bytes }, .stride = 0, .attributes = &.{} }};
    const pass: abi.gpu.Pass = .{ .image = .none, .width = 32, .height = 24, .pipelines = &pipelines, .draws = &.{.{ .pipeline = 0, .vertex_count = 3 }} };
    var out: std.Io.Writer.Allocating = .init(std.testing.allocator);
    defer out.deinit();
    try encode(&out.writer, pass);
    var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
    defer arena.deinit();
    const decoded = try decode(arena.allocator(), out.written());
    try std.testing.expectEqual(32, decoded.width);
    try std.testing.expectEqual(3, decoded.draws[0].vertex_count);
    for (0..out.written().len) |i| {
        _ = decode(arena.allocator(), out.written()[0..i]) catch continue;
        return error.AcceptedTruncatedScene;
    }
    var bad = pass;
    bad.width = 4097;
    try std.testing.expectError(error.BadScene, validate(bad));
    var draw = pass.draws[0];
    draw.pipeline = 1;
    bad = pass;
    bad.draws = &.{draw};
    try std.testing.expectError(error.BadScene, validate(bad));
}

test "GPU postprocess keeps v1 readable and validates the complete second pass" {
    const code = std.mem.asBytes(&[_]u32{ 0x07230203, 0, 0, 0, 0 });
    const pipelines = [_]abi.gpu.Pipeline{.{ .vertex = .{ .code = code }, .fragment = .{ .code = code }, .stride = 0, .attributes = &.{} }};
    const pass: abi.gpu.Pass = .{ .image = .none, .width = 32, .height = 24, .pipelines = &pipelines, .draws = &.{.{ .pipeline = 0, .vertex_count = 3 }} };
    const post: abi.gpu.PostProcess = .{ .vertex = .{ .code = code }, .fragment = .{ .code = code } };
    var out: std.Io.Writer.Allocating = .init(std.testing.allocator);
    defer out.deinit();
    var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
    defer arena.deinit();
    try encode(&out.writer, pass);
    try std.testing.expect((try decodeFrame(arena.allocator(), out.written())).post == null);
    out.clearRetainingCapacity();
    try encodePostProcess(&out.writer, pass, post);
    const frame = try decodeFrame(arena.allocator(), out.written());
    try std.testing.expectEqual(32, frame.pass.width);
    try std.testing.expectEqualSlices(u8, code, frame.post.?.fragment.code);
    for (0..out.written().len) |i| {
        _ = decodeFrame(arena.allocator(), out.written()[0..i]) catch continue;
        return error.AcceptedTruncatedScene;
    }
    var bad = post;
    bad.vertex.uniform_buffers = 1;
    try std.testing.expectError(error.BadScene, validatePostProcess(bad));
    bad = post;
    bad.fragment.uniform_buffers = 1;
    try std.testing.expectError(error.BadScene, validatePostProcess(bad));
    bad = post;
    bad.fragment.storage_buffers = 1;
    try std.testing.expectError(error.BadShader, validatePostProcess(bad));
    out.written()[4] = 5;
    try std.testing.expectError(error.BadScene, decodeFrame(arena.allocator(), out.written()));
}

test "depth uses v3 and requires an attachment; legacy frames keep depth disabled" {
    const code = std.mem.asBytes(&[_]u32{ 0x07230203, 0, 0, 0, 0 });
    var pipelines = [_]abi.gpu.Pipeline{.{ .vertex = .{ .code = code }, .fragment = .{ .code = code }, .stride = 0, .attributes = &.{}, .depth_test = .less, .depth_write = true }};
    var pass: abi.gpu.Pass = .{ .image = .none, .width = 32, .height = 24, .pipelines = &pipelines, .draws = &.{.{ .pipeline = 0, .vertex_count = 3 }} };
    try std.testing.expectError(error.BadScene, validate(pass));
    pass.depth = true;
    var out: std.Io.Writer.Allocating = .init(std.testing.allocator);
    defer out.deinit();
    var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
    defer arena.deinit();
    try encode(&out.writer, pass);
    try std.testing.expectEqual(3, out.written()[4]);
    const decoded = try decode(arena.allocator(), out.written());
    try std.testing.expect(decoded.depth);
    try std.testing.expectEqual(abi.gpu.Compare.less, decoded.pipelines[0].depth_test.?);
    try std.testing.expect(decoded.pipelines[0].depth_write);
    const post: abi.gpu.PostProcess = .{ .vertex = .{ .code = code }, .fragment = .{ .code = code } };
    out.clearRetainingCapacity();
    try encodePostProcess(&out.writer, pass, post);
    const frame = try decodeFrame(arena.allocator(), out.written());
    try std.testing.expect(frame.post != null and frame.pass.depth);
    pass.depth = false;
    pipelines[0].depth_test = null;
    pipelines[0].depth_write = false;
    out.clearRetainingCapacity();
    try encode(&out.writer, pass);
    try std.testing.expectEqual(1, out.written()[4]);
    const legacy = try decode(arena.allocator(), out.written());
    try std.testing.expect(!legacy.depth and legacy.pipelines[0].depth_test == null and !legacy.pipelines[0].depth_write);
}

test "depth postprocess uses v4 and rejects missing or multisampled source depth" {
    const code = std.mem.asBytes(&[_]u32{ 0x07230203, 0, 0, 0, 0 });
    const pipelines = [_]abi.gpu.Pipeline{.{ .vertex = .{ .code = code }, .fragment = .{ .code = code }, .stride = 0, .attributes = &.{} }};
    var pass: abi.gpu.Pass = .{ .image = .none, .width = 32, .height = 24, .depth = true, .pipelines = &pipelines, .draws = &.{.{ .pipeline = 0, .vertex_count = 3 }} };
    var post: abi.gpu.PostProcess = .{ .sample_depth = true, .vertex = .{ .code = code }, .fragment = .{ .code = code } };
    var out: std.Io.Writer.Allocating = .init(std.testing.allocator);
    defer out.deinit();
    var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
    defer arena.deinit();
    try encodePostProcess(&out.writer, pass, post);
    try std.testing.expectEqual(4, out.written()[4]);
    try std.testing.expect((try decodeFrame(arena.allocator(), out.written())).post.?.sample_depth);
    for (0..out.written().len) |i| {
        _ = decodeFrame(arena.allocator(), out.written()[0..i]) catch continue;
        return error.AcceptedTruncatedScene;
    }
    pass.depth = false;
    try std.testing.expectError(error.BadScene, encodePostProcess(&out.writer, pass, post));
    pass.depth = true;
    pass.samples = 4;
    try std.testing.expectError(error.BadScene, encodePostProcess(&out.writer, pass, post));
    pass.samples = 1;
    post.sample_depth = false;
    out.clearRetainingCapacity();
    try encodePostProcess(&out.writer, pass, post);
    try std.testing.expectEqual(3, out.written()[4]);
    try std.testing.expect(!(try decodeFrame(arena.allocator(), out.written())).post.?.sample_depth);
}