16 Commits
Author SHA1 Message Date
adrien e03cb3f285 Added back VRAM budget check for GpuBuffer, must be forgotten when refactoring it 2026-05-22 00:17:54 +02:00
adrien 14def5d555 Updated example in README 2026-05-21 23:38:22 +02:00
adrien e61c5f775d Prevent building example when use as module 2026-05-21 23:33:54 +02:00
AdrienBouvais d503ce7dea Added optional label in definitions and added logs when alloc, free and device info 2026-05-21 10:26:20 +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
adrien af210e2fb2 Working self contained rendering (simple circle) 2026-05-20 11:46:06 +02:00
adrien 545c4b98e9 Create a GpuTextureView 2026-05-20 10:56:35 +02:00
adrien 45c0f3180e Created a GpuTextureDef 2026-05-20 09:55:34 +02:00
adrien fc57bee3af Created GpuPrimitiveTolopogy to replace c.WGPUPrimitiveTopology 2026-05-20 09:37:46 +02:00
adrien bcb1b1e98b GpuRender now take a GpuTextureFormat and not a c.WGPUTextureFormat 2026-05-20 09:24:37 +02:00
22 changed files with 857 additions and 551 deletions
+144 -47
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,21 +34,23 @@ 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 = &.{ .{
.label = "add",
.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) },
} }, },
},
); );
defer add_cp.deinit();
// 4. Setup CPU data // 4. Setup CPU data
const len: usize = 16; const len: usize = 16;
@@ -62,12 +66,13 @@ pub fn main(init: std.process.Init) !void {
// 5. Initialize raw GPU Buffers // 5. Initialize raw GPU Buffers
const byte_size = len * @sizeOf(f16); const byte_size = len * @sizeOf(f16);
const buf_a = try GpuBuffer.init(gloc, byte_size, .initMany(&.{ .Storage, .CopyDst, .CopySrc })); const buf_a = try GpuBuffer.init(gloc, .{ .label = "a", .size = byte_size, .usage = .initMany(&.{ .Storage, .CopyDst, .CopySrc }) });
const buf_b = try GpuBuffer.init(gloc, byte_size, .initMany(&.{ .Storage, .CopyDst, .CopySrc })); const buf_b = try GpuBuffer.init(gloc, .{ .label = "b", .size = byte_size, .usage = .initMany(&.{ .Storage, .CopyDst, .CopySrc }) });
const buf_out = try GpuBuffer.init(gloc, byte_size, .initMany(&.{ .Storage, .CopyDst, .CopySrc })); const buf_out = try GpuBuffer.init(gloc, .{ .label = "out", .size = byte_size, .usage = .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);
@@ -84,53 +89,145 @@ 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 GpuArenaAllocator = gpu.GpuArenaAllocator;
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. Init VRAM Arena
var grena = GpuArenaAllocator.init(allocator, device.gpuAllocator());
defer grena.deinit();
const gloc = grena.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. Load Texture into GpuBuffer
const cpu_staging_cpu = try texture.buffCopy(gloc);
defer cpu_staging_cpu.deinit();
// 8. Read GpuBuffer to CPU
// This need to be free manually because CPU memory
const pixels = try cpu_staging_cpu.read(allocator, u8);
defer allocator.free(pixels);
// 9. Write 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,
+1 -34
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,39 +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);
} }
const exe = b.addExecutable(.{
.name = "circle",
.root_module = b.createModule(.{
.root_source_file = b.path("src/circle.zig"),
.target = target,
.optimize = optimize,
.imports = &.{},
}),
});
exe.root_module.addIncludePath(b.path("libs/wgpu-native/include"));
exe.root_module.addLibraryPath(b.path("libs/wgpu-native/lib"));
exe.root_module.addObjectFile(b.path("libs/wgpu-native/lib/libwgpu_native.a"));
// Platform-specific system frameworks needed by wgpu-native
if (t.os.tag == .macos) {
exe.root_module.linkFramework("Metal", .{});
exe.root_module.linkFramework("QuartzCore", .{});
exe.root_module.linkFramework("Foundation", .{});
exe.root_module.linkFramework("CoreGraphics", .{});
} else if (t.os.tag == .windows) {
exe.root_module.linkSystemLibrary("d3d12", .{});
exe.root_module.linkSystemLibrary("dxgi", .{});
exe.root_module.linkSystemLibrary("user32", .{});
} else {
exe.root_module.linkSystemLibrary("vulkan", .{});
exe.root_module.linkSystemLibrary("gcc_s", .{});
} }
b.installArtifact(exe);
const run_step = b.step("circle", "Run circle");
const run_cmd = b.addRunArtifact(exe);
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
+9 -9
View File
@@ -1,11 +1,13 @@
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;
pub const std_options = std.Options{ .log_level = .info };
/// Minimal implementation of a f16 Vector /// Minimal implementation of a f16 Vector
const Vec = struct { const Vec = struct {
buf: GpuBuffer, buf: GpuBuffer,
@@ -14,11 +16,10 @@ const Vec = struct {
// Changed: gloc is passed by value (const) // Changed: gloc is passed by value (const)
pub fn initZero(gloc: GpuAllocator, len: usize) !Vec { pub fn initZero(gloc: GpuAllocator, len: usize) !Vec {
return .{ return .{
.buf = try GpuBuffer.init( .buf = try GpuBuffer.init(gloc, .{
gloc, .size = len * @sizeOf(f16),
len * @sizeOf(f16), .usage = .initMany(&.{ .Storage, .CopyDst, .CopySrc }),
.initMany(&.{ .Storage, .CopyDst, .CopySrc }), }),
),
.len = len, .len = len,
}; };
} }
@@ -60,12 +61,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) },
+76
View File
@@ -0,0 +1,76 @@
const std = @import("std");
const gpu = @import("gpu");
const GpuDevice = gpu.GpuDevice;
const GpuArenaAllocator = gpu.GpuArenaAllocator;
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. Init VRAM Arena
var grena = GpuArenaAllocator.init(allocator, device.gpuAllocator());
defer grena.deinit();
const gloc = grena.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. Load Texture into GpuBuffer
const cpu_staging_cpu = try texture.buffCopy(gloc);
defer cpu_staging_cpu.deinit();
// 8. Read GpuBuffer to CPU
// This need to be free manually because CPU memory
const pixels = try cpu_staging_cpu.read(allocator, u8);
defer allocator.free(pixels);
// 9. Write 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]);
}
}
+13 -10
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,21 +13,23 @@ 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 = &.{ .{
.label = "add",
.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) },
} }, },
},
); );
defer add_cp.deinit();
// 4. Setup CPU data // 4. Setup CPU data
const len: usize = 16; const len: usize = 16;
@@ -43,12 +45,13 @@ pub fn main(init: std.process.Init) !void {
// 5. Initialize raw GPU Buffers // 5. Initialize raw GPU Buffers
const byte_size = len * @sizeOf(f16); const byte_size = len * @sizeOf(f16);
const buf_a = try GpuBuffer.init(gloc, byte_size, .initMany(&.{ .Storage, .CopyDst, .CopySrc })); const buf_a = try GpuBuffer.init(gloc, .{ .label = "a", .size = byte_size, .usage = .initMany(&.{ .Storage, .CopyDst, .CopySrc }) });
const buf_b = try GpuBuffer.init(gloc, byte_size, .initMany(&.{ .Storage, .CopyDst, .CopySrc })); const buf_b = try GpuBuffer.init(gloc, .{ .label = "b", .size = byte_size, .usage = .initMany(&.{ .Storage, .CopyDst, .CopySrc }) });
const buf_out = try GpuBuffer.init(gloc, byte_size, .initMany(&.{ .Storage, .CopyDst, .CopySrc })); const buf_out = try GpuBuffer.init(gloc, .{ .label = "out", .size = byte_size, .usage = .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);
-77
View File
@@ -1,77 +0,0 @@
// I am using this mnist reduced dataset https://www.kaggle.com/datasets/mohamedgamal07/reduced-mnist
const std = @import("std");
const gpu = @import("gpu");
const GpuDevice = gpu.GpuDevice;
const GpuArena = gpu.GpuArena;
const GpuBuffer = gpu.GpuBuffer;
const GpuProcess = gpu.GpuProcess;
const BATCHSIZE = 10;
const EPOCH = 10;
pub fn main(init: std.process.Init) !void {
const allocator = init.gpa;
const io = init.io;
// 1. Open GPU Device
const device = try GpuDevice.init(.{});
defer device.deinit();
// 2. Create a GPU Arena to manage VRAM
var grena = GpuArena.init(allocator, device);
defer grena.deinit();
const gloc = grena.gpuAllocator();
// 3. Load the WGSL compute pipeline
const add_process = try GpuProcess.init(device, @embedFile("shaders/add.wgsl"));
defer add_process.deinit();
var train_dir = try std.Io.Dir.cwd().openDir(io, "mnist/train", .{});
var images: [BATCHSIZE * 28 * 28]f16 = undefined;
for (EPOCH) |epoch| {
// Load random images from train dir
train_dir.openDir(io, "0", .{});
for (BATCHSIZE) |i| {
const file = try train_dir.openFile(io, "0.jpg", .{});
images[28 * 28 * i .. 28 * 28 * (i + 1)] = file.read
}
}
// 4. Setup CPU data
const len: usize = 16;
const data_a = try allocator.alloc(f16, len);
defer allocator.free(data_a);
const data_b = try allocator.alloc(f16, len);
defer allocator.free(data_b);
for (0..len) |i| {
data_a[i] = @floatFromInt(i);
data_b[i] = @floatFromInt(len - 1 - i);
}
// 5. Initialize raw GPU Buffers
// We pass the EnumSet inline using `.initMany` since the Enum itself isn't exported
const byte_size = len * @sizeOf(f16);
const buf_a = 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 }));
// Note: The buffers are safely tied to the GpuArena which will automatically
// release them at the end. You can also manually call buf_x.deinit() if desired.
// 6. Transfer data from CPU slices to GPU Buffers
try buf_a.load(f16, data_a);
try buf_b.load(f16, data_b);
// 7. Dispatch the Compute Process
// We pass the data type (f16) to allow GpuProcess to calculate chunks correctly
try add_process.run(gloc, f16, buf_a, buf_b, buf_out);
// 8. Map and copy the resulting buffer back to the CPU
const out = try buf_out.read(allocator, f16);
defer allocator.free(out);
std.debug.print("Result: {any}\n", .{out});
}
+34 -4
View File
@@ -6,6 +6,12 @@ pub const VTable = struct {
freeBuffer: *const fn (ctx: *anyopaque, buf_raw: c.WGPUBuffer) void, freeBuffer: *const fn (ctx: *anyopaque, buf_raw: c.WGPUBuffer) void,
allocTexture: *const fn (ctx: *anyopaque, desc: c.WGPUTextureDescriptor) anyerror!c.WGPUTexture, allocTexture: *const fn (ctx: *anyopaque, desc: c.WGPUTextureDescriptor) anyerror!c.WGPUTexture,
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,
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,
@@ -16,14 +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 {
return self.vtable.allocTextureView(self.ptr, texture, desc);
}
pub fn freeTextureView(self: @This(), raw: c.WGPUTextureView) void {
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);
} }
-107
View File
@@ -1,107 +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),
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),
};
}
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();
}
/// 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,
},
};
}
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, buf_raw: c.WGPUBuffer) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_buffers.fetchRemove(buf_raw)) |kv| {
c.wgpuBufferDestroy(buf_raw);
c.wgpuBufferRelease(buf_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, texture_raw: c.WGPUTexture) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_textures.fetchRemove(texture_raw)) |kv| {
c.wgpuTextureRelease(texture_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;
}
}
+222
View File
@@ -0,0 +1,222 @@
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;
const viewStr = @import("utils.zig").viewStr;
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 {
std.log.debug("Freeing GpuArenaAllocator (Used VRAM: {}/{} MB)", .{
self.allocated_vram_bytes / 1024 / 1024,
self.child_allocator.device.def.vram_bytes_limit / 1024 / 1024,
});
var it_buffer = self.tracked_buffers.keyIterator();
while (it_buffer.next()) |buf_ptr|
freeBuffer(self, buf_ptr.*);
self.tracked_buffers.deinit();
var it_tex = self.tracked_textures.keyIterator();
while (it_tex.next()) |buf_ptr|
freeTexture(self, buf_ptr.*);
self.tracked_textures.deinit();
var it_view = self.tracked_views.keyIterator();
while (it_view.next()) |buf_ptr|
freeTextureView(self, buf_ptr.*);
self.tracked_views.deinit();
var it_render = self.tracked_renders.keyIterator();
while (it_render.next()) |buf_ptr|
freeRenderPipeline(self, buf_ptr.*);
self.tracked_renders.deinit();
var it_compute = self.tracked_computes.keyIterator();
while (it_compute.next()) |buf_ptr|
freeComputePipeline(self, buf_ptr.*);
self.tracked_computes.deinit();
std.log.debug("Freed GpuArenaAllocator (Used VRAM: {}/{} MB)", .{
self.allocated_vram_bytes / 1024 / 1024,
self.child_allocator.device.def.vram_bytes_limit / 1024 / 1024,
});
}
/// 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 bytes = desc.size;
if (bytes > self.child_allocator.device.limits.maxBufferSize)
return error.SingleBufferExceedsLimit;
if (bytes + self.allocated_vram_bytes > self.child_allocator.device.def.vram_bytes_limit)
return error.ExceedsVramBudget;
const raw = try self.child_allocator.allocBuffer(desc);
self.tracked_buffers.putAssumeCapacity(raw, desc);
self.allocated_vram_bytes += desc.size;
std.log.debug("Allocated Buffer '{s}': {d} B (Total VRAM: {}/{} MB)", .{
viewStr(desc.label),
desc.size,
self.allocated_vram_bytes / 1024 / 1024,
self.child_allocator.device.def.vram_bytes_limit / 1024 / 1024,
});
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;
std.log.debug("Freed Buffer '{s}' (Total VRAM: {}/{} MB)", .{
viewStr(kv.value.label),
self.allocated_vram_bytes / 1024 / 1024,
self.child_allocator.device.def.vram_bytes_limit / 1024 / 1024,
});
}
}
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.def.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;
std.log.debug("Allocated Texture '{s}': {d} B (Total VRAM: {}/{} MB)", .{
viewStr(desc.label),
bytes_size,
self.allocated_vram_bytes / 1024 / 1024,
self.child_allocator.device.def.vram_bytes_limit / 1024 / 1024,
});
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;
std.log.debug("Freed Texture '{s}' (Total VRAM: {}/{} MB)", .{
viewStr(desc.label),
self.allocated_vram_bytes / 1024 / 1024,
self.child_allocator.device.def.vram_bytes_limit / 1024 / 1024,
});
}
}
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);
std.log.debug("Allocated Texture View '{s}'", .{viewStr(desc.label)});
return raw;
}
fn freeTextureView(ctx: *anyopaque, raw: c.WGPUTextureView) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_views.fetchRemove(raw)) |kv| {
self.child_allocator.freeTextureView(raw);
const desc = kv.value;
std.log.debug("Freed Texture View '{s}'", .{viewStr(desc.label)});
}
}
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);
std.log.debug("Allocated Render Pipeline '{s}'", .{viewStr(desc.label)});
return raw;
}
fn freeRenderPipeline(ctx: *anyopaque, raw: c.WGPURenderPipeline) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_renders.fetchRemove(raw)) |kv| {
self.child_allocator.freeRenderPipeline(raw);
const desc = kv.value;
std.log.debug("Freed Render Pipeline '{s}'", .{viewStr(desc.label)});
}
}
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);
std.log.debug("Allocated Compute Pipeline '{s}'", .{viewStr(desc.label)});
return raw;
}
fn freeComputePipeline(ctx: *anyopaque, raw: c.WGPUComputePipeline) void {
const self: *@This() = @ptrCast(@alignCast(ctx));
if (self.tracked_computes.fetchRemove(raw)) |kv| {
self.child_allocator.freeComputePipeline(raw);
const desc = kv.value;
std.log.debug("Freed Compute Pipeline '{s}'", .{viewStr(desc.label)});
}
}
+22 -15
View File
@@ -1,6 +1,7 @@
const std = @import("std"); const std = @import("std");
const c = @import("utils.zig").c; const c = @import("utils.zig").c;
const GpuAllocator = @import("GpuAllocator.zig"); const GpuAllocator = @import("GpuAllocator.zig");
const svOpt = @import("utils.zig").svOpt;
raw: c.WGPUBuffer, raw: c.WGPUBuffer,
size: u64, size: u64,
@@ -21,16 +22,25 @@ const BufferUsage = enum(u64) {
QueryResolve = 0x0000000000000200, QueryResolve = 0x0000000000000200,
}; };
/// Allocates the underlying WebGPU handle and registers it to the parent GpuAllocator const GpuBufferDef = struct {
pub fn init(gloc: GpuAllocator, size: u64, usage: std.EnumSet(BufferUsage)) !@This() { label: ?[]const u8 = null,
size: u64,
usage: std.EnumSet(BufferUsage),
};
pub fn init(gloc: GpuAllocator, def: GpuBufferDef) !@This() {
var use: u64 = 0; var use: u64 = 0;
var iter = usage.iterator(); var iter = def.usage.iterator();
while (iter.next()) |flag| use |= @intFromEnum(flag); while (iter.next()) |flag| use |= @intFromEnum(flag);
// Automatically align the buffer size forward to a multiple of 4 bytes under the hood // Automatically align the buffer size forward to a multiple of 4 bytes under the hood
const aligned_size = std.mem.alignForward(u64, size, 4); const aligned_size = std.mem.alignForward(u64, def.size, 4);
const raw_handle = try gloc.allocBuffer(.{ .size = aligned_size, .usage = use }); const raw_handle = try gloc.allocBuffer(.{
.size = aligned_size,
.usage = use,
.label = svOpt(def.label),
});
return .{ return .{
.raw = raw_handle, .raw = raw_handle,
.size = aligned_size, .size = aligned_size,
@@ -39,17 +49,14 @@ pub fn init(gloc: GpuAllocator, size: u64, usage: std.EnumSet(BufferUsage)) !@Th
}; };
} }
/// Unregisters from the parent GpuAllocator and cleanly destroys GPU resources
pub fn deinit(self: @This()) void { pub fn deinit(self: @This()) void {
self.gloc.freeBuffer(self.raw); self.gloc.freeBuffer(self.raw);
} }
/// Native getConstMappedRange wrapper
pub fn getConstMappedRange(self: @This(), offset: u64, size: u64) ?*const anyopaque { pub fn getConstMappedRange(self: @This(), offset: u64, size: u64) ?*const anyopaque {
return c.wgpuBufferGetConstMappedRange(self.raw, offset, size); return c.wgpuBufferGetConstMappedRange(self.raw, offset, size);
} }
/// Native mapAsync wrapper
pub fn mapAsync( pub fn mapAsync(
self: @This(), self: @This(),
mode: c.WGPUMapMode, mode: c.WGPUMapMode,
@@ -60,12 +67,11 @@ pub fn mapAsync(
_ = c.wgpuBufferMapAsync(self.raw, mode, offset, size, callback_info); _ = c.wgpuBufferMapAsync(self.raw, mode, offset, size, callback_info);
} }
/// Native unmap wrapper
pub fn unmap(self: @This()) void { pub fn unmap(self: @This()) void {
c.wgpuBufferUnmap(self.raw); c.wgpuBufferUnmap(self.raw);
} }
/// CPU to GPU. /// CPU to GPU
pub fn load( pub fn load(
self: @This(), self: @This(),
T: type, T: type,
@@ -92,14 +98,15 @@ pub fn load(
} }
} }
/// GPU to CPU
pub fn read(self: @This(), alloc: std.mem.Allocator, T: type) ![]T { pub fn read(self: @This(), alloc: std.mem.Allocator, T: type) ![]T {
const out = try alloc.alloc(T, @divExact(self.size, @sizeOf(T))); const out = try alloc.alloc(T, @divExact(self.size, @sizeOf(T)));
const staging = try init( const staging = try init(self.gloc, .{
self.gloc, .size = self.size,
self.size, .usage = .initMany(&.{ .MapRead, .CopyDst }),
.initMany(&.{ .MapRead, .CopyDst }), .label = "staging_read_buffer",
); });
defer staging.deinit(); defer staging.deinit();
const enc = c.wgpuDeviceCreateCommandEncoder(self.gloc.device.device, null) orelse return error.Encoder; const enc = c.wgpuDeviceCreateCommandEncoder(self.gloc.device.device, null) orelse return error.Encoder;
+15 -10
View File
@@ -1,5 +1,6 @@
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 svOpt = @import("utils.zig").svOpt;
const GpuAllocator = @import("GpuAllocator.zig"); const GpuAllocator = @import("GpuAllocator.zig");
const GpuBuffer = @import("GpuBuffer.zig"); const GpuBuffer = @import("GpuBuffer.zig");
const GpuDevice = @import("GpuDevice.zig"); const GpuDevice = @import("GpuDevice.zig");
@@ -11,6 +12,7 @@ pub const Binding = struct {
}; };
pub const ComputeDef = struct { pub const ComputeDef = struct {
label: ?[]const u8 = null,
bindings: []const Binding, bindings: []const Binding,
workgroup_size: u32 = 256, workgroup_size: u32 = 256,
max_workgroups: u32 = 65535, max_workgroups: u32 = 65535,
@@ -20,30 +22,33 @@ 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(.{
.label = svOpt(def.label),
.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.
@@ -108,11 +113,11 @@ pub fn run(
defer if (info_buf) |b| b.deinit(); defer if (info_buf) |b| b.deinit();
if (self.def.append_info_buffer) { if (self.def.append_info_buffer) {
info_buf = try GpuBuffer.init( info_buf = try GpuBuffer.init(gloc, .{
gloc, .size = @sizeOf(u32),
@sizeOf(u32), .usage = .initMany(&.{ .Uniform, .CopyDst }),
.initMany(&.{ .Uniform, .CopyDst }), .label = "compute_info_buffer",
); });
c.wgpuQueueWriteBuffer(gloc.device.queue, info_buf.?.raw, 0, &elements_count, @sizeOf(u32)); c.wgpuQueueWriteBuffer(gloc.device.queue, info_buf.?.raw, 0, &elements_count, @sizeOf(u32));
entries_buf[entry_count] = .{ entries_buf[entry_count] = .{
+101 -6
View File
@@ -1,13 +1,17 @@
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 svOpt = @import("utils.zig").svOpt;
const GpuAllocator = @import("GpuAllocator.zig");
const GpuTextureFormat = @import("lib.zig").GpuTextureFormat;
const Ctx = struct { const Ctx = struct {
adapter: c.WGPUAdapter = null, adapter: c.WGPUAdapter = null,
device: c.WGPUDevice = null, device: c.WGPUDevice = null,
}; };
const GpuDeviceConfig = struct { const GpuDeviceDef = struct {
label: ?[]const u8 = null,
/// VRAM limit. Default 2 GB /// VRAM limit. Default 2 GB
vram_bytes_limit: u64 = 2 * 1024 * 1024 * 1024, vram_bytes_limit: u64 = 2 * 1024 * 1024 * 1024,
power_preference: enum(c_uint) { power_preference: enum(c_uint) {
@@ -24,9 +28,9 @@ device: c.WGPUDevice,
queue: c.WGPUQueue, queue: c.WGPUQueue,
limits: c.WGPULimits, limits: c.WGPULimits,
config: GpuDeviceConfig, def: GpuDeviceDef,
pub fn init(config: GpuDeviceConfig) !@This() { pub fn init(def: GpuDeviceDef) !@This() {
const instance = c.wgpuCreateInstance( const instance = c.wgpuCreateInstance(
&std.mem.zeroes(c.WGPUInstanceDescriptor), &std.mem.zeroes(c.WGPUInstanceDescriptor),
) orelse return error.NoInstance; ) orelse return error.NoInstance;
@@ -35,13 +39,25 @@ pub fn init(config: GpuDeviceConfig) !@This() {
var ctx = Ctx{}; var ctx = Ctx{};
_ = c.wgpuInstanceRequestAdapter( _ = c.wgpuInstanceRequestAdapter(
instance, instance,
&.{ .powerPreference = @intFromEnum(config.power_preference) }, &.{ .powerPreference = @intFromEnum(def.power_preference) },
.{ .callback = onAdapter, .userdata1 = &ctx }, .{ .callback = onAdapter, .userdata1 = &ctx },
); );
c.wgpuInstanceProcessEvents(instance); c.wgpuInstanceProcessEvents(instance);
const adapter = ctx.adapter orelse return error.NoAdapter; const adapter = ctx.adapter orelse return error.NoAdapter;
errdefer c.wgpuAdapterRelease(adapter); errdefer c.wgpuAdapterRelease(adapter);
var adapter_info = std.mem.zeroes(c.WGPUAdapterInfo);
_ = c.wgpuAdapterGetInfo(adapter, &adapter_info);
std.log.info("=== WebGPU Device Initialized ===", .{});
if (adapter_info.device.length > 0 and adapter_info.device.data != null) {
std.log.info(" Device Name : {s}", .{adapter_info.device.data[0..adapter_info.device.length]});
}
if (adapter_info.architecture.length > 0 and adapter_info.architecture.data != null) {
std.log.info(" Architecture : {s}", .{adapter_info.architecture.data[0..adapter_info.architecture.length]});
}
std.log.info(" Backend Type : {d}", .{adapter_info.backendType});
var supported_features = std.mem.zeroes(c.WGPUSupportedFeatures); var supported_features = std.mem.zeroes(c.WGPUSupportedFeatures);
c.wgpuAdapterGetFeatures(adapter, &supported_features); c.wgpuAdapterGetFeatures(adapter, &supported_features);
@@ -49,6 +65,11 @@ pub fn init(config: GpuDeviceConfig) !@This() {
supported_limits.nextInChain = null; supported_limits.nextInChain = null;
if (c.wgpuAdapterGetLimits(adapter, &supported_limits) != 1) return error.FailedToGetAdapterLimits; if (c.wgpuAdapterGetLimits(adapter, &supported_limits) != 1) return error.FailedToGetAdapterLimits;
std.log.info(" Max Buf Size : {d} MB", .{supported_limits.maxBufferSize / 1024 / 1024});
std.log.info(" Max Storage : {d} MB", .{supported_limits.maxStorageBufferBindingSize / 1024 / 1024});
std.log.info(" Max Workgroup: X: {d}, Y: {d}, Z: {d}", .{ supported_limits.maxComputeWorkgroupSizeX, supported_limits.maxComputeWorkgroupSizeY, supported_limits.maxComputeWorkgroupSizeZ });
std.log.info(" VRAM Budget : {d} MB", .{def.vram_bytes_limit / 1024 / 1024});
var has_f16 = false; var has_f16 = false;
for (0..supported_features.featureCount) |i| { for (0..supported_features.featureCount) |i| {
if (supported_features.features[i] == c.WGPUFeatureName_ShaderF16) { if (supported_features.features[i] == c.WGPUFeatureName_ShaderF16) {
@@ -56,6 +77,8 @@ pub fn init(config: GpuDeviceConfig) !@This() {
break; break;
} }
} }
std.log.info(" Shader F16 : {}", .{has_f16});
std.log.info("=================================", .{});
var feature_buf = [_]c.WGPUFeatureName{c.WGPUFeatureName_ShaderF16}; var feature_buf = [_]c.WGPUFeatureName{c.WGPUFeatureName_ShaderF16};
const required_features: []const c.WGPUFeatureName = const required_features: []const c.WGPUFeatureName =
@@ -63,7 +86,7 @@ pub fn init(config: GpuDeviceConfig) !@This() {
const device_descriptor = c.WGPUDeviceDescriptor{ const device_descriptor = c.WGPUDeviceDescriptor{
.nextInChain = null, .nextInChain = null,
.label = sv("TensorCompilerDevice"), .label = svOpt(def.label),
.requiredFeatureCount = required_features.len, .requiredFeatureCount = required_features.len,
.requiredFeatures = if (required_features.len > 0) required_features.ptr else null, .requiredFeatures = if (required_features.len > 0) required_features.ptr else null,
.requiredLimits = &supported_limits, .requiredLimits = &supported_limits,
@@ -82,7 +105,7 @@ pub fn init(config: GpuDeviceConfig) !@This() {
.device = device, .device = device,
.queue = c.wgpuDeviceGetQueue(device), .queue = c.wgpuDeviceGetQueue(device),
.limits = supported_limits, .limits = supported_limits,
.config = config, .def = def,
}; };
} }
@@ -127,3 +150,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);
}
+31 -14
View File
@@ -1,34 +1,49 @@
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 svOpt = @import("utils.zig").svOpt;
const GpuAllocator = @import("GpuAllocator.zig"); const GpuAllocator = @import("GpuAllocator.zig");
const GpuBuffer = @import("GpuBuffer.zig"); const GpuBuffer = @import("GpuBuffer.zig");
const GpuDevice = @import("GpuDevice.zig"); const GpuDevice = @import("GpuDevice.zig");
const GpuTextureView = @import("GpuTextureView.zig");
const GpuTextureFormat = @import("lib.zig").GpuTextureFormat;
pub const Binding = struct { pub const Binding = struct {
element_size: u32 = 0, element_size: u32 = 0,
}; };
pub const RenderDef = struct { pub const GpuRenderDef = struct {
label: ?[]const u8 = null,
bindings: []const Binding = &.{}, bindings: []const Binding = &.{},
/// The surface texture format we are rendering to (e.g., BGRA8Unorm) /// The surface texture format we are rendering to (e.g., BGRA8Unorm)
texture_format: c.WGPUTextureFormat, texture_format: GpuTextureFormat,
/// The names of the entry points inside your WGSL code /// The names of the entry points inside your WGSL code
vertex_entry: []const u8 = "vs_main", vertex_entry: []const u8 = "vs_main",
fragment_entry: []const u8 = "fs_main", fragment_entry: []const u8 = "fs_main",
/// Primitive topology, default to triangle list /// Primitive topology, default to triangle list
topology: c.WGPUPrimitiveTopology = c.WGPUPrimitiveTopology_TriangleList, topology: GpuPrimitiveTopology = .TriangleList,
}; };
pip: c.WGPURenderPipeline, const GpuPrimitiveTopology = enum(c_uint) {
def: RenderDef, Undefined = 0x00000000,
PointList = 0x00000001,
LineList = 0x00000002,
LineStrip = 0x00000003,
TriangleList = 0x00000004,
TriangleStrip = 0x00000005,
Force32 = 0x7FFFFFFF,
};
pub fn init(device: GpuDevice, wgsl: []const u8, def: RenderDef) !@This() { gloc: GpuAllocator,
pip: c.WGPURenderPipeline,
def: GpuRenderDef,
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);
@@ -40,7 +55,7 @@ pub fn init(device: GpuDevice, wgsl: []const u8, def: RenderDef) !@This() {
}; };
const color_target = c.WGPUColorTargetState{ const color_target = c.WGPUColorTargetState{
.format = def.texture_format, .format = @intFromEnum(def.texture_format),
.blend = &blend, .blend = &blend,
.writeMask = c.WGPUColorWriteMask_All, .writeMask = c.WGPUColorWriteMask_All,
}; };
@@ -54,13 +69,14 @@ pub fn init(device: GpuDevice, wgsl: []const u8, def: RenderDef) !@This() {
}; };
// 3. Compile the Complete Render Pipeline // 3. Compile the Complete Render Pipeline
const pip = c.wgpuDeviceCreateRenderPipeline(device.device, &.{ const pip = try gloc.allocRenderPipeline(.{
.label = svOpt(def.label),
.vertex = .{ .vertex = .{
.module = shader, .module = shader,
.entryPoint = sv(def.vertex_entry), .entryPoint = sv(def.vertex_entry),
}, },
.primitive = .{ .primitive = .{
.topology = def.topology, .topology = @intFromEnum(def.topology),
.stripIndexFormat = c.WGPUIndexFormat_Undefined, .stripIndexFormat = c.WGPUIndexFormat_Undefined,
.frontFace = c.WGPUFrontFace_CCW, .frontFace = c.WGPUFrontFace_CCW,
.cullMode = c.WGPUCullMode_None, .cullMode = c.WGPUCullMode_None,
@@ -71,16 +87,17 @@ pub fn init(device: GpuDevice, wgsl: []const u8, def: RenderDef) !@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.
@@ -88,7 +105,7 @@ pub fn deinit(self: @This()) void {
pub fn draw( pub fn draw(
self: @This(), self: @This(),
gloc: GpuAllocator, gloc: GpuAllocator,
target_view: c.WGPUTextureView, target_view: GpuTextureView,
vertex_count: u32, vertex_count: u32,
args: anytype, args: anytype,
) !void { ) !void {
@@ -133,7 +150,7 @@ pub fn draw(
defer c.wgpuCommandEncoderRelease(enc); defer c.wgpuCommandEncoderRelease(enc);
const color_attachment = c.WGPURenderPassColorAttachment{ const color_attachment = c.WGPURenderPassColorAttachment{
.view = target_view, .view = target_view.raw,
.resolveTarget = null, .resolveTarget = null,
.loadOp = c.WGPULoadOp_Clear, .loadOp = c.WGPULoadOp_Clear,
.storeOp = c.WGPUStoreOp_Store, .storeOp = c.WGPUStoreOp_Store,
+97 -45
View File
@@ -1,54 +1,92 @@
const std = @import("std"); const std = @import("std");
const c = @import("utils.zig").c; const c = @import("utils.zig").c;
const svOpt = @import("utils.zig").svOpt;
const GpuAllocator = @import("GpuAllocator.zig"); const GpuAllocator = @import("GpuAllocator.zig");
const GpuBuffer = @import("GpuBuffer.zig");
const GpuTextureFormat = @import("lib.zig").GpuTextureFormat; const GpuTextureFormat = @import("lib.zig").GpuTextureFormat;
const GpuTextureUsage = @import("lib.zig").GpuTextureUsage;
const TextureUsage = enum(u64) { pub const GpuTextureDef = struct {
None = 0x0000000000000000, label: ?[]const u8 = null,
CopySrc = 0x0000000000000001, size: c.WGPUExtent3D,
CopyDst = 0x0000000000000002, usage: std.EnumSet(GpuTextureUsage),
TextureBinding = 0x0000000000000004, format: GpuTextureFormat,
StorageBinding = 0x0000000000000008,
RenderAttachment = 0x0000000000000010,
TransientAttachment = 0x0000000000000020,
}; };
raw: c.WGPUTexture, raw: c.WGPUTexture,
size: c.WGPUExtent3D,
usage: c.WGPUTextureUsage,
format: GpuTextureFormat,
gloc: GpuAllocator, gloc: GpuAllocator,
def: GpuTextureDef,
/// Allocates the underlying WebGPU handle and registers it to the parent GpuAllocator pub fn init(gloc: GpuAllocator, def: GpuTextureDef) !@This() {
pub fn init(gloc: GpuAllocator, format: GpuTextureFormat, size: c.WGPUExtent3D, usage: std.EnumSet(TextureUsage)) !@This() {
var use: u64 = 0; var use: u64 = 0;
var iter = usage.iterator(); var iter = def.usage.iterator();
while (iter.next()) |flag| use |= @intFromEnum(flag); while (iter.next()) |flag| use |= @intFromEnum(flag);
const desc = c.WGPUTextureDescriptor{ const desc = c.WGPUTextureDescriptor{
.label = svOpt(def.label),
.usage = use, .usage = use,
.dimension = c.WGPUTextureDimension_2D, .dimension = c.WGPUTextureDimension_2D,
.size = size, .size = def.size,
.format = @intCast(@intFromEnum(format)), .format = @intFromEnum(def.format),
.mipLevelCount = 1, .mipLevelCount = 1,
.sampleCount = 1, .sampleCount = 1,
}; };
const raw = try gloc.allocTexture(desc); const raw = try gloc.allocTexture(desc);
return .{ .gloc = gloc, .raw = raw, .size = size, .format = format, .usage = use }; return .{ .gloc = gloc, .raw = raw, .def = def };
} }
/// Unregisters from the parent GpuAllocator and cleanly destroys GPU resources
pub fn deinit(self: @This()) void { pub fn deinit(self: @This()) void {
self.gloc.freeTexture(self.raw); self.gloc.freeTexture(self.raw);
} }
/// Native getConstMappedRange wrapper
pub fn getConstMappedRange(self: @This(), offset: u64, size: u64) ?*const anyopaque { pub fn getConstMappedRange(self: @This(), offset: u64, size: u64) ?*const anyopaque {
return c.wgpuBufferGetConstMappedRange(self.raw, offset, size); return c.wgpuBufferGetConstMappedRange(self.raw, offset, size);
} }
/// Native mapAsync wrapper pub fn bytesSize(self: @This()) u32 {
return self.bytesSizeRow() * self.def.size.height;
}
pub fn bytesSizeRow(self: @This()) u32 {
return self.def.size.width * self.def.format.bytesPerPixel();
}
/// Return a GpuBuffer containing a copy of the texture.
pub fn buffCopy(self: @This(), gloc: GpuAllocator) !GpuBuffer {
const buf = try GpuBuffer.init(gloc, .{
.size = self.bytesSize(),
.usage = .initMany(&.{ .CopyDst, .CopySrc }),
.label = "texture_copy_buffer",
});
const enc = c.wgpuDeviceCreateCommandEncoder(gloc.device.device, null) orelse return error.Encoder;
defer c.wgpuCommandEncoderRelease(enc);
const src_copy = c.WGPUTexelCopyTextureInfo{
.texture = self.raw,
.mipLevel = 0,
.origin = .{ .x = 0, .y = 0, .z = 0 },
.aspect = c.WGPUTextureAspect_All,
};
const dst_copy = c.WGPUTexelCopyBufferInfo{
.buffer = buf.raw,
.layout = .{
.offset = 0,
.bytesPerRow = self.bytesSizeRow(),
.rowsPerImage = self.def.size.height,
},
};
c.wgpuCommandEncoderCopyTextureToBuffer(enc, &src_copy, &dst_copy, &self.def.size);
const cmd = c.wgpuCommandEncoderFinish(enc, null);
defer c.wgpuCommandBufferRelease(cmd);
c.wgpuQueueSubmit(gloc.device.queue, 1, &cmd);
return buf;
}
pub fn mapAsync( pub fn mapAsync(
self: @This(), self: @This(),
mode: c.WGPUMapMode, mode: c.WGPUMapMode,
@@ -59,12 +97,11 @@ pub fn mapAsync(
_ = c.wgpuBufferMapAsync(self.raw, mode, offset, size, callback_info); _ = c.wgpuBufferMapAsync(self.raw, mode, offset, size, callback_info);
} }
/// Native unmap wrapper
pub fn unmap(self: @This()) void { pub fn unmap(self: @This()) void {
c.wgpuBufferUnmap(self.raw); c.wgpuBufferUnmap(self.raw);
} }
/// CPU to GPU. /// CPU to GPU
pub fn load( pub fn load(
self: @This(), self: @This(),
T: type, T: type,
@@ -72,37 +109,52 @@ pub fn load(
) !void { ) !void {
const bytes = data.len * @sizeOf(T); const bytes = data.len * @sizeOf(T);
if (bytes == self.size) { c.wgpuQueueWriteTexture(
// Aligned path: direct download self.gloc.device.queue,
c.wgpuQueueWriteBuffer(self.gloc.device.queue, self.raw, 0, data.ptr, self.size); &.{
} else { .texture = self.raw,
// Unaligned path: Split the write into an aligned chunk and a padded remainder .mipLevel = 0,
// to support arbitrary lengths without any allocations or large stack arrays. .origin = .{ .x = 0, .y = 0, .z = 0 },
const aligned_part = (bytes / 4) * 4; .aspect = c.WGPUTextureAspect_All,
if (aligned_part > 0) { },
c.wgpuQueueWriteBuffer(self.gloc.device.queue, self.raw, 0, data.ptr, aligned_part); data.ptr,
} bytes,
&.{
var remainder_buf: [4]u8 = .{ 0, 0, 0, 0 }; .offset = 0,
const data_bytes = std.mem.sliceAsBytes(data); .bytesPerRow = self.bytesSizeRow(),
@memcpy(remainder_buf[0 .. bytes - aligned_part], data_bytes[aligned_part..bytes]); .rowsPerImage = self.def.size.height,
},
c.wgpuQueueWriteBuffer(self.gloc.device.queue, self.raw, aligned_part, &remainder_buf, 4); &self.def.size,
} );
} }
// GPU to CPU
pub fn read(self: @This(), alloc: std.mem.Allocator, T: type) ![]T { pub fn read(self: @This(), alloc: std.mem.Allocator, T: type) ![]T {
const out = try alloc.alloc(T, @divExact(self.size, @sizeOf(T))); const out = try alloc.alloc(T, @divExact(self.size, @sizeOf(T)));
const staging = try init( const staging = try init(self.gloc, .{
self.gloc, .size = self.size,
self.size, .usage = .initMany(&.{ .MapRead, .CopyDst }),
.initMany(&.{ .MapRead, .CopyDst }), .label = "texture_read_staging",
); });
defer staging.deinit(); defer staging.deinit();
const enc = c.wgpuDeviceCreateCommandEncoder(self.gloc.device.device, null) orelse return error.Encoder; const enc = c.wgpuDeviceCreateCommandEncoder(self.gloc.device.device, null) orelse return error.Encoder;
c.wgpuCommandEncoderCopyBufferToBuffer(enc, self.raw, 0, staging.raw, 0, self.size); const src_copy = c.WGPUTexelCopyTextureInfo{
.texture = self.raw,
.mipLevel = 0,
.origin = .{ .x = 0, .y = 0, .z = 0 },
.aspect = c.WGPUTextureAspect_All,
};
const dst_copy = c.WGPUTexelCopyBufferInfo{
.buffer = staging.raw,
.layout = .{
.offset = 0,
.bytesPerRow = self.bytesSizeRow(),
.rowsPerImage = self.def.size.height,
},
};
c.wgpuCommandEncoderCopyTextureToBuffer(enc, &src_copy, &dst_copy, &self.def.size);
const cmd = c.wgpuCommandEncoderFinish(enc, null); const cmd = c.wgpuCommandEncoderFinish(enc, null);
defer c.wgpuCommandEncoderRelease(enc); defer c.wgpuCommandEncoderRelease(enc);
defer c.wgpuCommandBufferRelease(cmd); defer c.wgpuCommandBufferRelease(cmd);
+35
View File
@@ -0,0 +1,35 @@
const std = @import("std");
const c = @import("utils.zig").c;
const svOpt = @import("utils.zig").svOpt;
const GpuAllocator = @import("GpuAllocator.zig");
const GpuTexture = @import("lib.zig").GpuTexture;
const GpuTextureFormat = @import("lib.zig").GpuTextureFormat;
const GpuTextureUsage = @import("lib.zig").GpuTextureUsage;
pub const GpuViewDef = struct {
label: ?[]const u8 = null,
usage: std.EnumSet(GpuTextureUsage) = .empty,
format: GpuTextureFormat = .Undefined,
};
raw: c.WGPUTextureView,
gloc: GpuAllocator,
pub fn init(gloc: GpuAllocator, texture: GpuTexture, def: GpuViewDef) !@This() {
var use: u64 = 0;
var iter = def.usage.iterator();
while (iter.next()) |flag| use |= @intFromEnum(flag);
const raw = try gloc.allocTextureView(texture.raw, .{
.label = svOpt(def.label),
.format = @intFromEnum(def.format),
.usage = use,
.mipLevelCount = 1,
.arrayLayerCount = 1,
});
return .{ .gloc = gloc, .raw = raw };
}
pub fn deinit(self: @This()) void {
self.gloc.freeTextureView(self.raw);
}
-113
View File
@@ -1,113 +0,0 @@
const std = @import("std");
const gpu = @import("lib.zig");
const c = @import("utils.zig").c;
const sv = @import("utils.zig").sv;
const GpuDevice = gpu.GpuDevice;
const GpuArena = gpu.GpuArena;
const GpuBuffer = gpu.GpuBuffer;
const GpuRender = gpu.GpuRender;
const GpuTexture = gpu.GpuTexture;
pub fn main(init: std.process.Init) !void {
const allocator = init.gpa;
// 1. Open the raw headless GPU Device you shared
const device = try GpuDevice.init(.{});
defer device.deinit();
var grena = GpuArena.init(allocator, device);
defer grena.deinit();
const gloc = grena.gpuAllocator();
const width: u32 = 512;
const height: u32 = 512;
const render_format = c.WGPUTextureFormat_RGBA8Unorm;
// 2. Load our Render Pipeline (Procedural Triangle Strip)
const circle_rp = try GpuRender.init(
device,
@embedFile("shaders/circle.wgsl"),
.{
.bindings = &.{},
.texture_format = render_format,
.topology = c.WGPUPrimitiveTopology_TriangleStrip,
},
);
defer circle_rp.deinit();
// 3. Create the offscreen VRAM texture to render into
const texture = try GpuTexture.init(
gloc,
.RGBA8Unorm,
.{ .width = width, .height = height, .depthOrArrayLayers = 1 },
.initMany(&.{ .RenderAttachment, .CopySrc }),
);
defer texture.deinit();
const target_view = c.wgpuTextureCreateView(texture.raw, null) orelse return error.View;
defer c.wgpuTextureViewRelease(target_view);
// 4. Create a staging buffer to pull pixels from VRAM to CPU
// 4 bytes per pixel (RGBA8)
const row_bytes = width * 4;
const buffer_bytes = row_bytes * height;
// Create a regular GpuBuffer set up to receive texture copy transfers
const cpu_staging_buf = try GpuBuffer.init(gloc, buffer_bytes, .initMany(&.{ .CopyDst, .CopySrc }));
// 5. Draw the Circle Frame into the texture view!
try circle_rp.draw(gloc, target_view, 4, .{});
// 6. Copy the texture data into our CPU staging buffer
const enc = c.wgpuDeviceCreateCommandEncoder(device.device, null) orelse return error.Encoder;
defer c.wgpuCommandEncoderRelease(enc);
const src_copy = c.WGPUTexelCopyTextureInfo{
.texture = texture.raw,
.mipLevel = 0,
.origin = .{ .x = 0, .y = 0, .z = 0 },
.aspect = c.WGPUTextureAspect_All,
};
const dst_copy = c.WGPUTexelCopyBufferInfo{
.buffer = cpu_staging_buf.raw,
.layout = .{
.offset = 0,
.bytesPerRow = row_bytes,
.rowsPerImage = height,
},
};
const copy_size = c.WGPUExtent3D{ .width = width, .height = height, .depthOrArrayLayers = 1 };
c.wgpuCommandEncoderCopyTextureToBuffer(enc, &src_copy, &dst_copy, &copy_size);
const cmd = c.wgpuCommandEncoderFinish(enc, null);
defer c.wgpuCommandBufferRelease(cmd);
c.wgpuQueueSubmit(device.queue, 1, &cmd);
// 7. Map and read the raw image bytes back to CPU
// (This uses whatever slice-reading helpers your `GpuBuffer` wrapper provides)
const pixels = try cpu_staging_buf.read(allocator, u8);
defer allocator.free(pixels);
// Now you have the raw binary image data! Let's output a simple Netpbm PPM image file
// so you can actually open and look at your rendered circle.
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 {
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]);
}
}
+13 -2
View File
@@ -1,12 +1,13 @@
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");
pub const GpuRender = @import("GpuRender.zig"); pub const GpuRender = @import("GpuRender.zig");
pub const GpuTexture = @import("GpuTexture.zig"); pub const GpuTexture = @import("GpuTexture.zig");
pub const GpuTextureView = @import("GpuTextureView.zig");
pub const GpuTextureFormat = enum(c_int) { pub const GpuTextureFormat = enum(c_uint) {
Undefined = 0, Undefined = 0,
R8Unorm = 1, R8Unorm = 1,
R8Snorm = 2, R8Snorm = 2,
@@ -174,3 +175,13 @@ pub const GpuTextureFormat = enum(c_int) {
}; };
} }
}; };
pub const GpuTextureUsage = enum(u64) {
None = 0x0000000000000000,
CopySrc = 0x0000000000000001,
CopyDst = 0x0000000000000002,
TextureBinding = 0x0000000000000004,
StorageBinding = 0x0000000000000008,
RenderAttachment = 0x0000000000000010,
TransientAttachment = 0x0000000000000020,
};
-24
View File
@@ -1,24 +0,0 @@
enable f16;
@group(0) @binding(0) var<storage, read> A: array<f16>;
@group(0) @binding(1) var<storage, read> B: array<f16>;
@group(0) @binding(2) var<storage, read_write> C: array<f16>;
@group(0) @binding(3) var<uniform> size: u32;
@compute @workgroup_size(256)
fn main(
@builtin(global_invocation_id) global_id : vec3<u32>,
@builtin(num_workgroups) num_workgroups: vec3<u32>
) {
// 1. Calculate the total number of threads across the entire grid
let total_threads = num_workgroups.x * 256u;
// 2. Start at this thread's unique global ID
var index = global_id.x;
// 3. Stride through the tensor elements
while (index < size) {
C[index] = A[index] + B[index];
index += total_threads; // Jump forward by the total thread count
}
}
+14
View File
@@ -3,3 +3,17 @@ pub const c = @cImport(@cInclude("wgpu.h"));
pub fn sv(s: []const u8) c.WGPUStringView { pub fn sv(s: []const u8) c.WGPUStringView {
return .{ .data = s.ptr, .length = s.len }; return .{ .data = s.ptr, .length = s.len };
} }
/// Allows safely passing an optional Zig string to a WebGPU string view.
pub fn svOpt(s: ?[]const u8) c.WGPUStringView {
if (s) |str| return sv(str);
return .{ .data = null, .length = 0 };
}
/// Helper to print a WGPUStringView in your logs.
pub fn viewStr(view: c.WGPUStringView) []const u8 {
if (view.data != null and view.length > 0) {
return view.data[0..view.length];
}
return "unnamed";
}