core

package
v0.21.2 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2026 License: MIT Imports: 9 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")

	// ErrDeviceLost is returned when the GPU device is lost (e.g., driver crash, GPU reset).
	ErrDeviceLost = errors.New("device lost")

	// ErrDeviceDestroyed is returned when operating on a destroyed device.
	ErrDeviceDestroyed = errors.New("device destroyed")

	// ErrResourceDestroyed is returned when operating on a destroyed resource.
	ErrResourceDestroyed = errors.New("resource destroyed")
)

Base errors for the core package.

View Source
var (
	// ErrSurfaceNotConfigured is returned when attempting to acquire or present
	// on a surface that has not been configured.
	ErrSurfaceNotConfigured = errors.New("core: surface is not configured")

	// ErrSurfaceAlreadyAcquired is returned when attempting to acquire a texture
	// while one is already acquired.
	ErrSurfaceAlreadyAcquired = errors.New("core: surface texture already acquired")

	// ErrSurfaceNoTextureAcquired is returned when attempting to present or discard
	// without an acquired texture.
	ErrSurfaceNoTextureAcquired = errors.New("core: no surface texture acquired")

	// ErrSurfaceConfigureWhileAcquired is returned when attempting to configure
	// a surface while a texture is still acquired.
	ErrSurfaceConfigureWhileAcquired = errors.New("core: cannot configure surface while texture is acquired")

	// ErrSurfaceNilDevice is returned when a nil device is passed to Configure.
	ErrSurfaceNilDevice = errors.New("core: device must not be nil")

	// ErrSurfaceNilConfig is returned when a nil config is passed to Configure.
	ErrSurfaceNilConfig = errors.New("core: surface configuration must not be nil")
)

Surface lifecycle errors.

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 AvailableBackendProviders added in v0.10.0

func AvailableBackendProviders() []gputypes.Backend

AvailableBackendProviders returns all registered backend provider gputypes. The order is non-deterministic.

func DebugMode added in v0.14.0

func DebugMode() bool

DebugMode returns whether debug mode is currently enabled.

func DeviceDestroyComputePipeline added in v0.8.1

func DeviceDestroyComputePipeline(pipelineID ComputePipelineID) error

DeviceDestroyComputePipeline destroys a compute pipeline.

After calling this function, the compute pipeline ID becomes invalid and must not be used.

Returns an error if the pipeline ID is invalid.

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) (gputypes.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) (gputypes.AdapterInfo, error)

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

func GetAdapterLimits

func GetAdapterLimits(id AdapterID) (gputypes.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) (gputypes.Features, error)

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

func GetDeviceLimits

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

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

func IsCreateBindGroupError added in v0.20.0

func IsCreateBindGroupError(err error) bool

IsCreateBindGroupError returns true if the error is a CreateBindGroupError.

func IsCreateBindGroupLayoutError added in v0.20.0

func IsCreateBindGroupLayoutError(err error) bool

IsCreateBindGroupLayoutError returns true if the error is a CreateBindGroupLayoutError.

func IsCreateBufferError added in v0.9.0

func IsCreateBufferError(err error) bool

IsCreateBufferError returns true if the error is a CreateBufferError.

func IsCreateCommandEncoderError added in v0.9.0

func IsCreateCommandEncoderError(err error) bool

IsCreateCommandEncoderError returns true if the error is a CreateCommandEncoderError.

func IsCreateComputePipelineError added in v0.20.0

func IsCreateComputePipelineError(err error) bool

IsCreateComputePipelineError returns true if the error is a CreateComputePipelineError.

func IsCreateRenderPipelineError added in v0.20.0

func IsCreateRenderPipelineError(err error) bool

IsCreateRenderPipelineError returns true if the error is a CreateRenderPipelineError.

func IsCreateSamplerError added in v0.20.0

func IsCreateSamplerError(err error) bool

IsCreateSamplerError returns true if the error is a CreateSamplerError.

func IsCreateShaderModuleError added in v0.20.0

func IsCreateShaderModuleError(err error) bool

IsCreateShaderModuleError returns true if the error is a CreateShaderModuleError.

func IsCreateTextureError added in v0.20.0

func IsCreateTextureError(err error) bool

IsCreateTextureError returns true if the error is a CreateTextureError.

func IsEncoderStateError added in v0.9.0

func IsEncoderStateError(err error) bool

IsEncoderStateError returns true if the error is an EncoderStateError.

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 deprecated

func QueueOnSubmittedWorkDone(id QueueID) error

QueueOnSubmittedWorkDone returns when all submitted work completes.

Deprecated: This is the legacy ID-based API. For new code, use the HAL-based API via Queue.OnSubmittedWorkDone() (when implemented).

This function is currently a no-op as the ID-based API does not perform actual GPU operations. It exists for backward compatibility.

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 deprecated

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

QueueSubmit submits command buffers to the queue.

Deprecated: This is the legacy ID-based API. For new code, use the HAL-based API via Device and Queue structs from resource.go.

This function validates command buffer IDs but does not perform actual GPU submission. It exists for backward compatibility with existing code.

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 deprecated

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

QueueWriteBuffer writes data to a buffer through the queue.

Deprecated: This is the legacy ID-based API. For new code, use the HAL-based API via Queue.WriteBuffer() (when implemented).

This function validates IDs but does not perform actual GPU writes. It exists for backward compatibility with existing code.

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 deprecated

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

QueueWriteTexture writes data to a texture through the queue.

Deprecated: This is the legacy ID-based API. For new code, use the HAL-based API via Queue.WriteTexture() (when implemented).

This function validates parameters but does not perform actual GPU writes. It exists for backward compatibility with existing code.

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 RegisterBackendProvider added in v0.10.0

func RegisterBackendProvider(provider BackendProvider)

RegisterBackendProvider registers a backend provider for use by the Core API. This is typically called from init() functions in backend registration files.

If a provider for the same backend type is already registered, it is replaced.

func RegisterHALBackends added in v0.10.0

func RegisterHALBackends()

RegisterHALBackends automatically registers all HAL backends as Core backend providers. This is called during Core initialization to make HAL backends available.

This function queries the HAL registry for all registered backends and creates wrapper providers for them.

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.

func ResetLeakTracker added in v0.14.0

func ResetLeakTracker()

ResetLeakTracker clears the resource tracker. Useful for test cleanup.

func SetDebugMode added in v0.14.0

func SetDebugMode(enabled bool)

SetDebugMode enables or disables resource tracking. When enabled, all GPU resource allocations and releases are tracked, and ReportLeaks can be used to find unreleased resources. Should be called before any GPU operations.

func ValidateBindGroupDescriptor added in v0.20.0

func ValidateBindGroupDescriptor(desc *hal.BindGroupDescriptor) error

ValidateBindGroupDescriptor validates a bind group descriptor. Returns nil if valid, or a *CreateBindGroupError describing the first validation failure.

func ValidateBindGroupLayoutDescriptor added in v0.20.0

func ValidateBindGroupLayoutDescriptor(desc *hal.BindGroupLayoutDescriptor, limits gputypes.Limits) error

ValidateBindGroupLayoutDescriptor validates a bind group layout descriptor against device limits. Returns nil if valid, or a *CreateBindGroupLayoutError describing the first validation failure.

func ValidateComputePipelineDescriptor added in v0.20.0

func ValidateComputePipelineDescriptor(desc *hal.ComputePipelineDescriptor) error

ValidateComputePipelineDescriptor validates a compute pipeline descriptor. Returns nil if valid, or a *CreateComputePipelineError describing the first validation failure.

func ValidateRenderPipelineDescriptor added in v0.20.0

func ValidateRenderPipelineDescriptor(desc *hal.RenderPipelineDescriptor, limits gputypes.Limits) error

ValidateRenderPipelineDescriptor validates a render pipeline descriptor against device limits. Returns nil if valid, or a *CreateRenderPipelineError describing the first validation failure.

func ValidateSamplerDescriptor added in v0.20.0

func ValidateSamplerDescriptor(desc *hal.SamplerDescriptor) error

ValidateSamplerDescriptor validates a sampler descriptor. Returns nil if valid, or a *CreateSamplerError describing the first validation failure.

func ValidateShaderModuleDescriptor added in v0.20.0

func ValidateShaderModuleDescriptor(desc *hal.ShaderModuleDescriptor) error

ValidateShaderModuleDescriptor validates a shader module descriptor. Returns nil if valid, or a *CreateShaderModuleError describing the first validation failure.

func ValidateTextureDescriptor added in v0.20.0

func ValidateTextureDescriptor(desc *hal.TextureDescriptor, limits gputypes.Limits) error

ValidateTextureDescriptor validates a texture descriptor against device limits. Returns nil if valid, or a *CreateTextureError describing the first validation failure.

Types

type Adapter

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

Adapter represents a physical GPU adapter.

func (*Adapter) Capabilities added in v0.10.0

func (a *Adapter) Capabilities() *hal.Capabilities

Capabilities returns the adapter's full capability information. Returns nil for mock adapters.

func (*Adapter) HALAdapter added in v0.10.0

func (a *Adapter) HALAdapter() hal.Adapter

HALAdapter returns the underlying HAL adapter, if available. Returns nil for mock adapters created without HAL integration.

func (*Adapter) HasHAL added in v0.10.0

func (a *Adapter) HasHAL() bool

HasHAL returns true if the adapter has HAL integration.

type AdapterID

type AdapterID = ID[adapterMarker]

AdapterID identifies an Adapter resource.

type BackendProvider added in v0.10.0

type BackendProvider interface {
	// Variant returns the backend type identifier (Vulkan, Metal, DX12, etc.).
	Variant() gputypes.Backend

	// CreateInstance creates a HAL instance with the given descriptor.
	// Returns an error if the backend is not available (e.g., drivers missing).
	CreateInstance(desc *hal.InstanceDescriptor) (hal.Instance, error)

	// IsAvailable returns true if the backend can be used on this system.
	// This is a lightweight check that doesn't create resources.
	IsAvailable() bool
}

BackendProvider bridges the Core API to HAL backend implementations. It provides a consistent interface for creating HAL instances and enumerating real GPU adapters.

Backend providers are registered globally via RegisterBackendProvider() and are queried during Instance creation to enumerate real GPUs.

func FilterBackendsByMask added in v0.10.0

func FilterBackendsByMask(mask gputypes.Backends) []BackendProvider

FilterBackendsByMask filters backend providers by the enabled backends mask. Returns only providers whose variant is enabled in the mask.

func GetBackendProvider added in v0.10.0

func GetBackendProvider(variant gputypes.Backend) (BackendProvider, bool)

GetBackendProvider returns a registered backend provider by type. Returns (nil, false) if no provider is registered for the given type.

func GetOrderedBackendProviders added in v0.10.0

func GetOrderedBackendProviders() []BackendProvider

GetOrderedBackendProviders returns registered providers in priority order. Higher priority backends (Vulkan, Metal) come first. Only returns providers that are registered and available.

func SelectBestBackendProvider added in v0.10.0

func SelectBestBackendProvider() BackendProvider

SelectBestBackendProvider returns the highest-priority available backend provider. Returns nil if no backends are registered.

type BindGroup

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

BindGroup represents a collection of resources bound together with HAL integration.

BindGroup wraps a HAL bind group handle. Resource references are not stored yet to keep the implementation simple — that is future work.

func NewBindGroup added in v0.21.0

func NewBindGroup(
	halGroup hal.BindGroup,
	device *Device,
	label string,
) *BindGroup

NewBindGroup creates a core BindGroup wrapping a HAL bind group.

Parameters:

  • halGroup: The HAL bind group to wrap (ownership transferred)
  • device: The parent device
  • label: Debug label for the bind group

func (*BindGroup) Destroy added in v0.21.0

func (bg *BindGroup) Destroy()

Destroy releases the HAL bind group.

This method is idempotent - calling it multiple times is safe. After calling Destroy(), Raw() returns nil.

func (*BindGroup) IsDestroyed added in v0.21.0

func (bg *BindGroup) IsDestroyed() bool

IsDestroyed returns true if the bind group has been destroyed.

func (*BindGroup) Label added in v0.21.0

func (bg *BindGroup) Label() string

Label returns the bind group's debug label.

func (*BindGroup) Raw added in v0.21.0

func (bg *BindGroup) Raw(guard *SnatchGuard) hal.BindGroup

Raw returns the underlying HAL bind group if it hasn't been snatched.

type BindGroupID

type BindGroupID = ID[bindGroupMarker]

BindGroupID identifies a BindGroup resource.

type BindGroupLayout

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

BindGroupLayout represents the layout of a bind group with HAL integration.

BindGroupLayout wraps a HAL bind group layout handle and stores the layout entries.

func NewBindGroupLayout added in v0.21.0

func NewBindGroupLayout(
	halLayout hal.BindGroupLayout,
	device *Device,
	entries []gputypes.BindGroupLayoutEntry,
	label string,
) *BindGroupLayout

NewBindGroupLayout creates a core BindGroupLayout wrapping a HAL bind group layout.

Parameters:

  • halLayout: The HAL bind group layout to wrap (ownership transferred)
  • device: The parent device
  • entries: The binding entries in this layout
  • label: Debug label for the bind group layout

func (*BindGroupLayout) Destroy added in v0.21.0

func (bgl *BindGroupLayout) Destroy()

Destroy releases the HAL bind group layout.

This method is idempotent - calling it multiple times is safe. After calling Destroy(), Raw() returns nil.

func (*BindGroupLayout) Entries added in v0.21.0

Entries returns the binding entries in this layout.

The returned slice is a direct reference to the internal entries. Callers must not modify the returned slice.

func (*BindGroupLayout) EntryCount added in v0.21.0

func (bgl *BindGroupLayout) EntryCount() int

EntryCount returns the number of binding entries in this layout.

func (*BindGroupLayout) IsDestroyed added in v0.21.0

func (bgl *BindGroupLayout) IsDestroyed() bool

IsDestroyed returns true if the bind group layout has been destroyed.

func (*BindGroupLayout) Label added in v0.21.0

func (bgl *BindGroupLayout) Label() string

Label returns the bind group layout's debug label.

func (*BindGroupLayout) Raw added in v0.21.0

Raw returns the underlying HAL bind group layout if it hasn't been snatched.

type BindGroupLayoutID

type BindGroupLayoutID = ID[bindGroupLayoutMarker]

BindGroupLayoutID identifies a BindGroupLayout resource.

type Buffer

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

Buffer represents a GPU buffer with HAL integration.

Buffer wraps a HAL buffer handle and provides safe access to GPU memory. The HAL buffer is wrapped in a Snatchable to enable safe deferred destruction.

Buffer maintains backward compatibility with the ID-based API while adding HAL integration for actual GPU operations.

func NewBuffer added in v0.9.0

func NewBuffer(
	halBuffer hal.Buffer,
	device *Device,
	usage gputypes.BufferUsage,
	size uint64,
	label string,
) *Buffer

NewBuffer creates a core Buffer wrapping a HAL buffer.

This is the constructor for buffers with full HAL integration. The buffer takes ownership of the HAL buffer and will destroy it when the Buffer is destroyed.

Parameters:

  • halBuffer: The HAL buffer to wrap (ownership transferred)
  • device: The parent device
  • usage: Buffer usage flags
  • size: Buffer size in bytes
  • label: Debug label for the buffer

Returns a new Buffer ready for use.

func (*Buffer) Destroy added in v0.9.0

func (b *Buffer) Destroy()

Destroy releases the HAL buffer.

This method is idempotent - calling it multiple times is safe. After calling Destroy(), Raw() returns nil.

func (*Buffer) Device added in v0.9.0

func (b *Buffer) Device() *Device

Device returns the parent device for this buffer.

Returns nil if the buffer has no HAL integration.

func (*Buffer) HasHAL added in v0.9.0

func (b *Buffer) HasHAL() bool

HasHAL returns true if the buffer has HAL integration.

func (*Buffer) IsDestroyed added in v0.9.0

func (b *Buffer) IsDestroyed() bool

IsDestroyed returns true if the buffer has been destroyed.

func (*Buffer) IsInitialized added in v0.9.0

func (b *Buffer) IsInitialized(offset, size uint64) bool

IsInitialized returns true if a region of the buffer is initialized.

func (*Buffer) Label added in v0.9.0

func (b *Buffer) Label() string

Label returns the buffer's debug label.

func (*Buffer) MapState added in v0.9.0

func (b *Buffer) MapState() BufferMapState

MapState returns the current mapping state of the buffer.

func (*Buffer) MarkInitialized added in v0.9.0

func (b *Buffer) MarkInitialized(offset, size uint64)

MarkInitialized marks a region of the buffer as initialized.

func (*Buffer) Raw added in v0.9.0

func (b *Buffer) Raw(guard *SnatchGuard) hal.Buffer

Raw returns the underlying HAL buffer if it hasn't been snatched.

The caller must hold a SnatchGuard obtained from the device's SnatchLock. This ensures the buffer won't be destroyed during access.

Returns nil if:

  • The buffer has no HAL integration (ID-based API only)
  • The HAL buffer has been snatched (buffer destroyed)

func (*Buffer) SetMapState added in v0.9.0

func (b *Buffer) SetMapState(state BufferMapState)

SetMapState updates the mapping state of the buffer. Caller must hold appropriate synchronization (device snatch lock).

func (*Buffer) Size added in v0.9.0

func (b *Buffer) Size() uint64

Size returns the buffer size in bytes.

func (*Buffer) TrackingData added in v0.9.0

func (b *Buffer) TrackingData() *TrackingData

TrackingData returns the tracking data for this buffer.

func (*Buffer) Usage added in v0.9.0

func (b *Buffer) Usage() gputypes.BufferUsage

Usage returns the buffer's usage flags.

type BufferID

type BufferID = ID[bufferMarker]

BufferID identifies a Buffer resource.

func DeviceCreateBuffer deprecated

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

DeviceCreateBuffer creates a buffer on this device.

Deprecated: This is the legacy ID-based API. For new code, use the HAL-based API: Device.CreateBuffer() which provides full GPU integration. See resource.go for the HAL-based implementation.

This function creates a placeholder buffer without actual GPU resources. It exists for backward compatibility with existing code.

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

type BufferInitTracker added in v0.9.0

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

BufferInitTracker tracks which parts of a buffer have been initialized.

This is used for validation to ensure uninitialized memory is not read.

func NewBufferInitTracker added in v0.9.0

func NewBufferInitTracker(size uint64) *BufferInitTracker

NewBufferInitTracker creates a new initialization tracker for a buffer.

The tracker divides the buffer into chunks and tracks which chunks have been initialized (written to).

func (*BufferInitTracker) IsInitialized added in v0.9.0

func (t *BufferInitTracker) IsInitialized(offset, size uint64) bool

IsInitialized returns true if a region is fully initialized.

func (*BufferInitTracker) MarkInitialized added in v0.9.0

func (t *BufferInitTracker) MarkInitialized(offset, size uint64)

MarkInitialized marks a region as initialized in the tracker.

type BufferMapState added in v0.9.0

type BufferMapState int

BufferMapState represents the current mapping state of a buffer.

const (
	// BufferMapStateIdle indicates the buffer is not mapped.
	BufferMapStateIdle BufferMapState = iota
	// BufferMapStatePending indicates a mapping operation is in progress.
	BufferMapStatePending
	// BufferMapStateMapped indicates the buffer is currently mapped.
	BufferMapStateMapped
)

type BufferUses added in v0.9.0

type BufferUses uint32

BufferUses tracks how a buffer is used within a command buffer.

const (
	// BufferUsesNone indicates no usage.
	BufferUsesNone BufferUses = 0
	// BufferUsesVertex indicates vertex buffer usage.
	BufferUsesVertex BufferUses = 1 << iota
	// BufferUsesIndex indicates index buffer usage.
	BufferUsesIndex
	// BufferUsesUniform indicates uniform buffer usage.
	BufferUsesUniform
	// BufferUsesStorage indicates storage buffer usage.
	BufferUsesStorage
	// BufferUsesIndirect indicates indirect buffer usage.
	BufferUsesIndirect
	// BufferUsesCopySrc indicates copy source usage.
	BufferUsesCopySrc
	// BufferUsesCopyDst indicates copy destination usage.
	BufferUsesCopyDst
)

type CommandBuffer

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

CommandBuffer represents a recorded command buffer with HAL integration.

CommandBuffer wraps a HAL command buffer handle. Command buffers are immutable after encoding and can be submitted to a queue exactly once.

func NewCommandBuffer added in v0.21.0

func NewCommandBuffer(
	halBuffer hal.CommandBuffer,
	device *Device,
	label string,
) *CommandBuffer

NewCommandBuffer creates a core CommandBuffer wrapping a HAL command buffer.

Parameters:

  • halBuffer: The HAL command buffer to wrap (ownership transferred)
  • device: The parent device
  • label: Debug label for the command buffer

func (*CommandBuffer) IsSubmitted added in v0.21.0

func (cb *CommandBuffer) IsSubmitted() bool

IsSubmitted returns whether the command buffer has been submitted.

func (*CommandBuffer) MarkSubmitted added in v0.21.0

func (cb *CommandBuffer) MarkSubmitted() error

MarkSubmitted transitions the command buffer to the submitted state.

Returns an error if the buffer has already been submitted.

func (*CommandBuffer) Raw added in v0.21.0

func (cb *CommandBuffer) Raw(guard *SnatchGuard) hal.CommandBuffer

Raw returns the underlying HAL command buffer if it hasn't been snatched.

type CommandBufferID

type CommandBufferID = ID[commandBufferMarker]

CommandBufferID identifies a CommandBuffer resource.

func CommandEncoderFinish added in v0.8.1

func CommandEncoderFinish(id CommandEncoderID) (CommandBufferID, error)

CommandEncoderFinish finishes recording and returns a command buffer. The command encoder cannot be used after this call.

Parameters:

  • id: The command encoder ID to finish.

Returns the command buffer ID and any error encountered.

type CommandBufferMutable added in v0.9.0

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

CommandBufferMutable holds mutable state during encoding.

This tracks resources used within a command buffer for validation and synchronization purposes.

type CommandBufferSubmitState added in v0.21.0

type CommandBufferSubmitState int

CommandBufferSubmitState represents the submission state of a command buffer.

const (
	// CommandBufferSubmitStateAvailable means the buffer is ready for submission.
	CommandBufferSubmitStateAvailable CommandBufferSubmitState = iota

	// CommandBufferSubmitStateSubmitted means the buffer has been submitted to a queue.
	CommandBufferSubmitStateSubmitted
)

type CommandEncoder

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

CommandEncoder represents a command encoder with HAL integration.

CommandEncoder wraps a HAL command encoder handle and tracks the encoder's lifecycle state. The state machine ensures commands are recorded in the correct order: passes must be opened and closed properly, and encoding must be finished before the resulting command buffer can be submitted.

State transitions:

Recording     -> BeginRenderPass()  -> InRenderPass
Recording     -> BeginComputePass() -> InComputePass
InRenderPass  -> EndRenderPass()    -> Recording
InComputePass -> EndComputePass()   -> Recording
Recording     -> Finish()           -> Finished
Any           -> RecordError()      -> Error

func NewCommandEncoder added in v0.21.0

func NewCommandEncoder(
	halEncoder hal.CommandEncoder,
	device *Device,
	label string,
) *CommandEncoder

NewCommandEncoder creates a core CommandEncoder wrapping a HAL command encoder.

The encoder starts in the Recording state, ready to record commands.

Parameters:

  • halEncoder: The HAL command encoder to wrap (ownership transferred)
  • device: The parent device
  • label: Debug label for the command encoder

func (*CommandEncoder) BeginComputePass added in v0.21.0

func (e *CommandEncoder) BeginComputePass() error

BeginComputePass validates the encoder state and transitions to InComputePass.

The encoder must be in the Recording state. After this call, the encoder is locked in the InComputePass state until EndComputePass is called.

func (*CommandEncoder) BeginRenderPass added in v0.21.0

func (e *CommandEncoder) BeginRenderPass() error

BeginRenderPass validates the encoder state and transitions to InRenderPass.

The encoder must be in the Recording state. After this call, the encoder is locked in the InRenderPass state until EndRenderPass is called.

func (*CommandEncoder) EncoderLabel added in v0.21.0

func (e *CommandEncoder) EncoderLabel() string

Label returns the encoder's debug label.

func (*CommandEncoder) EndComputePass added in v0.21.0

func (e *CommandEncoder) EndComputePass() error

EndComputePass validates the encoder state and transitions back to Recording.

The encoder must be in the InComputePass state.

func (*CommandEncoder) EndRenderPass added in v0.21.0

func (e *CommandEncoder) EndRenderPass() error

EndRenderPass validates the encoder state and transitions back to Recording.

The encoder must be in the InRenderPass state.

func (*CommandEncoder) ErrorMessage added in v0.21.0

func (e *CommandEncoder) ErrorMessage() string

ErrorMessage returns the recorded error message, or empty string if none.

func (*CommandEncoder) Finish added in v0.21.0

func (e *CommandEncoder) Finish() error

Finish validates the encoder state and transitions to Finished.

The encoder must be in the Recording state with no open passes. Returns an error if the encoder is in the Error state, not in Recording state, or has open passes.

func (*CommandEncoder) PassState added in v0.21.0

func (e *CommandEncoder) PassState() CommandEncoderPassState

PassState returns the current pass lifecycle state.

func (*CommandEncoder) RawEncoder added in v0.21.0

func (ce *CommandEncoder) RawEncoder() hal.CommandEncoder

RawEncoder returns the underlying HAL command encoder.

func (*CommandEncoder) RecordError added in v0.21.0

func (e *CommandEncoder) RecordError(msg string)

RecordError records the first error encountered by this encoder.

The encoder transitions to the Error state. Subsequent calls to RecordError are ignored, preserving the first error message.

type CommandEncoderID

type CommandEncoderID = ID[commandEncoderMarker]

CommandEncoderID identifies a CommandEncoder resource.

func DeviceCreateCommandEncoder added in v0.8.1

func DeviceCreateCommandEncoder(id DeviceID, label string) (CommandEncoderID, error)

DeviceCreateCommandEncoder creates a new command encoder for recording GPU commands. This is the entry point for recording command buffers.

Parameters:

  • id: The device ID to create the encoder on.
  • label: Optional debug label for the encoder.

Returns the command encoder ID and any error encountered.

type CommandEncoderImpl added in v0.8.1

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

CommandEncoderImpl provides command encoder functionality. It wraps hal.CommandEncoder with validation and ID-based resource lookup.

func (*CommandEncoderImpl) BeginComputePass added in v0.8.1

func (e *CommandEncoderImpl) BeginComputePass(desc *ComputePassDescriptor) (*ComputePassEncoder, error)

BeginComputePass begins a new compute pass within this command encoder. The returned ComputePassEncoder is used to record compute commands.

Parameters:

  • desc: Optional descriptor with label and timestamp writes. Pass nil for default settings.

The compute pass must be ended with End() before:

  • Beginning another pass (compute or render)
  • Finishing the command encoder

Returns the compute pass encoder and any error encountered.

type CommandEncoderPassState added in v0.21.0

type CommandEncoderPassState int

CommandEncoderPassState represents the current state of a command encoder with respect to pass lifecycle.

const (
	// CommandEncoderPassStateRecording means the encoder is recording commands
	// outside of any pass.
	CommandEncoderPassStateRecording CommandEncoderPassState = iota

	// CommandEncoderPassStateInRenderPass means the encoder is inside a render pass.
	CommandEncoderPassStateInRenderPass

	// CommandEncoderPassStateInComputePass means the encoder is inside a compute pass.
	CommandEncoderPassStateInComputePass

	// CommandEncoderPassStateFinished means encoding is complete.
	CommandEncoderPassStateFinished

	// CommandEncoderPassStateError means the encoder encountered an error.
	CommandEncoderPassStateError
)

func (CommandEncoderPassState) String added in v0.21.0

func (s CommandEncoderPassState) String() string

String returns a human-readable representation of the pass state.

type CommandEncoderState added in v0.8.1

type CommandEncoderState int

CommandEncoderState tracks the state of a command encoder.

const (
	// CommandEncoderStateRecording means the encoder is actively recording commands.
	CommandEncoderStateRecording CommandEncoderState = iota

	// CommandEncoderStateEnded means the encoder has finished and produced a command buffer.
	CommandEncoderStateEnded

	// CommandEncoderStateError means the encoder encountered an error.
	CommandEncoderStateError
)

type CommandEncoderStatus added in v0.9.0

type CommandEncoderStatus int32

CommandEncoderStatus represents the current state of a command encoder.

State machine transitions:

Recording -> (BeginRenderPass/BeginComputePass) -> Locked
Locked    -> (EndRenderPass/EndComputePass)     -> Recording
Recording -> Finish()                           -> Finished
Finished  -> (submitted to queue)               -> Consumed
Any state -> (error)                            -> Error
const (
	// CommandEncoderStatusRecording - ready to record commands.
	CommandEncoderStatusRecording CommandEncoderStatus = iota

	// CommandEncoderStatusLocked - a pass is in progress.
	CommandEncoderStatusLocked

	// CommandEncoderStatusFinished - encoding complete, ready for submit.
	CommandEncoderStatusFinished

	// CommandEncoderStatusError - an error occurred.
	CommandEncoderStatusError

	// CommandEncoderStatusConsumed - submitted to queue.
	CommandEncoderStatusConsumed
)

func (CommandEncoderStatus) String added in v0.9.0

func (s CommandEncoderStatus) String() string

String returns a human-readable representation of the status.

type ComputePassDescriptor added in v0.8.1

type ComputePassDescriptor struct {
	// Label is an optional debug name for the compute pass.
	Label string

	// TimestampWrites are timestamp queries to write at pass boundaries (optional).
	TimestampWrites *ComputePassTimestampWrites
}

ComputePassDescriptor describes how to create a compute pass.

type ComputePassEncoder added in v0.8.1

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

ComputePassEncoder records compute commands within a compute pass. It wraps hal.ComputePassEncoder with validation and ID-based resource lookup.

func (*ComputePassEncoder) Dispatch added in v0.8.1

func (e *ComputePassEncoder) Dispatch(x, y, z uint32)

Dispatch dispatches compute work. This executes the compute shader with the specified number of workgroups.

Parameters:

  • x, y, z: The number of workgroups to dispatch in each dimension.

Each workgroup runs the compute shader's workgroup_size threads. The total threads = x * y * z * workgroup_size.

Note: This method does not return an error. Dispatch errors are deferred to command buffer submission time, matching the WebGPU error model.

func (*ComputePassEncoder) DispatchIndirect added in v0.8.1

func (e *ComputePassEncoder) DispatchIndirect(buffer BufferID, offset uint64) error

DispatchIndirect dispatches compute work with GPU-generated parameters. The dispatch parameters are read from the specified buffer.

Parameters:

  • buffer: The buffer containing DispatchIndirectArgs at the given offset.
  • offset: The byte offset into the buffer (must be 4-byte aligned).

The buffer must contain the following structure at the offset:

struct DispatchIndirectArgs {
    x: u32,     // Number of workgroups in X
    y: u32,     // Number of workgroups in Y
    z: u32,     // Number of workgroups in Z
}

Returns an error if the buffer ID is invalid or the offset is not aligned.

func (*ComputePassEncoder) End added in v0.8.1

func (e *ComputePassEncoder) End()

End finishes the compute pass. After this call, the encoder cannot be used again. Any subsequent method calls will return errors.

func (*ComputePassEncoder) SetBindGroup added in v0.8.1

func (e *ComputePassEncoder) SetBindGroup(index uint32, group BindGroupID, offsets []uint32) error

SetBindGroup sets a bind group for the given index. The bind group provides resources (buffers, textures, samplers) to shaders.

Parameters:

  • index: The bind group index (0, 1, 2, or 3).
  • group: The bind group ID to bind.
  • offsets: Dynamic offsets for dynamic uniform/storage buffers (can be nil).

Returns an error if the bind group ID is invalid or if the encoder has ended.

func (*ComputePassEncoder) SetPipeline added in v0.8.1

func (e *ComputePassEncoder) SetPipeline(pipeline ComputePipelineID) error

SetPipeline sets the active compute pipeline for subsequent dispatch calls. The pipeline must have been created on the same device as this encoder.

Returns an error if the pipeline ID is invalid.

type ComputePassTimestampWrites added in v0.8.1

type ComputePassTimestampWrites struct {
	// QuerySet is the query set to write timestamps to.
	QuerySet QuerySetID

	// BeginningOfPassWriteIndex is the query index for pass start.
	// Use nil to skip.
	BeginningOfPassWriteIndex *uint32

	// EndOfPassWriteIndex is the query index for pass end.
	// Use nil to skip.
	EndOfPassWriteIndex *uint32
}

ComputePassTimestampWrites describes timestamp query writes for a compute pass.

type ComputePipeline

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

ComputePipeline represents a compute pipeline with HAL integration.

ComputePipeline wraps a HAL compute pipeline handle.

func GetComputePipeline added in v0.8.1

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

GetComputePipeline retrieves compute pipeline data. Returns an error if the pipeline ID is invalid.

func NewComputePipeline added in v0.21.0

func NewComputePipeline(
	halPipeline hal.ComputePipeline,
	device *Device,
	label string,
) *ComputePipeline

NewComputePipeline creates a core ComputePipeline wrapping a HAL compute pipeline.

Parameters:

  • halPipeline: The HAL compute pipeline to wrap (ownership transferred)
  • device: The parent device
  • label: Debug label for the compute pipeline

func (*ComputePipeline) Destroy added in v0.21.0

func (cp *ComputePipeline) Destroy()

Destroy releases the HAL compute pipeline.

This method is idempotent - calling it multiple times is safe. After calling Destroy(), Raw() returns nil.

func (*ComputePipeline) IsDestroyed added in v0.21.0

func (cp *ComputePipeline) IsDestroyed() bool

IsDestroyed returns true if the compute pipeline has been destroyed.

func (*ComputePipeline) Label added in v0.21.0

func (cp *ComputePipeline) Label() string

Label returns the compute pipeline's debug label.

func (*ComputePipeline) Raw added in v0.21.0

Raw returns the underlying HAL compute pipeline if it hasn't been snatched.

type ComputePipelineDescriptor added in v0.8.1

type ComputePipelineDescriptor struct {
	// Label is a debug label for the pipeline.
	Label string

	// Layout is the pipeline layout.
	// If zero, an automatic layout will be derived from the shader.
	Layout PipelineLayoutID

	// Compute describes the compute shader stage.
	Compute ProgrammableStage
}

ComputePipelineDescriptor describes a compute pipeline. This is the Core layer descriptor that uses resource IDs.

type ComputePipelineID

type ComputePipelineID = ID[computePipelineMarker]

ComputePipelineID identifies a ComputePipeline resource.

func DeviceCreateComputePipeline deprecated added in v0.8.1

func DeviceCreateComputePipeline(deviceID DeviceID, desc *ComputePipelineDescriptor) (ComputePipelineID, error)

DeviceCreateComputePipeline creates a compute pipeline on this device.

Deprecated: This is the legacy ID-based API. For new code, use the HAL-based API: Device.CreateComputePipeline() (when implemented).

This function creates a placeholder pipeline without actual GPU resources. It exists for backward compatibility with existing code.

The pipeline combines a compute shader with a pipeline layout to define how resources are bound and the shader is executed.

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

type CoreCommandBuffer added in v0.9.0

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

CoreCommandBuffer is a finished command recording ready for submission.

This is created by CoreCommandEncoder.Finish() and can be submitted to a queue for execution.

func (*CoreCommandBuffer) Device added in v0.9.0

func (cb *CoreCommandBuffer) Device() *Device

Device returns the parent device.

func (*CoreCommandBuffer) Label added in v0.9.0

func (cb *CoreCommandBuffer) Label() string

Label returns the debug label.

func (*CoreCommandBuffer) Raw added in v0.9.0

Raw returns the underlying HAL command buffer.

type CoreCommandEncoder added in v0.9.0

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

CoreCommandEncoder records GPU commands for submission.

This is the HAL-integrated command encoder that bridges core command recording to HAL command encoders. The state machine ensures commands are recorded in the correct order and validates encoder state transitions.

CoreCommandEncoder is thread-safe for concurrent access.

func (*CoreCommandEncoder) BeginComputePass added in v0.9.0

BeginComputePass begins a compute pass.

The encoder must be in the Recording state. After this call, the encoder transitions to the Locked state.

Returns the compute pass encoder and nil on success. Returns nil and an error if the encoder is not in Recording state.

func (*CoreCommandEncoder) BeginRenderPass added in v0.9.0

BeginRenderPass begins a render pass.

The encoder must be in the Recording state. After this call, the encoder transitions to the Locked state.

Returns the render pass encoder and nil on success. Returns nil and an error if the encoder is not in Recording state.

func (*CoreCommandEncoder) Device added in v0.9.0

func (e *CoreCommandEncoder) Device() *Device

Device returns the parent device.

func (*CoreCommandEncoder) EndComputePass added in v0.9.0

func (e *CoreCommandEncoder) EndComputePass(pass *CoreComputePassEncoder) error

EndComputePass ends the current compute pass.

The encoder must be in the Locked state with an active compute pass. After this call, the encoder transitions back to the Recording state.

This is called internally by CoreComputePassEncoder.End().

func (*CoreCommandEncoder) EndRenderPass added in v0.9.0

func (e *CoreCommandEncoder) EndRenderPass(pass *CoreRenderPassEncoder) error

EndRenderPass ends the current render pass.

The encoder must be in the Locked state with an active render pass. After this call, the encoder transitions back to the Recording state.

This is called internally by CoreRenderPassEncoder.End().

func (*CoreCommandEncoder) Error added in v0.9.0

func (e *CoreCommandEncoder) Error() error

Error returns the error that caused the Error state, or nil.

func (*CoreCommandEncoder) Finish added in v0.9.0

func (e *CoreCommandEncoder) Finish() (*CoreCommandBuffer, error)

Finish completes encoding and returns a command buffer.

The encoder must be in the Recording state (not in a pass). After this call, the encoder transitions to the Finished state.

Returns the command buffer and nil on success. Returns nil and an error if the encoder is not in Recording state.

func (*CoreCommandEncoder) Label added in v0.9.0

func (e *CoreCommandEncoder) Label() string

Label returns the encoder's debug label.

func (*CoreCommandEncoder) MarkConsumed added in v0.9.0

func (e *CoreCommandEncoder) MarkConsumed()

MarkConsumed marks the encoder as consumed after submission.

This is called by the queue after successful submission.

func (*CoreCommandEncoder) RawEncoder added in v0.18.0

func (e *CoreCommandEncoder) RawEncoder() hal.CommandEncoder

RawEncoder returns the underlying HAL command encoder for direct HAL access. Requires the device's snatch lock to be held. Returns nil if the encoder has been snatched or the device is destroyed.

func (*CoreCommandEncoder) SetError added in v0.20.0

func (e *CoreCommandEncoder) SetError(err error)

SetError records a deferred error on this encoder.

The error transitions the encoder to the Error state and will be returned by Finish(). This implements the WebGPU deferred error pattern where encoding-phase errors are collected and surfaced at Finish() time.

func (*CoreCommandEncoder) Status added in v0.9.0

Status returns the current encoder status.

type CoreComputePassDescriptor added in v0.9.0

type CoreComputePassDescriptor struct {
	// Label is an optional debug name.
	Label string
}

CoreComputePassDescriptor describes a compute pass for HAL-integrated API.

type CoreComputePassEncoder added in v0.9.0

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

CoreComputePassEncoder records compute commands within a pass.

This is the HAL-integrated compute pass encoder that bridges core compute commands to HAL compute pass encoder.

func (*CoreComputePassEncoder) Dispatch added in v0.9.0

func (p *CoreComputePassEncoder) Dispatch(x, y, z uint32)

Dispatch dispatches compute work.

func (*CoreComputePassEncoder) DispatchIndirect added in v0.9.0

func (p *CoreComputePassEncoder) DispatchIndirect(buffer *Buffer, offset uint64)

DispatchIndirect dispatches compute work with GPU-generated parameters.

func (*CoreComputePassEncoder) End added in v0.9.0

func (p *CoreComputePassEncoder) End() error

End ends the compute pass.

func (*CoreComputePassEncoder) RawPass added in v0.18.0

RawPass returns the underlying HAL compute pass encoder for direct HAL access.

func (*CoreComputePassEncoder) SetPipeline added in v0.9.0

func (p *CoreComputePassEncoder) SetPipeline(pipeline *ComputePipeline)

SetPipeline sets the compute pipeline.

type CoreRenderPassEncoder added in v0.9.0

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

CoreRenderPassEncoder records render commands within a pass.

This is the HAL-integrated render pass encoder that bridges core render commands to HAL render pass encoder.

func (*CoreRenderPassEncoder) Draw added in v0.9.0

func (p *CoreRenderPassEncoder) Draw(vertexCount, instanceCount, firstVertex, firstInstance uint32)

Draw draws primitives.

func (*CoreRenderPassEncoder) DrawIndexed added in v0.9.0

func (p *CoreRenderPassEncoder) DrawIndexed(indexCount, instanceCount, firstIndex uint32, baseVertex int32, firstInstance uint32)

DrawIndexed draws indexed primitives.

func (*CoreRenderPassEncoder) DrawIndexedIndirect added in v0.9.0

func (p *CoreRenderPassEncoder) DrawIndexedIndirect(buffer *Buffer, offset uint64)

DrawIndexedIndirect draws indexed primitives with GPU-generated parameters.

func (*CoreRenderPassEncoder) DrawIndirect added in v0.9.0

func (p *CoreRenderPassEncoder) DrawIndirect(buffer *Buffer, offset uint64)

DrawIndirect draws primitives with GPU-generated parameters.

func (*CoreRenderPassEncoder) End added in v0.9.0

func (p *CoreRenderPassEncoder) End() error

End ends the render pass.

func (*CoreRenderPassEncoder) RawPass added in v0.18.0

RawPass returns the underlying HAL render pass encoder for direct HAL access.

func (*CoreRenderPassEncoder) SetBlendConstant added in v0.9.0

func (p *CoreRenderPassEncoder) SetBlendConstant(color *gputypes.Color)

SetBlendConstant sets the blend constant color.

func (*CoreRenderPassEncoder) SetIndexBuffer added in v0.9.0

func (p *CoreRenderPassEncoder) SetIndexBuffer(buffer *Buffer, format gputypes.IndexFormat, offset uint64)

SetIndexBuffer sets the index buffer.

func (*CoreRenderPassEncoder) SetPipeline added in v0.9.0

func (p *CoreRenderPassEncoder) SetPipeline(pipeline *RenderPipeline)

SetPipeline sets the render pipeline.

func (*CoreRenderPassEncoder) SetScissorRect added in v0.9.0

func (p *CoreRenderPassEncoder) SetScissorRect(x, y, width, height uint32)

SetScissorRect sets the scissor rectangle.

func (*CoreRenderPassEncoder) SetStencilReference added in v0.9.0

func (p *CoreRenderPassEncoder) SetStencilReference(reference uint32)

SetStencilReference sets the stencil reference value.

func (*CoreRenderPassEncoder) SetVertexBuffer added in v0.9.0

func (p *CoreRenderPassEncoder) SetVertexBuffer(slot uint32, buffer *Buffer, offset uint64)

SetVertexBuffer sets a vertex buffer.

func (*CoreRenderPassEncoder) SetViewport added in v0.9.0

func (p *CoreRenderPassEncoder) SetViewport(x, y, width, height, minDepth, maxDepth float32)

SetViewport sets the viewport.

type CreateBindGroupError added in v0.20.0

type CreateBindGroupError struct {
	Kind     CreateBindGroupErrorKind
	Label    string
	HALError error
}

CreateBindGroupError represents an error during bind group creation.

func (*CreateBindGroupError) Error added in v0.20.0

func (e *CreateBindGroupError) Error() string

Error implements the error interface.

func (*CreateBindGroupError) Unwrap added in v0.20.0

func (e *CreateBindGroupError) Unwrap() error

Unwrap returns the underlying HAL error, if any.

type CreateBindGroupErrorKind added in v0.20.0

type CreateBindGroupErrorKind int

CreateBindGroupErrorKind represents the type of bind group creation error.

const (
	// CreateBindGroupErrorMissingLayout indicates the layout was nil.
	CreateBindGroupErrorMissingLayout CreateBindGroupErrorKind = iota
	// CreateBindGroupErrorHAL indicates the HAL backend failed.
	CreateBindGroupErrorHAL
)

type CreateBindGroupLayoutError added in v0.20.0

type CreateBindGroupLayoutError struct {
	Kind             CreateBindGroupLayoutErrorKind
	Label            string
	DuplicateBinding uint32
	BindingCount     uint32
	MaxBindings      uint32
	HALError         error
}

CreateBindGroupLayoutError represents an error during bind group layout creation.

func (*CreateBindGroupLayoutError) Error added in v0.20.0

Error implements the error interface.

func (*CreateBindGroupLayoutError) Unwrap added in v0.20.0

func (e *CreateBindGroupLayoutError) Unwrap() error

Unwrap returns the underlying HAL error, if any.

type CreateBindGroupLayoutErrorKind added in v0.20.0

type CreateBindGroupLayoutErrorKind int

CreateBindGroupLayoutErrorKind represents the type of bind group layout creation error.

const (
	// CreateBindGroupLayoutErrorDuplicateBinding indicates duplicate binding numbers.
	CreateBindGroupLayoutErrorDuplicateBinding CreateBindGroupLayoutErrorKind = iota
	// CreateBindGroupLayoutErrorTooManyBindings indicates too many bindings.
	CreateBindGroupLayoutErrorTooManyBindings
	// CreateBindGroupLayoutErrorHAL indicates the HAL backend failed.
	CreateBindGroupLayoutErrorHAL
)

type CreateBufferError added in v0.9.0

type CreateBufferError struct {
	Kind          CreateBufferErrorKind
	Label         string
	RequestedSize uint64
	MaxSize       uint64
	HALError      error
}

CreateBufferError represents an error during buffer creation.

func (*CreateBufferError) Error added in v0.9.0

func (e *CreateBufferError) Error() string

Error implements the error interface.

func (*CreateBufferError) Unwrap added in v0.9.0

func (e *CreateBufferError) Unwrap() error

Unwrap returns the underlying HAL error, if any.

type CreateBufferErrorKind added in v0.9.0

type CreateBufferErrorKind int

CreateBufferErrorKind represents the type of buffer creation error.

const (
	// CreateBufferErrorZeroSize indicates buffer size was zero.
	CreateBufferErrorZeroSize CreateBufferErrorKind = iota
	// CreateBufferErrorMaxBufferSize indicates buffer size exceeded device limit.
	CreateBufferErrorMaxBufferSize
	// CreateBufferErrorEmptyUsage indicates no usage flags were specified.
	CreateBufferErrorEmptyUsage
	// CreateBufferErrorInvalidUsage indicates unknown usage flags were specified.
	CreateBufferErrorInvalidUsage
	// CreateBufferErrorMapReadWriteExclusive indicates both MAP_READ and MAP_WRITE were specified.
	CreateBufferErrorMapReadWriteExclusive
	// CreateBufferErrorHAL indicates the HAL backend failed to create the buffer.
	CreateBufferErrorHAL
)

type CreateCommandEncoderError added in v0.9.0

type CreateCommandEncoderError struct {
	Kind     CreateCommandEncoderErrorKind
	Label    string
	HALError error
}

CreateCommandEncoderError represents an error during command encoder creation.

func (*CreateCommandEncoderError) Error added in v0.9.0

func (e *CreateCommandEncoderError) Error() string

Error implements the error interface.

func (*CreateCommandEncoderError) Unwrap added in v0.9.0

func (e *CreateCommandEncoderError) Unwrap() error

Unwrap returns the underlying HAL error, if any.

type CreateCommandEncoderErrorKind added in v0.9.0

type CreateCommandEncoderErrorKind int

CreateCommandEncoderErrorKind represents the type of command encoder creation error.

const (
	// CreateCommandEncoderErrorHAL indicates the HAL backend failed to create the encoder.
	CreateCommandEncoderErrorHAL CreateCommandEncoderErrorKind = iota
)

type CreateComputePipelineError added in v0.20.0

type CreateComputePipelineError struct {
	Kind     CreateComputePipelineErrorKind
	Label    string
	HALError error
}

CreateComputePipelineError represents an error during compute pipeline creation.

func (*CreateComputePipelineError) Error added in v0.20.0

Error implements the error interface.

func (*CreateComputePipelineError) Unwrap added in v0.20.0

func (e *CreateComputePipelineError) Unwrap() error

Unwrap returns the underlying HAL error, if any.

type CreateComputePipelineErrorKind added in v0.20.0

type CreateComputePipelineErrorKind int

CreateComputePipelineErrorKind represents the type of compute pipeline creation error.

const (
	// CreateComputePipelineErrorMissingModule indicates the compute shader module was nil.
	CreateComputePipelineErrorMissingModule CreateComputePipelineErrorKind = iota
	// CreateComputePipelineErrorMissingEntryPoint indicates the compute entry point was empty.
	CreateComputePipelineErrorMissingEntryPoint
	// CreateComputePipelineErrorHAL indicates the HAL backend failed to create the pipeline.
	CreateComputePipelineErrorHAL
)

type CreateRenderPipelineError added in v0.20.0

type CreateRenderPipelineError struct {
	Kind        CreateRenderPipelineErrorKind
	Label       string
	TargetCount uint32
	MaxTargets  uint32
	SampleCount uint32
	HALError    error
}

CreateRenderPipelineError represents an error during render pipeline creation.

func (*CreateRenderPipelineError) Error added in v0.20.0

func (e *CreateRenderPipelineError) Error() string

Error implements the error interface.

func (*CreateRenderPipelineError) Unwrap added in v0.20.0

func (e *CreateRenderPipelineError) Unwrap() error

Unwrap returns the underlying HAL error, if any.

type CreateRenderPipelineErrorKind added in v0.20.0

type CreateRenderPipelineErrorKind int

CreateRenderPipelineErrorKind represents the type of render pipeline creation error.

const (
	// CreateRenderPipelineErrorMissingVertexModule indicates the vertex shader module was nil.
	CreateRenderPipelineErrorMissingVertexModule CreateRenderPipelineErrorKind = iota
	// CreateRenderPipelineErrorMissingVertexEntryPoint indicates the vertex entry point was empty.
	CreateRenderPipelineErrorMissingVertexEntryPoint
	// CreateRenderPipelineErrorMissingFragmentModule indicates the fragment shader module was nil.
	CreateRenderPipelineErrorMissingFragmentModule
	// CreateRenderPipelineErrorMissingFragmentEntryPoint indicates the fragment entry point was empty.
	CreateRenderPipelineErrorMissingFragmentEntryPoint
	// CreateRenderPipelineErrorNoFragmentTargets indicates the fragment stage had no color targets.
	CreateRenderPipelineErrorNoFragmentTargets
	// CreateRenderPipelineErrorTooManyColorTargets indicates too many color targets.
	CreateRenderPipelineErrorTooManyColorTargets
	// CreateRenderPipelineErrorInvalidSampleCount indicates an invalid multisample count.
	CreateRenderPipelineErrorInvalidSampleCount
	// CreateRenderPipelineErrorHAL indicates the HAL backend failed to create the pipeline.
	CreateRenderPipelineErrorHAL
)

type CreateSamplerError added in v0.20.0

type CreateSamplerError struct {
	Kind        CreateSamplerErrorKind
	Label       string
	LodMinClamp float32
	LodMaxClamp float32
	Anisotropy  uint16
	HALError    error
}

CreateSamplerError represents an error during sampler creation.

func (*CreateSamplerError) Error added in v0.20.0

func (e *CreateSamplerError) Error() string

Error implements the error interface.

func (*CreateSamplerError) Unwrap added in v0.20.0

func (e *CreateSamplerError) Unwrap() error

Unwrap returns the underlying HAL error, if any.

type CreateSamplerErrorKind added in v0.20.0

type CreateSamplerErrorKind int

CreateSamplerErrorKind represents the type of sampler creation error.

const (
	// CreateSamplerErrorInvalidLodMinClamp indicates LodMinClamp was negative.
	CreateSamplerErrorInvalidLodMinClamp CreateSamplerErrorKind = iota
	// CreateSamplerErrorInvalidLodMaxClamp indicates LodMaxClamp was less than LodMinClamp.
	CreateSamplerErrorInvalidLodMaxClamp
	// CreateSamplerErrorInvalidAnisotropy indicates anisotropy was zero.
	CreateSamplerErrorInvalidAnisotropy
	// CreateSamplerErrorAnisotropyRequiresLinearFiltering indicates anisotropy > 1 requires linear filtering.
	CreateSamplerErrorAnisotropyRequiresLinearFiltering
	// CreateSamplerErrorHAL indicates the HAL backend failed to create the sampler.
	CreateSamplerErrorHAL
)

type CreateShaderModuleError added in v0.20.0

type CreateShaderModuleError struct {
	Kind     CreateShaderModuleErrorKind
	Label    string
	HALError error
}

CreateShaderModuleError represents an error during shader module creation.

func (*CreateShaderModuleError) Error added in v0.20.0

func (e *CreateShaderModuleError) Error() string

Error implements the error interface.

func (*CreateShaderModuleError) Unwrap added in v0.20.0

func (e *CreateShaderModuleError) Unwrap() error

Unwrap returns the underlying HAL error, if any.

type CreateShaderModuleErrorKind added in v0.20.0

type CreateShaderModuleErrorKind int

CreateShaderModuleErrorKind represents the type of shader module creation error.

const (
	// CreateShaderModuleErrorNoSource indicates neither WGSL nor SPIRV source was provided.
	CreateShaderModuleErrorNoSource CreateShaderModuleErrorKind = iota
	// CreateShaderModuleErrorDualSource indicates both WGSL and SPIRV sources were provided.
	CreateShaderModuleErrorDualSource
	// CreateShaderModuleErrorHAL indicates the HAL backend failed to create the shader module.
	CreateShaderModuleErrorHAL
)

type CreateTextureError added in v0.20.0

type CreateTextureError struct {
	Kind             CreateTextureErrorKind
	Label            string
	RequestedWidth   uint32
	RequestedHeight  uint32
	RequestedDepth   uint32
	MaxDimension     uint32
	RequestedMips    uint32
	MaxMips          uint32
	RequestedSamples uint32
	HALError         error
}

CreateTextureError represents an error during texture creation.

func (*CreateTextureError) Error added in v0.20.0

func (e *CreateTextureError) Error() string

Error implements the error interface.

func (*CreateTextureError) Unwrap added in v0.20.0

func (e *CreateTextureError) Unwrap() error

Unwrap returns the underlying HAL error, if any.

type CreateTextureErrorKind added in v0.20.0

type CreateTextureErrorKind int

CreateTextureErrorKind represents the type of texture creation error.

const (
	// CreateTextureErrorZeroDimension indicates a texture dimension was zero.
	CreateTextureErrorZeroDimension CreateTextureErrorKind = iota
	// CreateTextureErrorMaxDimension indicates a texture dimension exceeded the device limit.
	CreateTextureErrorMaxDimension
	// CreateTextureErrorMaxArrayLayers indicates array layers exceeded the device limit.
	CreateTextureErrorMaxArrayLayers
	// CreateTextureErrorInvalidMipLevelCount indicates an invalid mip level count.
	CreateTextureErrorInvalidMipLevelCount
	// CreateTextureErrorInvalidSampleCount indicates an invalid sample count (must be 1 or 4).
	CreateTextureErrorInvalidSampleCount
	// CreateTextureErrorMultisampleMipLevel indicates multisampled texture must have mip level count of 1.
	CreateTextureErrorMultisampleMipLevel
	// CreateTextureErrorMultisampleDimension indicates multisampled texture must be 2D.
	CreateTextureErrorMultisampleDimension
	// CreateTextureErrorMultisampleArrayLayers indicates multisampled texture must have 1 array layer.
	CreateTextureErrorMultisampleArrayLayers
	// CreateTextureErrorMultisampleStorageBinding indicates multisampled texture cannot have storage binding.
	CreateTextureErrorMultisampleStorageBinding
	// CreateTextureErrorEmptyUsage indicates no usage flags were specified.
	CreateTextureErrorEmptyUsage
	// CreateTextureErrorInvalidUsage indicates unknown usage flags were specified.
	CreateTextureErrorInvalidUsage
	// CreateTextureErrorInvalidFormat indicates an invalid texture format.
	CreateTextureErrorInvalidFormat
	// CreateTextureErrorInvalidDimension indicates an invalid texture dimension.
	CreateTextureErrorInvalidDimension
	// CreateTextureErrorHAL indicates the HAL backend failed to create the texture.
	CreateTextureErrorHAL
)

type Device

type Device struct {

	// Adapter is the adapter this device was created from (ID-based API).
	Adapter AdapterID
	// Queue is the device's default queue (ID-based API).
	Queue QueueID

	// Label is a debug label for the device.
	Label string
	// Features contains the features enabled on this device.
	Features gputypes.Features
	// Limits contains the resource limits of this device.
	Limits gputypes.Limits
	// contains filtered or unexported fields
}

Device represents a logical GPU device.

Device wraps a HAL device handle and provides safe access to GPU resources. The HAL device is wrapped in a Snatchable to enable safe deferred destruction.

The Device maintains backward compatibility with the ID-based API while adding HAL integration for actual GPU operations.

func GetDevice

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

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

func NewDevice added in v0.9.0

func NewDevice(
	halDevice hal.Device,
	adapter *Adapter,
	features gputypes.Features,
	limits gputypes.Limits,
	label string,
) *Device

NewDevice creates a new Device wrapping a HAL device.

This is the constructor for devices with full HAL integration. The device takes ownership of the HAL device and will destroy it when the Device is destroyed.

Parameters:

  • halDevice: The HAL device to wrap (ownership transferred)
  • adapter: The parent adapter struct
  • features: Enabled features for this device
  • limits: Resource limits for this device
  • label: Debug label for the device

Returns a new Device ready for use.

func (*Device) AssociatedQueue added in v0.9.0

func (d *Device) AssociatedQueue() *Queue

AssociatedQueue returns the associated queue for this device.

Returns nil if the queue has not been set.

func (*Device) CreateBuffer added in v0.9.0

func (d *Device) CreateBuffer(desc *gputypes.BufferDescriptor) (*Buffer, error)

CreateBuffer creates a new buffer on this device.

Validation performed:

  • Device must be valid (not destroyed)
  • Size must be > 0
  • Size must not exceed MaxBufferSize device limit
  • Usage must not be empty
  • Usage must not contain unknown bits
  • MAP_READ and MAP_WRITE are mutually exclusive

Size is automatically aligned to COPY_BUFFER_ALIGNMENT (4 bytes).

Returns the buffer and nil on success. Returns nil and an error if validation fails or HAL creation fails.

func (*Device) CreateCommandEncoder added in v0.9.0

func (d *Device) CreateCommandEncoder(label string) (*CoreCommandEncoder, error)

CreateCommandEncoder creates a new command encoder on this device.

The encoder is created in the Recording state, ready to record commands.

Parameters:

  • label: Debug label for the encoder.

Returns the encoder and nil on success. Returns nil and an error if the device is destroyed or HAL creation fails.

func (*Device) Destroy added in v0.9.0

func (d *Device) Destroy()

Destroy releases the HAL device and marks the device as invalid.

This method is idempotent - calling it multiple times is safe. After calling Destroy(), IsValid() returns false and Raw() returns nil.

If the device has no HAL integration (ID-based API only), this only marks the device as invalid.

func (*Device) HasHAL added in v0.9.0

func (d *Device) HasHAL() bool

HasHAL returns true if the device has HAL integration.

Devices created via NewDevice have HAL integration. Devices created via the ID-based API (CreateDevice) do not.

func (*Device) IsValid added in v0.9.0

func (d *Device) IsValid() bool

IsValid returns true if the device is still valid for use.

A device becomes invalid after Destroy() is called.

func (*Device) ParentAdapter added in v0.9.0

func (d *Device) ParentAdapter() *Adapter

ParentAdapter returns the parent adapter for this device.

Returns nil if the device has no HAL integration.

func (*Device) PopErrorScope added in v0.14.0

func (d *Device) PopErrorScope() *GPUError

PopErrorScope pops the most recently pushed error scope and returns the captured error, if any.

Returns the captured GPUError, or nil if no matching error occurred within the scope. Panics if the error scope stack is empty (no matching PushErrorScope was called).

Note: Error scopes are LIFO -- the last pushed scope is popped first.

func (*Device) PushErrorScope added in v0.14.0

func (d *Device) PushErrorScope(filter ErrorFilter)

PushErrorScope pushes a new error scope onto this device's error scope stack.

The scope will capture the first error matching the specified filter type. Error scopes are LIFO (stack-based) -- the last pushed scope is checked first.

Each PushErrorScope must be paired with a corresponding PopErrorScope.

Example usage:

device.PushErrorScope(core.ErrorFilterValidation)
// ... GPU operations that might produce validation errors
gpuErr := device.PopErrorScope()
if gpuErr != nil {
    log.Printf("Validation error: %s", gpuErr.Message)
}

func (*Device) Raw added in v0.9.0

func (d *Device) Raw(guard *SnatchGuard) hal.Device

Raw returns the underlying HAL device if it hasn't been snatched.

The caller must hold a SnatchGuard obtained from the device's SnatchLock. This ensures the device won't be destroyed during access.

Returns nil if:

  • The device has no HAL integration (ID-based API only)
  • The HAL device has been snatched (device destroyed)

func (*Device) SetAssociatedQueue added in v0.9.0

func (d *Device) SetAssociatedQueue(queue *Queue)

SetAssociatedQueue sets the associated queue for this device.

This is called internally when creating a device to link it with its queue.

func (*Device) SnatchLock added in v0.9.0

func (d *Device) SnatchLock() *SnatchLock

SnatchLock returns the device's snatch lock for resource coordination.

The snatch lock must be held when accessing the raw HAL device or when destroying resources associated with this device.

Returns nil if the device has no HAL integration.

func (*Device) TrackerIndices added in v0.9.0

func (d *Device) TrackerIndices() *TrackerIndexAllocators

TrackerIndices returns the tracker index allocators for this device.

Returns nil if the device has no HAL integration.

type DeviceID

type DeviceID = ID[deviceMarker]

DeviceID identifies a Device resource.

func CreateDevice

func CreateDevice(adapterID AdapterID, desc *gputypes.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 *gputypes.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 EncoderStateError added in v0.9.0

type EncoderStateError struct {
	Operation string
	Status    CommandEncoderStatus
}

EncoderStateError represents an invalid state transition error.

func (*EncoderStateError) Error added in v0.9.0

func (e *EncoderStateError) Error() string

Error implements the error interface.

type Epoch

type Epoch = uint32

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

type ErrorFilter added in v0.14.0

type ErrorFilter int

ErrorFilter specifies which error types to capture in an error scope.

Error scopes allow programmatic capture of GPU validation errors, out-of-memory conditions, and internal errors per the W3C WebGPU spec.

const (
	// ErrorFilterValidation captures validation errors.
	// These occur when API usage violates the WebGPU specification
	// (e.g., invalid descriptors, missing resources, state errors).
	ErrorFilterValidation ErrorFilter = iota

	// ErrorFilterOutOfMemory captures out-of-memory errors.
	// These occur when GPU memory allocation fails.
	ErrorFilterOutOfMemory

	// ErrorFilterInternal captures internal errors.
	// These occur due to implementation bugs or unexpected GPU behavior.
	ErrorFilterInternal
)

func (ErrorFilter) String added in v0.14.0

func (f ErrorFilter) String() string

String returns a human-readable name for the error filter.

type ErrorScopeManager added in v0.14.0

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

ErrorScopeManager manages a stack of error scopes for a device.

Error scopes allow users to programmatically capture GPU errors instead of relying on uncaptured error callbacks. Scopes are LIFO (stack-based): the most recently pushed scope is checked first when reporting errors.

This follows the W3C WebGPU error scope specification: https://www.w3.org/TR/webgpu/#error-scopes

ErrorScopeManager is safe for concurrent use.

func NewErrorScopeManager added in v0.14.0

func NewErrorScopeManager() *ErrorScopeManager

NewErrorScopeManager creates a new ErrorScopeManager with an empty scope stack.

func (*ErrorScopeManager) PopErrorScope added in v0.14.0

func (m *ErrorScopeManager) PopErrorScope() (*GPUError, error)

PopErrorScope pops the most recently pushed error scope and returns the captured error, if any.

Returns the captured GPUError, or nil if no matching error occurred. Returns an error (second return value) if the scope stack is empty.

This must be called once for each PushErrorScope call.

func (*ErrorScopeManager) PushErrorScope added in v0.14.0

func (m *ErrorScopeManager) PushErrorScope(filter ErrorFilter)

PushErrorScope pushes a new error scope onto the stack.

The scope will capture the first error matching the specified filter. Multiple scopes can be pushed to capture different error types simultaneously.

Each PushErrorScope must be paired with a corresponding PopErrorScope.

func (*ErrorScopeManager) ReportError added in v0.14.0

func (m *ErrorScopeManager) ReportError(filter ErrorFilter, message string) bool

ReportError reports a GPU error to the error scope stack.

The error is delivered to the topmost scope whose filter matches the error type. Only the first error per scope is captured; subsequent matching errors are silently discarded.

If no scope matches (either the stack is empty or no scope has a matching filter), the error is considered "uncaptured". The method returns false in this case, allowing the caller to handle uncaptured errors (e.g., via a device lost callback or logging).

Returns true if the error was captured by a scope, false otherwise.

func (*ErrorScopeManager) ScopeDepth added in v0.14.0

func (m *ErrorScopeManager) ScopeDepth() int

ScopeDepth returns the current number of pushed error scopes.

This is primarily useful for debugging and testing.

type ExclusiveSnatchGuard added in v0.9.0

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

ExclusiveSnatchGuard represents a held write lock on a SnatchLock.

It must be released by calling Release() when done. Not releasing the guard will cause a deadlock.

func (*ExclusiveSnatchGuard) Release added in v0.9.0

func (g *ExclusiveSnatchGuard) Release()

Release releases the write lock. This must be called exactly once. Subsequent calls are no-ops.

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 GPUError added in v0.14.0

type GPUError struct {
	// Type identifies the category of the error.
	Type ErrorFilter

	// Message provides a human-readable description of the error.
	Message string
}

GPUError represents a captured GPU error from an error scope.

GPUError is returned by ErrorScopeManager.PopErrorScope when an error was captured within the scope. It implements the error interface for convenient integration with Go error handling.

func (*GPUError) Error added in v0.14.0

func (e *GPUError) 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 *gputypes.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. If HAL backends are available, real GPU adapters will be enumerated. Otherwise, a mock adapter is created for testing purposes.

func NewInstanceWithMock added in v0.10.0

func NewInstanceWithMock(desc *gputypes.InstanceDescriptor) *Instance

NewInstanceWithMock creates a new WebGPU instance with mock adapters. This is primarily for testing without requiring real GPU hardware.

func (*Instance) Backends

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

Backends returns the enabled backends for this instance.

func (*Instance) Destroy added in v0.10.0

func (i *Instance) Destroy()

Destroy releases all resources associated with this instance. This includes unregistering all adapters and destroying HAL instances. After calling Destroy, the instance should not be used.

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() gputypes.InstanceFlags

Flags returns the instance flags.

func (*Instance) HALInstance added in v0.18.0

func (i *Instance) HALInstance() hal.Instance

HALInstance returns the first available HAL instance, or nil if none. Used by the public API for surface creation without creating duplicate HAL instances.

func (*Instance) HasHALAdapters added in v0.10.0

func (i *Instance) HasHALAdapters() bool

HasHALAdapters returns true if any real HAL adapters are available.

func (*Instance) IsMock added in v0.10.0

func (i *Instance) IsMock() bool

IsMock returns true if the instance is using mock adapters. Mock adapters are used when no HAL backends are available or when the instance was explicitly created with NewInstanceWithMock.

func (*Instance) RequestAdapter

func (i *Instance) RequestAdapter(options *gputypes.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 LeakReport added in v0.14.0

type LeakReport struct {
	// Count is the total number of unreleased resources.
	Count int
	// Types maps resource type names to their counts.
	Types map[string]int
}

LeakReport contains information about unreleased GPU resources.

func ReportLeaks added in v0.14.0

func ReportLeaks() *LeakReport

ReportLeaks returns information about unreleased GPU resources. Only meaningful when debug mode is enabled via SetDebugMode(true). Returns nil if no leaks are detected.

func (*LeakReport) String added in v0.14.0

func (r *LeakReport) String() string

String returns a human-readable summary of the leak report.

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 {
	// contains filtered or unexported fields
}

PipelineLayout represents the layout of a pipeline with HAL integration.

PipelineLayout wraps a HAL pipeline layout handle and stores the bind group layout count. It does not store pointers to BindGroupLayout to avoid circular references.

func NewPipelineLayout added in v0.21.0

func NewPipelineLayout(
	halLayout hal.PipelineLayout,
	device *Device,
	bindGroupLayoutCount int,
	label string,
) *PipelineLayout

NewPipelineLayout creates a core PipelineLayout wrapping a HAL pipeline layout.

Parameters:

  • halLayout: The HAL pipeline layout to wrap (ownership transferred)
  • device: The parent device
  • bindGroupLayoutCount: Number of bind group layouts
  • label: Debug label for the pipeline layout

func (*PipelineLayout) BindGroupLayoutCount added in v0.21.0

func (pl *PipelineLayout) BindGroupLayoutCount() int

BindGroupLayoutCount returns the number of bind group layouts in this pipeline layout.

func (*PipelineLayout) Destroy added in v0.21.0

func (pl *PipelineLayout) Destroy()

Destroy releases the HAL pipeline layout.

This method is idempotent - calling it multiple times is safe. After calling Destroy(), Raw() returns nil.

func (*PipelineLayout) IsDestroyed added in v0.21.0

func (pl *PipelineLayout) IsDestroyed() bool

IsDestroyed returns true if the pipeline layout has been destroyed.

func (*PipelineLayout) Label added in v0.21.0

func (pl *PipelineLayout) Label() string

Label returns the pipeline layout's debug label.

func (*PipelineLayout) Raw added in v0.21.0

func (pl *PipelineLayout) Raw(guard *SnatchGuard) hal.PipelineLayout

Raw returns the underlying HAL pipeline layout if it hasn't been snatched.

type PipelineLayoutID

type PipelineLayoutID = ID[pipelineLayoutMarker]

PipelineLayoutID identifies a PipelineLayout resource.

type PrepareFrameFunc added in v0.21.0

type PrepareFrameFunc func() (width, height uint32, changed bool)

PrepareFrameFunc is a platform hook called before acquiring a surface texture. It returns the current surface dimensions and whether they changed since the last call. If changed is true, the surface will be reconfigured with the new dimensions before acquiring.

type ProgrammableStage added in v0.8.1

type ProgrammableStage struct {
	// Module is the shader module containing the entry point.
	Module ShaderModuleID

	// EntryPoint is the name of the entry point function in the shader.
	EntryPoint string

	// Constants are pipeline-overridable constants.
	// The keys are the constant names and values are their overridden values.
	Constants map[string]float64
}

ProgrammableStage describes a programmable shader stage.

type QuerySet

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

QuerySet represents a set of queries with HAL integration.

QuerySet wraps a HAL query set handle and stores query set properties.

func NewQuerySet added in v0.21.0

func NewQuerySet(
	halQuerySet hal.QuerySet,
	device *Device,
	queryType hal.QueryType,
	count uint32,
	label string,
) *QuerySet

NewQuerySet creates a core QuerySet wrapping a HAL query set.

Parameters:

  • halQuerySet: The HAL query set to wrap (ownership transferred)
  • device: The parent device
  • queryType: The type of queries in this set
  • count: Number of queries in the set
  • label: Debug label for the query set

func (*QuerySet) Count added in v0.21.0

func (qs *QuerySet) Count() uint32

Count returns the number of queries in the set.

func (*QuerySet) Destroy added in v0.21.0

func (qs *QuerySet) Destroy()

Destroy releases the HAL query set.

This method is idempotent - calling it multiple times is safe. After calling Destroy(), Raw() returns nil.

func (*QuerySet) IsDestroyed added in v0.21.0

func (qs *QuerySet) IsDestroyed() bool

IsDestroyed returns true if the query set has been destroyed.

func (*QuerySet) Label added in v0.21.0

func (qs *QuerySet) Label() string

Label returns the query set's debug label.

func (*QuerySet) QueryType added in v0.21.0

func (qs *QuerySet) QueryType() hal.QueryType

QueryType returns the type of queries in this set.

func (*QuerySet) Raw added in v0.21.0

func (qs *QuerySet) Raw(guard *SnatchGuard) hal.QuerySet

Raw returns the underlying HAL query set if it hasn't been snatched.

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 RenderPassColorAttachment added in v0.9.0

type RenderPassColorAttachment struct {
	// View is the texture view to render to.
	View *TextureView

	// ResolveTarget is the MSAA resolve target (optional).
	ResolveTarget *TextureView

	// LoadOp specifies what to do at pass start.
	LoadOp gputypes.LoadOp

	// StoreOp specifies what to do at pass end.
	StoreOp gputypes.StoreOp

	// ClearValue is the clear color (used if LoadOp is Clear).
	ClearValue gputypes.Color
}

RenderPassColorAttachment describes a color attachment.

type RenderPassDepthStencilAttachment added in v0.9.0

type RenderPassDepthStencilAttachment struct {
	// View is the texture view to use.
	View *TextureView

	// DepthLoadOp specifies what to do with depth at pass start.
	DepthLoadOp gputypes.LoadOp

	// DepthStoreOp specifies what to do with depth at pass end.
	DepthStoreOp gputypes.StoreOp

	// DepthClearValue is the depth clear value.
	DepthClearValue float32

	// DepthReadOnly makes the depth aspect read-only.
	DepthReadOnly bool

	// StencilLoadOp specifies what to do with stencil at pass start.
	StencilLoadOp gputypes.LoadOp

	// StencilStoreOp specifies what to do with stencil at pass end.
	StencilStoreOp gputypes.StoreOp

	// StencilClearValue is the stencil clear value.
	StencilClearValue uint32

	// StencilReadOnly makes the stencil aspect read-only.
	StencilReadOnly bool
}

RenderPassDepthStencilAttachment describes a depth/stencil attachment.

type RenderPassDescriptor added in v0.9.0

type RenderPassDescriptor struct {
	// Label is an optional debug name.
	Label string

	// ColorAttachments are the color render targets.
	ColorAttachments []RenderPassColorAttachment

	// DepthStencilAttachment is the depth/stencil target (optional).
	DepthStencilAttachment *RenderPassDepthStencilAttachment
}

RenderPassDescriptor describes a render pass.

type RenderPipeline

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

RenderPipeline represents a render pipeline with HAL integration.

RenderPipeline wraps a HAL render pipeline handle.

func NewRenderPipeline added in v0.21.0

func NewRenderPipeline(
	halPipeline hal.RenderPipeline,
	device *Device,
	label string,
) *RenderPipeline

NewRenderPipeline creates a core RenderPipeline wrapping a HAL render pipeline.

Parameters:

  • halPipeline: The HAL render pipeline to wrap (ownership transferred)
  • device: The parent device
  • label: Debug label for the render pipeline

func (*RenderPipeline) Destroy added in v0.21.0

func (rp *RenderPipeline) Destroy()

Destroy releases the HAL render pipeline.

This method is idempotent - calling it multiple times is safe. After calling Destroy(), Raw() returns nil.

func (*RenderPipeline) IsDestroyed added in v0.21.0

func (rp *RenderPipeline) IsDestroyed() bool

IsDestroyed returns true if the render pipeline has been destroyed.

func (*RenderPipeline) Label added in v0.21.0

func (rp *RenderPipeline) Label() string

Label returns the render pipeline's debug label.

func (*RenderPipeline) Raw added in v0.21.0

func (rp *RenderPipeline) Raw(guard *SnatchGuard) hal.RenderPipeline

Raw returns the underlying HAL render pipeline if it hasn't been snatched.

type RenderPipelineID

type RenderPipelineID = ID[renderPipelineMarker]

RenderPipelineID identifies a RenderPipeline resource.

type Sampler

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

Sampler represents a texture sampler with HAL integration.

Sampler wraps a HAL sampler handle. Samplers are immutable after creation and have no mutable state beyond their HAL handle.

func NewSampler added in v0.21.0

func NewSampler(
	halSampler hal.Sampler,
	device *Device,
	label string,
) *Sampler

NewSampler creates a core Sampler wrapping a HAL sampler.

Parameters:

  • halSampler: The HAL sampler to wrap (ownership transferred)
  • device: The parent device
  • label: Debug label for the sampler

func (*Sampler) Destroy added in v0.21.0

func (s *Sampler) Destroy()

Destroy releases the HAL sampler.

This method is idempotent - calling it multiple times is safe. After calling Destroy(), Raw() returns nil.

func (*Sampler) IsDestroyed added in v0.21.0

func (s *Sampler) IsDestroyed() bool

IsDestroyed returns true if the sampler has been destroyed.

func (*Sampler) Label added in v0.21.0

func (s *Sampler) Label() string

Label returns the sampler's debug label.

func (*Sampler) Raw added in v0.21.0

func (s *Sampler) Raw(guard *SnatchGuard) hal.Sampler

Raw returns the underlying HAL sampler if it hasn't been snatched.

type SamplerID

type SamplerID = ID[samplerMarker]

SamplerID identifies a Sampler resource.

type ShaderModule

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

ShaderModule represents a compiled shader module with HAL integration.

ShaderModule wraps a HAL shader module handle.

func NewShaderModule added in v0.21.0

func NewShaderModule(
	halModule hal.ShaderModule,
	device *Device,
	label string,
) *ShaderModule

NewShaderModule creates a core ShaderModule wrapping a HAL shader module.

Parameters:

  • halModule: The HAL shader module to wrap (ownership transferred)
  • device: The parent device
  • label: Debug label for the shader module

func (*ShaderModule) Destroy added in v0.21.0

func (sm *ShaderModule) Destroy()

Destroy releases the HAL shader module.

This method is idempotent - calling it multiple times is safe. After calling Destroy(), Raw() returns nil.

func (*ShaderModule) IsDestroyed added in v0.21.0

func (sm *ShaderModule) IsDestroyed() bool

IsDestroyed returns true if the shader module has been destroyed.

func (*ShaderModule) Label added in v0.21.0

func (sm *ShaderModule) Label() string

Label returns the shader module's debug label.

func (*ShaderModule) Raw added in v0.21.0

func (sm *ShaderModule) Raw(guard *SnatchGuard) hal.ShaderModule

Raw returns the underlying HAL shader module if it hasn't been snatched.

type ShaderModuleID

type ShaderModuleID = ID[shaderModuleMarker]

ShaderModuleID identifies a ShaderModule resource.

func DeviceCreateShaderModule deprecated

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

DeviceCreateShaderModule creates a shader module.

Deprecated: This is the legacy ID-based API. For new code, use the HAL-based API: Device.CreateShaderModule() (when implemented).

This function creates a placeholder shader module without actual GPU resources. It exists for backward compatibility with existing code.

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

type SnatchGuard added in v0.9.0

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

SnatchGuard represents a held read lock on a SnatchLock.

It must be released by calling Release() when done. Not releasing the guard will cause a deadlock.

func (*SnatchGuard) Release added in v0.9.0

func (g *SnatchGuard) Release()

Release releases the read lock. This must be called exactly once. Subsequent calls are no-ops.

type SnatchLock added in v0.9.0

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

SnatchLock provides device-global coordination for snatchable resources.

Multiple resources can be accessed concurrently using read guards, but destruction (snatching) requires an exclusive write guard. This prevents resources from being destroyed while they're being accessed.

Thread-safe for concurrent use.

func NewSnatchLock added in v0.9.0

func NewSnatchLock() *SnatchLock

NewSnatchLock creates a new SnatchLock.

func (*SnatchLock) Read added in v0.9.0

func (l *SnatchLock) Read() *SnatchGuard

Read acquires a read lock and returns a SnatchGuard. Multiple goroutines can hold read locks simultaneously.

The returned guard must be released by calling Release(). Using defer is recommended:

guard := lock.Read()
defer guard.Release()

func (*SnatchLock) Write added in v0.9.0

func (l *SnatchLock) Write() *ExclusiveSnatchGuard

Write acquires an exclusive write lock and returns an ExclusiveSnatchGuard. Only one goroutine can hold the write lock, and it blocks all readers.

The returned guard must be released by calling Release(). Using defer is recommended:

guard := lock.Write()
defer guard.Release()

type Snatchable added in v0.9.0

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

Snatchable wraps a value that can be "snatched" for destruction.

The value can be accessed via Get() while it hasn't been snatched, and can be taken via Snatch() exactly once. After being snatched, Get() returns nil.

Thread-safe for concurrent use.

func NewSnatchable added in v0.9.0

func NewSnatchable[T any](value T) *Snatchable[T]

NewSnatchable creates a new Snatchable wrapper for the given value. The value is stored by pointer for efficient access.

func (*Snatchable[T]) Get added in v0.9.0

func (s *Snatchable[T]) Get(_ *SnatchGuard) *T

Get returns a pointer to the wrapped value if it hasn't been snatched. Returns nil if the value has already been snatched.

The caller must hold a SnatchGuard obtained from a SnatchLock. This ensures that the value won't be snatched during access.

Note: The guard parameter is used for API clarity and to enforce the pattern of acquiring a lock before accessing snatchable resources.

func (*Snatchable[T]) IsSnatched added in v0.9.0

func (s *Snatchable[T]) IsSnatched() bool

IsSnatched returns true if the value has been snatched.

func (*Snatchable[T]) Snatch added in v0.9.0

func (s *Snatchable[T]) Snatch(_ *ExclusiveSnatchGuard) *T

Snatch takes ownership of the wrapped value for destruction. Returns the value if it hasn't been snatched yet, nil otherwise.

This can only succeed once - subsequent calls return nil.

The caller must hold an ExclusiveSnatchGuard obtained from a SnatchLock. This ensures exclusive access during the snatch operation.

Note: The guard parameter is used for API clarity and to enforce the pattern of acquiring exclusive lock before snatching.

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 {
	// contains filtered or unexported fields
}

Surface represents a rendering surface with HAL integration.

Surface wraps a HAL surface handle. Unlike other resources, surfaces are owned by the Instance (not Device) and outlive devices, so the HAL handle is stored directly rather than in a Snatchable.

Surface manages a state machine: Unconfigured -> Configured -> Acquired -> Configured. All state transitions are protected by a mutex.

func NewSurface added in v0.21.0

func NewSurface(
	halSurface hal.Surface,
	label string,
) *Surface

NewSurface creates a core Surface wrapping a HAL surface.

The surface starts in the Unconfigured state. Call Configure() before acquiring textures.

Parameters:

  • halSurface: The HAL surface to wrap (ownership transferred)
  • label: Debug label for the surface

func (*Surface) AcquireTexture added in v0.21.0

func (s *Surface) AcquireTexture(fence hal.Fence) (*hal.AcquiredSurfaceTexture, error)

AcquireTexture acquires the next surface texture for rendering.

The surface must be in the Configured state. If a PrepareFrame hook is registered and reports that dimensions changed, the surface is automatically reconfigured before acquiring.

After a successful acquire, the surface enters the Acquired state. The caller must either Present or DiscardTexture before acquiring again.

func (*Surface) Config added in v0.21.0

func (s *Surface) Config() *hal.SurfaceConfiguration

Config returns the current surface configuration. Returns nil if the surface is unconfigured.

func (*Surface) Configure added in v0.21.0

func (s *Surface) Configure(device *Device, config *hal.SurfaceConfiguration) error

Configure configures the surface with the given device and settings.

The surface must not have an acquired texture. If the surface is already configured, it will be reconfigured with the new settings.

After Configure, the surface enters the Configured state and is ready to acquire textures.

func (*Surface) DiscardTexture added in v0.21.0

func (s *Surface) DiscardTexture()

DiscardTexture discards the acquired surface texture without presenting it.

Use this if rendering failed or was canceled. If no texture is acquired, this is a no-op.

func (*Surface) Present added in v0.21.0

func (s *Surface) Present(queue hal.Queue) error

Present presents the acquired surface texture to the screen.

The surface must be in the Acquired state. After presenting, the surface returns to the Configured state and is ready to acquire again.

func (*Surface) RawSurface added in v0.21.0

func (s *Surface) RawSurface() hal.Surface

RawSurface returns the underlying HAL surface.

func (*Surface) SetPrepareFrame added in v0.21.0

func (s *Surface) SetPrepareFrame(fn PrepareFrameFunc)

SetPrepareFrame registers a platform hook that is called before acquiring a texture.

The hook returns the current surface dimensions and whether they changed. If changed is true, the surface is automatically reconfigured before acquiring.

Pass nil to remove the hook.

func (*Surface) State added in v0.21.0

func (s *Surface) State() SurfaceState

State returns the current lifecycle state of the surface.

func (*Surface) Unconfigure added in v0.21.0

func (s *Surface) Unconfigure()

Unconfigure removes the surface configuration and returns to the Unconfigured state.

If a texture is currently acquired, it is discarded first. If the surface is already unconfigured, this is a no-op.

type SurfaceID

type SurfaceID = ID[surfaceMarker]

SurfaceID identifies a Surface resource.

type SurfaceState added in v0.21.0

type SurfaceState int

SurfaceState represents the lifecycle state of a surface.

const (
	// SurfaceStateUnconfigured indicates the surface has not been configured.
	SurfaceStateUnconfigured SurfaceState = iota

	// SurfaceStateConfigured indicates the surface is configured and ready to acquire textures.
	SurfaceStateConfigured

	// SurfaceStateAcquired indicates a texture has been acquired and not yet presented or discarded.
	SurfaceStateAcquired
)

type Texture

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

Texture represents a GPU texture with HAL integration.

Texture wraps a HAL texture handle and stores WebGPU texture properties. The HAL texture is wrapped in a Snatchable to enable safe deferred destruction.

func NewTexture added in v0.21.0

func NewTexture(
	halTexture hal.Texture,
	device *Device,
	format gputypes.TextureFormat,
	dimension gputypes.TextureDimension,
	usage gputypes.TextureUsage,
	size gputypes.Extent3D,
	mipLevelCount uint32,
	sampleCount uint32,
	label string,
) *Texture

NewTexture creates a core Texture wrapping a HAL texture.

Parameters:

  • halTexture: The HAL texture to wrap (ownership transferred)
  • device: The parent device
  • format: Texture pixel format
  • dimension: Texture dimension (1D, 2D, 3D)
  • usage: Texture usage flags
  • size: Texture dimensions
  • mipLevelCount: Number of mip levels
  • sampleCount: Number of samples per pixel
  • label: Debug label for the texture

func (*Texture) Destroy added in v0.21.0

func (t *Texture) Destroy()

Destroy releases the HAL texture.

This method is idempotent - calling it multiple times is safe. After calling Destroy(), Raw() returns nil.

func (*Texture) Dimension added in v0.21.0

func (t *Texture) Dimension() gputypes.TextureDimension

Dimension returns the texture's dimension (1D, 2D, 3D).

func (*Texture) Format added in v0.21.0

func (t *Texture) Format() gputypes.TextureFormat

Format returns the texture's pixel format.

func (*Texture) IsDestroyed added in v0.21.0

func (t *Texture) IsDestroyed() bool

IsDestroyed returns true if the texture has been destroyed.

func (*Texture) Label added in v0.21.0

func (t *Texture) Label() string

Label returns the texture's debug label.

func (*Texture) MipLevelCount added in v0.21.0

func (t *Texture) MipLevelCount() uint32

MipLevelCount returns the number of mip levels.

func (*Texture) Raw added in v0.21.0

func (t *Texture) Raw(guard *SnatchGuard) hal.Texture

Raw returns the underlying HAL texture if it hasn't been snatched.

func (*Texture) SampleCount added in v0.21.0

func (t *Texture) SampleCount() uint32

SampleCount returns the number of samples per pixel.

func (*Texture) Size added in v0.21.0

func (t *Texture) Size() gputypes.Extent3D

Size returns the texture's dimensions.

func (*Texture) Usage added in v0.21.0

func (t *Texture) Usage() gputypes.TextureUsage

Usage returns the texture's usage flags.

type TextureID

type TextureID = ID[textureMarker]

TextureID identifies a Texture resource.

func DeviceCreateTexture deprecated

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

DeviceCreateTexture creates a texture on this device.

Deprecated: This is the legacy ID-based API. For new code, use the HAL-based API: Device.CreateTexture() (when implemented).

This function creates a placeholder texture without actual GPU resources. It exists for backward compatibility with existing code.

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

type TextureUses added in v0.9.0

type TextureUses uint32

TextureUses tracks how a texture is used within a command buffer.

const (
	// TextureUsesNone indicates no usage.
	TextureUsesNone TextureUses = 0
	// TextureUsesSampled indicates sampled texture usage.
	TextureUsesSampled TextureUses = 1 << iota
	// TextureUsesStorage indicates storage texture usage.
	TextureUsesStorage
	// TextureUsesRenderAttachment indicates render attachment usage.
	TextureUsesRenderAttachment
	// TextureUsesCopySrc indicates copy source usage.
	TextureUsesCopySrc
	// TextureUsesCopyDst indicates copy destination usage.
	TextureUsesCopyDst
)

type TextureView

type TextureView struct {
	// HAL is the underlying HAL texture view handle.
	// Set by the public API layer when creating texture views with real HAL backends.
	HAL hal.TextureView
}

TextureView represents a view into a texture.

type TextureViewID

type TextureViewID = ID[textureViewMarker]

TextureViewID identifies a TextureView resource.

type TrackerIndex added in v0.9.0

type TrackerIndex uint32

TrackerIndex is a dense index for efficient resource state tracking.

Unlike resource IDs (which use epochs and may be sparse), tracker indices are always dense (0, 1, 2, ...) for efficient array access.

This is a stub - full implementation in CORE-006.

const InvalidTrackerIndex TrackerIndex = ^TrackerIndex(0)

InvalidTrackerIndex represents an unassigned tracker index.

type TrackerIndexAllocators added in v0.9.0

type TrackerIndexAllocators struct{}

TrackerIndexAllocators manages tracker indices per resource type.

This is used to assign unique indices to resources for tracking their state and usage across command buffer recording and submission.

Stub implementation - will be expanded in CORE-006.

func NewTrackerIndexAllocators added in v0.9.0

func NewTrackerIndexAllocators() *TrackerIndexAllocators

NewTrackerIndexAllocators creates a new TrackerIndexAllocators.

type TrackingData added in v0.9.0

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

TrackingData holds per-resource tracking information.

Each resource that needs state tracking during command encoding embeds a TrackingData struct to hold its tracker index.

This is a stub - full implementation in CORE-006.

func NewTrackingData added in v0.9.0

func NewTrackingData(_ *TrackerIndexAllocators) *TrackingData

NewTrackingData creates tracking data for a resource.

This is a stub - full implementation in CORE-006.

func (*TrackingData) Index added in v0.9.0

func (t *TrackingData) Index() TrackerIndex

Index returns the tracker index for this 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.

Directories

Path Synopsis
Package track provides resource state tracking infrastructure.
Package track provides resource state tracking infrastructure.

Jump to

Keyboard shortcuts

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