spencrc/hello-triangle-zig-wgpu
Zig-language example demonstrating very basic rendering using wgpu-native.
d4e35d81f30ec1398d5b40744968459d5a8786e6022397baacd9e7c90a0d6906c61cb4f256ac4e1c8f1ae3e7561f11e0bf0c6d122f9a53f68991c26dOpens a window using glfw and draws a triangle with wgpu-native, all in Zig. Builds and runs on Windows, Linux (using either X11 or Wayland), and MacOS.
This project depends on:
If you want to build this project using zig-gamedev/zglfw, you'll have to make very minor changes to the parameters passed to each glfw function call. The bindings used here aim to mirror zig-gamedev/zglfw's enums and function names whilst remaining as close as possible to glfw's function definitions.
The glfw_wgpu.zig file serves as an extension to glfw for use with wgpu-native. It's accompanied by metal_layer.m which provides the Objective-C code necessary for retrieving the Metal layer on MacOS systems.
glfw_wgpu simply provides the following function:
fn createSurface(instance: *wgpu.Instance, window: *glfw.Window) !*wgpu.Surface;
Given a glfw window, createSurface returns a wgpu surface that correlates to the window's backend.
You can add glfw_wgpu as a dependency to your project by running zig fetch in your project,
zig fetch --save "git+https://github.com/spencrc/hello-triangle-zig-wgpu.git`
Then, you'll need to add glfw_webgpu as an import to your executable. It should look something like this:
const glfw_wgpu_dep = b.dependency("glfw_wgpu", .{
.target = target,
.optimize = optimize,
});
const exe = b.addExecutable(.{
.name = "your_project",
.root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
.imports = &.{
.{ .name = "glfw_wgpu", .module = glfw_wgpu_dep.module("glfw_wgpu") },
},
}),
});
Alternatively, if you wish to use glfw_wgpu but don't want to rely on the same dependencies, you can simply copy lib/ into your project's root and glfw_wgpu.zig into your project's src/. Then, include the following in your build.zig for MacOS support:
if (target.result.os.tag == .macos) {
exe.root_module.addCSourceFile(.{
.file = b.path("lib/metal/metal_layer.m"),
.language = .objective_c,
});
exe.root_module.linkFramework("QuartzCore", .{});
exe.root_module.linkFramework("Metal", .{});
}
This project is based on the Hello Triangle from the C++ Learn WebGPU native course.
glfw_wgpu.zig is based on TheOnlySilverClaw/Valdala's surface.zig, whilst metal_layer.m is a copy of metal_layer.m.
Please check out Valdala!