summaryrefslogtreecommitdiff
path: root/src/gltf.zig
blob: 2d4ca476853bf8fb3cb8233e4673681c1ffc6918 (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
//! glTF/GLB documents backed by cgltf. Native/libc module; no renderer required.
//! The input bytes must outlive Document: GLB buffers can point into them.
//! C allocations are released by deinit; raw cgltf data stays available in `data`.
const std = @import("std");
pub const c = @import("cgltf_c");
pub const scene = @import("gltf_scene.zig");
pub const Scene = scene.Scene;
/// Build-time code generation, not comptime glTF parsing.
pub const generate = @import("gltf_generate.zig").generate;

test {
    _ = @import("gltf_generate.zig");
    _ = scene;
}

pub const Error = error{
    DataTooShort,
    UnknownFormat,
    InvalidJson,
    InvalidGltf,
    InvalidOptions,
    FileNotFound,
    IoError,
    OutOfMemory,
    LegacyGltf,
    InvalidAccessor,
    MissingBuffer,
};

fn check(result: c.cgltf_result) Error!void {
    return switch (result) {
        c.cgltf_result_success => {},
        c.cgltf_result_data_too_short => error.DataTooShort,
        c.cgltf_result_unknown_format => error.UnknownFormat,
        c.cgltf_result_invalid_json => error.InvalidJson,
        c.cgltf_result_invalid_gltf => error.InvalidGltf,
        c.cgltf_result_invalid_options => error.InvalidOptions,
        c.cgltf_result_file_not_found => error.FileNotFound,
        c.cgltf_result_io_error => error.IoError,
        c.cgltf_result_out_of_memory => error.OutOfMemory,
        c.cgltf_result_legacy_gltf => error.LegacyGltf,
        else => error.InvalidGltf,
    };
}

pub const Document = struct {
    data: *c.cgltf_data,

    /// Parses and validates structure. Does not perform filesystem I/O.
    pub fn parse(bytes: []const u8) Error!Document {
        const options = std.mem.zeroes(c.cgltf_options);
        var data: ?*c.cgltf_data = null;
        try check(c.cgltf_parse(&options, bytes.ptr, bytes.len, &data));
        const doc: Document = .{ .data = data.? };
        errdefer doc.deinit();
        try check(c.cgltf_validate(doc.data));
        return doc;
    }

    pub fn deinit(self: Document) void {
        c.cgltf_free(self.data);
    }

    /// Binds GLB/data-URI buffers. A non-null source path also permits external
    /// buffer files, resolved relative to that glTF file; only pass trusted paths.
    /// Images and compressed geometry are not decoded by this module.
    pub fn loadBuffers(self: Document, source_path: ?[:0]const u8) Error!void {
        const options = std.mem.zeroes(c.cgltf_options);
        try check(c.cgltf_load_buffers(&options, self.data, if (source_path) |p| p.ptr else null));
        try check(c.cgltf_validate(self.data));
    }

    pub fn nodes(self: Document) []c.cgltf_node {
        return if (self.data.nodes_count == 0) &.{} else self.data.nodes[0..self.data.nodes_count];
    }

    pub fn findNode(self: Document, name: []const u8) ?*c.cgltf_node {
        for (self.nodes()) |*node| {
            if (node.name != null and std.mem.eql(u8, std.mem.span(node.name), name)) return node;
        }
        return null;
    }
};

/// Borrowed JSON, ready for std.json.parseFromSlice with the caller's schema.
pub fn extrasJson(extras: *const c.cgltf_extras) ?[]const u8 {
    return if (extras.data != null) std.mem.span(extras.data) else null;
}

/// Read one element after loadBuffers; handles strides, normalization and sparse
/// accessors. Bounds and component count are checked before entering C.
pub fn readFloats(accessor: [*c]const c.cgltf_accessor, index: usize, out: []f32) Error!void {
    if (accessor == null or index >= accessor.*.count or out.len == 0 or out.len != c.cgltf_num_components(accessor.*.type)) return error.InvalidAccessor;
    if (accessor.*.is_sparse != 0 and
        (c.cgltf_buffer_view_data(accessor.*.sparse.indices_buffer_view) == null or
            c.cgltf_buffer_view_data(accessor.*.sparse.values_buffer_view) == null)) return error.MissingBuffer;
    if (c.cgltf_accessor_read_float(accessor, index, out.ptr, out.len) == 0) return error.MissingBuffer;
}

test "node names and arbitrary typed extras survive parsing" {
    const bytes =
        \\{"asset":{"version":"2.0"},"nodes":[{"name":"Target","extras":{"role":"look_at_target","id":"target","future":1}}]}
    ;
    const doc = try Document.parse(bytes);
    defer doc.deinit();
    try doc.loadBuffers(null);
    const node = doc.findNode("Target").?;
    const meta = try std.json.parseFromSlice(struct { role: []const u8, id: []const u8 }, std.testing.allocator, extrasJson(&node.extras).?, .{ .ignore_unknown_fields = true });
    defer meta.deinit();
    try std.testing.expectEqualStrings("look_at_target", meta.value.role);
    try std.testing.expectEqualStrings("target", meta.value.id);
    try std.testing.expect(doc.findNode("missing") == null);
    try std.testing.expect(extrasJson(&std.mem.zeroes(c.cgltf_extras)) == null);
}

test "embedded buffers and accessor bounds" {
    const bytes =
        \\{"asset":{"version":"2.0"},"buffers":[{"byteLength":4,"uri":"data:application/octet-stream;base64,AACAPw=="}],"bufferViews":[{"buffer":0,"byteLength":4}],"accessors":[{"bufferView":0,"componentType":5126,"count":1,"type":"SCALAR"}]}
    ;
    const doc = try Document.parse(bytes);
    defer doc.deinit();
    const accessor = &doc.data.accessors[0];
    var value: [1]f32 = undefined;
    try std.testing.expectError(error.MissingBuffer, readFloats(accessor, 0, &value));
    try doc.loadBuffers(null);
    try readFloats(accessor, 0, &value);
    try std.testing.expectEqual(@as(f32, 1), value[0]);
    try std.testing.expectError(error.InvalidAccessor, readFloats(accessor, 1, &value));
    var wrong: [3]f32 = undefined;
    try std.testing.expectError(error.InvalidAccessor, readFloats(accessor, 0, &wrong));
}

test "malformed and truncated input fails" {
    try std.testing.expectError(error.DataTooShort, Document.parse("glTF"));
    try std.testing.expectError(error.InvalidJson, Document.parse("{\"asset\": invalid json}"));
    const invalid =
        \\{"asset":{"version":"2.0"},"buffers":[{"byteLength":4}],"bufferViews":[{"buffer":0,"byteLength":16}],"accessors":[{"bufferView":0,"componentType":5126,"count":4,"type":"SCALAR"}]}
    ;
    try std.testing.expectError(error.DataTooShort, Document.parse(invalid));
}

test "sparse values need loaded buffers and preserve zero base elements" {
    const bytes =
        \\{"asset":{"version":"2.0"},"buffers":[{"byteLength":16,"uri":"data:application/octet-stream;base64,AQAAAAAAgD8AAABAAABAQA=="}],"bufferViews":[{"buffer":0,"byteLength":1},{"buffer":0,"byteOffset":4,"byteLength":12}],"accessors":[{"componentType":5126,"count":2,"type":"VEC3","sparse":{"count":1,"indices":{"bufferView":0,"componentType":5121},"values":{"bufferView":1}}}]}
    ;
    const doc = try Document.parse(bytes);
    defer doc.deinit();
    const accessor = &doc.data.accessors[0];
    var out: [3]f32 = undefined;
    try std.testing.expectError(error.MissingBuffer, readFloats(accessor, 1, &out));
    try doc.loadBuffers(null);
    try readFloats(accessor, 0, &out);
    try std.testing.expectEqualSlices(f32, &.{ 0, 0, 0 }, &out);
    try readFloats(accessor, 1, &out);
    try std.testing.expectEqualSlices(f32, &.{ 1, 2, 3 }, &out);
}