gogpu/wgpu 是一个托管在 GitHub 上的开源项目,主要使用 Go 编写,采用 MIT License 许可证,目前获得 210 个 Star、34 次 Fork。
仓库全名
gogpu/wgpu
README 摘要
wgpu Unified Go WebGPU — Three Backends, One API Pure Go · Rust FFI · Browser WASM — build tag selects the stack Part of the GoGPU ecosystem Overview wgpu is the unified Go WebGPU package with three independent implementations selected by build tags — like Chrome (Dawn) and Firefox (wgpu) implementing the same W3C spec. Key Features Category | Capabilities | Backends | Vulkan, Metal, DirectX 12, OpenGL ES, Software,…
wgpu is the unified Go WebGPU package with three independent implementations selected by build tags — like Chrome (Dawn) and Firefox (wgpu) implementing the same W3C spec.
WGSL via gogpu/naga compiler (SPIR-V, HLSL, MSL, GLSL, DXIL)
Compute
Compute shaders and GPU→CPU readback on every native backend (software: see its known gaps below)
Present
Damage-aware presentation — compositor dirty rects
Ray Tracing
Not usable yet: HAL code only, no public API, not run on a GPU. Public inline ray queries are planned, Vulkan first (status, #369)
Debug
Leak detection, error scopes on every build, validation layers, DRED diagnostics (DX12), structured logging (log/slog)
Build
Zero CGO, simple go build
Installation
go get github.com/gogpu/wgpu
Requirements: Go 1.25+
Build:
CGO_ENABLED=0 go build
Note: wgpu uses Pure Go FFI via goffi. Both CGO_ENABLED=0 (default, zero C compiler dependency) and CGO_ENABLED=1 (for race detector or coexistence with CGO libraries) are supported.
Android/arm64 Vulkan is a guarded preview, documented separately in
Android Vulkan preview. It is not yet a full support claim.
New surface integrations should use the explicit safe or unsafe target API
described in Surface targets. The original
two-uintptr method remains available as a compatibility adapter.
Rust FFI backend (optional, through wgpu-native):
go build -tags rust
Requires wgpu-native v29 binary. Set WGPU_NATIVE_PATH or place in system PATH. See go-webgpu/webgpu for details.
With go-webgpu/webgpu v0.5.5, -tags rust is not usable for real rendering: on Linux amd64 and Intel macOS it aborts at adapter request, and on Windows vertex buffers, depth attachments and explicit bind group layouts abort or crash (see the 0.34.6 known issues in CHANGELOG.md). These are fixed in go-webgpu/webgpu’s next release.
Browser (WASM):
GOOS=js GOARCH=wasm go build -o app.wasm .
Three implementations, one API — build tags select the stack:
Build Tag
Implementation
Use Case
(default)
Pure Go → core → HAL → Vulkan/Metal/DX12/GLES/Software
Zero deps, cross-compile
-tags rust
go-webgpu/webgpu → wgpu-native v29
wgpu-native’s backends
GOOS=js
syscall/js → Browser WebGPU
Web applications
API consistency: The public API compiles on all build targets. The HAL() accessors on Instance, Adapter, Device and Surface exist on every build and return hal.Handles in that build’s terms — the native backend’s handles, KindWebGPU handles behind the wgpu-native binding, or KindBrowser on the browser build — and a nil or released object answers the zero Handles (KindUnknown). Use RequestAdapter → RequestDevice for the standard cross-backend path.
Quick Start
package main
import (
"fmt"
"github.com/gogpu/wgpu" // Platform backends register automatically (ADR-083)
)
func main() {
// Create instance
instance, _ := wgpu.CreateInstance(nil)
defer instance.Release()
// Request high-performance GPU
// (or pick one explicitly: instance.EnumerateAdapters() lists every
// adapter the instance knows on the native and browser builds, each
// usable with RequestDevice; the -tags rust build has no enumeration
// until the wgpu-native binding exposes it)
adapter, _ := instance.RequestAdapter(&wgpu.RequestAdapterOptions{
PowerPreference: wgpu.PowerPreferenceHighPerformance,
})
defer adapter.Release()
// Get adapter info
// (adapter.Identity() adds hardware identity where the backend reports
// it: DeviceUUID/PCIBusID on Vulkan — NVMLString() matches nvidia-smi —
// AdapterLUID on Windows, MetalRegistryID on Metal, zero elsewhere)
info := adapter.Info()
fmt.Printf("GPU: %s (%s)\n", info.Name, info.Backend)
// Create device
device, _ := adapter.RequestDevice(nil)
defer device.Release()
// Create a GPU buffer
buffer, _ := device.CreateBuffer(&wgpu.BufferDescriptor{
Label: "My Buffer",
Size: 1024,
Usage: wgpu.BufferUsageStorage | wgpu.BufferUsageCopyDst,
})
defer buffer.Release()
// Write data to buffer
if err := device.Queue().WriteBuffer(buffer, 0, []byte{1, 2, 3, 4}); err != nil {
panic(err)
}
}
WebGPU-spec-compliant dual-layer API. Primary path is blocking + context.Context
(idiomatic Go, zero allocation); escape hatch MapAsync + Device.Poll is for
game loops that cannot afford to block.
// Primary: blocking, idiomatic, zero-alloc.
// Map blocks until the GPU finishes writing the buffer (or ctx cancels).
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := stagingBuf.Map(ctx, wgpu.MapModeRead, 0, size); err != nil {
log.Fatal(err)
}
defer stagingBuf.Unmap()
rng, _ := stagingBuf.MappedRange(0, size)
data := rng.Bytes() // []byte view, zero copy, valid until Unmap
process(data)
// Escape hatch: async, non-blocking, for render loops.
pending, _ := stagingBuf.MapAsync(wgpu.MapModeRead, 0, size)
// Continue rendering; auto-polled on next Queue.Submit.
renderFrame()
if ready, _ := pending.Status(); ready {
rng, _ := stagingBuf.MappedRange(0, size)
process(rng.Bytes())
stagingBuf.Unmap()
}
Safety guarantees: UAF protection via generation counters on MappedRange,
ErrBufferDestroyed on destroy-during-pending, ErrMapCanceled on unmap-during-pending,
ErrMapRangeOverlap for overlapping MappedRange calls, MAP_ALIGNMENT = 8
validation, thread-safe concurrent Device.Poll.
Design follows Rust wgpu’s buffer mapping model with Go-idiomatic error handling.
Features: WGSL compute shaders, storage/uniform buffers, indirect dispatch, GPU timestamp queries for render and compute passes (Vulkan, DX12 and Windows GLES; not yet on Metal), with Queue.GetTimestampPeriod, WebGPU-compliant Buffer.Map / MapAsync GPU→CPU readback with context.Context integration.
Architecture
wgpu/
├── *.go # Public API (import "github.com/gogpu/wgpu")
├── hal/ # Public interop surface (BackendKind, Handles)
├── internal/
│ ├── core/ # Validation, state tracking, deferred resource destruction
│ ├── hal/ # Hardware Abstraction Layer
│ │ ├── allbackends/ # Platform-specific backend auto-registration
│ │ ├── noop/ # No-op backend (testing)
│ │ ├── software/ # CPU software rasterizer
│ │ ├── gles/ # OpenGL 3.3+ / OpenGL ES 3.0+
│ │ ├── vulkan/ # Pure Go Vulkan backend
│ │ ├── metal/ # Metal
│ │ └── dx12/ # DirectX 12
├── examples/
│ ├── compute-copy/ # GPU buffer copy with compute shader
│ └── compute-sum/ # Parallel reduction on GPU
└── cmd/
├── raytracing-headless/ # HAL acceleration structure build, rays traced on the CPU
├── vk-gen/ # Vulkan bindings generator
└── ... # Backend integration tests
Public API
The root package (import "github.com/gogpu/wgpu") provides a safe, ergonomic API aligned with the W3C WebGPU specification. It wraps internal/core and internal/hal into user-friendly types:
For the default (Pure Go) path, importing github.com/gogpu/wgpu registers the
platform backends by default (ADR-083). No blank import is needed:
import "github.com/gogpu/wgpu"
// Registered by default:
// - Windows: Vulkan, DX12, GLES (386, amd64, arm64)
// - Linux: Vulkan, GLES (amd64, arm64)
// - macOS: Metal (amd64, arm64; MoltenVK only with -tags wgpu_moltenvk)
// - Android: Vulkan, GLES (arm64)
The Pure Go software backend is registered by default (ADR-083, v0.35.0): no blank import is needed. It is
outside the default adapter set, so an empty Backends mask keeps every existing program’s adapters and picks
unchanged. Select it by naming gputypes.BackendsSoftware in the mask; RequestAdapterOptions.ForceFallbackAdapter
then prefers it over other CPU adapters such as WARP and llvmpipe. -tags wgpu_nosoftware leaves it out of the
build.
Other GOOS/GOARCH combinations are outside the default registration set and get no backend: the backend packages are
not importable outside the module. Some of them, for example linux/386, cannot build the Pure Go backends at all
because goffi has no syscall files for that architecture.
Opt out per backend with -tags wgpu_novulkan, wgpu_nodx12, wgpu_nometal,
wgpu_nogles or wgpu_nosoftware. wgpu_nosoftware also removes the software
device from wgputest. On macOS, default registration covers Metal only:
Vulkan through MoltenVK is opt-in with -tags wgpu_moltenvk. GOOS=ios
satisfies the darwin tag, so iOS builds in the default set register Metal.
Works with Mesa llvmpipe for software-only environments
Software Backend
CPU rasterizer for headless and windowed rendering. Always compiled — no build tags or GPU hardware required.
import "github.com/gogpu/wgpu"
// The software backend is registered by default. Name gputypes.BackendsSoftware
// in the instance mask to select it; with RequestAdapterOptions.ForceFallbackAdapter
// it is preferred over other CPU adapters. -tags wgpu_nosoftware leaves it out.
// Use cases:
// - CI/CD testing without GPU
// - Server-side image generation
// - Fallback when GPU unavailable
// - Embedded systems without GPU
Rasterization Features:
Clip-space clipping, then the viewport transform (SetViewport, depth range)
Edge function triangle rasterization (Pineda algorithm) with the top-left fill rule
Perspective-correct interpolation; @interpolate(linear) and flat (first vertex)
2x2 quads with helper invocations for derivatives and implicit-LOD mip selection
Depth test (all 8 compare functions)
Stencil test (all 8 operations, front and back faces)
Blending (13 factors without dual-source, 5 operations)
4-sample multisampled colour: coverage at the standard sample positions, one shade per pixel, per-sample
blending under the pipeline’s sample mask, and a resolve that averages in linear (sRGB decoded and re-encoded)
BC1-BC7 and ETC2/EAC texture sampling (texture-compression-bc, texture-compression-etc2)
Encoded commands run at Queue.Submit
SPIR-V interpreter — executes vertex/fragment/compute shaders on CPU. Designed for shader debugging, CI/CD testing, and GPU-less environments — not for production rendering (interpreted, much slower than JIT software renderers such as SwiftShader).
Known gaps: no ASTC; no depth-clip-control or frag_depth; multisampling is colour-only — multisampled
depth/stencil, alpha to coverage and sampling a multisampled texture are refused with an error.
Shader memory limits: a shader’s Private variables may total 64 KiB, the Function variables of one function
64 KiB, its Workgroup variables 1 MiB, its composite and null constants 1 MiB, and any type at most maxBufferSize
(the WebGPU limit on workgroup storage per entry point applies as well). WebGPU sets no limit for these; they are
eight times the WGSL guarantees for Private and Function storage. What one invocation holds live may reach 256 MiB
and a compute workgroup 1 GiB. A module over them fails pipeline creation. The software backend runs raw SPIR-V
within these documented limits; it is not a sandbox for hostile SPIR-V. For untrusted shaders, use WGSL, which naga
validates.
Debug & Testing:
Render pass instrumentation: HAL debug log events and RenderPassStats for the repository’s CI end-to-end assertions
Public wgpu.HeadlessSurfaceTarget + Surface.ReadPixels() lifecycle for deterministic headless render verification; snapshots are owned, tightly packed RGBA8
HAL GetFramebuffer() remains as a compatibility alias for existing software-backend callers; new root API code should use Surface.ReadPixels()
Damage-aware partial blit with pixel-level test coverage
See Surface targets
for the complete configure → acquire → render → submit → present → readback
recipe and the explicit non-WebGPU support contract.
Linux X11:XPutImage via goffi (Skia pattern), BGRA = X11 ZPixmap native format
macOS: CGImage + setContents: (CALayer) or Metal nextDrawable + replaceRegion (CAMetalLayer). Contributor: @k-chimi
Environment Variables
Variable
Values
Description
GOGPU_DX12_DXIL
1
Enable DXIL direct compilation on DX12 (experimental). Bypasses HLSL→FXC, generates DXIL bytecode directly from naga IR. SM 6.0+, zero external dependencies. Default: off (uses HLSL→FXC).
GOGPU_DX12_DXIL_OVERRIDE_VS
file path
Replace vertex shader DXIL with contents of the given file. For debugging only.
GOGPU_DX12_DXIL_OVERRIDE_PS
file path
Replace pixel shader DXIL with contents of the given file. For debugging only.
GOGPU_DX12_DXIL_VALIDATE
1
With GOGPU_DX12_DXIL=1, validate each DXIL blob with dxil.dll before pipeline creation and log the validator’s message; a rejected blob is written to a file in the system temp directory. For debugging only.
GOGPU_DX12_FORCE_HWND
1
Create DX12 swap chains for the window handle even when the surface asks for premultiplied alpha, which otherwise uses DirectComposition. For tools such as RenderDoc that cannot capture through DirectComposition.
Note: Backend selection (GOGPU_GRAPHICS_API) is handled by gogpu (the app framework), not by wgpu directly. See gogpu documentation for GOGPU_GRAPHICS_API=vulkan|dx12|metal|gles|software.
The architecture follows gfx-rs/wgpu, the Rust WebGPU implementation:
wgpu-core, wgpu-hal and wgpu-types. Thanks to its authors and contributors for the design we build on.
评论