diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-16 18:04:21 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-16 18:04:21 -0300 |
| commit | e77b01d4b5504cea08a3f88cf8502897d868a1d3 (patch) | |
| tree | c8e643d234dd26d920cbc563bfa7f740febf1fc7 /src/gltf_render/root.zig | |
| parent | d3074636fff0fbcd5fd9b71c0c3b1c1f5c0c1285 (diff) | |
| download | sketchbook-e77b01d4b5504cea08a3f88cf8502897d868a1d3.tar.gz sketchbook-e77b01d4b5504cea08a3f88cf8502897d868a1d3.zip | |
Add glTF scene rendering, resource setup and 9P controls
Diffstat (limited to 'src/gltf_render/root.zig')
| -rw-r--r-- | src/gltf_render/root.zig | 164 |
1 files changed, 164 insertions, 0 deletions
diff --git a/src/gltf_render/root.zig b/src/gltf_render/root.zig new file mode 100644 index 0000000..6bf8673 --- /dev/null +++ b/src/gltf_render/root.zig @@ -0,0 +1,164 @@ +//! Basic opaque glTF drawing. Geometry uploads once; each frame submits transforms. +//! shortcut: base colors only; add texture/alpha handling when the assets need it. +const std = @import("std"); +const sk = @import("sketch"); +const gltf = @import("gltf"); +const shaders = @import("shaders"); +const types = @import("types"); +pub const math = @import("math.zig"); +pub const Camera = math.Camera; +pub const Vertex = types.Vertex; +pub const supported = true; +const gpu = sk.abi.gpu; + +/// Camera projection plus the sampled node transform; no Blender constraint solver. +pub fn sceneCamera(scene: *const gltf.Scene, node_index: usize) !Camera { + if (node_index >= scene.nodes.len) return error.InvalidCameraNode; + const node = scene.nodes[node_index]; + const index = node.camera orelse return error.NodeHasNoCamera; + const m = node.world; + var camera: Camera = .{ + .eye = .{ m[12], m[13], m[14] }, + .target = .{ m[12] - m[8], m[13] - m[9], m[14] - m[10] }, + .up = .{ m[4], m[5], m[6] }, + }; + switch (scene.cameras[index]) { + .perspective => |p| { + camera.fov = p.yfov; + camera.near = p.znear; + camera.far = p.zfar orelse std.math.inf(f32); + camera.aspect_ratio = p.aspect_ratio; + }, + .orthographic => |o| { + camera.orthographic = .{ .xmag = o.xmag, .ymag = o.ymag }; + camera.near = o.znear; + camera.far = o.zfar; + }, + } + return camera; +} + +pub const Geometry = struct { + vertices: []const Vertex, + buffer: sk.abi.Buffer = .none, + pub fn upload(g: *Geometry, host: sk.Host) !void { + if (g.buffer != .none) return; + const bytes = std.mem.sliceAsBytes(g.vertices); + if (bytes.len == 0 or bytes.len > std.math.maxInt(u32)) return error.InvalidGeometrySize; + g.buffer = host.newBuffer(@intCast(bytes.len)); + if (g.buffer == .none) return error.GpuBufferCreationFailed; + errdefer g.release(host); + try host.writeBuffer(g.buffer, 0, bytes); + } + pub fn release(g: *Geometry, host: sk.Host) void { + if (g.buffer != .none) host.freeBuffer(g.buffer); + g.buffer = .none; + } +}; + +pub const Model = struct { + scene: gltf.Scene, + geometry: []Geometry, + /// Read the generated asset filename, validate its binding hash, and upload once. + pub fn load(setup: *sk.Init, comptime asset: type) !Model { + const bytes = setup.host.readFile(asset.source_path); + var hash: [32]u8 = undefined; + std.crypto.hash.sha2.Sha256.hash(bytes, &hash, .{}); + if (!std.mem.eql(u8, &hash, &asset.source_sha256)) return error.SceneChangedRebuildBindings; + var model = try Model.init(setup.session, bytes); + errdefer model.release(setup.host); + for (model.geometry) |*g| try g.upload(setup.host); + return model; + } + /// Allocate in the sketch's Session arena; GPU handles share its host lifetime. + pub fn init(arena: std.mem.Allocator, bytes: []const u8) !Model { + const doc = try gltf.Document.parse(bytes); + defer doc.deinit(); + try doc.loadBuffers(null); + var scene = try gltf.Scene.init(arena, doc); + errdefer scene.deinit(); + const geometry = try arena.alloc(Geometry, scene.meshes.len); + for (scene.meshes, geometry) |mesh, *g| { + var count: usize = 0; + for (mesh.primitives) |primitive| count = try std.math.add(usize, count, primitive.indices.len); + const vertices = try arena.alloc(Vertex, count); + var offset: usize = 0; + // Opaque materials share one pipeline: carry color per vertex to batch a mesh. + for (mesh.primitives) |primitive| { + for (primitive.indices) |index| { + const source = primitive.vertices[index]; + vertices[offset] = .{ .position = source.position, .normal = source.normal, .color = primitive.color }; + offset += 1; + } + } + g.* = .{ .vertices = vertices }; + } + return .{ .scene = scene, .geometry = geometry }; + } + pub fn release(m: *Model, host: sk.Host) void { + for (m.geometry) |*g| g.release(host); + } +}; + +/// Imperative frame builder: add a whole scene, individual meshes, or geometry. +pub const View = struct { + frame: *sk.Frame, + image: sk.Image, + width: u32, + height: u32, + vp: math.Mat4, + draws: std.ArrayList(gpu.Draw) = .empty, + background: [4]f32 = .{ 0.54, 0.72, 0.83, 1 }, + + pub fn init(f: *sk.Frame, image: sk.Image, width: u32, height: u32, camera: Camera) View { + return .{ .frame = f, .image = image, .width = width, .height = height, .vp = camera.matrix(@as(f32, @floatFromInt(width)) / @as(f32, @floatFromInt(height))) }; + } + pub fn scene(v: *View, model: *Model) !void { + for (model.scene.nodes) |node| if (node.visible) { + if (node.mesh) |index| try v.mesh(model, index, node.world); + }; + } + pub fn mesh(v: *View, model: *Model, index: usize, transform: math.Mat4) !void { + if (index >= model.geometry.len) return error.InvalidMesh; + try v.triangles(&model.geometry[index], transform, .{ 1, 1, 1, 1 }); + } + pub fn triangles(v: *View, geometry: *Geometry, transform: math.Mat4, color: [4]f32) !void { + if (geometry.buffer == .none) return error.GeometryNotUploaded; + try v.draws.append(v.frame.scratch, .{ + .pipeline = 0, + .vertex_count = @intCast(geometry.vertices.len), + .vertex_storage = v.frame.keep(sk.abi.Buffer, &.{geometry.buffer}), + .vertex_uniforms = gpu.uniform(v.frame.scratch, types.Transform{ + .model = @bitCast(transform), + .view_projection = @bitCast(v.vp), + .color = color, + }), + }); + } + pub fn end(v: *View) void { + v.frame.gpu(.{ + .label = "gltf scene", + .image = v.image, + .width = v.width, + .height = v.height, + .depth = true, + .clear = v.background, + .pipelines = &.{pipeline}, + .draws = v.draws.items, + }); + } +}; +const pipeline: gpu.Pipeline = .{ + .vertex = .{ .code = shaders.basic_vert, .uniform_buffers = 1, .storage_buffers = 1 }, + .fragment = .{ .code = shaders.basic_frag }, + .stride = 0, + .attributes = &.{}, + .blend = .none, + .depth_test = .less, + .depth_write = true, +}; +comptime { + // std430 scalar storage is ten contiguous floats, with no vec3 padding. + if (@sizeOf(Vertex) != 40 or @offsetOf(Vertex, "normal") != 12 or @offsetOf(Vertex, "color") != 24) @compileError("unexpected glTF vertex layout"); + gpu.assertStd140(types.Transform); +} |
