summaryrefslogtreecommitdiff
path: root/src/gltf.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-16 18:04:21 -0300
committerGabriel Schneider <[email protected]>2026-11-16 18:04:21 -0300
commite77b01d4b5504cea08a3f88cf8502897d868a1d3 (patch)
treec8e643d234dd26d920cbc563bfa7f740febf1fc7 /src/gltf.zig
parentd3074636fff0fbcd5fd9b71c0c3b1c1f5c0c1285 (diff)
downloadsketchbook-e77b01d4b5504cea08a3f88cf8502897d868a1d3.tar.gz
sketchbook-e77b01d4b5504cea08a3f88cf8502897d868a1d3.zip
Add glTF scene rendering, resource setup and 9P controls
Diffstat (limited to 'src/gltf.zig')
-rw-r--r--src/gltf.zig156
1 files changed, 156 insertions, 0 deletions
diff --git a/src/gltf.zig b/src/gltf.zig
new file mode 100644
index 0000000..2d4ca47
--- /dev/null
+++ b/src/gltf.zig
@@ -0,0 +1,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);
+}