summaryrefslogtreecommitdiff
path: root/src/gltf_generate.zig
blob: a1d1449cf37ecc89eb24c6a4dc9ff3a17d35ba56 (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
//! Runs before compilation: glTF labels/extras become ordinary Zig constants.
const std = @import("std");
const gltf = @import("gltf.zig");

pub fn generate(allocator: std.mem.Allocator, bytes: []const u8, source_path: []const u8) ![]u8 {
    const doc = try gltf.Document.parse(bytes);
    defer doc.deinit();
    var out: std.ArrayList(u8) = .empty;
    defer out.deinit(allocator);
    try out.appendSlice(allocator, "// Generated from glTF; do not edit.\n");
    try out.print(allocator, "pub const source_path: []const u8 = \"{f}\";\n", .{std.zig.fmtString(source_path)});
    var hash: [32]u8 = undefined;
    std.crypto.hash.sha2.Sha256.hash(bytes, &hash, .{});
    try out.appendSlice(allocator, "pub const source_sha256: [32]u8 = .{");
    for (hash) |byte| try out.print(allocator, "{d},", .{byte});
    try out.appendSlice(allocator, "};\n");
    try labels(allocator, &out, "nodes", doc.nodes(), doc.data);
    try labels(allocator, &out, "animations", if (doc.data.animations_count == 0) &.{} else doc.data.animations[0..doc.data.animations_count], doc.data);
    try labels(allocator, &out, "cameras", if (doc.data.cameras_count == 0) &.{} else doc.data.cameras[0..doc.data.cameras_count], doc.data);
    try labels(allocator, &out, "meshes", if (doc.data.meshes_count == 0) &.{} else doc.data.meshes[0..doc.data.meshes_count], doc.data);
    try labels(allocator, &out, "materials", if (doc.data.materials_count == 0) &.{} else doc.data.materials[0..doc.data.materials_count], doc.data);
    const source = try allocator.allocSentinel(u8, out.items.len, 0);
    defer allocator.free(source);
    @memcpy(source, out.items);
    var ast = try std.zig.Ast.parse(allocator, source, .{});
    defer ast.deinit(allocator);
    if (ast.errors.len != 0) return error.InvalidGeneratedZig;
    return ast.renderAlloc(allocator);
}

fn labels(a: std.mem.Allocator, out: *std.ArrayList(u8), category: []const u8, items: anytype, data: *const gltf.c.cgltf_data) !void {
    var names: std.StringHashMapUnmanaged(void) = .empty;
    defer names.deinit(a);
    try out.print(a, "pub const {s} = struct {{\n", .{category});
    for (items, 0..) |item, index| {
        if (item.name == null) continue;
        const name = item.name[0..gltf.c.cgltf_decode_string(item.name)];
        if (name.len == 0) continue;
        const entry = try names.getOrPut(a, name);
        if (entry.found_existing) return error.DuplicateLabel;
        try out.print(a, "pub const {f} = .{{ .index = @as(usize, {d}), .extras = ", .{ std.zig.fmtId(name), index });
        if (gltf.extrasJson(&item.extras)) |json| {
            const parsed = try std.json.parseFromSlice(std.json.Value, a, json, .{});
            defer parsed.deinit();
            try value(a, out, parsed.value);
        } else try out.appendSlice(a, ".{}");
        if (@TypeOf(item) == gltf.c.cgltf_node) {
            try out.appendSlice(a, ", .camera = @as(?usize, ");
            if (item.camera != null) {
                try out.print(a, "{d}", .{gltf.c.cgltf_camera_index(data, item.camera)});
            } else try out.appendSlice(a, "null");
            try out.appendSlice(a, "), .mesh = @as(?usize, ");
            if (item.mesh != null) {
                try out.print(a, "{d}", .{gltf.c.cgltf_mesh_index(data, item.mesh)});
            } else try out.appendSlice(a, "null");
            try out.appendSlice(a, ")");
        }
        try out.appendSlice(a, " };\n");
    }
    try out.appendSlice(a, "};\n");
}

fn value(a: std.mem.Allocator, out: *std.ArrayList(u8), json: std.json.Value) std.mem.Allocator.Error!void {
    switch (json) {
        .null => try out.appendSlice(a, "null"),
        .bool => |v| try out.appendSlice(a, if (v) "true" else "false"),
        .integer => |v| try out.print(a, "@as(i64, {d})", .{v}),
        .float => |v| try out.print(a, "@as(f64, {e})", .{v}),
        .number_string => |v| try out.appendSlice(a, v),
        .string => |v| try out.print(a, "@as([]const u8, \"{f}\")", .{std.zig.fmtString(v)}),
        .array => |array| {
            try out.appendSlice(a, ".{");
            for (array.items) |item| {
                try value(a, out, item);
                try out.appendSlice(a, ",");
            }
            try out.appendSlice(a, "}");
        },
        .object => |object| {
            try out.appendSlice(a, ".{");
            for (object.keys(), object.values()) |key, item| {
                try out.print(a, ".{f} = ", .{std.zig.fmtId(key)});
                try value(a, out, item);
                try out.appendSlice(a, ",");
            }
            try out.appendSlice(a, "}");
        },
    }
}

test "generated labels and nested metadata escape as valid Zig" {
    const source = try generate(std.testing.allocator,
        \\{"asset":{"version":"2.0"},"nodes":[{"name":"a\"b","extras":{"type":"look\nat","nested":{"enabled":true},"points":[1,2.5,-0.0,null]}},{"name":"while"},{"extras":{}}],"animations":[]}
    , "fixtures/a\"b.glb");
    defer std.testing.allocator.free(source);
    const terminated = try std.testing.allocator.allocSentinel(u8, source.len, 0);
    @memcpy(terminated, source);
    defer std.testing.allocator.free(terminated);
    var ast = try std.zig.Ast.parse(std.testing.allocator, terminated, .{});
    defer ast.deinit(std.testing.allocator);
    try std.testing.expectEqual(@as(usize, 0), ast.errors.len);
    try std.testing.expect(std.mem.indexOf(u8, source, "pub const source_path: []const u8 = \"fixtures/a\\\"b.glb\";") != null);
    try std.testing.expect(std.mem.indexOf(u8, source, "pub const @\"a\\\"b\"") != null);
    try std.testing.expect(std.mem.indexOf(u8, source, "pub const @\"while\"") != null);
    try std.testing.expect(std.mem.indexOf(u8, source, ".index = @as(usize, 1)") != null);
}

test "duplicate labels cannot silently choose an object" {
    try std.testing.expectError(error.DuplicateLabel, generate(std.testing.allocator,
        \\{"asset":{"version":"2.0"},"nodes":[{"name":"Camera"},{"name":"Camera"}]}
    , "fixtures/duplicate.glb"));
}