core

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2025 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package core provides validation and state management for WebGPU resources.

This package implements the core layer between the user-facing API and the hardware abstraction layer (HAL). It handles:

  • Type-safe resource identifiers (ID system)
  • Resource lifecycle management (Registry)
  • State tracking and validation
  • Error handling with detailed messages

Architecture:

types/  → Data structures (no logic)
core/   → Validation + State tracking (this package)
hal/    → Hardware abstraction layer

The design follows wgpu-core from the Rust wgpu project, adapted for idiomatic Go 1.25+ with generics and modern concurrency patterns.

ID System:

Resources are identified by type-safe IDs that combine an index and epoch:

type DeviceID = ID[deviceMarker]
id := NewID[deviceMarker](index, epoch)
index, epoch := id.Unzip()

The epoch prevents use-after-free bugs by invalidating old IDs when resources are recycled.

Registry Pattern:

Resources are stored in typed registries that manage their lifecycle:

registry := NewRegistry[Device, deviceMarker]()
id, err := registry.Register(device)
device, err := registry.Get(id)
registry.Unregister(id)

Thread Safety:

All types in this package are safe for concurrent use unless explicitly documented otherwise.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidID is returned when an ID is invalid or zero.
	ErrInvalidID = errors.New("invalid resource ID")

	// ErrResourceNotFound is returned when a resource is not found in the registry.
	ErrResourceNotFound = errors.New("resource not found")

	// ErrEpochMismatch is returned when the epoch of an ID doesn't match the stored resource.
	ErrEpochMismatch = errors.New("epoch mismatch: resource was recycled")

	// ErrRegistryFull is returned when the registry cannot allocate more IDs.
	ErrRegistryFull = errors.New("registry full: maximum resources reached")

	// ErrResourceInUse is returned when trying to unregister a resource that is still in use.
	ErrResourceInUse = errors.New("resource is still in use")

	// ErrAlreadyDestroyed is returned when operating on an already destroyed resource.
	ErrAlreadyDestroyed = errors.New("resource already destroyed")
)

Base errors for the core package.

Functions

func AdapterDrop

func AdapterDrop(id AdapterID) error

AdapterDrop releases the specified adapter and its associated resources. After calling this function, the adapter ID becomes invalid.

Returns an error if the adapter ID is invalid or if the adapter cannot be released (e.g., devices are still using it).

Note: Currently this is a simple unregister. In a full implementation, this would check for active devices and properly clean up resources.

func DeviceDrop

func DeviceDrop(id DeviceID) error

DeviceDrop destroys the device and its queue. After calling this function, the device ID and its queue ID become invalid.

Returns an error if the device ID is invalid or if the device cannot be released (e.g., resources are still using it).

Note: Currently this is a simple unregister. In a full implementation, this would check for active resources and properly clean up.

func GetAdapterFeatures

func GetAdapterFeatures(id AdapterID) (types.Features, error)

GetAdapterFeatures returns the features supported by the specified adapter. Returns an error if the adapter ID is invalid.

func GetAdapterInfo

func GetAdapterInfo(id AdapterID) (types.AdapterInfo, error)

GetAdapterInfo returns information about the specified adapter. Returns an error if the adapter ID is invalid.

func GetAdapterLimits

func GetAdapterLimits(id AdapterID) (types.Limits, error)

GetAdapterLimits returns the resource limits of the specified adapter. Returns an error if the adapter ID is invalid.

func GetDeviceFeatures

func GetDeviceFeatures(id DeviceID) (types.Features, error)

GetDeviceFeatures returns the device's enabled features. Returns an error if the device ID is invalid.

func GetDeviceLimits

func GetDeviceLimits(id DeviceID) (types.Limits, error)

GetDeviceLimits returns the device's limits. Returns an error if the device ID is invalid.

func IsFeatureError

func IsFeatureError(err error) bool

IsFeatureError returns true if the error is a FeatureError.

func IsIDError

func IsIDError(err error) bool

IsIDError returns true if the error is an IDError.

func IsLimitError

func IsLimitError(err error) bool

IsLimitError returns true if the error is a LimitError.

func IsValidationError

func IsValidationError(err error) bool

IsValidationError returns true if the error is a ValidationError.

func QueueOnSubmittedWorkDone

func QueueOnSubmittedWorkDone(id QueueID) error

QueueOnSubmittedWorkDone returns when all submitted work completes. In the Pure Go implementation, this is synchronous for now.

This function blocks until all work submitted to the queue before this call has completed execution on the GPU.

Returns an error if the queue ID is invalid.

func QueueSubmit

func QueueSubmit(id QueueID, commandBuffers []CommandBufferID) error

QueueSubmit submits command buffers to the queue. This is a placeholder implementation that will be expanded later.

The command buffers are executed in order. After submission, the command buffer IDs become invalid and cannot be reused.

Returns an error if the queue ID is invalid or if submission fails.

func QueueWriteBuffer

func QueueWriteBuffer(id QueueID, buffer BufferID, offset uint64, data []byte) error

QueueWriteBuffer writes data to a buffer through the queue. This is a placeholder implementation that will be expanded later.

This is a convenience method for updating buffer data without creating a staging buffer. The data is written at the specified offset in the buffer.

Returns an error if the queue ID or buffer ID is invalid, or if the write operation fails.

func QueueWriteTexture

func QueueWriteTexture(id QueueID, dst *types.ImageCopyTexture, data []byte, layout *types.TextureDataLayout, size *types.Extent3D) error

QueueWriteTexture writes data to a texture through the queue. This is a placeholder implementation that will be expanded later.

This is a convenience method for updating texture data without creating a staging buffer. The data is written to the specified texture region.

Returns an error if the queue ID or texture ID is invalid, or if the write operation fails.

func ResetGlobal

func ResetGlobal()

ResetGlobal resets the global instance for testing. This allows tests to start with a clean state. Should only be used in tests.

Types

type Adapter

type Adapter struct {
	// Info contains information about the adapter.
	Info types.AdapterInfo
	// Features contains the features supported by the adapter.
	Features types.Features
	// Limits contains the resource limits of the adapter.
	Limits types.Limits
	// Backend identifies which graphics backend this adapter uses.
	Backend types.Backend
}

Adapter represents a physical GPU adapter.

type AdapterID

type AdapterID = ID[adapterMarker]

AdapterID identifies an Adapter resource.

type BindGroup

type BindGroup struct{}

BindGroup represents a collection of resources bound together.

type BindGroupID

type BindGroupID = ID[bindGroupMarker]

BindGroupID identifies a BindGroup resource.

type BindGroupLayout

type BindGroupLayout struct{}

BindGroupLayout represents the layout of a bind group.

type BindGroupLayoutID

type BindGroupLayoutID = ID[bindGroupLayoutMarker]

BindGroupLayoutID identifies a BindGroupLayout resource.

type Buffer

type Buffer struct{}

Buffer represents a GPU buffer.

type BufferID

type BufferID = ID[bufferMarker]

BufferID identifies a Buffer resource.

func DeviceCreateBuffer

func DeviceCreateBuffer(id DeviceID, desc *types.BufferDescriptor) (BufferID, error)

DeviceCreateBuffer creates a buffer on this device. This is a placeholder implementation that will be expanded later.

Returns a buffer ID that can be used to access the buffer, or an error if buffer creation fails.

type CommandBuffer

type CommandBuffer struct{}

CommandBuffer represents a recorded command buffer.

type CommandBufferID

type CommandBufferID = ID[commandBufferMarker]

CommandBufferID identifies a CommandBuffer resource.

type CommandEncoder

type CommandEncoder struct{}

CommandEncoder represents a command encoder.

type CommandEncoderID

type CommandEncoderID = ID[commandEncoderMarker]

CommandEncoderID identifies a CommandEncoder resource.

type ComputePipeline

type ComputePipeline struct{}

ComputePipeline represents a compute pipeline.

type ComputePipelineID

type ComputePipelineID = ID[computePipelineMarker]

ComputePipelineID identifies a ComputePipeline resource.

type Device

type Device struct {
	// Adapter is the adapter this device was created from.
	Adapter AdapterID
	// Label is a debug label for the device.
	Label string
	// Features contains the features enabled on this device.
	Features types.Features
	// Limits contains the resource limits of this device.
	Limits types.Limits
	// Queue is the device's default queue.
	Queue QueueID
}

Device represents a logical GPU device.

func GetDevice

func GetDevice(id DeviceID) (*Device, error)

GetDevice retrieves device data. Returns an error if the device ID is invalid.

type DeviceID

type DeviceID = ID[deviceMarker]

DeviceID identifies a Device resource.

func CreateDevice

func CreateDevice(adapterID AdapterID, desc *types.DeviceDescriptor) (DeviceID, error)

CreateDevice creates a device from an adapter. This is called internally by RequestDevice in adapter.go.

The device is created with the specified features and limits, and a default queue is automatically created.

Returns the device ID and an error if device creation fails.

func RequestDevice

func RequestDevice(adapterID AdapterID, desc *types.DeviceDescriptor) (DeviceID, error)

RequestDevice creates a logical device from the specified adapter. The device is configured according to the provided descriptor.

The descriptor specifies:

  • Required features the device must support
  • Required limits the device must meet
  • Debug label for the device

Returns a DeviceID that can be used to access the device, or an error if device creation fails.

Common failure reasons:

  • Invalid adapter ID
  • Requested features not supported by adapter
  • Requested limits exceed adapter capabilities

type Epoch

type Epoch = uint32

Epoch is the generation component of a resource ID. It prevents use-after-free by invalidating old IDs.

type FeatureError

type FeatureError struct {
	Feature  string // Name of the missing feature
	Resource string // Resource that requires it
}

FeatureError represents a missing required feature.

func NewFeatureError

func NewFeatureError(resource, feature string) *FeatureError

NewFeatureError creates a new feature error.

func (*FeatureError) Error

func (e *FeatureError) Error() string

Error implements the error interface.

type Global

type Global struct {
	// contains filtered or unexported fields
}

Global is the singleton managing global WebGPU state. It holds the Hub (for GPU resources) and the surface registry.

The Global provides the top-level API for resource management, coordinating between surfaces and the GPU resource hub.

Thread-safe for concurrent use via singleton pattern.

func GetGlobal

func GetGlobal() *Global

GetGlobal returns the singleton Global instance. The instance is created lazily on first call.

func (*Global) Clear

func (g *Global) Clear()

Clear removes all resources from the global state. Note: This does not release IDs properly - use only for cleanup/testing.

func (*Global) GetSurface

func (g *Global) GetSurface(id SurfaceID) (Surface, error)

GetSurface retrieves a surface by ID.

func (*Global) Hub

func (g *Global) Hub() *Hub

Hub returns the GPU resource hub. The hub manages all GPU resources (adapters, devices, buffers, etc.).

func (*Global) RegisterSurface

func (g *Global) RegisterSurface(surface Surface) SurfaceID

RegisterSurface allocates a new ID and stores the surface. Surfaces are managed separately from other GPU resources because they're tied to windowing systems and created before adapters.

func (*Global) Stats

func (g *Global) Stats() map[string]uint64

Stats returns statistics about global resource usage. Returns surface count and all hub resource counts.

func (*Global) SurfaceCount

func (g *Global) SurfaceCount() uint64

SurfaceCount returns the number of registered surfaces.

func (*Global) UnregisterSurface

func (g *Global) UnregisterSurface(id SurfaceID) (Surface, error)

UnregisterSurface removes a surface by ID.

type Hub

type Hub struct {
	// contains filtered or unexported fields
}

Hub manages all resource registries for WebGPU. It's the central storage for all GPU resources (adapters, devices, buffers, etc.).

The Hub is organized by resource type, with each type having its own registry. This provides type-safe access to resources and automatic ID management.

Thread-safe for concurrent use.

func NewHub

func NewHub() *Hub

NewHub creates a new hub with initialized registries for all resource types.

func (*Hub) Clear

func (h *Hub) Clear()

Clear removes all resources from the hub. Note: This does not release IDs properly - use only for cleanup/testing.

func (*Hub) GetAdapter

func (h *Hub) GetAdapter(id AdapterID) (Adapter, error)

GetAdapter retrieves an adapter by ID.

func (*Hub) GetBindGroup

func (h *Hub) GetBindGroup(id BindGroupID) (BindGroup, error)

GetBindGroup retrieves a bind group by ID.

func (*Hub) GetBindGroupLayout

func (h *Hub) GetBindGroupLayout(id BindGroupLayoutID) (BindGroupLayout, error)

GetBindGroupLayout retrieves a bind group layout by ID.

func (*Hub) GetBuffer

func (h *Hub) GetBuffer(id BufferID) (Buffer, error)

GetBuffer retrieves a buffer by ID.

func (*Hub) GetCommandBuffer

func (h *Hub) GetCommandBuffer(id CommandBufferID) (CommandBuffer, error)

GetCommandBuffer retrieves a command buffer by ID.

func (*Hub) GetCommandEncoder

func (h *Hub) GetCommandEncoder(id CommandEncoderID) (CommandEncoder, error)

GetCommandEncoder retrieves a command encoder by ID.

func (*Hub) GetComputePipeline

func (h *Hub) GetComputePipeline(id ComputePipelineID) (ComputePipeline, error)

GetComputePipeline retrieves a compute pipeline by ID.

func (*Hub) GetDevice

func (h *Hub) GetDevice(id DeviceID) (Device, error)

GetDevice retrieves a device by ID.

func (*Hub) GetPipelineLayout

func (h *Hub) GetPipelineLayout(id PipelineLayoutID) (PipelineLayout, error)

GetPipelineLayout retrieves a pipeline layout by ID.

func (*Hub) GetQuerySet

func (h *Hub) GetQuerySet(id QuerySetID) (QuerySet, error)

GetQuerySet retrieves a query set by ID.

func (*Hub) GetQueue

func (h *Hub) GetQueue(id QueueID) (Queue, error)

GetQueue retrieves a queue by ID.

func (*Hub) GetRenderPipeline

func (h *Hub) GetRenderPipeline(id RenderPipelineID) (RenderPipeline, error)

GetRenderPipeline retrieves a render pipeline by ID.

func (*Hub) GetSampler

func (h *Hub) GetSampler(id SamplerID) (Sampler, error)

GetSampler retrieves a sampler by ID.

func (*Hub) GetShaderModule

func (h *Hub) GetShaderModule(id ShaderModuleID) (ShaderModule, error)

GetShaderModule retrieves a shader module by ID.

func (*Hub) GetTexture

func (h *Hub) GetTexture(id TextureID) (Texture, error)

GetTexture retrieves a texture by ID.

func (*Hub) GetTextureView

func (h *Hub) GetTextureView(id TextureViewID) (TextureView, error)

GetTextureView retrieves a texture view by ID.

func (*Hub) RegisterAdapter

func (h *Hub) RegisterAdapter(adapter *Adapter) AdapterID

RegisterAdapter allocates a new ID and stores the adapter.

func (*Hub) RegisterBindGroup

func (h *Hub) RegisterBindGroup(group BindGroup) BindGroupID

RegisterBindGroup allocates a new ID and stores the bind group.

func (*Hub) RegisterBindGroupLayout

func (h *Hub) RegisterBindGroupLayout(layout BindGroupLayout) BindGroupLayoutID

RegisterBindGroupLayout allocates a new ID and stores the bind group layout.

func (*Hub) RegisterBuffer

func (h *Hub) RegisterBuffer(buffer Buffer) BufferID

RegisterBuffer allocates a new ID and stores the buffer.

func (*Hub) RegisterCommandBuffer

func (h *Hub) RegisterCommandBuffer(buffer CommandBuffer) CommandBufferID

RegisterCommandBuffer allocates a new ID and stores the command buffer.

func (*Hub) RegisterCommandEncoder

func (h *Hub) RegisterCommandEncoder(encoder CommandEncoder) CommandEncoderID

RegisterCommandEncoder allocates a new ID and stores the command encoder.

func (*Hub) RegisterComputePipeline

func (h *Hub) RegisterComputePipeline(pipeline ComputePipeline) ComputePipelineID

RegisterComputePipeline allocates a new ID and stores the compute pipeline.

func (*Hub) RegisterDevice

func (h *Hub) RegisterDevice(device Device) DeviceID

RegisterDevice allocates a new ID and stores the device.

func (*Hub) RegisterPipelineLayout

func (h *Hub) RegisterPipelineLayout(layout PipelineLayout) PipelineLayoutID

RegisterPipelineLayout allocates a new ID and stores the pipeline layout.

func (*Hub) RegisterQuerySet

func (h *Hub) RegisterQuerySet(querySet QuerySet) QuerySetID

RegisterQuerySet allocates a new ID and stores the query set.

func (*Hub) RegisterQueue

func (h *Hub) RegisterQueue(queue Queue) QueueID

RegisterQueue allocates a new ID and stores the queue.

func (*Hub) RegisterRenderPipeline

func (h *Hub) RegisterRenderPipeline(pipeline RenderPipeline) RenderPipelineID

RegisterRenderPipeline allocates a new ID and stores the render pipeline.

func (*Hub) RegisterSampler

func (h *Hub) RegisterSampler(sampler Sampler) SamplerID

RegisterSampler allocates a new ID and stores the sampler.

func (*Hub) RegisterShaderModule

func (h *Hub) RegisterShaderModule(module ShaderModule) ShaderModuleID

RegisterShaderModule allocates a new ID and stores the shader module.

func (*Hub) RegisterTexture

func (h *Hub) RegisterTexture(texture Texture) TextureID

RegisterTexture allocates a new ID and stores the texture.

func (*Hub) RegisterTextureView

func (h *Hub) RegisterTextureView(view TextureView) TextureViewID

RegisterTextureView allocates a new ID and stores the texture view.

func (*Hub) ResourceCounts

func (h *Hub) ResourceCounts() map[string]uint64

ResourceCounts returns the count of each resource type in the hub. Useful for debugging and diagnostics.

func (*Hub) UnregisterAdapter

func (h *Hub) UnregisterAdapter(id AdapterID) (Adapter, error)

UnregisterAdapter removes an adapter by ID.

func (*Hub) UnregisterBindGroup

func (h *Hub) UnregisterBindGroup(id BindGroupID) (BindGroup, error)

UnregisterBindGroup removes a bind group by ID.

func (*Hub) UnregisterBindGroupLayout

func (h *Hub) UnregisterBindGroupLayout(id BindGroupLayoutID) (BindGroupLayout, error)

UnregisterBindGroupLayout removes a bind group layout by ID.

func (*Hub) UnregisterBuffer

func (h *Hub) UnregisterBuffer(id BufferID) (Buffer, error)

UnregisterBuffer removes a buffer by ID.

func (*Hub) UnregisterCommandBuffer

func (h *Hub) UnregisterCommandBuffer(id CommandBufferID) (CommandBuffer, error)

UnregisterCommandBuffer removes a command buffer by ID.

func (*Hub) UnregisterCommandEncoder

func (h *Hub) UnregisterCommandEncoder(id CommandEncoderID) (CommandEncoder, error)

UnregisterCommandEncoder removes a command encoder by ID.

func (*Hub) UnregisterComputePipeline

func (h *Hub) UnregisterComputePipeline(id ComputePipelineID) (ComputePipeline, error)

UnregisterComputePipeline removes a compute pipeline by ID.

func (*Hub) UnregisterDevice

func (h *Hub) UnregisterDevice(id DeviceID) (Device, error)

UnregisterDevice removes a device by ID.

func (*Hub) UnregisterPipelineLayout

func (h *Hub) UnregisterPipelineLayout(id PipelineLayoutID) (PipelineLayout, error)

UnregisterPipelineLayout removes a pipeline layout by ID.

func (*Hub) UnregisterQuerySet

func (h *Hub) UnregisterQuerySet(id QuerySetID) (QuerySet, error)

UnregisterQuerySet removes a query set by ID.

func (*Hub) UnregisterQueue

func (h *Hub) UnregisterQueue(id QueueID) (Queue, error)

UnregisterQueue removes a queue by ID.

func (*Hub) UnregisterRenderPipeline

func (h *Hub) UnregisterRenderPipeline(id RenderPipelineID) (RenderPipeline, error)

UnregisterRenderPipeline removes a render pipeline by ID.

func (*Hub) UnregisterSampler

func (h *Hub) UnregisterSampler(id SamplerID) (Sampler, error)

UnregisterSampler removes a sampler by ID.

func (*Hub) UnregisterShaderModule

func (h *Hub) UnregisterShaderModule(id ShaderModuleID) (ShaderModule, error)

UnregisterShaderModule removes a shader module by ID.

func (*Hub) UnregisterTexture

func (h *Hub) UnregisterTexture(id TextureID) (Texture, error)

UnregisterTexture removes a texture by ID.

func (*Hub) UnregisterTextureView

func (h *Hub) UnregisterTextureView(id TextureViewID) (TextureView, error)

UnregisterTextureView removes a texture view by ID.

func (*Hub) UpdateQueue

func (h *Hub) UpdateQueue(id QueueID, queue Queue) error

UpdateQueue updates a queue by ID.

type ID

type ID[T Marker] struct {
	// contains filtered or unexported fields
}

ID is a type-safe resource identifier parameterized by a marker type. Different resource types (Device, Buffer, Texture, etc.) have different marker types, preventing accidental misuse of IDs.

func FromRaw

func FromRaw[T Marker](raw RawID) ID[T]

FromRaw creates an ID from a raw representation. Use with caution - the caller must ensure type safety.

func NewID

func NewID[T Marker](index Index, epoch Epoch) ID[T]

NewID creates a new ID from index and epoch components.

func (ID[T]) Epoch

func (id ID[T]) Epoch() Epoch

Epoch returns the epoch component of the ID.

func (ID[T]) Index

func (id ID[T]) Index() Index

Index returns the index component of the ID.

func (ID[T]) IsZero

func (id ID[T]) IsZero() bool

IsZero returns true if the ID is zero (invalid).

func (ID[T]) Raw

func (id ID[T]) Raw() RawID

Raw returns the underlying RawID.

func (ID[T]) String

func (id ID[T]) String() string

String returns a string representation of the ID.

func (ID[T]) Unzip

func (id ID[T]) Unzip() (Index, Epoch)

Unzip extracts the index and epoch from the ID.

type IDError

type IDError struct {
	ID      RawID  // The problematic ID
	Message string // Error description
	Cause   error  // Underlying cause
}

IDError represents an error related to resource IDs.

func NewIDError

func NewIDError(id RawID, message string, cause error) *IDError

NewIDError creates a new ID error.

func (*IDError) Error

func (e *IDError) Error() string

Error implements the error interface.

func (*IDError) Unwrap

func (e *IDError) Unwrap() error

Unwrap returns the underlying cause.

type IdentityManager

type IdentityManager[T Marker] struct {
	// contains filtered or unexported fields
}

IdentityManager allocates and manages type-safe resource IDs.

It maintains a pool of available indices and tracks epochs to prevent use-after-free bugs. When an ID is released, its index is recycled but with an incremented epoch, ensuring old IDs become invalid.

Thread-safe for concurrent use.

func NewIdentityManager

func NewIdentityManager[T Marker]() *IdentityManager[T]

NewIdentityManager creates a new identity manager for the given marker type.

func (*IdentityManager[T]) Alloc

func (m *IdentityManager[T]) Alloc() ID[T]

Alloc allocates a fresh, never-before-seen ID.

If there are released IDs available, their indices are reused with an incremented epoch. Otherwise, a new index is allocated.

The epoch starts at 1 (not 0) so that zero IDs are always invalid.

func (*IdentityManager[T]) Count

func (m *IdentityManager[T]) Count() uint64

Count returns the number of currently allocated IDs.

func (*IdentityManager[T]) FreeCount

func (m *IdentityManager[T]) FreeCount() int

FreeCount returns the number of IDs available for reuse (for testing).

func (*IdentityManager[T]) NextIndex

func (m *IdentityManager[T]) NextIndex() Index

NextIndex returns the next index that would be allocated (for testing).

func (*IdentityManager[T]) Release

func (m *IdentityManager[T]) Release(id ID[T])

Release marks an ID as freed, making its index available for reuse.

After release, the ID becomes invalid. Any attempt to use it will fail with an epoch mismatch error.

type Index

type Index = uint32

Index is the index component of a resource ID. It identifies the slot in the storage array.

type Instance

type Instance struct {
	// contains filtered or unexported fields
}

Instance represents a WebGPU instance for GPU discovery and initialization. The instance is responsible for enumerating available GPU adapters and creating adapters based on application requirements.

An instance maintains the list of available backends and their configuration. It is the entry point for all WebGPU operations.

Thread-safe for concurrent use.

func NewInstance

func NewInstance(desc *types.InstanceDescriptor) *Instance

NewInstance creates a new WebGPU instance with the given descriptor. If desc is nil, default settings are used.

The instance will enumerate available GPU adapters based on the enabled backends specified in the descriptor.

func (*Instance) Backends

func (i *Instance) Backends() types.Backends

Backends returns the enabled backends for this instance.

func (*Instance) EnumerateAdapters

func (i *Instance) EnumerateAdapters() []AdapterID

EnumerateAdapters returns a list of all available GPU adapters. The adapters are filtered based on the backends enabled in the instance.

This method returns a snapshot of available adapters at the time of the call. The adapter list may change if GPUs are added or removed from the system.

func (*Instance) Flags

func (i *Instance) Flags() types.InstanceFlags

Flags returns the instance flags.

func (*Instance) RequestAdapter

func (i *Instance) RequestAdapter(options *types.RequestAdapterOptions) (AdapterID, error)

RequestAdapter requests an adapter matching the given options. Returns the first adapter that meets the requirements, or an error if none found.

Options control adapter selection:

  • PowerPreference: prefer low-power or high-performance adapters
  • ForceFallbackAdapter: use software rendering
  • CompatibleSurface: adapter must support the given surface

If options is nil, the first available adapter is returned.

type LimitError

type LimitError struct {
	Limit    string // Name of the limit
	Actual   uint64 // Actual value
	Maximum  uint64 // Maximum allowed value
	Resource string // Resource type affected
}

LimitError represents exceeding a resource limit.

func NewLimitError

func NewLimitError(resource, limit string, actual, maximum uint64) *LimitError

NewLimitError creates a new limit error.

func (*LimitError) Error

func (e *LimitError) Error() string

Error implements the error interface.

type Marker

type Marker interface {
	// contains filtered or unexported methods
}

Marker is a constraint for marker types used to distinguish ID types. Marker types are empty structs that provide compile-time type safety.

type PipelineLayout

type PipelineLayout struct{}

PipelineLayout represents the layout of a pipeline.

type PipelineLayoutID

type PipelineLayoutID = ID[pipelineLayoutMarker]

PipelineLayoutID identifies a PipelineLayout resource.

type QuerySet

type QuerySet struct{}

QuerySet represents a set of queries.

type QuerySetID

type QuerySetID = ID[querySetMarker]

QuerySetID identifies a QuerySet resource.

type Queue

type Queue struct {
	// Device is the device this queue belongs to.
	Device DeviceID
	// Label is a debug label for the queue.
	Label string
}

Queue represents a command queue for a device.

func GetQueue

func GetQueue(id QueueID) (*Queue, error)

GetQueue retrieves queue data. Returns an error if the queue ID is invalid.

type QueueID

type QueueID = ID[queueMarker]

QueueID identifies a Queue resource.

func GetDeviceQueue

func GetDeviceQueue(id DeviceID) (QueueID, error)

GetDeviceQueue returns the device's queue. Returns an error if the device ID is invalid.

type RawID

type RawID uint64

RawID is the underlying 64-bit representation of a resource identifier. Layout: lower 32 bits = index, upper 32 bits = epoch.

func Zip

func Zip(index Index, epoch Epoch) RawID

Zip combines an index and epoch into a RawID.

func (RawID) Epoch

func (id RawID) Epoch() Epoch

Epoch returns the epoch component of the RawID.

func (RawID) Index

func (id RawID) Index() Index

Index returns the index component of the RawID.

func (RawID) IsZero

func (id RawID) IsZero() bool

IsZero returns true if both index and epoch are zero.

func (RawID) String

func (id RawID) String() string

String returns a string representation of the RawID.

func (RawID) Unzip

func (id RawID) Unzip() (Index, Epoch)

Unzip extracts the index and epoch from a RawID.

type Registry

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

Registry manages the lifecycle of resources of a specific type.

It combines IdentityManager (for ID allocation) with Storage (for item storage) to provide a complete resource management solution.

Thread-safe for concurrent use.

func NewRegistry

func NewRegistry[T any, M Marker]() *Registry[T, M]

NewRegistry creates a new registry for the given types.

func (*Registry[T, M]) Clear

func (r *Registry[T, M]) Clear()

Clear removes all items from the registry. Note: This does not release IDs properly - use only for cleanup.

func (*Registry[T, M]) Contains

func (r *Registry[T, M]) Contains(id ID[M]) bool

Contains checks if an item exists at the given ID.

func (*Registry[T, M]) Count

func (r *Registry[T, M]) Count() uint64

Count returns the number of registered items.

func (*Registry[T, M]) ForEach

func (r *Registry[T, M]) ForEach(fn func(ID[M], T) bool)

ForEach iterates over all registered items. The callback receives the ID and item for each entry. Return false from the callback to stop iteration.

func (*Registry[T, M]) Get

func (r *Registry[T, M]) Get(id ID[M]) (T, error)

Get retrieves an item by ID. Returns the item and nil error if found, or zero value and error if not found or epoch mismatch.

func (*Registry[T, M]) GetMut

func (r *Registry[T, M]) GetMut(id ID[M], fn func(*T)) error

GetMut retrieves an item by ID for mutation. The callback is called with a pointer to the item if found. Returns nil if successful, or error if not found.

func (*Registry[T, M]) Register

func (r *Registry[T, M]) Register(item T) ID[M]

Register allocates a new ID and stores the item. Returns the allocated ID.

func (*Registry[T, M]) Unregister

func (r *Registry[T, M]) Unregister(id ID[M]) (T, error)

Unregister removes an item by ID and releases the ID for reuse. Returns the removed item and nil error, or zero value and error if not found.

type RenderPipeline

type RenderPipeline struct{}

RenderPipeline represents a render pipeline.

type RenderPipelineID

type RenderPipelineID = ID[renderPipelineMarker]

RenderPipelineID identifies a RenderPipeline resource.

type Sampler

type Sampler struct{}

Sampler represents a texture sampler.

type SamplerID

type SamplerID = ID[samplerMarker]

SamplerID identifies a Sampler resource.

type ShaderModule

type ShaderModule struct{}

ShaderModule represents a compiled shader module.

type ShaderModuleID

type ShaderModuleID = ID[shaderModuleMarker]

ShaderModuleID identifies a ShaderModule resource.

func DeviceCreateShaderModule

func DeviceCreateShaderModule(id DeviceID, desc *types.ShaderModuleDescriptor) (ShaderModuleID, error)

DeviceCreateShaderModule creates a shader module. This is a placeholder implementation that will be expanded later.

Returns a shader module ID that can be used to access the module, or an error if module creation fails.

type Storage

type Storage[T any, M Marker] struct {
	// contains filtered or unexported fields
}

Storage is an indexed array that stores items by their ID index.

It provides O(1) access to items using the index component of an ID, while validating the epoch to prevent use-after-free.

Thread-safe for concurrent use.

func NewStorage

func NewStorage[T any, M Marker](capacity int) *Storage[T, M]

NewStorage creates a new storage with optional initial capacity.

func (*Storage[T, M]) Capacity

func (s *Storage[T, M]) Capacity() int

Capacity returns the current capacity of the storage.

func (*Storage[T, M]) Clear

func (s *Storage[T, M]) Clear()

Clear removes all items from storage.

func (*Storage[T, M]) Contains

func (s *Storage[T, M]) Contains(id ID[M]) bool

Contains checks if an item exists at the given ID with matching epoch.

func (*Storage[T, M]) ForEach

func (s *Storage[T, M]) ForEach(fn func(ID[M], T) bool)

ForEach iterates over all valid items in storage. The callback receives the ID and item for each valid entry. Iteration order is by index.

func (*Storage[T, M]) Get

func (s *Storage[T, M]) Get(id ID[M]) (T, bool)

Get retrieves an item by ID, validating the epoch. Returns the item and true if found with matching epoch, zero value and false otherwise.

func (*Storage[T, M]) GetMut

func (s *Storage[T, M]) GetMut(id ID[M], fn func(*T)) bool

GetMut retrieves an item by ID for mutation. The callback is called with the item if found, while holding the write lock. Returns true if the item was found and the callback was called.

func (*Storage[T, M]) Insert

func (s *Storage[T, M]) Insert(id ID[M], item T)

Insert stores an item at the given ID's index with its epoch. If the index is beyond current capacity, the storage grows automatically.

func (*Storage[T, M]) Len

func (s *Storage[T, M]) Len() int

Len returns the number of valid items in storage.

func (*Storage[T, M]) Remove

func (s *Storage[T, M]) Remove(id ID[M]) (T, bool)

Remove removes an item by ID, returning it if found. Returns the item and true if found, zero value and false otherwise.

type StorageItem

type StorageItem interface {
}

StorageItem is a constraint for items that can be stored in Storage. Items must have an associated marker type for type-safe ID access.

type Surface

type Surface struct{}

Surface represents a rendering surface.

type SurfaceID

type SurfaceID = ID[surfaceMarker]

SurfaceID identifies a Surface resource.

type Texture

type Texture struct{}

Texture represents a GPU texture.

type TextureID

type TextureID = ID[textureMarker]

TextureID identifies a Texture resource.

func DeviceCreateTexture

func DeviceCreateTexture(id DeviceID, desc *types.TextureDescriptor) (TextureID, error)

DeviceCreateTexture creates a texture on this device. This is a placeholder implementation that will be expanded later.

Returns a texture ID that can be used to access the texture, or an error if texture creation fails.

type TextureView

type TextureView struct{}

TextureView represents a view into a texture.

type TextureViewID

type TextureViewID = ID[textureViewMarker]

TextureViewID identifies a TextureView resource.

type ValidationError

type ValidationError struct {
	Resource string // Resource type (e.g., "Buffer", "Texture")
	Field    string // Field that failed validation
	Message  string // Detailed error message
	Cause    error  // Underlying cause, if any
}

ValidationError represents a validation failure with context.

func NewValidationError

func NewValidationError(resource, field, message string) *ValidationError

NewValidationError creates a new validation error.

func NewValidationErrorf

func NewValidationErrorf(resource, field, format string, args ...any) *ValidationError

NewValidationErrorf creates a new validation error with formatted message.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Unwrap returns the underlying cause.

Jump to

Keyboard shortcuts

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