core

package
v0.19.5 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2026 License: MIT Imports: 8 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.

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 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 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.

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{}

BindGroup represents a collection of resources bound together.

type BindGroupID

type BindGroupID = ID[bindGroupMarker]

BindGroupID identifies a BindGroup resource.

type BindGroupLayout

type BindGroupLayout struct{}

BindGroupLayout represents the layout of a bind group.

type BindGroupLayoutID

type BindGroupLayoutID = ID[bindGroupLayoutMarker]

BindGroupLayoutID identifies a BindGroupLayout resource.

type Buffer

type Buffer struct {
	// 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{}

CommandBuffer represents a recorded command buffer.

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 CommandEncoder

type CommandEncoder struct{}

CommandEncoder represents a command encoder.

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 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{}

ComputePipeline represents a compute pipeline.

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.

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) 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 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 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{}

PipelineLayout represents the layout of a pipeline.

type PipelineLayoutID

type PipelineLayoutID = ID[pipelineLayoutMarker]

PipelineLayoutID identifies a PipelineLayout resource.

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{}

QuerySet represents a set of queries.

type QuerySetID

type QuerySetID = ID[querySetMarker]

QuerySetID identifies a QuerySet resource.

type Queue

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

Queue represents a command queue for a device.

func GetQueue

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

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

type QueueID

type QueueID = ID[queueMarker]

QueueID identifies a Queue resource.

func GetDeviceQueue

func GetDeviceQueue(id DeviceID) (QueueID, error)

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

type RawID

type RawID uint64

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

func Zip

func Zip(index Index, epoch Epoch) RawID

Zip combines an index and epoch into a RawID.

func (RawID) Epoch

func (id RawID) Epoch() Epoch

Epoch returns the epoch component of the RawID.

func (RawID) Index

func (id RawID) Index() Index

Index returns the index component of the RawID.

func (RawID) IsZero

func (id RawID) IsZero() bool

IsZero returns true if both index and epoch are zero.

func (RawID) String

func (id RawID) String() string

String returns a string representation of the RawID.

func (RawID) Unzip

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

Unzip extracts the index and epoch from a RawID.

type Registry

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

Registry manages the lifecycle of resources of a specific type.

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

Thread-safe for concurrent use.

func NewRegistry

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

NewRegistry creates a new registry for the given types.

func (*Registry[T, M]) Clear

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

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

func (*Registry[T, M]) Contains

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

Contains checks if an item exists at the given ID.

func (*Registry[T, M]) Count

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

Count returns the number of registered items.

func (*Registry[T, M]) ForEach

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

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

func (*Registry[T, M]) Get

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

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

func (*Registry[T, M]) GetMut

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

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

func (*Registry[T, M]) Register

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

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

func (*Registry[T, M]) Unregister

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

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

type 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{}

RenderPipeline represents a render pipeline.

type RenderPipelineID

type RenderPipelineID = ID[renderPipelineMarker]

RenderPipelineID identifies a RenderPipeline resource.

type Sampler

type Sampler struct{}

Sampler represents a texture sampler.

type SamplerID

type SamplerID = ID[samplerMarker]

SamplerID identifies a Sampler resource.

type ShaderModule

type ShaderModule struct{}

ShaderModule represents a compiled shader module.

type ShaderModuleID

type ShaderModuleID = ID[shaderModuleMarker]

ShaderModuleID identifies a ShaderModule resource.

func DeviceCreateShaderModule 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{}

Surface represents a rendering surface.

type SurfaceID

type SurfaceID = ID[surfaceMarker]

SurfaceID identifies a Surface resource.

type Texture

type Texture struct{}

Texture represents a GPU texture.

type TextureID

type TextureID = ID[textureMarker]

TextureID identifies a Texture resource.

func DeviceCreateTexture 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