gpucontext

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 27, 2026 License: MIT Imports: 1 Imported by: 0

README

gpucontext

Shared GPU infrastructure for the gogpu ecosystem.

Overview

gpucontext provides interfaces and utilities for sharing GPU resources across multiple packages without circular dependencies. It follows the pattern used by wgpu-types in the Rust ecosystem.

Installation

go get github.com/gogpu/gpucontext

Requires: Go 1.25+

Features

  • DeviceProvider — Interface for injecting GPU device and queue
  • EventSource — Interface for input events (keyboard, mouse, window)
  • Registry[T] — Generic registry with priority-based backend selection
  • WebGPU Types — Device, Queue, Adapter, Surface interfaces (zero dependencies)

Usage

DeviceProvider Pattern

The DeviceProvider interface enables dependency injection of GPU capabilities:

// In gogpu/gogpu - implements DeviceProvider
type App struct {
    device gpucontext.Device
    queue  gpucontext.Queue
}

func (app *App) Device() gpucontext.Device       { return app.device }
func (app *App) Queue() gpucontext.Queue         { return app.queue }
func (app *App) SurfaceFormat() gpucontext.TextureFormat { return app.format }
func (app *App) Adapter() gpucontext.Adapter     { return app.adapter }

// In gogpu/gg - uses DeviceProvider
func NewGPUCanvas(provider gpucontext.DeviceProvider) *Canvas {
    return &Canvas{
        device: provider.Device(),
        queue:  provider.Queue(),
    }
}
EventSource (for UI frameworks)

EventSource enables UI frameworks to receive input events from host applications:

// In gogpu/ui - uses EventSource
func (ui *UI) AttachEvents(source gpucontext.EventSource) {
    source.OnKeyPress(func(key gpucontext.Key, mods gpucontext.Modifiers) {
        ui.focused.HandleKeyDown(key, mods)
    })

    source.OnMousePress(func(button gpucontext.MouseButton, x, y float64) {
        widget := ui.hitTest(x, y)
        widget.HandleMouseDown(button, x, y)
    })
}

// In gogpu/gogpu - implements EventSource
type App struct {
    keyHandlers []func(gpucontext.Key, gpucontext.Modifiers)
}

func (app *App) OnKeyPress(fn func(gpucontext.Key, gpucontext.Modifiers)) {
    app.keyHandlers = append(app.keyHandlers, fn)
}
Backend Registry

The Registry[T] provides thread-safe registration with priority-based selection:

import "github.com/gogpu/gpucontext"

// Create registry with priority order
var backends = gpucontext.NewRegistry[Backend](
    gpucontext.WithPriority("vulkan", "dx12", "metal", "gles", "software"),
)

// Register backends (typically in init())
func init() {
    backends.Register("vulkan", NewVulkanBackend)
    backends.Register("software", NewSoftwareBackend)
}

// Get best available backend
backend := backends.Best()

// Or get specific backend
vulkan := backends.Get("vulkan")

// Check availability
if backends.Has("vulkan") {
    // Vulkan is available
}

// List all available
names := backends.Available() // ["vulkan", "software"]

Dependency Graph

                   gpucontext
                  (DeviceProvider, Registry, types)
                       ^
          +------------+------------+
          |            |            |
        gogpu         gg         born-ml/born
        (implements)  (uses)     (implements & uses)
          |
          v
        wgpu/hal

Ecosystem

Package Description
gogpu/gogpu Graphics framework, implements DeviceProvider
gogpu/gg 2D graphics, uses DeviceProvider
gogpu/wgpu Pure Go WebGPU implementation
born-ml/born ML framework, implements & uses

License

MIT License — see LICENSE for details.

Documentation

Overview

Package gpucontext provides shared GPU infrastructure for the gogpu ecosystem.

This package defines interfaces and utilities used across multiple gogpu projects to enable GPU resource sharing without circular dependencies:

  • DeviceProvider: Interface for providing GPU device and queue
  • Registry[T]: Generic registry for backend implementations
  • Type aliases: Convenience re-exports from wgpu/types

Consumers

  • gogpu/gogpu: Implements DeviceProvider via App/Renderer
  • gogpu/gg: Uses DeviceProvider for GPU-accelerated 2D rendering
  • born-ml/born: Implements and uses for GPU compute

Design Principles

This package follows the wgpu ecosystem pattern where shared types are separated from implementation (cf. wgpu-types in Rust).

The key insight is that GPU context (device + queue + related state) is a universal concept across Vulkan, CUDA, OpenGL, and WebGPU. By defining a minimal interface here, different packages can share GPU resources without depending on each other.

Example Usage

// In gogpu/gogpu - implements DeviceProvider
func (app *App) Device() gpucontext.Device { return app.renderer.device }
func (app *App) Queue() gpucontext.Queue { return app.renderer.queue }

// In gogpu/gg - uses DeviceProvider
func NewGPUCanvas(provider gpucontext.DeviceProvider) *Canvas {
    return &Canvas{
        device: provider.Device(),
        queue:  provider.Queue(),
    }
}

Reference: https://github.com/gogpu/gpucontext

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Adapter

type Adapter interface {
}

Adapter represents a physical GPU. Implemented by wgpu/hal.Adapter.

type Device

type Device interface {

	// Poll processes pending operations.
	Poll(wait bool)

	// Destroy releases the device resources.
	Destroy()
}

Device represents a logical GPU device. Implemented by wgpu/hal.Device.

type DeviceHandle

type DeviceHandle = DeviceProvider

DeviceHandle is an alias for DeviceProvider for backward compatibility. Deprecated: Use DeviceProvider instead.

type DeviceProvider

type DeviceProvider interface {
	// Device returns the WebGPU device handle.
	// The device is used for creating GPU resources (buffers, textures, pipelines).
	Device() Device

	// Queue returns the WebGPU command queue.
	// The queue is used for submitting command buffers to the GPU.
	Queue() Queue

	// SurfaceFormat returns the preferred texture format for the surface.
	// May return TextureFormatUndefined if no surface is attached (headless mode).
	// This is useful for creating render targets that match the surface format.
	SurfaceFormat() TextureFormat

	// Adapter returns the WebGPU adapter (optional, may be nil).
	// The adapter provides information about the GPU capabilities.
	// Some implementations may not expose the adapter.
	Adapter() Adapter
}

DeviceProvider provides access to GPU device, queue, and related resources. This interface enables dependency injection of GPU capabilities between packages without circular dependencies.

Implementations:

  • gogpu.App implements DeviceProvider via renderer
  • born.Session implements DeviceProvider for ML compute

Example usage in gg:

func NewGPUCanvas(provider gpucontext.DeviceProvider) *Canvas {
    return &Canvas{
        device: provider.Device(),
        queue:  provider.Queue(),
    }
}

type EventSource

type EventSource interface {

	// OnKeyPress registers a callback for key press events.
	OnKeyPress(func(key Key, mods Modifiers))

	// OnKeyRelease registers a callback for key release events.
	OnKeyRelease(func(key Key, mods Modifiers))

	// OnTextInput registers a callback for text input events.
	// Text input is the result of key presses after applying keyboard layouts
	// and input methods. This is the preferred way to handle text entry.
	OnTextInput(func(text string))

	// OnMouseMove registers a callback for mouse movement.
	OnMouseMove(func(x, y float64))

	// OnMousePress registers a callback for mouse button press.
	OnMousePress(func(button MouseButton, x, y float64))

	// OnMouseRelease registers a callback for mouse button release.
	OnMouseRelease(func(button MouseButton, x, y float64))

	// OnScroll registers a callback for scroll wheel events.
	// dx and dy are the scroll deltas (positive = right/down).
	OnScroll(func(dx, dy float64))

	// OnResize registers a callback for window resize.
	OnResize(func(width, height int))

	// OnFocus registers a callback for focus change.
	OnFocus(func(focused bool))
}

EventSource provides input events from the host application to UI frameworks.

This interface enables UI frameworks (like gogpu/ui) to receive user input events from the host window system. The host application (e.g., gogpu.App) implements EventSource and passes it to the UI layer.

Event callbacks are invoked on the main thread during the event loop. Callback functions should be fast and non-blocking.

Example usage in a UI framework:

func (ui *UI) AttachEvents(source gpucontext.EventSource) {
    source.OnMousePress(func(button MouseButton, x, y float64) {
        widget := ui.hitTest(x, y)
        if widget != nil {
            widget.HandleMouseDown(button, x, y)
        }
    })

    source.OnKeyPress(func(key Key, mods Modifiers) {
        ui.focused.HandleKeyDown(key, mods)
    })
}

Note: This interface is designed for gogpu ↔ ui integration. The rendering library (gg) does NOT use this interface.

type Instance

type Instance interface {
}

Instance is the entry point for GPU operations. Implemented by wgpu/hal.Instance.

type Key

type Key uint16

Key represents a keyboard key. Values follow a platform-independent virtual key code scheme.

const (
	KeyUnknown Key = iota

	// Letters
	KeyA
	KeyB
	KeyC
	KeyD
	KeyE
	KeyF
	KeyG
	KeyH
	KeyI
	KeyJ
	KeyK
	KeyL
	KeyM
	KeyN
	KeyO
	KeyP
	KeyQ
	KeyR
	KeyS
	KeyT
	KeyU
	KeyV
	KeyW
	KeyX
	KeyY
	KeyZ

	// Numbers
	Key0
	Key1
	Key2
	Key3
	Key4
	Key5
	Key6
	Key7
	Key8
	Key9

	// Function keys
	KeyF1
	KeyF2
	KeyF3
	KeyF4
	KeyF5
	KeyF6
	KeyF7
	KeyF8
	KeyF9
	KeyF10
	KeyF11
	KeyF12

	// Navigation
	KeyEscape
	KeyTab
	KeyBackspace
	KeyEnter
	KeySpace
	KeyInsert
	KeyDelete
	KeyHome
	KeyEnd
	KeyPageUp
	KeyPageDown
	KeyLeft
	KeyRight
	KeyUp
	KeyDown

	// Modifiers (as keys, not modifiers)
	KeyLeftShift
	KeyRightShift
	KeyLeftControl
	KeyRightControl
	KeyLeftAlt
	KeyRightAlt
	KeyLeftSuper
	KeyRightSuper

	// Punctuation
	KeyMinus
	KeyEqual
	KeyLeftBracket
	KeyRightBracket
	KeyBackslash
	KeySemicolon
	KeyApostrophe
	KeyGrave
	KeyComma
	KeyPeriod
	KeySlash

	// Numpad
	KeyNumpad0
	KeyNumpad1
	KeyNumpad2
	KeyNumpad3
	KeyNumpad4
	KeyNumpad5
	KeyNumpad6
	KeyNumpad7
	KeyNumpad8
	KeyNumpad9
	KeyNumpadDecimal
	KeyNumpadDivide
	KeyNumpadMultiply
	KeyNumpadSubtract
	KeyNumpadAdd
	KeyNumpadEnter

	// Other
	KeyCapsLock
	KeyScrollLock
	KeyNumLock
	KeyPrintScreen
	KeyPause
)

Common key codes. These match typical USB HID usage codes for cross-platform compatibility.

type Modifiers

type Modifiers uint8

Modifiers represents keyboard modifier keys.

const (
	// ModShift indicates the Shift key is pressed.
	ModShift Modifiers = 1 << iota

	// ModControl indicates the Control key is pressed.
	ModControl

	// ModAlt indicates the Alt key is pressed (Option on macOS).
	ModAlt

	// ModSuper indicates the Super key is pressed (Windows/Command).
	ModSuper

	// ModCapsLock indicates Caps Lock is active.
	ModCapsLock

	// ModNumLock indicates Num Lock is active.
	ModNumLock
)

func (Modifiers) HasAlt

func (m Modifiers) HasAlt() bool

HasAlt returns true if the Alt modifier is set.

func (Modifiers) HasControl

func (m Modifiers) HasControl() bool

HasControl returns true if the Control modifier is set.

func (Modifiers) HasShift

func (m Modifiers) HasShift() bool

HasShift returns true if the Shift modifier is set.

func (Modifiers) HasSuper

func (m Modifiers) HasSuper() bool

HasSuper returns true if the Super modifier is set.

type MouseButton

type MouseButton uint8

MouseButton represents a mouse button.

const (
	// MouseButtonLeft is the primary mouse button.
	MouseButtonLeft MouseButton = iota

	// MouseButtonRight is the secondary mouse button.
	MouseButtonRight

	// MouseButtonMiddle is the middle mouse button (scroll wheel click).
	MouseButtonMiddle

	// MouseButton4 is an extra mouse button.
	MouseButton4

	// MouseButton5 is an extra mouse button.
	MouseButton5
)

type NullEventSource

type NullEventSource struct{}

NullEventSource is an EventSource that ignores all event registrations. Used when events are not needed.

func (NullEventSource) OnFocus

func (NullEventSource) OnFocus(func(bool))

OnFocus does nothing.

func (NullEventSource) OnKeyPress

func (NullEventSource) OnKeyPress(func(Key, Modifiers))

OnKeyPress does nothing.

func (NullEventSource) OnKeyRelease

func (NullEventSource) OnKeyRelease(func(Key, Modifiers))

OnKeyRelease does nothing.

func (NullEventSource) OnMouseMove

func (NullEventSource) OnMouseMove(func(float64, float64))

OnMouseMove does nothing.

func (NullEventSource) OnMousePress

func (NullEventSource) OnMousePress(func(MouseButton, float64, float64))

OnMousePress does nothing.

func (NullEventSource) OnMouseRelease

func (NullEventSource) OnMouseRelease(func(MouseButton, float64, float64))

OnMouseRelease does nothing.

func (NullEventSource) OnResize

func (NullEventSource) OnResize(func(int, int))

OnResize does nothing.

func (NullEventSource) OnScroll

func (NullEventSource) OnScroll(func(float64, float64))

OnScroll does nothing.

func (NullEventSource) OnTextInput

func (NullEventSource) OnTextInput(func(string))

OnTextInput does nothing.

type OpenDevice

type OpenDevice struct {
	Device Device
	Queue  Queue
}

OpenDevice bundles a device and queue together. This is a convenience type for initialization.

type Queue

type Queue interface {
}

Queue represents a GPU command queue. Implemented by wgpu/hal.Queue.

type Registry

type Registry[T any] struct {
	// contains filtered or unexported fields
}

Registry provides thread-safe registration and lookup of named factories. It supports priority-based selection when multiple implementations exist.

Type parameter T is the type returned by factories.

Example:

var backends = gpucontext.NewRegistry[Backend](
    gpucontext.WithPriority("vulkan", "dx12", "metal", "gles", "software"),
)

backends.Register("vulkan", func() Backend { return NewVulkanBackend() })
backends.Register("software", func() Backend { return NewSoftwareBackend() })

best := backends.Best() // Returns vulkan if available, otherwise software

func NewRegistry

func NewRegistry[T any](opts ...RegistryOption) *Registry[T]

NewRegistry creates a new Registry with optional configuration.

func (*Registry[T]) Available

func (r *Registry[T]) Available() []string

Available returns all registered names. Thread-safe.

func (*Registry[T]) Best

func (r *Registry[T]) Best() T

Best returns the highest-priority registered implementation. Returns the zero value of T if no implementations are registered. Thread-safe.

func (*Registry[T]) BestName

func (r *Registry[T]) BestName() string

BestName returns the name of the highest-priority registered implementation. Returns empty string if no implementations are registered. Thread-safe.

func (*Registry[T]) Count

func (r *Registry[T]) Count() int

Count returns the number of registered factories. Thread-safe.

func (*Registry[T]) Get

func (r *Registry[T]) Get(name string) T

Get returns the factory output for the given name. Returns the zero value of T if not found. Thread-safe.

func (*Registry[T]) Has

func (r *Registry[T]) Has(name string) bool

Has returns true if a factory with the given name is registered. Thread-safe.

func (*Registry[T]) Register

func (r *Registry[T]) Register(name string, factory func() T)

Register adds a factory for the given name. If a factory with the same name already exists, it is replaced. Thread-safe.

func (*Registry[T]) Unregister

func (r *Registry[T]) Unregister(name string)

Unregister removes the factory with the given name. Thread-safe.

type RegistryOption

type RegistryOption func(*registryConfig)

RegistryOption configures a Registry.

func WithPriority

func WithPriority(names ...string) RegistryOption

WithPriority sets the priority order for backend selection. Backends listed first are preferred over backends listed later. Backends not in the list have lowest priority (in registration order).

type Surface

type Surface interface {
}

Surface represents a rendering surface (window). Implemented by wgpu/hal.Surface.

type TextureFormat

type TextureFormat uint32

TextureFormat specifies the format of texture data. Values match the WebGPU specification.

const (
	TextureFormatUndefined      TextureFormat = 0
	TextureFormatRGBA8Unorm     TextureFormat = 1
	TextureFormatRGBA8UnormSrgb TextureFormat = 2
	TextureFormatBGRA8Unorm     TextureFormat = 3
	TextureFormatBGRA8UnormSrgb TextureFormat = 4
)

Common texture formats matching WebGPU spec.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL