8 Commits
Author SHA1 Message Date
adrien 9c329a5a06 Prevent building examples when fetch 2026-05-20 15:59:28 +02:00
adrien 69f9cad2c1 Updated README ref 2026-05-20 15:45:02 +02:00
adrien c5d7fd927d Updated README and build.zon version 2026-05-20 14:04:25 +02:00
adrien 17977cc718 Merge branch 'render' 2026-05-20 13:47:43 +02:00
adrien 5104d61ef6 Synthax for compute example 2026-05-20 13:41:04 +02:00
adrien 7d5331aed7 Circle example use device allocator directly 2026-05-20 13:39:20 +02:00
adrien 7d425e4061 Changed how Allocator work to be more Zig like
Now GpuArena doesn't do everything.

- Created GpuDeviceAllocator that allocate to the device
- GpuArena become GpuArenaAllocator and use a child_allocator like
std.heap.ArenaAllocator
2026-05-20 13:32:37 +02:00
adrien a06b040a29 Render and COmpute Pipelines now use a gloc and is tracked by Arena 2026-05-20 12:29:41 +02:00
14 changed files with 446 additions and 232 deletions
+132 -43
View File
@@ -1,26 +1,28 @@
# Minimal Zig WebGPU Compute Library # Minimal Zig WebGPU Compute & Render Library
This is a minimal, self-contained Zig library designed to simplify running compute shaders using WebGPU. This is a minimal, self-contained Zig library designed to simplify running compute shaders and rendering pipelines using WebGPU. It abstracts away much of the boilerplate required for GPU device initialization, memory management, bind groups, and pipeline execution.
It abstracts away much of the boilerplate required for GPU device initialization, memory management, and pipeline execution.
## Core Modules ## Core Modules
The library exports five primary components: The library exports the following primary components:
* **`GpuDevice`**: Initializes the WebGPU instance, adapter, device, and queue. It is configured to prioritize high performance and automatically requests the `ShaderF16` feature if the adapter supports it. By default, it enforces a 2 GB VRAM limit. * **`GpuDevice`**: Initializes the WebGPU instance, adapter, device, and queue. It is configured to prioritize high performance and automatically requests the `ShaderF16` feature if the adapter supports it. It provides the base `GpuAllocator` for raw VRAM allocations.
* **`GpuArena` / `GpuAllocator`**: A memory management layer that tracks allocated VRAM bytes to prevent exceeding the device budget. The arena automatically destroys and releases all tracked WebGPU buffers when deinitialized. * **`GpuArenaAllocator`**: A memory management layer that wraps a base allocator to track and automatically destroy all allocated WebGPU buffers, textures, views, and pipelines when deinitialized.
* **`GpuBuffer`**: Wraps native WebGPU buffers. It automatically aligns buffer sizes forward to a multiple of 4 bytes. It provides a `.load()` method for CPU-to-GPU data transfers (handling both aligned and unaligned lengths smoothly) and a `.read()` method that utilizes a staging buffer to map GPU data back to the CPU. * **`GpuBuffer`**: Wraps native WebGPU buffers. It provides a `.load()` method for CPU-to-GPU data transfers and a `.read()` method that utilizes a staging buffer to map GPU data back to the CPU.
* **`GpuCompute`**: Compiles WGSL source code into a compute pipeline. When running, it automatically splits the work into manageable chunks (up to 1 GB at a time) and dispatches workgroups of size 256. * **`GpuCompute`**: Compiles WGSL source code into a compute pipeline and dispatches compute workgroups.
* **`GpuRender` / `GpuTexture` / `GpuTextureView`**: Components used to initialize render pipelines, set up render attachments (textures), and bind render targets for offscreen drawing.
## Quick Start Example ---
Below is a complete, self-contained example demonstrating how to initialize the GPU, load data, run a compute shader, and read the results back to the CPU: ## Example 1: Compute Pipeline
Below is a complete example demonstrating how to initialize the GPU via the device allocator, manage VRAM using a GPU Arena, run a compute shader, and read the results back to the CPU:
```zig ```zig
const std = @import("std"); const std = @import("std");
const gpu = @import("gpu"); const gpu = @import("gpu");
const GpuDevice = gpu.GpuDevice; const GpuDevice = gpu.GpuDevice;
const GpuArena = gpu.GpuArena; const GpuArenaAllocator = gpu.GpuArenaAllocator;
const GpuBuffer = gpu.GpuBuffer; const GpuBuffer = gpu.GpuBuffer;
const GpuCompute = gpu.GpuCompute; const GpuCompute = gpu.GpuCompute;
@@ -32,13 +34,13 @@ pub fn main(init: std.process.Init) !void {
defer device.deinit(); defer device.deinit();
// 2. Create a GPU Arena to manage VRAM // 2. Create a GPU Arena to manage VRAM
var grena = GpuArena.init(allocator, device); var grena = GpuArenaAllocator.init(allocator, device.gpuAllocator());
defer grena.deinit(); defer grena.deinit();
const gloc = grena.gpuAllocator(); const gloc = grena.gpuAllocator();
// 3. Load the WGSL compute pipeline // 3. Load the WGSL compute pipeline
const add_cp = try GpuCompute.init( const add_cp = try GpuCompute.init(
device, gloc,
@embedFile("shaders/add.wgsl"), @embedFile("shaders/add.wgsl"),
.{ .bindings = &.{ .{ .bindings = &.{
.{ .element_size = @sizeOf(f16) }, .{ .element_size = @sizeOf(f16) },
@@ -46,7 +48,6 @@ pub fn main(init: std.process.Init) !void {
.{ .element_size = @sizeOf(f16) }, .{ .element_size = @sizeOf(f16) },
} }, } },
); );
defer add_cp.deinit();
// 4. Setup CPU data // 4. Setup CPU data
const len: usize = 16; const len: usize = 16;
@@ -66,8 +67,8 @@ pub fn main(init: std.process.Init) !void {
const buf_b = try GpuBuffer.init(gloc, byte_size, .initMany(&.{ .Storage, .CopyDst, .CopySrc })); const buf_b = try GpuBuffer.init(gloc, byte_size, .initMany(&.{ .Storage, .CopyDst, .CopySrc }));
const buf_out = try GpuBuffer.init(gloc, byte_size, .initMany(&.{ .Storage, .CopyDst, .CopySrc })); const buf_out = try GpuBuffer.init(gloc, byte_size, .initMany(&.{ .Storage, .CopyDst, .CopySrc }));
// Note: The buffers are safely tied to the GpuArena which will automatically // Note: Buffers, pipelines, and other objects initialized with 'gloc'
// release them at the end. You can also manually call buf_x.deinit() if desired. // are safely tied to the GpuArenaAllocator and will automatically release.
// 6. Transfer data from CPU slices to GPU Buffers // 6. Transfer data from CPU slices to GPU Buffers
try buf_a.load(f16, data_a); try buf_a.load(f16, data_a);
@@ -84,53 +85,141 @@ pub fn main(init: std.process.Init) !void {
} }
``` ```
---
## Example 2: Rendering Pipeline (Offscreen to PPM Image)
This example demonstrates how to initialize a rendering pipeline, allocate an output texture target, draw primitives via WebGPU,
and pull the frame pixels back to the CPU to write a standard image file:
```zig
const std = @import("std");
const gpu = @import("gpu");
const GpuDevice = gpu.GpuDevice;
const GpuBuffer = gpu.GpuBuffer;
const GpuRender = gpu.GpuRender;
const GpuTexture = gpu.GpuTexture;
const GpuTextureView = gpu.GpuTextureView;
const width: u32 = 512;
const height: u32 = 512;
pub fn main(init: std.process.Init) !void {
const allocator = init.gpa;
// 1. Open GPU Device
const device = try GpuDevice.init(.{});
defer device.deinit();
// 2. Get base device GPU Allocator
const gloc = device.gpuAllocator();
// 3. Load Render Pipeline
const circle_rp = try GpuRender.init(
gloc,
@embedFile("shaders/circle.wgsl"),
.{ .bindings = &.{}, .texture_format = .RGBA8Unorm, .topology = .TriangleStrip },
);
defer circle_rp.deinit();
// 4. Create VRAM texture to render into
const texture = try GpuTexture.init(gloc, .{
.format = .RGBA8Unorm,
.size = .{ .width = width, .height = height, .depthOrArrayLayers = 1 },
.usage = .initMany(&.{ .RenderAttachment, .CopySrc }),
});
defer texture.deinit();
// 5. Create a view from texture
const view = try GpuTextureView.init(gloc, texture, .{});
defer view.deinit();
// 6. Run the rendering pipeline
try circle_rp.draw(gloc, view, 4, .{});
// 7. Copy Texture into a readable GPU staging buffer
const cpu_staging_buf = try texture.buffCopy(gloc);
defer cpu_staging_buf.deinit();
// 8. Read GpuBuffer to CPU memory
const pixels = try cpu_staging_buf.read(allocator, u8);
defer allocator.free(pixels);
// 9. Write out to a simple PPM image
try savePpm(init.io, "circle.ppm", width, height, pixels);
}
fn savePpm(io: std.Io, filename: []const u8, w: u32, h: u32, rgba_pixels: []const u8) !void {
const file = try std.Io.Dir.cwd().createFile(io, filename, .{});
defer file.close(io);
var buf: [255]u8 = undefined;
var writer = file.writer(io, &buf);
// PPM Header: P6 format means raw RGB bytes
try writer.interface.print("P6\n{d} {d}\n255\n", .{ w, h });
// Strip Alpha channel when writing out to standard RGB PPM format
var i: usize = 0;
while (i < rgba_pixels.len) : (i += 4) {
try writer.interface.writeAll(rgba_pixels[i .. i + 3]);
}
}
```
---
## Running Examples Locally
If you have cloned the repository, you can run the included examples directly using the Zig build system:
```bash
# Run the rendering example (generates circle.ppm)
zig build circle
# Run the compute example
zig build compute
# Run the compute benchmark
zig build bench_cp
```
---
## Dependencies ## Dependencies
* **`wgpu.h`**: The library relies on the WebGPU C API headers to bind to the native system graphics. * **`wgpu.h`**: The library relies on WebGPU C API headers to bind to the native system graphics.
## System Requirements ## System Requirements
Because this library binds to native system graphics APIs via `wgpu-native`, Because this library binds to native system graphics APIs via `wgpu-native`, you must ensure the appropriate development headers and libraries are available on your system before compiling.
you must ensure the appropriate development headers and libraries are available on your system before compiling.
### Linux (Vulkan) ### Linux (Vulkan)
You need the Vulkan development headers to compile the project, and a Vulkan-compatible driver to run it.
Depending on your distribution, install the following packages: * **Ubuntu / Debian:** `sudo apt update && sudo apt install libvulkan-dev mesa-vulkan-drivers`
* **Ubuntu / Debian:** * **Fedora / RHEL:** `sudo dnf install vulkan-devel mesa-vulkan-drivers`
```bash * **Arch Linux:** `sudo pacman -S vulkan-headers vulkan-icd-loader`
sudo apt update
sudo apt install libvulkan-dev mesa-vulkan-drivers
```
* **Fedora / RHEL:**
```bash
sudo dnf install vulkan-devel mesa-vulkan-drivers
```
* **Arch Linux:**
```bash
sudo pacman -S vulkan-headers vulkan-icd-loader
```
### macOS (Metal) ### macOS (Metal)
No extra installation is required.
The build script automatically links against the standard Apple frameworks provided by the Xcode Command Line Tools No extra installation required. Automatically links against `Metal`, `QuartzCore`, `Foundation`, and `CoreGraphics`.
(`Metal`, `QuartzCore`, `Foundation`, `CoreGraphics`).
### Windows (DirectX 12) ### Windows (DirectX 12)
No extra installation is required.
The build script automatically links against the standard Windows SDK libraries (`d3d12`, `dxgi`, `user32`). No extra installation required. Automatically links against `d3d12`, `dxgi`, and `user32`. Ensure you have MSVC build tools installed.
Ensure you have the MSVC build tools installed.
--- ---
## Adding to your project ## Adding to your project
To use this module in your own Zig project, add it to your `build.zig.zon`: Add it to your `build.zig.zon`:
```bash ```bash
zig fetch --save git+https://git.bouvais.lu/adrien/zig-wgpu zig fetch --save git+[https://git.bouvais.lu/adrien/zig-wgpu#ref=0.2.0](https://git.bouvais.lu/adrien/zig-wgpu)
``` ```
Then, in your `build.zig`, import and add the module to your executable: Then, expose it in your `build.zig`:
```zig ```zig
const zig_wgpu = b.dependency("zig-wgpu", .{ const zig_wgpu = b.dependency("zig-wgpu", .{
.target = target, .target = target,
+2
View File
@@ -29,6 +29,7 @@ pub fn build(b: *std.Build) !void {
mod.linkSystemLibrary("gcc_s", .{}); mod.linkSystemLibrary("gcc_s", .{});
} }
if (b.pkg_hash.len == 0) {
var threaded: std.Io.Threaded = .init_single_threaded; var threaded: std.Io.Threaded = .init_single_threaded;
const io = threaded.io(); const io = threaded.io();
@@ -56,4 +57,5 @@ pub fn build(b: *std.Build) !void {
const run_cmd = b.addRunArtifact(exe); const run_cmd = b.addRunArtifact(exe);
run_step.dependOn(&run_cmd.step); run_step.dependOn(&run_cmd.step);
} }
}
} }
+1 -1
View File
@@ -1,6 +1,6 @@
.{ .{
.name = .zig_wgpu, .name = .zig_wgpu,
.version = "0.1.0", .version = "0.2.0",
.fingerprint = 0x5d0e853acbc0c2c6, .fingerprint = 0x5d0e853acbc0c2c6,
.minimum_zig_version = "0.16.0", .minimum_zig_version = "0.16.0",
.dependencies = .{}, .dependencies = .{},
-4
View File
File diff suppressed because one or more lines are too long
+3 -4
View File
@@ -1,7 +1,7 @@
const std = @import("std"); const std = @import("std");
const gpu = @import("gpu"); const gpu = @import("gpu");
const GpuDevice = gpu.GpuDevice; const GpuDevice = gpu.GpuDevice;
const GpuArena = gpu.GpuArena; const GpuArenaAllocator = gpu.GpuArenaAllocator;
const GpuAllocator = gpu.GpuAllocator; const GpuAllocator = gpu.GpuAllocator;
const GpuBuffer = gpu.GpuBuffer; const GpuBuffer = gpu.GpuBuffer;
const GpuCompute = gpu.GpuCompute; const GpuCompute = gpu.GpuCompute;
@@ -60,12 +60,11 @@ pub fn main(init: std.process.Init) !void {
const device = try GpuDevice.init(.{ .vram_bytes_limit = 4 * 1024 * 1024 * 1024 }); const device = try GpuDevice.init(.{ .vram_bytes_limit = 4 * 1024 * 1024 * 1024 });
defer device.deinit(); defer device.deinit();
var grena = GpuArena.init(init.gpa, device); var grena = GpuArenaAllocator.init(init.gpa, device.gpuAllocator());
defer grena.deinit(); defer grena.deinit();
const gloc = grena.gpuAllocator(); const gloc = grena.gpuAllocator();
const add_pip = try GpuCompute.init(device, @embedFile("shaders/add.wgsl"), .{ .bindings = &.{ const add_pip = try GpuCompute.init(gloc, @embedFile("shaders/add.wgsl"), .{ .bindings = &.{
.{ .element_size = @sizeOf(f16) }, .{ .element_size = @sizeOf(f16) },
.{ .element_size = @sizeOf(f16) }, .{ .element_size = @sizeOf(f16) },
.{ .element_size = @sizeOf(f16) }, .{ .element_size = @sizeOf(f16) },
+4 -6
View File
@@ -1,7 +1,7 @@
const std = @import("std"); const std = @import("std");
const gpu = @import("gpu"); const gpu = @import("gpu");
const GpuDevice = gpu.GpuDevice; const GpuDevice = gpu.GpuDevice;
const GpuArena = gpu.GpuArena; const GpuArenaAllocator = gpu.GpuArenaAllocator;
const GpuBuffer = gpu.GpuBuffer; const GpuBuffer = gpu.GpuBuffer;
const GpuRender = gpu.GpuRender; const GpuRender = gpu.GpuRender;
const GpuTexture = gpu.GpuTexture; const GpuTexture = gpu.GpuTexture;
@@ -18,13 +18,11 @@ pub fn main(init: std.process.Init) !void {
defer device.deinit(); defer device.deinit();
// 2. Init VRAM Arena // 2. Init VRAM Arena
var grena = GpuArena.init(allocator, device); const gloc = device.gpuAllocator();
defer grena.deinit();
const gloc = grena.gpuAllocator();
// 3. Load Render Pipeline // 3. Load Render Pipeline
const circle_rp = try GpuRender.init( const circle_rp = try GpuRender.init(
device, // Change to gloc + track them gloc,
@embedFile("shaders/circle.wgsl"), @embedFile("shaders/circle.wgsl"),
.{ .bindings = &.{}, .texture_format = .RGBA8Unorm, .topology = .TriangleStrip }, .{ .bindings = &.{}, .texture_format = .RGBA8Unorm, .topology = .TriangleStrip },
); );
@@ -50,12 +48,12 @@ pub fn main(init: std.process.Init) !void {
defer cpu_staging_cpu.deinit(); defer cpu_staging_cpu.deinit();
// 8. Read GpuBuffer to CPU // 8. Read GpuBuffer to CPU
// This need to be free manually because CPU memory
const pixels = try cpu_staging_cpu.read(allocator, u8); const pixels = try cpu_staging_cpu.read(allocator, u8);
defer allocator.free(pixels); defer allocator.free(pixels);
// 9. Write a simple ppm image // 9. Write a simple ppm image
try savePpm(init.io, "circle.ppm", width, height, pixels); try savePpm(init.io, "circle.ppm", width, height, pixels);
std.debug.print("Successfully rendered circle to circle.ppm!\n", .{});
} }
fn savePpm(io: std.Io, filename: []const u8, w: u32, h: u32, rgba_pixels: []const u8) !void { fn savePpm(io: std.Io, filename: []const u8, w: u32, h: u32, rgba_pixels: []const u8) !void {
+5 -5
View File
@@ -1,7 +1,7 @@
const std = @import("std"); const std = @import("std");
const gpu = @import("gpu"); const gpu = @import("gpu");
const GpuDevice = gpu.GpuDevice; const GpuDevice = gpu.GpuDevice;
const GpuArena = gpu.GpuArena; const GpuArenaAllocator = gpu.GpuArenaAllocator;
const GpuBuffer = gpu.GpuBuffer; const GpuBuffer = gpu.GpuBuffer;
const GpuCompute = gpu.GpuCompute; const GpuCompute = gpu.GpuCompute;
@@ -13,13 +13,13 @@ pub fn main(init: std.process.Init) !void {
defer device.deinit(); defer device.deinit();
// 2. Create a GPU Arena to manage VRAM // 2. Create a GPU Arena to manage VRAM
var grena = GpuArena.init(allocator, device); var grena = GpuArenaAllocator.init(allocator, device.gpuAllocator());
defer grena.deinit(); defer grena.deinit();
const gloc = grena.gpuAllocator(); const gloc = grena.gpuAllocator();
// 3. Load the WGSL compute pipeline // 3. Load the WGSL compute pipeline
const add_cp = try GpuCompute.init( const add_cp = try GpuCompute.init(
device, gloc,
@embedFile("shaders/add.wgsl"), @embedFile("shaders/add.wgsl"),
.{ .bindings = &.{ .{ .bindings = &.{
.{ .element_size = @sizeOf(f16) }, .{ .element_size = @sizeOf(f16) },
@@ -27,7 +27,6 @@ pub fn main(init: std.process.Init) !void {
.{ .element_size = @sizeOf(f16) }, .{ .element_size = @sizeOf(f16) },
} }, } },
); );
defer add_cp.deinit();
// 4. Setup CPU data // 4. Setup CPU data
const len: usize = 16; const len: usize = 16;
@@ -47,8 +46,9 @@ pub fn main(init: std.process.Init) !void {
const buf_b = try GpuBuffer.init(gloc, byte_size, .initMany(&.{ .Storage, .CopyDst, .CopySrc })); const buf_b = try GpuBuffer.init(gloc, byte_size, .initMany(&.{ .Storage, .CopyDst, .CopySrc }));
const buf_out = try GpuBuffer.init(gloc, byte_size, .initMany(&.{ .Storage, .CopyDst, .CopySrc })); const buf_out = try GpuBuffer.init(gloc, byte_size, .initMany(&.{ .Storage, .CopyDst, .CopySrc }));
// Note: The buffers are safely tied to the GpuArena which will automatically // Note: Buffers are safely tied to the GpuArenaAllocator which will automatically
// release them at the end. You can also manually call buf_x.deinit() if desired. // release them at the end. You can also manually call buf_x.deinit() if desired.
// This will also release pipelines, textures, ect. Everything using a GpuAllocator to init.
// 6. Transfer data from CPU slices to GPU Buffers // 6. Transfer data from CPU slices to GPU Buffers
try buf_a.load(f16, data_a); try buf_a.load(f16, data_a);
+26 -6
View File
@@ -8,6 +8,10 @@ pub const VTable = struct {
freeTexture: *const fn (ctx: *anyopaque, buf_raw: c.WGPUTexture) void, freeTexture: *const fn (ctx: *anyopaque, buf_raw: c.WGPUTexture) void,
allocTextureView: *const fn (ctx: *anyopaque, texture: c.WGPUTexture, desc: c.WGPUTextureViewDescriptor) anyerror!c.WGPUTextureView, allocTextureView: *const fn (ctx: *anyopaque, texture: c.WGPUTexture, desc: c.WGPUTextureViewDescriptor) anyerror!c.WGPUTextureView,
freeTextureView: *const fn (ctx: *anyopaque, buf_raw: c.WGPUTextureView) void, freeTextureView: *const fn (ctx: *anyopaque, buf_raw: c.WGPUTextureView) void,
allocRenderPipeline: *const fn (ctx: *anyopaque, desc: c.WGPURenderPipelineDescriptor) anyerror!c.WGPURenderPipeline,
freeRenderPipeline: *const fn (ctx: *anyopaque, buf_raw: c.WGPURenderPipeline) void,
allocComputePipeline: *const fn (ctx: *anyopaque, desc: c.WGPUComputePipelineDescriptor) anyerror!c.WGPUComputePipeline,
freeComputePipeline: *const fn (ctx: *anyopaque, buf_raw: c.WGPUComputePipeline) void,
}; };
device: GpuDevice, device: GpuDevice,
@@ -18,22 +22,38 @@ pub fn allocBuffer(self: @This(), desc: c.WGPUBufferDescriptor) !c.WGPUBuffer {
return self.vtable.allocBuffer(self.ptr, desc); return self.vtable.allocBuffer(self.ptr, desc);
} }
pub fn freeBuffer(self: @This(), buf_raw: c.WGPUBuffer) void { pub fn freeBuffer(self: @This(), raw: c.WGPUBuffer) void {
self.vtable.freeBuffer(self.ptr, buf_raw); self.vtable.freeBuffer(self.ptr, raw);
} }
pub fn allocTexture(self: @This(), desc: c.WGPUTextureDescriptor) !c.WGPUTexture { pub fn allocTexture(self: @This(), desc: c.WGPUTextureDescriptor) !c.WGPUTexture {
return self.vtable.allocTexture(self.ptr, desc); return self.vtable.allocTexture(self.ptr, desc);
} }
pub fn freeTexture(self: @This(), buf_raw: c.WGPUTexture) void { pub fn freeTexture(self: @This(), raw: c.WGPUTexture) void {
self.vtable.freeTexture(self.ptr, buf_raw); self.vtable.freeTexture(self.ptr, raw);
} }
pub fn allocTextureView(self: @This(), texture: c.WGPUTexture, desc: c.WGPUTextureViewDescriptor) !c.WGPUTextureView { pub fn allocTextureView(self: @This(), texture: c.WGPUTexture, desc: c.WGPUTextureViewDescriptor) !c.WGPUTextureView {
return self.vtable.allocTextureView(self.ptr, texture, desc); return self.vtable.allocTextureView(self.ptr, texture, desc);
} }
pub fn freeTextureView(self: @This(), buf_raw: c.WGPUTextureView) void { pub fn freeTextureView(self: @This(), raw: c.WGPUTextureView) void {
self.vtable.freeTextureView(self.ptr, buf_raw); self.vtable.freeTextureView(self.ptr, raw);
}
pub fn allocRenderPipeline(self: @This(), desc: c.WGPURenderPipelineDescriptor) !c.WGPURenderPipeline {
return self.vtable.allocRenderPipeline(self.ptr, desc);
}
pub fn freeRenderPipeline(self: @This(), raw: c.WGPURenderPipeline) void {
self.vtable.freeRenderPipeline(self.ptr, raw);
}
pub fn allocComputePipeline(self: @This(), desc: c.WGPUComputePipelineDescriptor) !c.WGPUComputePipeline {
return self.vtable.allocComputePipeline(self.ptr, desc);
}
pub fn freeComputePipeline(self: @This(), raw: c.WGPUComputePipeline) void {
self.vtable.freeComputePipeline(self.ptr, raw);
} }
-129
View File
@@ -1,129 +0,0 @@
const std = @import("std");
const GpuDevice = @import("GpuDevice.zig");
const GpuAllocator = @import("GpuAllocator.zig");
const GpuTextureFormat = @import("lib.zig").GpuTextureFormat;
const c = @import("utils.zig").c;
device: GpuDevice,
tracked_buffers: std.AutoHashMap(c.WGPUBuffer, c.WGPUBufferDescriptor),
tracked_textures: std.AutoHashMap(c.WGPUTexture, c.WGPUTextureDescriptor),
tracked_views: std.AutoHashMap(c.WGPUTextureView, c.WGPUTextureViewDescriptor),
allocated_vram_bytes: u64 = 0,
pub fn init(cpu_allocator: std.mem.Allocator, device: GpuDevice) @This() {
return .{
.device = device,
.tracked_buffers = .init(cpu_allocator),
.tracked_textures = .init(cpu_allocator),
.tracked_views = .init(cpu_allocator),
};
}
pub fn deinit(self: *@This()) void {
var it_buffer = self.tracked_buffers.keyIterator();
while (it_buffer.next()) |buf_ptr| {
c.wgpuBufferDestroy(buf_ptr.*);
c.wgpuBufferRelease(buf_ptr.*);
}
self.tracked_buffers.deinit();
var it_texture = self.tracked_textures.keyIterator();
while (it_texture.next()) |tex_ptr|
c.wgpuTextureRelease(tex_ptr.*);
self.tracked_textures.deinit();
var it_view = self.tracked_views.keyIterator();
while (it_view.next()) |view_ptr|
c.wgpuTextureViewRelease(view_ptr.*);
self.tracked_views.deinit();
}
/// Returns the type-erased immutable interface wrapper
pub fn gpuAllocator(self: *@This()) GpuAllocator {
return .{
.device = self.device,
.ptr = self,
.vtable = &.{
.allocBuffer = allocBuffer,
.freeBuffer = freeBuffer,
.allocTexture = allocTexture,
.freeTexture = freeTexture,
.allocTextureView = allocTextureView,
.freeTextureView = freeTextureView,
},
};
}
fn allocBuffer(ctx: *anyopaque, desc: c.WGPUBufferDescriptor) anyerror!c.WGPUBuffer {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (desc.size > self.device.limits.maxBufferSize)
return error.SingleBufferExceedsLimit;
if (desc.size + self.allocated_vram_bytes > self.device.config.vram_bytes_limit)
return error.ExceedsVramBudget;
const buf = c.wgpuDeviceCreateBuffer(self.device.device, &desc) orelse return error.BufferAlloc;
errdefer {
c.wgpuBufferDestroy(buf);
c.wgpuBufferRelease(buf);
}
try self.tracked_buffers.put(buf, desc);
self.allocated_vram_bytes += desc.size;
return buf;
}
fn freeBuffer(ctx: *anyopaque, raw: c.WGPUBuffer) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_buffers.fetchRemove(raw)) |kv| {
c.wgpuBufferDestroy(raw);
c.wgpuBufferRelease(raw);
self.allocated_vram_bytes -= kv.value.size;
}
}
fn allocTexture(ctx: *anyopaque, desc: c.WGPUTextureDescriptor) anyerror!c.WGPUTexture {
const self: *@This() = @ptrCast(@alignCast(ctx));
const format: GpuTextureFormat = @enumFromInt(desc.format);
const bytes_size = desc.size.width * desc.size.height * format.bytesPerPixel();
if (bytes_size > self.device.limits.maxBufferSize)
return error.SingleBufferExceedsLimit;
if (bytes_size + self.allocated_vram_bytes > self.device.config.vram_bytes_limit)
return error.ExceedsVramBudget;
const texture = c.wgpuDeviceCreateTexture(self.device.device, &desc) orelse return error.Texture;
try self.tracked_textures.put(texture, desc);
self.allocated_vram_bytes += bytes_size;
return texture;
}
fn freeTexture(ctx: *anyopaque, raw: c.WGPUTexture) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_textures.fetchRemove(raw)) |kv| {
c.wgpuTextureRelease(raw);
const desc = kv.value;
const format: GpuTextureFormat = @enumFromInt(desc.format);
const bytes_size = desc.size.width * desc.size.height * format.bytesPerPixel();
self.allocated_vram_bytes -= bytes_size;
}
}
fn allocTextureView(ctx: *anyopaque, texture: c.WGPUTexture, desc: c.WGPUTextureViewDescriptor) anyerror!c.WGPUTextureView {
const self: *@This() = @ptrCast(@alignCast(ctx));
const view = c.wgpuTextureCreateView(texture, &desc) orelse return error.View;
try self.tracked_views.put(view, desc);
return view;
}
fn freeTextureView(ctx: *anyopaque, raw: c.WGPUTextureView) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_views.remove(raw))
c.wgpuTextureViewRelease(raw);
}
+163
View File
@@ -0,0 +1,163 @@
const std = @import("std");
const GpuDevice = @import("GpuDevice.zig");
const GpuAllocator = @import("GpuAllocator.zig");
const GpuTextureFormat = @import("lib.zig").GpuTextureFormat;
const c = @import("utils.zig").c;
child_allocator: GpuAllocator, // I use Zig naming child_allocator, but that should be a parent for me. Likely something idk
tracked_buffers: std.AutoHashMap(c.WGPUBuffer, c.WGPUBufferDescriptor),
tracked_textures: std.AutoHashMap(c.WGPUTexture, c.WGPUTextureDescriptor),
tracked_views: std.AutoHashMap(c.WGPUTextureView, c.WGPUTextureViewDescriptor),
tracked_renders: std.AutoHashMap(c.WGPURenderPipeline, c.WGPURenderPipelineDescriptor),
tracked_computes: std.AutoHashMap(c.WGPUComputePipeline, c.WGPUComputePipelineDescriptor),
allocated_vram_bytes: u64 = 0,
pub fn init(cpu_allocator: std.mem.Allocator, child_allocator: GpuAllocator) @This() {
return .{
.child_allocator = child_allocator,
.tracked_buffers = .init(cpu_allocator),
.tracked_textures = .init(cpu_allocator),
.tracked_views = .init(cpu_allocator),
.tracked_computes = .init(cpu_allocator),
.tracked_renders = .init(cpu_allocator),
};
}
pub fn deinit(self: *@This()) void {
var it_buffer = self.tracked_buffers.keyIterator();
while (it_buffer.next()) |buf_ptr|
self.child_allocator.freeBuffer(buf_ptr.*);
self.tracked_buffers.deinit();
var it_tex = self.tracked_textures.keyIterator();
while (it_tex.next()) |buf_ptr|
self.child_allocator.freeTexture(buf_ptr.*);
self.tracked_textures.deinit();
var it_view = self.tracked_views.keyIterator();
while (it_view.next()) |buf_ptr|
self.child_allocator.freeTextureView(buf_ptr.*);
self.tracked_views.deinit();
var it_render = self.tracked_renders.keyIterator();
while (it_render.next()) |buf_ptr|
self.child_allocator.freeRenderPipeline(buf_ptr.*);
self.tracked_renders.deinit();
var it_compute = self.tracked_computes.keyIterator();
while (it_compute.next()) |buf_ptr|
self.child_allocator.freeComputePipeline(buf_ptr.*);
self.tracked_computes.deinit();
}
/// Returns the type-erased immutable interface wrapper
pub fn gpuAllocator(self: *@This()) GpuAllocator {
return .{
.device = self.child_allocator.device,
.ptr = self,
.vtable = &.{
.allocBuffer = allocBuffer,
.freeBuffer = freeBuffer,
.allocTexture = allocTexture,
.freeTexture = freeTexture,
.allocTextureView = allocTextureView,
.freeTextureView = freeTextureView,
.allocRenderPipeline = allocRenderPipeline,
.freeRenderPipeline = freeRenderPipeline,
.allocComputePipeline = allocComputePipeline,
.freeComputePipeline = freeComputePipeline,
},
};
}
// NOTE: I use ensureTotalCapacity so I know that try self.tracked_x.put will not fail!
// Like that I dont have to use errdefer to release what I just allocated in VRAM
fn allocBuffer(ctx: *anyopaque, desc: c.WGPUBufferDescriptor) anyerror!c.WGPUBuffer {
const self: *@This() = @ptrCast(@alignCast(ctx));
try self.tracked_buffers.ensureTotalCapacity(self.tracked_buffers.count() + 1);
const raw = try self.child_allocator.allocBuffer(desc);
self.tracked_buffers.putAssumeCapacity(raw, desc);
self.allocated_vram_bytes += desc.size;
return raw;
}
fn freeBuffer(ctx: *anyopaque, raw: c.WGPUBuffer) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_buffers.fetchRemove(raw)) |kv| {
self.child_allocator.freeBuffer(raw);
self.allocated_vram_bytes -= kv.value.size;
}
}
fn allocTexture(ctx: *anyopaque, desc: c.WGPUTextureDescriptor) anyerror!c.WGPUTexture {
const self: *@This() = @ptrCast(@alignCast(ctx));
try self.tracked_textures.ensureTotalCapacity(self.tracked_textures.count() + 1);
const format: GpuTextureFormat = @enumFromInt(desc.format);
const bytes_size = desc.size.width * desc.size.height * format.bytesPerPixel();
if (bytes_size + self.allocated_vram_bytes > self.child_allocator.device.config.vram_bytes_limit)
return error.ExceedsVramBudget;
const raw = try self.child_allocator.allocTexture(desc);
self.tracked_textures.putAssumeCapacity(raw, desc);
self.allocated_vram_bytes += bytes_size;
return raw;
}
fn freeTexture(ctx: *anyopaque, raw: c.WGPUTexture) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_textures.fetchRemove(raw)) |kv| {
self.child_allocator.freeTexture(raw);
const desc = kv.value;
const format: GpuTextureFormat = @enumFromInt(desc.format);
const bytes_size = desc.size.width * desc.size.height * format.bytesPerPixel();
self.allocated_vram_bytes -= bytes_size;
}
}
fn allocTextureView(ctx: *anyopaque, texture: c.WGPUTexture, desc: c.WGPUTextureViewDescriptor) anyerror!c.WGPUTextureView {
const self: *@This() = @ptrCast(@alignCast(ctx));
try self.tracked_views.ensureTotalCapacity(self.tracked_views.count() + 1);
const raw = try self.child_allocator.allocTextureView(texture, desc);
self.tracked_views.putAssumeCapacity(raw, desc);
return raw;
}
fn freeTextureView(ctx: *anyopaque, raw: c.WGPUTextureView) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_views.remove(raw))
self.child_allocator.freeTextureView(raw);
}
fn allocRenderPipeline(ctx: *anyopaque, desc: c.WGPURenderPipelineDescriptor) anyerror!c.WGPURenderPipeline {
const self: *@This() = @ptrCast(@alignCast(ctx));
try self.tracked_renders.ensureTotalCapacity(self.tracked_renders.count() + 1);
const raw = try self.child_allocator.allocRenderPipeline(desc);
self.tracked_renders.putAssumeCapacity(raw, desc);
return raw;
}
fn freeRenderPipeline(ctx: *anyopaque, raw: c.WGPURenderPipeline) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_renders.remove(raw))
self.child_allocator.freeRenderPipeline(raw);
}
fn allocComputePipeline(ctx: *anyopaque, desc: c.WGPUComputePipelineDescriptor) anyerror!c.WGPUComputePipeline {
const self: *@This() = @ptrCast(@alignCast(ctx));
try self.tracked_computes.ensureTotalCapacity(self.tracked_computes.count() + 1);
const raw = try self.child_allocator.allocComputePipeline(desc);
self.tracked_computes.putAssumeCapacity(raw, desc);
return raw;
}
fn freeComputePipeline(ctx: *anyopaque, raw: c.WGPUComputePipeline) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_computes.remove(raw))
self.child_allocator.freeComputePipeline(raw);
}
+6 -6
View File
@@ -20,30 +20,30 @@ pub const ComputeDef = struct {
}; };
pip: c.WGPUComputePipeline, pip: c.WGPUComputePipeline,
gloc: GpuAllocator,
def: ComputeDef, def: ComputeDef,
pub fn init(device: GpuDevice, wgsl: []const u8, def: ComputeDef) !@This() { pub fn init(gloc: GpuAllocator, wgsl: []const u8, def: ComputeDef) !@This() {
var wgsl_src = c.WGPUShaderSourceWGSL{ var wgsl_src = c.WGPUShaderSourceWGSL{
.chain = .{ .sType = c.WGPUSType_ShaderSourceWGSL }, .chain = .{ .sType = c.WGPUSType_ShaderSourceWGSL },
.code = sv(wgsl), .code = sv(wgsl),
}; };
const shader = c.wgpuDeviceCreateShaderModule(device.device, &.{ const shader = c.wgpuDeviceCreateShaderModule(gloc.device.device, &.{
.nextInChain = @ptrCast(&wgsl_src), .nextInChain = @ptrCast(&wgsl_src),
}) orelse return error.Shader; }) orelse return error.Shader;
defer c.wgpuShaderModuleRelease(shader); defer c.wgpuShaderModuleRelease(shader);
const pip = c.wgpuDeviceCreateComputePipeline(device.device, &.{ const pip = try gloc.allocComputePipeline(.{ .compute = .{ .module = shader, .entryPoint = sv("main") } });
.compute = .{ .module = shader, .entryPoint = sv("main") },
}) orelse return error.Pipeline;
return .{ return .{
.gloc = gloc,
.pip = pip, .pip = pip,
.def = def, .def = def,
}; };
} }
pub fn deinit(self: @This()) void { pub fn deinit(self: @This()) void {
c.wgpuComputePipelineRelease(self.pip); self.gloc.freeComputePipeline(self.pip);
} }
/// Execute the compute pass with arbitrary buffer bindings via a tuple. /// Execute the compute pass with arbitrary buffer bindings via a tuple.
+74
View File
@@ -1,6 +1,8 @@
const std = @import("std"); const std = @import("std");
const c = @import("utils.zig").c; const c = @import("utils.zig").c;
const sv = @import("utils.zig").sv; const sv = @import("utils.zig").sv;
const GpuAllocator = @import("GpuAllocator.zig");
const GpuTextureFormat = @import("lib.zig").GpuTextureFormat;
// TODO: Make Allocator more zig like // TODO: Make Allocator more zig like
// - GpuDevice can return a GpuAllocator that just allocate and nothing else // - GpuDevice can return a GpuAllocator that just allocate and nothing else
@@ -132,3 +134,75 @@ fn onDevice(
const ctx: *Ctx = @ptrCast(@alignCast(userdata1.?)); const ctx: *Ctx = @ptrCast(@alignCast(userdata1.?));
ctx.device = device; ctx.device = device;
} }
// Allocation stuff
/// Returns the type-erased immutable interface wrapper
pub fn gpuAllocator(self: *const @This()) GpuAllocator {
return .{
.device = self.*,
.ptr = @ptrCast(@constCast(self)),
.vtable = &.{
.allocBuffer = allocBuffer,
.freeBuffer = freeBuffer,
.allocTexture = allocTexture,
.freeTexture = freeTexture,
.allocTextureView = allocTextureView,
.freeTextureView = freeTextureView,
.allocRenderPipeline = allocRenderPipeline,
.freeRenderPipeline = freeRenderPipeline,
.allocComputePipeline = allocComputePipeline,
.freeComputePipeline = freeComputePipeline,
},
};
}
fn allocBuffer(ctx: *anyopaque, desc: c.WGPUBufferDescriptor) anyerror!c.WGPUBuffer {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (desc.size > self.limits.maxBufferSize)
return error.SingleBufferExceedsLimit;
return c.wgpuDeviceCreateBuffer(self.device, &desc) orelse return error.BufferAlloc;
}
fn freeBuffer(_: *anyopaque, raw: c.WGPUBuffer) void {
c.wgpuBufferDestroy(raw);
c.wgpuBufferRelease(raw);
}
fn allocTexture(ctx: *anyopaque, desc: c.WGPUTextureDescriptor) anyerror!c.WGPUTexture {
const self: *@This() = @ptrCast(@alignCast(ctx));
const format: GpuTextureFormat = @enumFromInt(desc.format);
if (desc.size.width * desc.size.height * format.bytesPerPixel() > self.limits.maxBufferSize)
return error.SingleBufferExceedsLimit;
return c.wgpuDeviceCreateTexture(self.device, &desc) orelse return error.Texture;
}
fn freeTexture(_: *anyopaque, raw: c.WGPUTexture) void {
c.wgpuTextureRelease(raw);
}
fn allocTextureView(_: *anyopaque, texture: c.WGPUTexture, desc: c.WGPUTextureViewDescriptor) anyerror!c.WGPUTextureView {
return c.wgpuTextureCreateView(texture, &desc) orelse return error.View;
}
fn freeTextureView(_: *anyopaque, raw: c.WGPUTextureView) void {
c.wgpuTextureViewRelease(raw);
}
fn allocRenderPipeline(ctx: *anyopaque, desc: c.WGPURenderPipelineDescriptor) anyerror!c.WGPURenderPipeline {
const self: *@This() = @ptrCast(@alignCast(ctx));
return c.wgpuDeviceCreateRenderPipeline(self.device, &desc) orelse return error.Pipeline;
}
fn freeRenderPipeline(_: *anyopaque, raw: c.WGPURenderPipeline) void {
c.wgpuRenderPipelineRelease(raw);
}
fn allocComputePipeline(ctx: *anyopaque, desc: c.WGPUComputePipelineDescriptor) anyerror!c.WGPUComputePipeline {
const self: *@This() = @ptrCast(@alignCast(ctx));
return c.wgpuDeviceCreateComputePipeline(self.device, &desc) orelse return error.Pipeline;
}
fn freeComputePipeline(_: *anyopaque, raw: c.WGPUComputePipeline) void {
c.wgpuComputePipelineRelease(raw);
}
+7 -5
View File
@@ -32,15 +32,16 @@ const GpuPrimitiveTopology = enum(c_uint) {
Force32 = 0x7FFFFFFF, Force32 = 0x7FFFFFFF,
}; };
gloc: GpuAllocator,
pip: c.WGPURenderPipeline, pip: c.WGPURenderPipeline,
def: GpuRenderDef, def: GpuRenderDef,
pub fn init(device: GpuDevice, wgsl: []const u8, def: GpuRenderDef) !@This() { pub fn init(gloc: GpuAllocator, wgsl: []const u8, def: GpuRenderDef) !@This() {
var wgsl_src = c.WGPUShaderSourceWGSL{ var wgsl_src = c.WGPUShaderSourceWGSL{
.chain = .{ .sType = c.WGPUSType_ShaderSourceWGSL }, .chain = .{ .sType = c.WGPUSType_ShaderSourceWGSL },
.code = sv(wgsl), .code = sv(wgsl),
}; };
const shader = c.wgpuDeviceCreateShaderModule(device.device, &.{ const shader = c.wgpuDeviceCreateShaderModule(gloc.device.device, &.{
.nextInChain = @ptrCast(&wgsl_src), .nextInChain = @ptrCast(&wgsl_src),
}) orelse return error.Shader; }) orelse return error.Shader;
defer c.wgpuShaderModuleRelease(shader); defer c.wgpuShaderModuleRelease(shader);
@@ -66,7 +67,7 @@ pub fn init(device: GpuDevice, wgsl: []const u8, def: GpuRenderDef) !@This() {
}; };
// 3. Compile the Complete Render Pipeline // 3. Compile the Complete Render Pipeline
const pip = c.wgpuDeviceCreateRenderPipeline(device.device, &.{ const pip = try gloc.allocRenderPipeline(.{
.vertex = .{ .vertex = .{
.module = shader, .module = shader,
.entryPoint = sv(def.vertex_entry), .entryPoint = sv(def.vertex_entry),
@@ -83,16 +84,17 @@ pub fn init(device: GpuDevice, wgsl: []const u8, def: GpuRenderDef) !@This() {
.alphaToCoverageEnabled = 0, .alphaToCoverageEnabled = 0,
}, },
.fragment = &fragment_state, .fragment = &fragment_state,
}) orelse return error.Pipeline; });
return .{ return .{
.gloc = gloc,
.pip = pip, .pip = pip,
.def = def, .def = def,
}; };
} }
pub fn deinit(self: @This()) void { pub fn deinit(self: @This()) void {
c.wgpuRenderPipelineRelease(self.pip); self.gloc.freeRenderPipeline(self.pip);
} }
/// Execute the render pass targeting a specific frame texture view. /// Execute the render pass targeting a specific frame texture view.
+1 -1
View File
@@ -1,5 +1,5 @@
pub const GpuAllocator = @import("GpuAllocator.zig"); pub const GpuAllocator = @import("GpuAllocator.zig");
pub const GpuArena = @import("GpuArena.zig"); pub const GpuArenaAllocator = @import("GpuArenaAllocator.zig");
pub const GpuBuffer = @import("GpuBuffer.zig"); pub const GpuBuffer = @import("GpuBuffer.zig");
pub const GpuDevice = @import("GpuDevice.zig"); pub const GpuDevice = @import("GpuDevice.zig");
pub const GpuCompute = @import("GpuCompute.zig"); pub const GpuCompute = @import("GpuCompute.zig");