const std = @import("std"); const core = @import("mach-core"); const gpu = core.gpu; const zm = @import("zmath"); const vec = zm.f32x4; const Mat = zm.Mat; /// Holds information about how a perticular scene should be rendered. const SceneUniformBuffer = struct { view_proj_matrix: zm.Mat, }; /// Holds information about where and how an object should be rendered. const ObjectUniformBuffer = struct { model_matrix: zm.Mat, color: [3]f32, }; /// Describes the layout of each vertex that a primitive is made of. const VertexData = struct { position: [3]f32, }; /// Contains the data to render a primitive (3D shape or model). const PrimitiveData = struct { /// Vertices describe the "points" that a primitive is made out of. /// This buffer is of type `[]VertexData`. vertex_buffer: *gpu.Buffer, vertex_count: u32, /// Indices describe what vertices make up the triangles in a primitive. /// This buffer is of type `[]u32`. index_buffer: *gpu.Buffer, index_count: u32, // For example, `vertex_buffer` may have 4 points defining a square, but // since it needs to be rendered using 2 triangles, `index_buffer` will // contain 6 entries, `0, 1, 2` and `3, 2, 1` making up one triangle each. }; pub const App = @This(); app_timer: core.Timer, title_timer: core.Timer, pipeline: *gpu.RenderPipeline, scene_uniform_buffer: *gpu.Buffer, scene_bind_group: *gpu.BindGroup, object_uniform_buffers: [3]*gpu.Buffer, object_bind_groups: [3]*gpu.BindGroup, object_primitive_indices: [3]usize, primitives: [2]PrimitiveData, pub fn init(app: *App) !void { try core.init(.{}); app.app_timer = try core.Timer.start(); app.title_timer = try core.Timer.start(); const shader_module = core.device.createShaderModuleWGSL("shader.wgsl", @embedFile("shader.wgsl")); defer shader_module.release(); // Set up rendering pipeline. app.pipeline = core.device.createRenderPipeline(&.{ .vertex = gpu.VertexState.init(.{ .module = shader_module, .entry_point = "vertex_main", .buffers = &.{ gpu.VertexBufferLayout.init(.{ .array_stride = @sizeOf(VertexData), .step_mode = .vertex, .attributes = &.{ .{ .format = .float32x3, .shader_location = 0, .offset = @offsetOf(VertexData, "position") }, }, }), }, }), .fragment = &gpu.FragmentState.init(.{ .module = shader_module, .entry_point = "frag_main", .targets = &.{.{ .format = core.descriptor.format }}, }), .primitive = .{ .topology = .triangle_list, .front_face = .ccw, .cull_mode = .back, }, }); // Set up uniform buffers and bind groups. // The "scene" uniform contains information for each rendered scene. app.scene_uniform_buffer = core.device.createBuffer(&.{ .usage = .{ .copy_dst = true, .uniform = true }, .size = @sizeOf(SceneUniformBuffer), .mapped_at_creation = .false, }); // "Bind groups" are used to associate data from buffers with shader parameters. // So for example the `scene_bind_group` is accessible via `scene` in our shader. // Essentially, buffer = data, and bind group = binding parameter to that data. app.scene_bind_group = core.device.createBindGroup( &gpu.BindGroup.Descriptor.init(.{ .layout = app.pipeline.getBindGroupLayout(0), .entries = &.{ gpu.BindGroup.Entry.buffer(0, app.scene_uniform_buffer, 0, @sizeOf(SceneUniformBuffer)), }, }), ); // The "object" uniforms contain information about how to render each object in a scene. for (0..3) |i| { app.object_uniform_buffers[i] = core.device.createBuffer(&.{ .usage = .{ .copy_dst = true, .uniform = true }, .size = @sizeOf(ObjectUniformBuffer), .mapped_at_creation = .false, }); app.object_bind_groups[i] = core.device.createBindGroup( &gpu.BindGroup.Descriptor.init(.{ .layout = app.pipeline.getBindGroupLayout(1), .entries = &.{ gpu.BindGroup.Entry.buffer(0, app.object_uniform_buffers[i], 0, @sizeOf(ObjectUniformBuffer)), }, }), ); } // Upload object information (model matrix + color) to the GPU. const rotation = zm.rotationY(std.math.tau / 2.0); // The objects are rotated 180° to face the camera, or else we // would see the back side of the triangles, which are culled. core.queue.writeBuffer(app.object_uniform_buffers[0], 0, &[_]ObjectUniformBuffer{.{ .model_matrix = zm.transpose(zm.mul(rotation, zm.translation(-1.0, 0.25, 0.0))), .color = .{ 1.0, 0.0, 0.0 }, }}); app.object_primitive_indices[0] = 0; core.queue.writeBuffer(app.object_uniform_buffers[1], 0, &[_]ObjectUniformBuffer{.{ .model_matrix = zm.transpose(zm.mul(rotation, zm.translation(0.0, -0.25, 0.0))), .color = .{ 0.0, 1.0, 0.0 }, }}); app.object_primitive_indices[1] = 1; core.queue.writeBuffer(app.object_uniform_buffers[2], 0, &[_]ObjectUniformBuffer{.{ .model_matrix = zm.transpose(zm.mul(rotation, zm.translation(1.0, 0.0, 0.0))), .color = .{ 0.0, 0.0, 1.0 }, }}); app.object_primitive_indices[2] = 0; // Set up the primitives we want to render. // Triangle app.primitives[0] = createPrimitive( &.{ .{ .position = .{ 0.0, 0.5, 0.0 } }, .{ .position = .{ 0.5, -0.5, 0.0 } }, .{ .position = .{ -0.5, -0.5, 0.0 } }, }, // Note that the back faces of triangles are "culled", and thus not visible. // We need to take care to specify the vertices in counter-clock orientation. &.{ 0, 1, 2, }, ); // Square app.primitives[1] = createPrimitive( // 0--2 // | | // | | // 1--3 &.{ .{ .position = .{ -0.5, -0.5, 0.0 } }, .{ .position = .{ -0.5, 0.5, 0.0 } }, .{ .position = .{ 0.5, -0.5, 0.0 } }, .{ .position = .{ 0.5, 0.5, 0.0 } }, }, // 0--2 4 // | / /| // |/ / | // 1 5--3 &.{ 0, 1, 2, 3, 2, 1, }, ); } /// Creates a buffer on the GPU with the specified usage /// flags and immediately fills it with the provided data. fn createAndWriteBuffer( comptime T: type, data: []const T, usage: gpu.Buffer.UsageFlags, ) *gpu.Buffer { const buffer = core.device.createBuffer(&.{ .size = data.len * @sizeOf(T), .usage = usage, .mapped_at_creation = .false, }); core.queue.writeBuffer(buffer, 0, data); return buffer; } // Creates a primitive from the provided vertices and indices, // and uploads the buffers necessary to render it to the GPU. fn createPrimitive( vertices: []const VertexData, indices: []const u32, ) PrimitiveData { return .{ .vertex_buffer = createAndWriteBuffer(VertexData, vertices, .{ .vertex = true, .copy_dst = true }), .vertex_count = @intCast(vertices.len), .index_buffer = createAndWriteBuffer(u32, indices, .{ .index = true, .copy_dst = true }), .index_count = @intCast(indices.len), }; } pub fn deinit(app: *App) void { // Using `defer` here, so we can specify them // in the order they were created in `init`. defer core.deinit(); defer app.pipeline.release(); defer app.scene_uniform_buffer.release(); defer app.scene_bind_group.release(); defer for (app.object_uniform_buffers) |b| b.release(); defer for (app.object_bind_groups) |g| g.release(); defer for (app.primitives) |p| { p.vertex_buffer.release(); p.index_buffer.release(); }; } pub fn update(app: *App) !bool { var iter = core.pollEvents(); while (iter.next()) |event| { switch (event) { .close => return true, else => {}, } } // Set up a view matrix from the camera transform. // This moves everything to be relative to the camera. // TODO: Actually implement camera transform instead of hardcoding a look-at matrix. // const view_matrix = zm.inverse(app.camera_transform); const time = app.app_timer.read(); const x = @cos(time * std.math.tau / 10); const y = @sin(time * std.math.tau / 10); const view_matrix = zm.lookAtLh(vec(x, y, -2, 1), vec(0, 0, 0, 1), vec(0, 1, 0, 1)); // Set up a projection matrix using the size of the window. // The perspective projection will make things further away appear smaller. const width: f32 = @floatFromInt(core.descriptor.width); const height: f32 = @floatFromInt(core.descriptor.height); const field_of_view = std.math.degreesToRadians(f32, 45.0); const proj_matrix = zm.perspectiveFovLh(field_of_view, width / height, 0.1, 10); const view_proj_matrix = zm.mul(view_matrix, proj_matrix); // Get back buffer texture to render to. const back_buffer_view = core.swap_chain.getCurrentTextureView().?; defer back_buffer_view.release(); // Once rendering is done (hence `defer`), swap back buffer to the front to display. defer core.swap_chain.present(); const render_pass_info = gpu.RenderPassDescriptor.init(.{ .color_attachments = &.{.{ .view = back_buffer_view, .clear_value = std.mem.zeroes(gpu.Color), .load_op = .clear, .store_op = .store, }}, }); // Create a `WGPUCommandEncoder` which provides an interface for recording GPU commands. const encoder = core.device.createCommandEncoder(null); defer encoder.release(); // Write to the scene uniform buffer for this set of commands. encoder.writeBuffer(app.scene_uniform_buffer, 0, &[_]SceneUniformBuffer{.{ // All matrices the GPU has to work with need to be transposed, // because WebGPU uses column-major matrices while zmath is row-major. .view_proj_matrix = zm.transpose(view_proj_matrix), }}); { const pass = encoder.beginRenderPass(&render_pass_info); defer pass.release(); defer pass.end(); pass.setPipeline(app.pipeline); pass.setBindGroup(0, app.scene_bind_group, &.{}); for (app.object_bind_groups, 0..) |object_bind_group, i| { // Set the vertex and index buffer used to render this object // to the primitive it wants to use (either triangle or square). const primitive_index = app.object_primitive_indices[i]; const primitive = app.primitives[primitive_index]; pass.setVertexBuffer(0, primitive.vertex_buffer, 0, primitive.vertex_count * @sizeOf(VertexData)); pass.setIndexBuffer(primitive.index_buffer, .uint32, 0, primitive.index_count * @sizeOf(u32)); // Set the bind group for an object we want to render. pass.setBindGroup(1, object_bind_group, &.{}); // Draw a number of triangles as specified in the index buffer. pass.drawIndexed(primitive.index_count, 1, 0, 0, 0); } } // Finish recording commands, creating a `WGPUCommandBuffer`. var command = encoder.finish(null); defer command.release(); // Submit the command(s) to the GPU. core.queue.submit(&.{command}); // Update the window title to show FPS and input frequency. if (app.title_timer.read() >= 1.0) { app.title_timer.reset(); try core.printTitle("Triangle [ {d}fps ] [ Input {d}hz ]", .{ core.frameRate(), core.inputRate() }); } return false; }