gogpu/gogpu 是一个托管在 GitHub 上的开源项目,主要使用 Go 编写,采用 MIT License 许可证,目前获得 453 个 Star、38 次 Fork。
仓库全名
gogpu/gogpu
README 摘要
GoGPU Pure Go GPU Computing Ecosystem GPU power, Go simplicity. Zero CGO. Overview 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),…
Pure Go GPU Computing Ecosystem
GPU power, Go simplicity. Zero CGO.
Overview
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.
Key Features
Category
Capabilities
Backends
Pure Go (default), Rust FFI (-tags rust), Browser WASM — via gogpu/wgpu
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())
Text Input (IME)
Windows (IMM32) and macOS (NSTextInputClient): composition start/update/end with preedit and UTF-8 cursor ranges, committed text, candidate-area placement; password and hidden content keep the system IME disabled; Linux X11/Wayland to follow (#331)
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)
Result: A window with a rendered triangle in approximately 20 lines of code, compared to 480+ lines of raw WebGPU.
Backend Selection (ADR-038)
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
Graphics API (Vulkan/DX12/Metal/GLES) is selected independently from the backend:
// Force Vulkan on Windows (instead of auto-detected default)
app := gogpu.NewApp(gogpu.DefaultConfig().
WithGraphicsAPI(gogpu.GraphicsAPIVulkan))
// Force DirectX 12 on Windows
app := gogpu.NewApp(gogpu.DefaultConfig().
WithGraphicsAPI(gogpu.GraphicsAPIDX12))
// Force GLES (useful for testing or compatibility)
app := gogpu.NewApp(gogpu.DefaultConfig().
WithGraphicsAPI(gogpu.GraphicsAPIGLES))
// Software backend — no GPU required, always available
// Renders to screen (GDI, X11, Wayland SHM, macOS) or headless (CI/testing)
app := gogpu.NewApp(gogpu.DefaultConfig().
WithGraphicsAPI(gogpu.GraphicsAPISoftware))
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
Environment Variables
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 regions
Config.With*() methods in code take precedence over environment variables.
Resource Management
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 needed
Resources 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.
The shared provider is also what gogpu/gg uses
for its GPU accelerator.
SurfaceView (Zero-Copy Rendering)
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.
Window & Platform Integration
App implements gpucontext.WindowProvider and gpucontext.PlatformProvider for UI frameworks:
// Window geometry and DPI
w, h := app.Size() // logical points (DIP)
fw, fh := app.PhysicalSize() // physical pixels (framebuffer)
scale := app.ScaleFactor() // 1.0 = standard, 2.0 = Retina/HiDPI
app.RequestSize(1024, 768) // resize at runtime (all platforms, DPI-aware)
// Clipboard
text, _ := app.ClipboardRead()
app.ClipboardWrite("copied text")
// Cursor management
app.SetCursor(gpucontext.CursorPointer) // hand cursor
app.SetCursor(gpucontext.CursorText) // I-beam for text input
// Mouse grab / pointer lock (FPS games, 3D editors)
app.SetCursorMode(gpucontext.CursorModeLocked) // hide + capture relative deltas (SDL parity)
app.SetCursorMode(gpucontext.CursorModeConfined) // visible, confined to window
app.SetCursorMode(gpucontext.CursorModeNormal) // release
// System preferences
if app.DarkMode() { /* switch to dark theme */ }
if app.ReduceMotion() { /* disable animations */ }
if app.HighContrast() { /* increase contrast */ }
fontMul := app.FontScale() // user's font size preference
Native printing contract
Applications provide complete PDF/document bytes and can submit them to the
desktop native print backends without coupling UI code to an operating system:
job, err := app.Print(ctx, gogpu.NewPDFDocument("report.pdf", pdfBytes), gogpu.PrintOptions{})
if err != nil {
// Invalid input, unavailable native services, or an unsupported platform.
return err
}
if err := <-job.Done(); err != nil {
// context.Canceled means cancellation; other errors are native/spool errors.
return err
}
See docs/PRINTING.md for parent-window, ownership, and
lifecycle semantics. The desktop backends accept PDF input through Windows
PrintDlgEx/GDI, macOS PDFKit/AppKit, and the Linux xdg-desktop-portal; browser
printing remains unsupported.
macOS System Menu
Native menu bar with role-based items (About, Preferences, Quit, etc.):
Menu can be set before or after Run(). On non-macOS platforms these calls are no-ops. See examples/menu/ for a complete example.
Ebiten-Style Input Polling
For game loops, use the polling-based Input API:
import "github.com/gogpu/gogpu/input"
app.OnUpdate(func(dt float64) {
inp := app.Input()
// Keyboard
if inp.Keyboard().JustPressed(input.KeySpace) {
player.Jump()
}
if inp.Keyboard().Pressed(input.KeyLeft) {
player.MoveLeft(dt)
}
// Mouse
x, y := inp.Mouse().Position()
if inp.Mouse().JustPressed(input.MouseButtonLeft) {
player.Shoot(x, y)
}
})
All input methods are thread-safe and work with the frame-based update loop.
SDL-Style Event Queue
For game developers who prefer explicit event processing (SDL/Pygame pattern):
app.OnUpdate(func(dt float64) {
for ev, ok := app.PollInputEvent(); ok; ev, ok = app.PollInputEvent() {
switch e := ev.(type) {
case gpucontext.KeyEvent:
if e.Pressed && e.Key == gpucontext.KeyEscape {
app.Quit()
}
case gpucontext.PointerEvent:
if e.Type == gpucontext.PointerDown {
player.Shoot(e.X, e.Y)
}
case gpucontext.ScrollEvent:
camera.Zoom(e.DeltaY)
}
}
})
Three input models coexist — callbacks, polling, and event queue — all driven from the same internal dispatch. Use whichever fits your use case. Zero overhead for unused models.
Multi-Window Input
Each window can have its own input handlers. App.EventSource() receives events from whichever window is focused:
// Create secondary window
w2, _ := app.NewWindow(gogpu.DefaultConfig().WithTitle("Inspector"))
// Per-window input
w2.SetOnKeyPress(func(key gpucontext.Key, mods gpucontext.Modifiers) {
// fires only when w2 is focused
})
w2.SetOnPointer(func(ev gpucontext.PointerEvent) {
// pointer events for this window
})
// App-level: receives from ANY focused window
app.EventSource().OnKeyPress(func(key gpucontext.Key, mods gpucontext.Modifiers) {
if key == gpucontext.KeyN && mods.HasControl() {
// Ctrl+N works regardless of which window is focused
}
})
All input events flow through centralized dispatch with WindowID routing (winit/SDL3/Qt6 pattern).
Window Lifecycle (ADR-026)
GPU Device is independent of any window. Closing a window destroys its surface but the device stays alive — remaining windows keep rendering. Same API on desktop, mobile, and web.
// App lifecycle state: Idle → Running → Suspending → Suspended → Resuming
state := app.Lifecycle() // AppRunning on desktop
if state.IsActive() { ... } // true for Running/Suspending/Resuming
// Exit policy
app.SetQuitOnLastWindowClosed(false) // tray/headless: stay alive with zero windows
// Surface lifecycle (desktop: once at init; mobile: per-ANativeWindow)
app.OnSurfaceAvailable(func() { /* create GPU resources */ })
app.OnSurfaceDestroyed(func() { /* drop GPU surfaces NOW */ })
// GPU loss (0.56.0): a lost surface is transient and gogpu recreates it —
// drawing calls match ErrSurfaceLost meanwhile; a lost device is terminal
// and Run returns the error after the callback
app.OnSurfaceLost(func(err error) { /* your state may need a redraw */ })
app.OnDeviceLost(func(err error) { /* release what the device owned */ })
// App lifecycle (desktop: no-ops; mobile: Activity/UIApplication events)
app.OnResumed(func() { /* app visible */ })
app.OnSuspended(func() { /* app backgrounded, stop rendering */ })
app.OnMemoryWarning(func() { /* free caches */ })
See examples/lifecycle/ for a visual demo: close the primary window, the secondary keeps rendering.
Both loss callbacks run on the event-loop goroutine and must not block. They fire once per episode: after a
device loss, surface episodes are considered delivered. Device-loss detection is per backend — the DX12
health check and backends whose submit reports a lost device; three consecutive failed surface recreates
escalate to device loss. The full contract is in the App.OnSurfaceLost and App.OnDeviceLost docs.
Event-Driven Rendering
GoGPU uses a three-state rendering model for optimal power efficiency:
State
Condition
CPU Usage
Latency
Idle
No activity
0% (blocks on OS events)
<1ms wakeup
Animating
Active animation tokens
VSync (~60fps)
Smooth
Continuous
WithContinuousRender(true)
100% (game loop)
Immediate
// Event-driven mode (default — 0% CPU when idle)
app := gogpu.NewApp(gogpu.DefaultConfig())
// Start animation — renders at VSync while token is alive
token := app.StartAnimation()
// ... animation runs at 60fps ...
token.Stop() // Loop returns to idle (0% CPU)
// Request single-frame redraw from any goroutine
app.RequestRedraw()
Multiple animation tokens can be active simultaneously. The loop renders continuously until all tokens are stopped.
Resource Cleanup
Use OnClose to release GPU resources before the renderer is destroyed:
OnClose runs on the render thread before Renderer.Destroy(), ensuring textures, bind groups, and pipelines are released while the device is still alive.
GoGPU uses multi-thread architecture (Ebiten/Gio pattern) for professional responsiveness:
Main thread: Window events only (Win32/Cocoa/X11 message pump), centralized input dispatch
Render thread: All GPU operations (device, swapchain, commands)
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.
Rust backend: Rust/wgpu-native selection lives inside gogpu/wgpu via build tags (ADR-038). Build with -tags rust and install wgpu-native: go run github.com/go-webgpu/webgpu/cmd/setup@latest
Platform Support
Windows
Native Win32 windowing with Vulkan, DirectX 12, GLES, and Software backends.
Input methods (IME) are supported through IMM32: composition events, committed text and candidate-window placement reach the app through the gpucontext IME contract.
Linux
X11 and Wayland support with Vulkan, GLES, and Software (headless) backends.
X11 — pure Go X11 protocol with libX11 loaded via goffi for Vulkan surface creation. Multi-touch input via XInput2 wire protocol.
Wayland — single libwayland-client connection via goffi for all Wayland operations (surface, input, xdg-shell, CSD, pointer constraints). Server-side decorations via zxdg_decoration_manager_v1, client-side decorations (CSD) with subsurface title bar when SSD unavailable. Pointer lock via zwp_pointer_constraints_v1 + zwp_relative_pointer_v1. Tested on WSLg, GNOME, KDE, sway, niri, COSMIC.
macOS
Pure Go Cocoa implementation via goffi Objective-C runtime, with Metal and Software (headless) backends:
Native system window tabbing supported via Config.WithTabbingMode(gogpu.TabbingPreferred) — windows with the same TabbingIdentifier group into macOS system tabs automatically.
Input methods (IME) are supported through NSTextInputClient: marked text and commits reach the app while GPU renders the preedit.
Note: macOS Cocoa requires UI operations on the main thread. GoGPU handles this automatically.
Linux platform hero — 3 bug reports, 13+ comments with detailed stack traces and diagnostics. His persistence uncovered the critical goffi stack spill bug affecting all Linux/macOS users
评论