summaryrefslogtreecommitdiff
path: root/src/gltf_render
diff options
context:
space:
mode:
Diffstat (limited to 'src/gltf_render')
-rw-r--r--src/gltf_render/basic.frag10
-rw-r--r--src/gltf_render/basic.vert16
-rw-r--r--src/gltf_render/math.zig67
-rw-r--r--src/gltf_render/root.zig164
-rw-r--r--src/gltf_render/types.zig13
-rw-r--r--src/gltf_render/web.zig2
6 files changed, 272 insertions, 0 deletions
diff --git a/src/gltf_render/basic.frag b/src/gltf_render/basic.frag
new file mode 100644
index 0000000..73209ea
--- /dev/null
+++ b/src/gltf_render/basic.frag
@@ -0,0 +1,10 @@
+#version 450
+layout(location = 0) in vec3 world_normal;
+layout(location = 1) in vec4 color;
+layout(location = 0) out vec4 out_color;
+void main() {
+ vec3 normal = normalize(world_normal);
+ if (!gl_FrontFacing) normal = -normal;
+ float light = 0.42 + 0.58 * max(dot(normal, normalize(vec3(-0.45, 0.85, 0.3))), 0.0);
+ out_color = vec4(pow(max(color.rgb * light, vec3(0.0)), vec3(1.0 / 2.2)), 1.0);
+}
diff --git a/src/gltf_render/basic.vert b/src/gltf_render/basic.vert
new file mode 100644
index 0000000..3239a38
--- /dev/null
+++ b/src/gltf_render/basic.vert
@@ -0,0 +1,16 @@
+#version 450
+#extension GL_GOOGLE_include_directive : require
+layout(std430, set = 0, binding = 0) readonly buffer Vertices { float data[]; };
+#include "Transform.glsl"
+layout(location = 0) out vec3 world_normal;
+layout(location = 1) out vec4 color;
+void main() {
+ uint offset = uint(gl_VertexIndex) * 10;
+ vec3 position = vec3(data[offset], data[offset+1], data[offset+2]);
+ vec3 normal = vec3(data[offset+3], data[offset+4], data[offset+5]);
+ mat4 model = mat4(transform.model[0], transform.model[1], transform.model[2], transform.model[3]);
+ mat4 vp = mat4(transform.view_projection[0], transform.view_projection[1], transform.view_projection[2], transform.view_projection[3]);
+ gl_Position = vp * model * vec4(position, 1.0);
+ world_normal = transpose(inverse(mat3(model))) * normal;
+ color = transform.color * vec4(data[offset+6], data[offset+7], data[offset+8], data[offset+9]);
+}
diff --git a/src/gltf_render/math.zig b/src/gltf_render/math.zig
new file mode 100644
index 0000000..6279ce4
--- /dev/null
+++ b/src/gltf_render/math.zig
@@ -0,0 +1,67 @@
+const std = @import("std");
+pub const Mat4 = [16]f32;
+pub const identity: Mat4 = .{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
+pub fn multiply(a: Mat4, b: Mat4) Mat4 {
+ var out: Mat4 = @splat(0);
+ for (0..4) |col| for (0..4) |row| {
+ for (0..4) |k| out[col * 4 + row] += a[k * 4 + row] * b[col * 4 + k];
+ };
+ return out;
+}
+fn sub(a: [3]f32, b: [3]f32) [3]f32 {
+ return .{ a[0] - b[0], a[1] - b[1], a[2] - b[2] };
+}
+fn dot(a: [3]f32, b: [3]f32) f32 {
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+}
+fn cross(a: [3]f32, b: [3]f32) [3]f32 {
+ return .{ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] };
+}
+fn unit(a: [3]f32) [3]f32 {
+ const n = @sqrt(dot(a, a));
+ return .{ a[0] / n, a[1] / n, a[2] / n };
+}
+pub const Camera = struct {
+ eye: [3]f32,
+ target: [3]f32,
+ up: [3]f32 = .{ 0, 1, 0 },
+ fov: f32 = std.math.pi / 3.0,
+ near: f32 = 0.1,
+ far: f32 = 300,
+ aspect_ratio: ?f32 = null,
+ orthographic: ?struct { xmag: f32, ymag: f32 } = null,
+ /// Right-handed, column-major; depth range 0..1, camera forward -Z.
+ pub fn matrix(c: Camera, aspect: f32) Mat4 {
+ const z = unit(sub(c.eye, c.target));
+ const x = unit(cross(c.up, z));
+ const y = cross(z, x);
+ const view: Mat4 = .{ x[0], y[0], z[0], 0, x[1], y[1], z[1], 0, x[2], y[2], z[2], 0, -dot(x, c.eye), -dot(y, c.eye), -dot(z, c.eye), 1 };
+ const scale = 1 / @tan(c.fov / 2);
+ const d = c.near - c.far;
+ const projection: Mat4 = if (c.orthographic) |o|
+ .{ 1 / o.xmag, 0, 0, 0, 0, 1 / o.ymag, 0, 0, 0, 0, 1 / d, 0, 0, 0, c.near / d, 1 }
+ else if (std.math.isInf(c.far))
+ .{ scale / (c.aspect_ratio orelse aspect), 0, 0, 0, 0, scale, 0, 0, 0, 0, -1, -1, 0, 0, -c.near, 0 }
+ else
+ .{ scale / (c.aspect_ratio orelse aspect), 0, 0, 0, 0, scale, 0, 0, 0, 0, c.far / d, -1, 0, 0, c.near * c.far / d, 0 };
+ return multiply(projection, view);
+ }
+};
+test "perspective maps near and far to zero and one" {
+ const camera: Camera = .{ .eye = .{ 0, 0, 0 }, .target = .{ 0, 0, -1 } };
+ const m = camera.matrix(1);
+ try std.testing.expectApproxEqAbs(@as(f32, 0), (m[10] * -camera.near + m[14]) / camera.near, 0.00001);
+ try std.testing.expectApproxEqAbs(@as(f32, 1), (m[10] * -camera.far + m[14]) / camera.far, 0.00001);
+}
+
+test "orthographic and infinite perspective keep valid depth" {
+ var camera: Camera = .{ .eye = .{ 0, 0, 0 }, .target = .{ 0, 0, -1 }, .orthographic = .{ .xmag = 2, .ymag = 3 } };
+ const ortho = camera.matrix(1);
+ try std.testing.expectApproxEqAbs(@as(f32, 0), ortho[10] * -camera.near + ortho[14], 0.00001);
+ try std.testing.expectApproxEqAbs(@as(f32, 1), ortho[10] * -camera.far + ortho[14], 0.00001);
+ camera.orthographic = null;
+ camera.far = std.math.inf(f32);
+ const infinite = camera.matrix(1);
+ for (infinite) |v| try std.testing.expect(std.math.isFinite(v));
+ try std.testing.expectApproxEqAbs(@as(f32, 0), (infinite[10] * -camera.near + infinite[14]) / camera.near, 0.00001);
+}
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);
+}
diff --git a/src/gltf_render/types.zig b/src/gltf_render/types.zig
new file mode 100644
index 0000000..29b784f
--- /dev/null
+++ b/src/gltf_render/types.zig
@@ -0,0 +1,13 @@
+//! These types generate the GLSL vertex and uniform declarations.
+pub const Vertex = extern struct {
+ position: [3]f32,
+ normal: [3]f32,
+ color: [4]f32 = .{ 1, 1, 1, 1 },
+ pub const glsl = .vertex;
+};
+pub const Transform = extern struct {
+ model: [4][4]f32,
+ view_projection: [4][4]f32,
+ color: [4]f32,
+ pub const glsl = .{ .uniform = .{ .set = 1, .instance = "transform" } };
+};
diff --git a/src/gltf_render/web.zig b/src/gltf_render/web.zig
new file mode 100644
index 0000000..f8dc252
--- /dev/null
+++ b/src/gltf_render/web.zig
@@ -0,0 +1,2 @@
+//! The cgltf loader currently requires libc; the existing 2D web game still works.
+pub const supported = false;