纯 Go GPU 应用程序框架 — 窗口化、输入、生命周期和平台抽象。属于 GoGPU 生态系统的一部分。
GoGPU
Pure Go GPU Computing Ecosystem
GPU power, Go simplicity. Zero CGO.
gogpu is the application framework of the GoGPU ecosystem — windowing, input, lifecycle management, and platform abstraction for GPU-accelerated applications. Part of a 1.1M+ LOC Pure Go ecosystem across 15 repositories.
Built on gogpu/wgpu — the unified Go WebGPU package with three backends: Pure Go (default), Rust FFI (-tags rust), and Browser WASM.
| Category | Capabilities |
|---|---|
| Backends | Pure Go (default), Rust FFI (-tags rust), Browser WASM — via gogpu/wgpu |
| Graphics API | Runtime selection: Vulkan, DX12, Metal, GLES, Software |
| Platforms | Windows (Vulkan/DX12/GLES), Linux X11/Wayland (Vulkan/GLES), macOS (Metal), Browser/WASM (WebGPU) |
| Rendering | Event-driven three-state model (idle/animating/continuous), 0% CPU when idle (lazy acquire), zero-copy surface rendering, damage-aware presentation |
| Input Models | Three coexisting models: callbacks (EventSource), state polling (Input(), Ebiten-style), SDL-style event queue (PollInputEvent()) |
| Graphics | Windowing, input handling, multi-keyboard layout (X11 XKB + Wayland xkbcommon), AltGr/international text input (unified xkbcommon, ADR-029), key repeat on all platforms (Wayland client-side timer, ADR-033), texture loading, frameless windows, runtime window resize (RequestSize), mouse grab / pointer lock (Win32 + X11 + Wayland, SDL parity), OS drag-and-drop: incoming (all 4 desktop platforms) + outgoing drag source (StartDrag, all 5 platforms), GPU adapter power preference, native macOS window tabbing, native system menus (macOS + Windows), native file dialogs (macOS + Windows + Linux D-Bus/zenity/kdialog), native print contract and desktop backends (Windows/macOS/Linux portal) |
| Scroll | ScrollPhase + IsMomentum for macOS trackpad momentum detection (ADR-032), pixel/line/page delta modes |
| Sound | 12 UI sound types (UWP ElementSoundPlayer parity): Click, Invoke, Focus, Navigate, Show/Hide, feedback. winmm, NSSound, canberra |
| Compute | Full compute shader support |
| Window Chrome | Frameless windows with custom title bars, DWM shadow, hit-test regions |
| HiDPI | Per-monitor DPI, runtime DPI change (ScaleChangedEvent on all platforms), WM_DPICHANGED, logical/physical coordinate split, WithSize in logical DIP (ADR-030, ADR-059) |
| Integration | DeviceProvider, WindowProvider, PlatformProvider, WindowChrome, SurfaceView |
| Logging | Structured logging via log/slog, silent by default |
| Build | Zero CGO with Pure Go backend |
go get github.com/gogpu/gogpuRequirements:
CGO_ENABLED=0 (Pure Go FFI requires CGO disabled)Zero dependencies — just works:
CGO_ENABLED=0 go run .Note: On macOS and some Linux distros, CGO is enabled by default. Always set
CGO_ENABLED=0when building GoGPU projects.
package main
import (
"github.com/gogpu/gogpu"
"github.com/gogpu/gogpu/gmath"
)
func main() {
app := gogpu.NewApp(gogpu.DefaultConfig().
WithTitle("Hello GoGPU").
WithSize(800, 600))
app.OnDraw(func(dc *gogpu.Context) {
dc.DrawTriangleColor(gmath.DarkGray)
})
app.Run()
}Result: A window with a rendered triangle in approximately 20 lines of code, compared to 480+ lines of raw WebGPU.
Backend selection is handled inside gogpu/wgpu via build tags. gogpu uses wgpu.CreateInstance() — the build tag determines which implementation runs.
# Pure Go (default, zero dependencies)
go build ./...
# Rust FFI (requires wgpu-native v29 shared library)
go build -tags rust ./...
# Download wgpu-native automatically:
go run github.com/go-webgpu/webgpu/cmd/setup@latest| Backend | Build Tag | Use Case |
|---|---|---|
| Pure Go | (default) | Zero deps, cross-compile, air-gapped deploy |
| Rust FFI | -tags rust |
Battle-tested GPU drivers, max compatibility |
| Browser | GOOS=js GOARCH=wasm |
Web applications |
Note: Rust backend requires wgpu-native. See go-webgpu/webgpu for setup.
Graphics API (Vulkan/DX12/Metal/GLES) is selected independently from the backend:
…| Graphics API | Platforms | Constant |
|---|---|---|
| Auto | All (default) | gogpu.GraphicsAPIAuto |
| Vulkan | Windows, Linux | gogpu.GraphicsAPIVulkan |
| DX12 | Windows | gogpu.GraphicsAPIDX12 |
| Metal | macOS | gogpu.GraphicsAPIMetal |
| GLES | Windows, Linux | gogpu.GraphicsAPIGLES |
| Software | All (no GPU needed) | gogpu.GraphicsAPISoftware |
All settings can be overridden via environment variables (no code changes needed):
| Variable | Values | Default | Purpose |
|---|---|---|---|
GOGPU_GRAPHICS_API |
vulkan, dx12, metal, gles, software |
auto | GPU backend selection |
GOGPU_POWER_PREFERENCE |
low, high |
none | GPU power/performance trade-off |
GOGPU_RENDER_MODE |
auto, cpu, gpu |
auto | 2D rendering path (ADR-020) |
GOGPU_DEBUG_DAMAGE |
1 |
off | Show damage region overlay (ADR-021) |
GOGPU_STATS |
1 |
off | Enable GPU upload/resource stats (#484) |
# Examples:
GOGPU_GRAPHICS_API=vulkan ./myapp # Force Vulkan
GOGPU_GRAPHICS_API=software ./myapp # Force software renderer
GOGPU_RENDER_MODE=cpu ./myapp # Force CPU rasterizer (benchmarking)
GOGPU_DEBUG_DAMAGE=overlay ./myapp # Show green overlay on dirty regionsConfig.With*() methods in code take precedence over environment variables.
GPU resources are automatically cleaned up on shutdown when registered with TrackResource:
canvas, _ := ggcanvas.New(provider, 800, 600)
app.TrackResource(canvas) // auto-closed on shutdown, no OnClose neededResources are closed in LIFO (reverse) order after GPU idle, before device destruction. The shutdown sequence is: WaitIdle → tracked resources → OnClose → Renderer.Destroy().
ggcanvas auto-registration: When created via a provider that implements ResourceTracker (like App), ggcanvas auto-registers — no TrackResource call needed.
GC safety net: Textures use runtime.AddCleanup as a fallback — if you forget Destroy(), the GC will eventually clean up GPU resources. This is a safety net, not a replacement for explicit cleanup.
// Load from file (PNG, JPEG)
tex, err := renderer.LoadTexture("sprite.png")
defer tex.Destroy()
// Create from Go image
img := image.NewRGBA(image.Rect(0, 0, 128, 128))
tex, err := renderer.NewTextureFromImage(img)
// With custom filtering options
opts := gogpu.TextureOptions{
MagFilter: gputypes.FilterModeNearest, // Crisp pixels
AddressModeU: gputypes.AddressModeRepeat, // Tiling
}
tex, err := renderer.LoadTextureWithOptions("tile.png", opts)GoGPU exposes GPU resources through the DeviceProvider interface for integration with external libraries:
type DeviceProvider interface {
Device() hal.Device // HAL GPU device (type-safe Go interface)
Queue() hal.Queue // HAL command queue
SurfaceFormat() gputypes.TextureFormat
}
// Usage
provider := app.DeviceProvider()
device := provider.Device() // hal.Device — 30+ methods with error returns
queue := provider.Queue() // hal.Queue — Submit, WriteBuffer, ReadBufferFor integration with external libraries like gogpu/gg, use the standard gpucontext interfaces:
…This enables enterprise-grade dependency injection between packages without circular imports.
For GPU compute and custom rendering, access the wgpu device directly:
provider := app.DeviceProvider()
device := provider.Device() // *wgpu.Device — full WebGPU API
queue := device.Queue() // *wgpu.Queue — command submissionUsed for compute shaders, custom render pipelines, and by gogpu/gg GPU accelerator.
For direct GPU rendering without CPU readback:
app.OnDraw(func(dc *gogpu.Context) {
view := dc.SurfaceView() // Current frame's GPU texture view
// Pass to ggcanvas.RenderDirect() for zero-copy compositing
})This eliminates the GPU→CPU→GPU round-trip when integrating with gg/ggcanvas.
App implements gpucontext.WindowProvider and gpucontext.PlatformProvider for UI frameworks:
…Applications provide complete PDF/document bytes and can submit them to the desktop native print backends without coupling UI code to an operating system:
…See examples/particles for a full GPU particle simulation
(compute + render in one window) and
wgpu/examples/compute-particles
for a headless compute example.
GoGPU uses log/slog for structured logging, silent by default:
import "log/slog"
// Enable info-level logging
gogpu.SetLogger(slog.Default())
// Enable debug-level logging for full diagnostics
gogpu.SetLogger(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
Level: slog.LevelDebug,
})))
// Get current logger
logger := gogpu.Logger()Log levels: Debug (texture creation, pipeline state), Info (backend selected, adapter info), Warn (resource cleanup errors).
GoGPU uses multi-thread architecture (Ebiten/Gio pattern) for professional responsiveness:
All input events (keyboard, pointer, scroll, text) flow through a single centralized event queue with WindowID tagging — the same pattern used by winit, SDL3, and Qt6.
This ensures windows never show "Not Responding" during heavy GPU operations.
…| Package | Purpose |
|---|---|
gogpu (root) |
App, Config, Context, Renderer, Texture |
gpu/ |
Backend selection (HAL-based) |
gpu/types/ |
BackendType, GraphicsAPI enums |
gpu/backend/native/ |
HAL backend creation (Vulkan/Metal/DX12/GLES/Software selection) |
gmath/ |
Vec2, Vec3, Vec4, Mat4, Color |
window/ |
Window configuration |
input/ |
Keyboard and mouse input |
sound/ |
Platform system sounds — 12 types: Click, Invoke, Focus, Navigate, Show/Hide, Alert, Error, Warning, Success (UWP parity) |
internal/platform/ |
Platform-specific windowing (Win32, Cocoa, X11, Wayland, Browser) |
internal/thread/ |
Multi-thread rendering (RenderLoop) |
Rust backend: Rust/wgpu-native selection lives inside gogpu/wgpu via build tags (ADR-038). Build with
-tags rustand install wgpu-native:go run github.com/go-webgpu/webgpu/cmd/setup@latest
Native Win32 windowing with Vulkan, DirectX 12, GLES, and Software backends.
X11 and Wayland support with Vulkan, GLES, and Software (headless) backends.
暂无开放 Issues,或尚未同步最近议题。