Documentation
¶
Overview ¶
Package wgpu provides Zero-CGO WebGPU bindings for Go.
This package wraps wgpu-native (Rust WebGPU implementation) using pure Go FFI via syscall on Windows and dlopen on Unix. No CGO is required.
Thread Safety ¶
The following operations are safe for concurrent use:
- Init and library initialization (protected by sync.Once)
- Instance.RequestAdapter (callback registry protected by mutex)
- Adapter.RequestDevice (callback registry protected by mutex)
- Device.PopErrorScopeAsync (callback registry protected by mutex)
- Buffer.MapAsync (callback registry protected by mutex)
- Read-only queries: Adapter.GetLimits, Adapter.GetInfo, Adapter.EnumerateFeatures, Adapter.HasFeature
- Read-only queries: Device.GetLimits, Device.GetFeatures, Device.HasFeature
- Read-only queries: Surface.GetCapabilities
The following operations are NOT safe for concurrent use on the same object:
- Surface.Configure, Surface.GetCurrentTexture, Surface.Present (must be called from a single goroutine, typically the render loop)
- CommandEncoder methods (single encoder should not be shared between goroutines)
- RenderPassEncoder and ComputePassEncoder methods
- Buffer.GetMappedRange and Buffer.Unmap
General rule: different GPU objects can be used from different goroutines, but a single object should not be accessed concurrently. This matches the WebGPU spec threading model.
Quick Start ¶
// Initialize the library
if err := wgpu.Init(); err != nil {
log.Fatal(err)
}
// Create instance
instance, err := wgpu.CreateInstance(nil)
if err != nil {
log.Fatal(err)
}
defer instance.Release()
// Request adapter (GPU)
adapter, err := instance.RequestAdapter(nil)
if err != nil {
log.Fatal(err)
}
defer adapter.Release()
// Request device
device, err := adapter.RequestDevice(nil)
if err != nil {
log.Fatal(err)
}
defer device.Release()
Core Objects ¶
The WebGPU API is structured around several core object types:
- Instance: Entry point to the WebGPU API
- Adapter: Represents a physical GPU
- Device: Logical device for creating resources
- Queue: Command submission queue
- Buffer: GPU memory buffer
- Texture: GPU texture resource
- Sampler: Texture sampling configuration
- ShaderModule: Compiled shader code (WGSL)
- BindGroup: Resource bindings for shaders
- RenderPipeline: Configuration for rendering
- ComputePipeline: Configuration for compute
- CommandEncoder: Records GPU commands
- RenderPassEncoder: Records render commands
- ComputePassEncoder: Records compute commands
Resource Management ¶
All WebGPU objects must be released when no longer needed:
buffer := device.CreateBuffer(&wgpu.BufferDescriptor{...})
defer buffer.Release()
Render Pipeline ¶
A typical render pipeline setup:
// Create shader module
shader := device.CreateShaderModuleWGSL(shaderCode)
defer shader.Release()
// Create render pipeline
pipeline := device.CreateRenderPipeline(&wgpu.RenderPipelineDescriptor{
Vertex: wgpu.VertexState{
Module: vsModule,
EntryPoint: "main",
Buffers: []wgpu.VertexBufferLayout{vertexBufferLayout},
},
Fragment: &wgpu.FragmentState{
Module: fsModule,
EntryPoint: "main",
Targets: []wgpu.ColorTargetState{{Format: format, WriteMask: gputypes.ColorWriteMaskAll}},
},
// ... other configuration
})
defer pipeline.Release()
Compute Pipeline ¶
For GPU compute operations:
pipeline := device.CreateComputePipelineSimple(nil, shader, "main") defer pipeline.Release() // Dispatch compute work computePass := encoder.BeginComputePass(nil) computePass.SetPipeline(pipeline) computePass.SetBindGroup(0, bindGroup, nil) computePass.DispatchWorkgroups(workgroupCount, 1, 1) computePass.End()
Indirect Drawing ¶
GPU-driven rendering using indirect buffers:
// Create indirect buffer with draw args
args := wgpu.DrawIndirectArgs{
VertexCount: 3,
InstanceCount: 100,
}
// Write to buffer...
// Draw using GPU-specified parameters
renderPass.DrawIndirect(indirectBuffer, 0)
RenderBundle ¶
Pre-record render commands for efficient replay:
bundleEncoder := device.CreateRenderBundleEncoderSimple(
[]gputypes.TextureFormat{surfaceFormat},
gputypes.TextureFormatUndefined,
1,
)
bundleEncoder.SetPipeline(pipeline)
bundleEncoder.Draw(3, 1, 0, 0)
bundle := bundleEncoder.Finish(nil)
defer bundle.Release()
// Later, in a render pass:
renderPass.ExecuteBundles([]*wgpu.RenderBundle{bundle})
Platform Support ¶
Supported platforms:
- Windows (x64) - uses syscall.LazyDLL
- Linux (x64, arm64) - uses goffi/dlopen
- macOS (x64, arm64) - uses goffi/dlopen
Dependencies ¶
This package requires wgpu-native library:
- Windows: wgpu_native.dll
- Linux: libwgpu_native.so
- macOS: libwgpu_native.dylib
Download from: https://github.com/gfx-rs/wgpu-native/releases
Index ¶
- Constants
- Variables
- func DebugMode() bool
- func Init() error
- func ResetLeakTracker()
- func SetDebugMode(enabled bool)
- type Adapter
- func (a *Adapter) EnumerateFeatures() []FeatureName
- func (a *Adapter) GetInfo() (*AdapterInfoGo, error)
- func (a *Adapter) GetLimits() (*SupportedLimits, error)
- func (a *Adapter) Handle() uintptr
- func (a *Adapter) HasFeature(feature FeatureName) bool
- func (a *Adapter) Release()
- func (a *Adapter) RequestDevice(options *DeviceDescriptor) (*Device, error)
- type AdapterInfo
- type AdapterInfoGo
- type AdapterType
- type BackendType
- type BindGroup
- type BindGroupDescriptor
- type BindGroupEntry
- type BindGroupLayout
- type BindGroupLayoutDescriptor
- type BindGroupLayoutEntry
- type BlendComponent
- type BlendState
- type Bool
- type Buffer
- func (b *Buffer) Destroy()
- func (b *Buffer) GetMapState() BufferMapState
- func (b *Buffer) GetMappedRange(offset, size uint64) unsafe.Pointer
- func (b *Buffer) GetSize() uint64
- func (b *Buffer) GetUsage() gputypes.BufferUsage
- func (b *Buffer) Handle() uintptr
- func (b *Buffer) MapAsync(device *Device, mode MapMode, offset, size uint64) error
- func (b *Buffer) Release()
- func (b *Buffer) Unmap()
- type BufferBindingLayout
- type BufferDescriptor
- type BufferMapCallbackInfo
- type BufferMapState
- type CallbackMode
- type ChainedStruct
- type ChainedStructOut
- type Color
- type ColorTargetState
- type CommandBuffer
- type CommandBufferDescriptor
- type CommandEncoder
- func (enc *CommandEncoder) BeginComputePass(desc *ComputePassDescriptor) *ComputePassEncoder
- func (enc *CommandEncoder) BeginRenderPass(desc *RenderPassDescriptor) *RenderPassEncoder
- func (enc *CommandEncoder) ClearBuffer(buffer *Buffer, offset, size uint64)
- func (enc *CommandEncoder) CopyBufferToBuffer(src *Buffer, srcOffset uint64, dst *Buffer, dstOffset uint64, size uint64)
- func (enc *CommandEncoder) CopyBufferToTexture(source *TexelCopyBufferInfo, destination *TexelCopyTextureInfo, ...)
- func (enc *CommandEncoder) CopyTextureToBuffer(source *TexelCopyTextureInfo, destination *TexelCopyBufferInfo, ...)
- func (enc *CommandEncoder) CopyTextureToTexture(source *TexelCopyTextureInfo, destination *TexelCopyTextureInfo, ...)
- func (enc *CommandEncoder) Finish(desc *CommandBufferDescriptor) *CommandBuffer
- func (enc *CommandEncoder) Handle() uintptr
- func (enc *CommandEncoder) InsertDebugMarker(markerLabel string)
- func (enc *CommandEncoder) PopDebugGroup()
- func (enc *CommandEncoder) PushDebugGroup(groupLabel string)
- func (enc *CommandEncoder) Release()
- func (enc *CommandEncoder) ResolveQuerySet(querySet *QuerySet, firstQuery, queryCount uint32, destination *Buffer, ...)
- func (enc *CommandEncoder) WriteTimestamp(querySet *QuerySet, queryIndex uint32)
- type CommandEncoderDescriptor
- type ComputePassDescriptor
- type ComputePassEncoder
- func (cpe *ComputePassEncoder) DispatchWorkgroups(x, y, z uint32)
- func (cpe *ComputePassEncoder) DispatchWorkgroupsIndirect(indirectBuffer *Buffer, indirectOffset uint64)
- func (cpe *ComputePassEncoder) End()
- func (cpe *ComputePassEncoder) Handle() uintptr
- func (cpe *ComputePassEncoder) Release()
- func (cpe *ComputePassEncoder) SetBindGroup(groupIndex uint32, group *BindGroup, dynamicOffsets []uint32)
- func (cpe *ComputePassEncoder) SetPipeline(pipeline *ComputePipeline)
- type ComputePipeline
- type ComputePipelineDescriptor
- type DepthStencilState
- type Device
- func (d *Device) CreateBindGroup(desc *BindGroupDescriptor) *BindGroup
- func (d *Device) CreateBindGroupLayout(desc *BindGroupLayoutDescriptor) *BindGroupLayout
- func (d *Device) CreateBindGroupLayoutSimple(entries []BindGroupLayoutEntry) *BindGroupLayout
- func (d *Device) CreateBindGroupSimple(layout *BindGroupLayout, entries []BindGroupEntry) *BindGroup
- func (d *Device) CreateBuffer(desc *BufferDescriptor) *Buffer
- func (d *Device) CreateCommandEncoder(desc *CommandEncoderDescriptor) *CommandEncoder
- func (d *Device) CreateComputePipeline(desc *ComputePipelineDescriptor) *ComputePipeline
- func (d *Device) CreateComputePipelineSimple(layout *PipelineLayout, shader *ShaderModule, entryPoint string) *ComputePipeline
- func (d *Device) CreateDepthTexture(width, height uint32, format gputypes.TextureFormat) *Texture
- func (d *Device) CreateLinearSampler() *Sampler
- func (d *Device) CreateNearestSampler() *Sampler
- func (d *Device) CreatePipelineLayout(desc *PipelineLayoutDescriptor) *PipelineLayout
- func (d *Device) CreatePipelineLayoutSimple(layouts []*BindGroupLayout) *PipelineLayout
- func (d *Device) CreateQuerySet(desc *QuerySetDescriptor) *QuerySet
- func (d *Device) CreateRenderBundleEncoder(desc *RenderBundleEncoderDescriptor) *RenderBundleEncoder
- func (d *Device) CreateRenderBundleEncoderSimple(colorFormats []gputypes.TextureFormat, depthFormat gputypes.TextureFormat, ...) *RenderBundleEncoder
- func (d *Device) CreateRenderPipeline(desc *RenderPipelineDescriptor) *RenderPipeline
- func (d *Device) CreateRenderPipelineSimple(layout *PipelineLayout, vertexShader *ShaderModule, vertexEntryPoint string, ...) *RenderPipeline
- func (d *Device) CreateSampler(desc *SamplerDescriptor) *Sampler
- func (d *Device) CreateShaderModule(desc *ShaderModuleDescriptor) *ShaderModule
- func (d *Device) CreateShaderModuleWGSL(code string) *ShaderModule
- func (d *Device) CreateTexture(desc *TextureDescriptor) *Texture
- func (d *Device) GetFeatures() []FeatureName
- func (d *Device) GetLimits() (*SupportedLimits, error)
- func (d *Device) GetQueue() *Queue
- func (d *Device) Handle() uintptr
- func (d *Device) HasFeature(feature FeatureName) bool
- func (d *Device) Poll(wait bool) bool
- func (d *Device) PopErrorScope(instance *Instance) (ErrorType, string)deprecated
- func (d *Device) PopErrorScopeAsync(instance *Instance) (ErrorType, string, error)
- func (d *Device) PushErrorScope(filter ErrorFilter)
- func (d *Device) Release()
- type DeviceDescriptor
- type DeviceLostReason
- type DispatchIndirectArgs
- type DrawIndexedIndirectArgs
- type DrawIndirectArgs
- type ErrorFilter
- type ErrorType
- type FeatureLevel
- type FeatureName
- type FragmentState
- type Future
- type Instance
- func (inst *Instance) CreateSurfaceFromWaylandSurface(display, surface uintptr) (*Surface, error)
- func (inst *Instance) CreateSurfaceFromXlibWindow(display uintptr, window uint64) (*Surface, error)
- func (i *Instance) Handle() uintptr
- func (i *Instance) ProcessEvents()
- func (i *Instance) Release()
- func (i *Instance) RequestAdapter(options *RequestAdapterOptions) (*Adapter, error)
- type InstanceCapabilities
- type InstanceDescriptor
- type LeakReport
- type Library
- type Limits
- type MapAsyncStatus
- type MapMode
- type Mat4
- func Mat4Identity() Mat4
- func Mat4LookAt(eye, center, up Vec3) Mat4
- func Mat4Perspective(fovY, aspect, near, far float32) Mat4
- func Mat4RotateX(radians float32) Mat4
- func Mat4RotateY(radians float32) Mat4
- func Mat4RotateZ(radians float32) Mat4
- func Mat4Scale(x, y, z float32) Mat4
- func Mat4Translate(x, y, z float32) Mat4
- type MultisampleState
- type OptionalBool
- type PipelineLayout
- type PipelineLayoutDescriptor
- type PopErrorScopeStatus
- type PrimitiveState
- type Proc
- type ProgrammableStageDescriptor
- type QuerySet
- type QuerySetDescriptor
- type QueryType
- type Queue
- func (q *Queue) Handle() uintptr
- func (q *Queue) Release()
- func (q *Queue) Submit(commands ...*CommandBuffer)
- func (q *Queue) WriteBuffer(buffer *Buffer, offset uint64, data []byte)
- func (q *Queue) WriteBufferRaw(buffer *Buffer, offset uint64, data unsafe.Pointer, size uint64)
- func (q *Queue) WriteTexture(dest *TexelCopyTextureInfo, data []byte, layout *TexelCopyBufferLayout, ...)
- type RenderBundle
- type RenderBundleDescriptor
- type RenderBundleEncoder
- func (rbe *RenderBundleEncoder) Draw(vertexCount, instanceCount, firstVertex, firstInstance uint32)
- func (rbe *RenderBundleEncoder) DrawIndexed(indexCount, instanceCount, firstIndex uint32, baseVertex int32, ...)
- func (rbe *RenderBundleEncoder) DrawIndexedIndirect(indirectBuffer *Buffer, indirectOffset uint64)
- func (rbe *RenderBundleEncoder) DrawIndirect(indirectBuffer *Buffer, indirectOffset uint64)
- func (rbe *RenderBundleEncoder) Finish(desc *RenderBundleDescriptor) *RenderBundle
- func (rbe *RenderBundleEncoder) Handle() uintptr
- func (rbe *RenderBundleEncoder) Release()
- func (rbe *RenderBundleEncoder) SetBindGroup(groupIndex uint32, group *BindGroup, dynamicOffsets []uint32)
- func (rbe *RenderBundleEncoder) SetIndexBuffer(buffer *Buffer, format gputypes.IndexFormat, offset, size uint64)
- func (rbe *RenderBundleEncoder) SetPipeline(pipeline *RenderPipeline)
- func (rbe *RenderBundleEncoder) SetVertexBuffer(slot uint32, buffer *Buffer, offset, size uint64)
- type RenderBundleEncoderDescriptor
- type RenderPassColorAttachment
- type RenderPassDepthStencilAttachment
- type RenderPassDescriptor
- type RenderPassEncoder
- func (rpe *RenderPassEncoder) Draw(vertexCount, instanceCount, firstVertex, firstInstance uint32)
- func (rpe *RenderPassEncoder) DrawIndexed(indexCount, instanceCount, firstIndex uint32, baseVertex int32, ...)
- func (rpe *RenderPassEncoder) DrawIndexedIndirect(indirectBuffer *Buffer, indirectOffset uint64)
- func (rpe *RenderPassEncoder) DrawIndirect(indirectBuffer *Buffer, indirectOffset uint64)
- func (rpe *RenderPassEncoder) End()
- func (rpe *RenderPassEncoder) ExecuteBundles(bundles []*RenderBundle)
- func (rpe *RenderPassEncoder) Handle() uintptr
- func (rpe *RenderPassEncoder) InsertDebugMarker(markerLabel string)
- func (rpe *RenderPassEncoder) PopDebugGroup()
- func (rpe *RenderPassEncoder) PushDebugGroup(groupLabel string)
- func (rpe *RenderPassEncoder) Release()
- func (rpe *RenderPassEncoder) SetBindGroup(groupIndex uint32, group *BindGroup, dynamicOffsets []uint32)
- func (rpe *RenderPassEncoder) SetBlendConstant(color *Color)
- func (rpe *RenderPassEncoder) SetIndexBuffer(buffer *Buffer, format gputypes.IndexFormat, offset, size uint64)
- func (rpe *RenderPassEncoder) SetPipeline(pipeline *RenderPipeline)
- func (rpe *RenderPassEncoder) SetScissorRect(x, y, width, height uint32)
- func (rpe *RenderPassEncoder) SetStencilReference(reference uint32)
- func (rpe *RenderPassEncoder) SetVertexBuffer(slot uint32, buffer *Buffer, offset, size uint64)
- func (rpe *RenderPassEncoder) SetViewport(x, y, width, height, minDepth, maxDepth float32)
- type RenderPassTimestampWrites
- type RenderPipeline
- type RenderPipelineDescriptor
- type RequestAdapterCallbackInfo
- type RequestAdapterOptions
- type RequestAdapterStatus
- type RequestDeviceCallbackInfo
- type RequestDeviceStatus
- type SType
- type Sampler
- type SamplerBindingLayout
- type SamplerDescriptor
- type ShaderModule
- type ShaderModuleDescriptor
- type ShaderSourceWGSL
- type StencilFaceState
- type StorageTextureBindingLayout
- type StringView
- type SupportedFeatures
- type SupportedLimits
- type Surface
- func (s *Surface) Configure(config *SurfaceConfiguration)
- func (s *Surface) GetCapabilities(adapter *Adapter) (*SurfaceCapabilities, error)
- func (s *Surface) GetCurrentTexture() (*SurfaceTexture, error)
- func (s *Surface) Handle() uintptr
- func (s *Surface) Present()
- func (s *Surface) Release()
- func (s *Surface) Unconfigure()
- type SurfaceCapabilities
- type SurfaceConfiguration
- type SurfaceGetCurrentTextureStatus
- type SurfaceTexture
- type TexelCopyBufferInfo
- type TexelCopyBufferLayout
- type TexelCopyTextureInfo
- type Texture
- func (t *Texture) CreateView(desc *TextureViewDescriptor) *TextureView
- func (t *Texture) Destroy()
- func (t *Texture) GetDepthOrArrayLayers() uint32
- func (t *Texture) GetFormat() gputypes.TextureFormat
- func (t *Texture) GetHeight() uint32
- func (t *Texture) GetMipLevelCount() uint32
- func (t *Texture) GetWidth() uint32
- func (t *Texture) Handle() uintptr
- func (t *Texture) Release()
- type TextureAspect
- type TextureBindingLayout
- type TextureDescriptor
- type TextureView
- type TextureViewDescriptor
- type Vec3
- type Vec4
- type VertexAttribute
- type VertexBufferLayout
- type VertexState
- type WGPUError
- type WGPUStatus
Examples ¶
Constants ¶
const DepthSliceUndefined uint32 = 0xFFFFFFFF
DepthSliceUndefined is used for 2D textures in color attachments.
const TimestampLocationUndefined uint32 = 0xFFFFFFFF
TimestampLocationUndefined indicates no timestamp write at this location.
Variables ¶
var ( ErrSurfaceNeedsReconfigure = &WGPUError{Op: "Surface.GetCurrentTexture", Message: "surface needs reconfigure"} ErrSurfaceLost = &WGPUError{Op: "Surface.GetCurrentTexture", Message: "surface lost"} ErrSurfaceTimeout = &WGPUError{Op: "Surface.GetCurrentTexture", Message: "surface texture timeout"} ErrSurfaceOutOfMemory = &WGPUError{Op: "Surface.GetCurrentTexture", Message: "out of memory"} ErrSurfaceDeviceLost = &WGPUError{Op: "Surface.GetCurrentTexture", Message: "device lost"} )
Error values for surface operations. These are sentinel errors for programmatic error handling via errors.Is().
var ( // ErrValidation matches any WebGPU validation error. ErrValidation = &WGPUError{Type: ErrorTypeValidation} // ErrOutOfMemory matches any WebGPU out-of-memory error. ErrOutOfMemory = &WGPUError{Type: ErrorTypeOutOfMemory} // ErrInternal matches any WebGPU internal error. ErrInternal = &WGPUError{Type: ErrorTypeInternal} // ErrDeviceLost matches device lost errors. ErrDeviceLost = &WGPUError{Type: ErrorTypeUnknown, Message: "device lost"} )
Sentinel errors for programmatic error handling via errors.Is().
Usage:
if errors.Is(err, wgpu.ErrValidation) {
// handle validation error
}
var ErrLibraryNotLoaded = errors.New("wgpu: native library not loaded or failed to initialize")
ErrLibraryNotLoaded is returned when wgpu-native library is not loaded or failed to initialize.
Functions ¶
func DebugMode ¶ added in v0.3.0
func DebugMode() bool
DebugMode returns whether debug mode is currently enabled.
func Init ¶
func Init() error
Init initializes the wgpu library. Called automatically on first use. Can be called explicitly to check for initialization errors early.
func ResetLeakTracker ¶ added in v0.3.0
func ResetLeakTracker()
ResetLeakTracker clears the resource tracker. Useful for test cleanup.
func SetDebugMode ¶ added in v0.3.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 {
// contains filtered or unexported fields
}
Adapter represents a physical GPU and its capabilities. Obtained via Instance.RequestAdapter, release with Adapter.Release.
func (*Adapter) EnumerateFeatures ¶
func (a *Adapter) EnumerateFeatures() []FeatureName
EnumerateFeatures retrieves all features supported by this adapter. Returns a slice of FeatureName values.
func (*Adapter) GetInfo ¶
func (a *Adapter) GetInfo() (*AdapterInfoGo, error)
GetInfo retrieves information about this adapter. The returned AdapterInfoGo contains Go strings copied from C memory. Returns nil if the adapter is nil or if the operation fails.
func (*Adapter) GetLimits ¶
func (a *Adapter) GetLimits() (*SupportedLimits, error)
GetLimits retrieves the limits of this adapter. Returns nil if the adapter is nil or if the operation fails.
func (*Adapter) HasFeature ¶
func (a *Adapter) HasFeature(feature FeatureName) bool
HasFeature checks if the adapter supports a specific feature.
func (*Adapter) RequestDevice ¶
func (a *Adapter) RequestDevice(options *DeviceDescriptor) (*Device, error)
RequestDevice requests a GPU device from the adapter. This is a synchronous wrapper that blocks until the device is available.
type AdapterInfo ¶
type AdapterInfo struct {
NextInChain uintptr // *ChainedStructOut
Vendor StringView
Architecture StringView
Device StringView
Description StringView
BackendType BackendType
AdapterType AdapterType
VendorID uint32
DeviceID uint32
}
AdapterInfo contains information about the adapter.
type AdapterInfoGo ¶
type AdapterInfoGo struct {
Vendor string
Architecture string
Device string
Description string
BackendType BackendType
AdapterType AdapterType
VendorID uint32
DeviceID uint32
}
AdapterInfoGo is the Go-friendly version of AdapterInfo with actual strings.
type AdapterType ¶
type AdapterType uint32
AdapterType describes the type of GPU adapter.
const ( // AdapterTypeDiscreteGPU indicates a dedicated/discrete GPU (best performance). AdapterTypeDiscreteGPU AdapterType = 0x00000001 // AdapterTypeIntegratedGPU indicates an integrated GPU (shared with CPU). AdapterTypeIntegratedGPU AdapterType = 0x00000002 // AdapterTypeCPU indicates a software/CPU-based renderer. AdapterTypeCPU AdapterType = 0x00000003 // AdapterTypeUnknown indicates the adapter type could not be determined. AdapterTypeUnknown AdapterType = 0x00000004 )
type BackendType ¶
type BackendType uint32
BackendType describes the graphics backend being used.
const ( // BackendTypeUndefined indicates no backend is specified. BackendTypeUndefined BackendType = 0x00000000 // BackendTypeNull indicates a null/mock backend (for testing). BackendTypeNull BackendType = 0x00000001 // BackendTypeWebGPU indicates the native WebGPU backend. BackendTypeWebGPU BackendType = 0x00000002 // BackendTypeD3D11 indicates the Direct3D 11 backend (Windows). BackendTypeD3D11 BackendType = 0x00000003 // BackendTypeD3D12 indicates the Direct3D 12 backend (Windows). BackendTypeD3D12 BackendType = 0x00000004 // BackendTypeMetal indicates the Metal backend (macOS/iOS). BackendTypeMetal BackendType = 0x00000005 // BackendTypeVulkan indicates the Vulkan backend (cross-platform). BackendTypeVulkan BackendType = 0x00000006 // BackendTypeOpenGL indicates the OpenGL backend. BackendTypeOpenGL BackendType = 0x00000007 // BackendTypeOpenGLES indicates the OpenGL ES backend (mobile/embedded). BackendTypeOpenGLES BackendType = 0x00000008 )
type BindGroup ¶
type BindGroup struct {
// contains filtered or unexported fields
}
BindGroup binds actual GPU resources (buffers, textures, samplers) to shader slots. Create with Device.CreateBindGroup, release with BindGroup.Release.
type BindGroupDescriptor ¶
type BindGroupDescriptor struct {
NextInChain uintptr // *ChainedStruct
Label StringView
Layout uintptr // WGPUBindGroupLayout
EntryCount uintptr // size_t
Entries uintptr // *BindGroupEntry
}
BindGroupDescriptor describes a bind group.
type BindGroupEntry ¶
type BindGroupEntry struct {
NextInChain uintptr // *ChainedStruct
Binding uint32
Buffer uintptr // WGPUBuffer (nullable)
Offset uint64
Size uint64
Sampler uintptr // WGPUSampler (nullable)
TextureView uintptr // WGPUTextureView (nullable)
}
BindGroupEntry describes a single binding in a bind group.
func BufferBindingEntry ¶
func BufferBindingEntry(binding uint32, buffer *Buffer, offset, size uint64) BindGroupEntry
BufferBindingEntry creates a BindGroupEntry for a buffer.
func SamplerBindingEntry ¶
func SamplerBindingEntry(binding uint32, sampler *Sampler) BindGroupEntry
SamplerBindingEntry creates a BindGroupEntry for a sampler.
func TextureBindingEntry ¶
func TextureBindingEntry(binding uint32, textureView *TextureView) BindGroupEntry
TextureBindingEntry creates a BindGroupEntry for a texture view.
type BindGroupLayout ¶
type BindGroupLayout struct {
// contains filtered or unexported fields
}
BindGroupLayout defines the layout of resource bindings for a shader stage. Create with Device.CreateBindGroupLayout, release with BindGroupLayout.Release.
func (*BindGroupLayout) Handle ¶
func (bgl *BindGroupLayout) Handle() uintptr
Handle returns the underlying handle.
func (*BindGroupLayout) Release ¶
func (bgl *BindGroupLayout) Release()
Release releases the bind group layout.
type BindGroupLayoutDescriptor ¶
type BindGroupLayoutDescriptor struct {
NextInChain uintptr // *ChainedStruct
Label StringView
EntryCount uintptr // size_t
Entries uintptr // *BindGroupLayoutEntry
}
BindGroupLayoutDescriptor describes a bind group layout.
type BindGroupLayoutEntry ¶
type BindGroupLayoutEntry struct {
NextInChain uintptr // *ChainedStruct
Binding uint32
Visibility gputypes.ShaderStage
Buffer BufferBindingLayout
Sampler SamplerBindingLayout
Texture TextureBindingLayout
StorageTexture StorageTextureBindingLayout
}
BindGroupLayoutEntry describes a single binding in a bind group layout.
type BlendComponent ¶
type BlendComponent struct {
Operation gputypes.BlendOperation
SrcFactor gputypes.BlendFactor
DstFactor gputypes.BlendFactor
}
BlendComponent describes blend state for a color component.
type BlendState ¶
type BlendState struct {
Color BlendComponent
Alpha BlendComponent
}
BlendState describes how colors are blended.
type Buffer ¶
type Buffer struct {
// contains filtered or unexported fields
}
Buffer represents a block of GPU-accessible memory. Create with Device.CreateBuffer, release with Buffer.Release.
func (*Buffer) GetMapState ¶
func (b *Buffer) GetMapState() BufferMapState
GetMapState returns the current mapping state of this buffer.
func (*Buffer) GetMappedRange ¶
GetMappedRange returns a pointer to the mapped buffer data. The buffer must be mapped (either via MapAsync or MappedAtCreation). offset and size specify the range to access. Returns nil if the buffer is not mapped or the range is invalid.
func (*Buffer) GetUsage ¶
func (b *Buffer) GetUsage() gputypes.BufferUsage
GetUsage returns the usage flags of this buffer.
func (*Buffer) MapAsync ¶
MapAsync maps a buffer for reading or writing. This is a synchronous wrapper that blocks until the mapping is complete. The device parameter is used to poll for completion. After MapAsync succeeds, use GetMappedRange to access the data. Call Unmap when done to release the mapping.
type BufferBindingLayout ¶
type BufferBindingLayout struct {
NextInChain uintptr // *ChainedStruct
Type gputypes.BufferBindingType
HasDynamicOffset Bool
MinBindingSize uint64
}
BufferBindingLayout describes buffer binding properties.
type BufferDescriptor ¶
type BufferDescriptor struct {
NextInChain uintptr // *ChainedStruct
Label StringView // Buffer label for debugging
Usage gputypes.BufferUsage // How the buffer will be used
Size uint64 // Size in bytes
MappedAtCreation Bool // If true, buffer is mapped when created
}
BufferDescriptor describes a buffer to create.
type BufferMapCallbackInfo ¶
type BufferMapCallbackInfo struct {
NextInChain uintptr // *ChainedStruct
Mode CallbackMode
Callback uintptr // Function pointer
Userdata1 uintptr
Userdata2 uintptr
}
BufferMapCallbackInfo holds callback configuration for MapAsync.
type BufferMapState ¶
type BufferMapState uint32
BufferMapState describes the mapping state of a buffer.
const ( // BufferMapStateUnmapped indicates the buffer is not mapped. BufferMapStateUnmapped BufferMapState = 0x00000001 // BufferMapStatePending indicates a map operation is in progress. BufferMapStatePending BufferMapState = 0x00000002 // BufferMapStateMapped indicates the buffer is currently mapped and accessible. BufferMapStateMapped BufferMapState = 0x00000003 )
type CallbackMode ¶
type CallbackMode uint32
CallbackMode controls how callbacks are fired.
const ( // CallbackModeWaitAnyOnly fires callbacks only during WaitAny calls. CallbackModeWaitAnyOnly CallbackMode = 0x00000001 // CallbackModeAllowProcessEvents fires callbacks during ProcessEvents calls. CallbackModeAllowProcessEvents CallbackMode = 0x00000002 // CallbackModeAllowSpontaneous allows callbacks to fire at any time. CallbackModeAllowSpontaneous CallbackMode = 0x00000003 )
type ChainedStruct ¶
ChainedStruct is used for struct chaining (input).
type ChainedStructOut ¶
ChainedStructOut is used for struct chaining (output).
type Color ¶
type Color struct {
R, G, B, A float64
}
Color represents RGBA color with double precision.
type ColorTargetState ¶
type ColorTargetState struct {
Format gputypes.TextureFormat
Blend *BlendState // nil for no blending
WriteMask gputypes.ColorWriteMask
}
ColorTargetState describes a render target in a render pipeline.
type CommandBuffer ¶
type CommandBuffer struct {
// contains filtered or unexported fields
}
CommandBuffer holds encoded GPU commands ready for submission via Queue.Submit. Obtained from CommandEncoder.Finish, release with CommandBuffer.Release.
func (*CommandBuffer) Handle ¶
func (cb *CommandBuffer) Handle() uintptr
Handle returns the underlying handle.
func (*CommandBuffer) Release ¶
func (cb *CommandBuffer) Release()
Release releases the command buffer.
type CommandBufferDescriptor ¶
type CommandBufferDescriptor struct {
NextInChain uintptr // *ChainedStruct
Label StringView
}
CommandBufferDescriptor describes a command buffer.
type CommandEncoder ¶
type CommandEncoder struct {
// contains filtered or unexported fields
}
CommandEncoder records GPU commands into a CommandBuffer. Create with Device.CreateCommandEncoder, finalize with CommandEncoder.Finish.
func (*CommandEncoder) BeginComputePass ¶
func (enc *CommandEncoder) BeginComputePass(desc *ComputePassDescriptor) *ComputePassEncoder
BeginComputePass begins a compute pass.
func (*CommandEncoder) BeginRenderPass ¶
func (enc *CommandEncoder) BeginRenderPass(desc *RenderPassDescriptor) *RenderPassEncoder
BeginRenderPass begins a render pass.
func (*CommandEncoder) ClearBuffer ¶
func (enc *CommandEncoder) ClearBuffer(buffer *Buffer, offset, size uint64)
ClearBuffer clears a region of a buffer to zeros. size = 0 means clear from offset to end of buffer.
func (*CommandEncoder) CopyBufferToBuffer ¶
func (enc *CommandEncoder) CopyBufferToBuffer(src *Buffer, srcOffset uint64, dst *Buffer, dstOffset uint64, size uint64)
CopyBufferToBuffer copies data between buffers.
func (*CommandEncoder) CopyBufferToTexture ¶
func (enc *CommandEncoder) CopyBufferToTexture(source *TexelCopyBufferInfo, destination *TexelCopyTextureInfo, copySize *gputypes.Extent3D)
CopyBufferToTexture copies data from a buffer to a texture. Errors are reported via Device error scopes, not as return values.
func (*CommandEncoder) CopyTextureToBuffer ¶
func (enc *CommandEncoder) CopyTextureToBuffer(source *TexelCopyTextureInfo, destination *TexelCopyBufferInfo, copySize *gputypes.Extent3D)
CopyTextureToBuffer copies data from a texture to a buffer. Errors are reported via Device error scopes, not as return values.
func (*CommandEncoder) CopyTextureToTexture ¶
func (enc *CommandEncoder) CopyTextureToTexture(source *TexelCopyTextureInfo, destination *TexelCopyTextureInfo, copySize *gputypes.Extent3D)
CopyTextureToTexture copies data from one texture to another. Errors are reported via Device error scopes, not as return values.
func (*CommandEncoder) Finish ¶
func (enc *CommandEncoder) Finish(desc *CommandBufferDescriptor) *CommandBuffer
Finish finishes recording and returns a command buffer.
func (*CommandEncoder) Handle ¶
func (enc *CommandEncoder) Handle() uintptr
Handle returns the underlying handle.
func (*CommandEncoder) InsertDebugMarker ¶
func (enc *CommandEncoder) InsertDebugMarker(markerLabel string)
InsertDebugMarker inserts a single debug marker label. This is useful for GPU debugging tools to identify specific command points.
func (*CommandEncoder) PopDebugGroup ¶
func (enc *CommandEncoder) PopDebugGroup()
PopDebugGroup ends the current debug group. Must match a preceding PushDebugGroup call.
func (*CommandEncoder) PushDebugGroup ¶
func (enc *CommandEncoder) PushDebugGroup(groupLabel string)
PushDebugGroup begins a labeled debug group. Use PopDebugGroup to end the group. Groups can be nested.
func (*CommandEncoder) Release ¶
func (enc *CommandEncoder) Release()
Release releases the command encoder.
func (*CommandEncoder) ResolveQuerySet ¶
func (enc *CommandEncoder) ResolveQuerySet(querySet *QuerySet, firstQuery, queryCount uint32, destination *Buffer, destinationOffset uint64)
ResolveQuerySet resolves query results to a buffer. The buffer must have BufferUsageQueryResolve usage.
func (*CommandEncoder) WriteTimestamp ¶
func (enc *CommandEncoder) WriteTimestamp(querySet *QuerySet, queryIndex uint32)
WriteTimestamp writes a timestamp to a query. Note: This is a wgpu-native extension. Prefer pass-level timestamps via RenderPassTimestampWrites or ComputePassTimestampWrites when possible.
type CommandEncoderDescriptor ¶
type CommandEncoderDescriptor struct {
NextInChain uintptr // *ChainedStruct
Label StringView
}
CommandEncoderDescriptor describes a command encoder.
type ComputePassDescriptor ¶
type ComputePassDescriptor struct {
NextInChain uintptr // *ChainedStruct
Label StringView
TimestampWrites uintptr // *ComputePassTimestampWrites (nullable)
}
ComputePassDescriptor describes a compute pass.
type ComputePassEncoder ¶
type ComputePassEncoder struct {
// contains filtered or unexported fields
}
ComputePassEncoder records dispatch commands within a compute pass. Begin with CommandEncoder.BeginComputePass, end with ComputePassEncoder.End.
func (*ComputePassEncoder) DispatchWorkgroups ¶
func (cpe *ComputePassEncoder) DispatchWorkgroups(x, y, z uint32)
DispatchWorkgroups dispatches compute work.
func (*ComputePassEncoder) DispatchWorkgroupsIndirect ¶
func (cpe *ComputePassEncoder) DispatchWorkgroupsIndirect(indirectBuffer *Buffer, indirectOffset uint64)
DispatchWorkgroupsIndirect dispatches compute work using parameters from a GPU buffer. indirectBuffer must contain a DispatchIndirectArgs structure:
- workgroupCountX (uint32)
- workgroupCountY (uint32)
- workgroupCountZ (uint32)
func (*ComputePassEncoder) Handle ¶
func (cpe *ComputePassEncoder) Handle() uintptr
Handle returns the underlying handle.
func (*ComputePassEncoder) Release ¶
func (cpe *ComputePassEncoder) Release()
Release releases the compute pass encoder.
func (*ComputePassEncoder) SetBindGroup ¶
func (cpe *ComputePassEncoder) SetBindGroup(groupIndex uint32, group *BindGroup, dynamicOffsets []uint32)
SetBindGroup sets a bind group.
func (*ComputePassEncoder) SetPipeline ¶
func (cpe *ComputePassEncoder) SetPipeline(pipeline *ComputePipeline)
SetPipeline sets the compute pipeline.
type ComputePipeline ¶
type ComputePipeline struct {
// contains filtered or unexported fields
}
ComputePipeline is a compiled compute pipeline configuration. Create with Device.CreateComputePipeline, release with ComputePipeline.Release.
func (*ComputePipeline) GetBindGroupLayout ¶
func (cp *ComputePipeline) GetBindGroupLayout(groupIndex uint32) *BindGroupLayout
GetBindGroupLayout returns the bind group layout at the given index. Useful for auto-layout pipelines.
func (*ComputePipeline) Handle ¶
func (cp *ComputePipeline) Handle() uintptr
Handle returns the underlying handle.
func (*ComputePipeline) Release ¶
func (cp *ComputePipeline) Release()
Release releases the compute pipeline.
type ComputePipelineDescriptor ¶
type ComputePipelineDescriptor struct {
NextInChain uintptr // *ChainedStruct
Label StringView
Layout uintptr // WGPUPipelineLayout (nullable)
Compute ProgrammableStageDescriptor
}
ComputePipelineDescriptor describes a compute pipeline.
type DepthStencilState ¶
type DepthStencilState struct {
Format gputypes.TextureFormat
DepthWriteEnabled bool
DepthCompare gputypes.CompareFunction
StencilFront StencilFaceState
StencilBack StencilFaceState
StencilReadMask uint32
StencilWriteMask uint32
DepthBias int32
DepthBiasSlopeScale float32
DepthBiasClamp float32
}
DepthStencilState describes depth and stencil test state (user API).
type Device ¶
type Device struct {
// contains filtered or unexported fields
}
Device is the logical connection to a GPU, used to create all other resources. Obtained via Adapter.RequestDevice, release with Device.Release.
func (*Device) CreateBindGroup ¶
func (d *Device) CreateBindGroup(desc *BindGroupDescriptor) *BindGroup
CreateBindGroup creates a bind group.
func (*Device) CreateBindGroupLayout ¶
func (d *Device) CreateBindGroupLayout(desc *BindGroupLayoutDescriptor) *BindGroupLayout
CreateBindGroupLayout creates a bind group layout. Entries are converted from gputypes to wgpu-native enum values before FFI call.
func (*Device) CreateBindGroupLayoutSimple ¶
func (d *Device) CreateBindGroupLayoutSimple(entries []BindGroupLayoutEntry) *BindGroupLayout
CreateBindGroupLayoutSimple creates a bind group layout with the given entries.
func (*Device) CreateBindGroupSimple ¶
func (d *Device) CreateBindGroupSimple(layout *BindGroupLayout, entries []BindGroupEntry) *BindGroup
CreateBindGroupSimple creates a bind group with buffer entries.
func (*Device) CreateBuffer ¶
func (d *Device) CreateBuffer(desc *BufferDescriptor) *Buffer
CreateBuffer creates a new GPU buffer.
func (*Device) CreateCommandEncoder ¶
func (d *Device) CreateCommandEncoder(desc *CommandEncoderDescriptor) *CommandEncoder
CreateCommandEncoder creates a command encoder.
func (*Device) CreateComputePipeline ¶
func (d *Device) CreateComputePipeline(desc *ComputePipelineDescriptor) *ComputePipeline
CreateComputePipeline creates a compute pipeline.
func (*Device) CreateComputePipelineSimple ¶
func (d *Device) CreateComputePipelineSimple(layout *PipelineLayout, shader *ShaderModule, entryPoint string) *ComputePipeline
CreateComputePipelineSimple creates a compute pipeline with the given shader and entry point. If layout is nil, auto layout is used.
func (*Device) CreateDepthTexture ¶
func (d *Device) CreateDepthTexture(width, height uint32, format gputypes.TextureFormat) *Texture
CreateDepthTexture creates a depth texture with the specified dimensions and format. This is a convenience function for creating depth buffers for render passes.
func (*Device) CreateLinearSampler ¶
CreateLinearSampler creates a sampler with linear filtering.
func (*Device) CreateNearestSampler ¶
CreateNearestSampler creates a sampler with nearest filtering.
func (*Device) CreatePipelineLayout ¶
func (d *Device) CreatePipelineLayout(desc *PipelineLayoutDescriptor) *PipelineLayout
CreatePipelineLayout creates a pipeline layout.
func (*Device) CreatePipelineLayoutSimple ¶
func (d *Device) CreatePipelineLayoutSimple(layouts []*BindGroupLayout) *PipelineLayout
CreatePipelineLayoutSimple creates a pipeline layout with the given bind group layouts.
func (*Device) CreateQuerySet ¶
func (d *Device) CreateQuerySet(desc *QuerySetDescriptor) *QuerySet
CreateQuerySet creates a new QuerySet for GPU profiling/timestamps.
func (*Device) CreateRenderBundleEncoder ¶
func (d *Device) CreateRenderBundleEncoder(desc *RenderBundleEncoderDescriptor) *RenderBundleEncoder
CreateRenderBundleEncoder creates a render bundle encoder for pre-recording render commands. Render bundles allow you to pre-record a sequence of render commands that can be replayed multiple times, which is useful for static geometry.
func (*Device) CreateRenderBundleEncoderSimple ¶
func (d *Device) CreateRenderBundleEncoderSimple(colorFormats []gputypes.TextureFormat, depthFormat gputypes.TextureFormat, sampleCount uint32) *RenderBundleEncoder
CreateRenderBundleEncoderSimple creates a render bundle encoder with common settings.
func (*Device) CreateRenderPipeline ¶
func (d *Device) CreateRenderPipeline(desc *RenderPipelineDescriptor) *RenderPipeline
CreateRenderPipeline creates a render pipeline.
func (*Device) CreateRenderPipelineSimple ¶
func (d *Device) CreateRenderPipelineSimple( layout *PipelineLayout, vertexShader *ShaderModule, vertexEntryPoint string, fragmentShader *ShaderModule, fragmentEntryPoint string, targetFormat gputypes.TextureFormat, ) *RenderPipeline
CreateRenderPipelineSimple creates a simple render pipeline with common defaults.
func (*Device) CreateSampler ¶
func (d *Device) CreateSampler(desc *SamplerDescriptor) *Sampler
CreateSampler creates a sampler with the specified descriptor.
func (*Device) CreateShaderModule ¶
func (d *Device) CreateShaderModule(desc *ShaderModuleDescriptor) *ShaderModule
CreateShaderModule creates a shader module from a descriptor. For WGSL shaders, use CreateShaderModuleWGSL instead.
func (*Device) CreateShaderModuleWGSL ¶
func (d *Device) CreateShaderModuleWGSL(code string) *ShaderModule
CreateShaderModuleWGSL creates a shader module from WGSL source code.
func (*Device) CreateTexture ¶
func (d *Device) CreateTexture(desc *TextureDescriptor) *Texture
CreateTexture creates a texture with the specified descriptor. Enum values are converted from gputypes to wgpu-native values before FFI call.
func (*Device) GetFeatures ¶ added in v0.3.0
func (d *Device) GetFeatures() []FeatureName
GetFeatures retrieves all features enabled on this device. Returns a slice of FeatureName values.
func (*Device) GetLimits ¶ added in v0.3.0
func (d *Device) GetLimits() (*SupportedLimits, error)
GetLimits retrieves the limits of this device. Returns the same Limits struct format as Adapter.GetLimits(). The FFI call uses SupportedLimits (which wraps Limits with nextInChain).
func (*Device) HasFeature ¶ added in v0.3.0
func (d *Device) HasFeature(feature FeatureName) bool
HasFeature checks if the device has a specific feature enabled.
func (*Device) Poll ¶
Poll polls the device for completed work. If wait is true, blocks until there is work to process. Returns true if the queue is empty. This is a wgpu-native extension.
func (*Device) PopErrorScope
deprecated
Deprecated: PopErrorScope panics on failure. Use PopErrorScopeAsync instead.
PopErrorScope pops the current error scope and returns the first error caught. This is a synchronous wrapper that blocks until the result is available.
IMPORTANT: You must have pushed an error scope before calling this. Calling PopErrorScope on an empty stack will cause a panic in wgpu-native. Use PopErrorScopeAsync if you need to handle empty stack gracefully.
Returns:
- ErrorType: The type of error that occurred (ErrorTypeNoError if no error)
- string: Error message (empty if no error)
Note: Error scopes are LIFO - the last pushed scope is popped first.
func (*Device) PopErrorScopeAsync ¶
PopErrorScopeAsync pops the current error scope and returns the first error caught. This version returns an error instead of panicking if the operation fails.
Returns:
- ErrorType: The type of error that occurred (ErrorTypeNoError if no error)
- string: Error message (empty if no error)
- error: An error if the operation failed (e.g., empty stack)
Note: Error scopes are LIFO - the last pushed scope is popped first. If the error scope stack is empty, returns an error instead of panicking.
func (*Device) PushErrorScope ¶
func (d *Device) PushErrorScope(filter ErrorFilter)
PushErrorScope pushes an error scope for catching GPU errors. Errors of the specified filter type will be caught until PopErrorScope is called. Error scopes are LIFO (stack-based) - last pushed scope is popped first.
IMPORTANT: You must call PopErrorScope for each PushErrorScope. Popping an empty stack will cause a panic in wgpu-native (known limitation). Users should track push/pop calls manually to avoid stack underflow.
Example usage:
device.PushErrorScope(ErrorFilterValidation)
// ... GPU operations that might produce validation errors
errType, message := device.PopErrorScope(instance)
if errType != ErrorTypeNoError {
log.Printf("Validation error: %s", message)
}
type DeviceDescriptor ¶
type DeviceDescriptor struct {
NextInChain uintptr // *ChainedStruct
}
DeviceDescriptor configures device creation. For now, passing nil uses default settings.
type DeviceLostReason ¶
type DeviceLostReason uint32
DeviceLostReason describes why a device was lost.
const ( // DeviceLostReasonUnknown indicates the device was lost for an unknown reason. DeviceLostReasonUnknown DeviceLostReason = 0x00000001 // DeviceLostReasonDestroyed indicates the device was explicitly destroyed. DeviceLostReasonDestroyed DeviceLostReason = 0x00000002 // DeviceLostReasonInstanceDropped indicates the instance was dropped. DeviceLostReasonInstanceDropped DeviceLostReason = 0x00000003 // DeviceLostReasonFailedCreation indicates device creation failed. DeviceLostReasonFailedCreation DeviceLostReason = 0x00000004 )
type DispatchIndirectArgs ¶
type DispatchIndirectArgs struct {
WorkgroupCountX uint32 // Number of workgroups in X dimension
WorkgroupCountY uint32 // Number of workgroups in Y dimension
WorkgroupCountZ uint32 // Number of workgroups in Z dimension
}
DispatchIndirectArgs contains arguments for indirect compute dispatch. This struct must be written to a Buffer for use with DispatchWorkgroupsIndirect. Size: 12 bytes, must be aligned to 4 bytes.
type DrawIndexedIndirectArgs ¶
type DrawIndexedIndirectArgs struct {
IndexCount uint32 // Number of indices to draw
InstanceCount uint32 // Number of instances to draw
FirstIndex uint32 // First index in the index buffer
BaseVertex int32 // Value added to vertex index before indexing into vertex buffer
FirstInstance uint32 // First instance index
}
DrawIndexedIndirectArgs contains arguments for indirect indexed draw calls. This struct must be written to a Buffer for use with DrawIndexedIndirect. Size: 20 bytes, must be aligned to 4 bytes.
type DrawIndirectArgs ¶
type DrawIndirectArgs struct {
VertexCount uint32 // Number of vertices to draw
InstanceCount uint32 // Number of instances to draw
FirstVertex uint32 // First vertex index
FirstInstance uint32 // First instance index
}
DrawIndirectArgs contains arguments for indirect (GPU-driven) draw calls. This struct must be written to a Buffer for use with DrawIndirect. Size: 16 bytes, must be aligned to 4 bytes.
type ErrorFilter ¶
type ErrorFilter uint32
ErrorFilter filters error types in error scopes.
const ( // ErrorFilterValidation catches validation errors. ErrorFilterValidation ErrorFilter = 0x00000001 // ErrorFilterOutOfMemory catches out-of-memory errors. ErrorFilterOutOfMemory ErrorFilter = 0x00000002 // ErrorFilterInternal catches internal errors. ErrorFilterInternal ErrorFilter = 0x00000003 )
type ErrorType ¶
type ErrorType uint32
ErrorType describes the type of error that occurred.
const ( // ErrorTypeNoError indicates no error occurred. ErrorTypeNoError ErrorType = 0x00000001 // ErrorTypeValidation indicates a validation error. ErrorTypeValidation ErrorType = 0x00000002 // ErrorTypeOutOfMemory indicates an out-of-memory error. ErrorTypeOutOfMemory ErrorType = 0x00000003 // ErrorTypeInternal indicates an internal error. ErrorTypeInternal ErrorType = 0x00000004 // ErrorTypeUnknown indicates an unknown error. ErrorTypeUnknown ErrorType = 0x00000005 )
type FeatureLevel ¶
type FeatureLevel uint32
FeatureLevel indicates the WebGPU feature level.
const ( // FeatureLevelCompatibility indicates the compatibility feature level (WebGPU compat). FeatureLevelCompatibility FeatureLevel = 0x00000001 // FeatureLevelCore indicates the core feature level (full WebGPU). FeatureLevelCore FeatureLevel = 0x00000002 )
type FeatureName ¶
type FeatureName uint32
FeatureName describes a WebGPU feature that can be requested.
const ( // FeatureNameTimestampQuery enables timestamp query support. FeatureNameTimestampQuery FeatureName = 0x00000003 )
type FragmentState ¶
type FragmentState struct {
Module *ShaderModule
EntryPoint string
Targets []ColorTargetState
}
FragmentState describes the fragment stage of a render pipeline.
type Instance ¶
type Instance struct {
// contains filtered or unexported fields
}
Instance is the entry point to the WebGPU API. Create with CreateInstance, release with Instance.Release.
func CreateInstance ¶
func CreateInstance(desc *InstanceDescriptor) (*Instance, error)
CreateInstance creates a new WebGPU instance. Pass nil for default configuration.
func (*Instance) CreateSurfaceFromWaylandSurface ¶
CreateSurfaceFromWaylandSurface creates a surface from a Wayland surface. display is the wl_display pointer. surface is the wl_surface pointer.
func (*Instance) CreateSurfaceFromXlibWindow ¶
CreateSurfaceFromXlibWindow creates a surface from an X11 Xlib window. display is the X11 Display pointer. window is the X11 Window ID (XID).
func (*Instance) ProcessEvents ¶
func (i *Instance) ProcessEvents()
ProcessEvents processes pending async events.
func (*Instance) RequestAdapter ¶
func (i *Instance) RequestAdapter(options *RequestAdapterOptions) (*Adapter, error)
RequestAdapter requests a GPU adapter from the instance. This is a synchronous wrapper that blocks until the adapter is available.
type InstanceCapabilities ¶
type InstanceCapabilities struct {
NextInChain uintptr // *ChainedStructOut
TimedWaitAnyEnable Bool
TimedWaitAnyMaxCount uint64
// contains filtered or unexported fields
}
InstanceCapabilities describes instance capabilities. Note: This struct has specific padding requirements to match C layout.
type InstanceDescriptor ¶
type InstanceDescriptor struct {
NextInChain uintptr // *ChainedStruct
Features InstanceCapabilities
}
InstanceDescriptor describes an Instance.
type LeakReport ¶ added in v0.3.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.3.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.3.0
func (r *LeakReport) String() string
String returns a human-readable summary of the leak report.
type Library ¶
type Library interface {
// NewProc retrieves a procedure (function) from the library.
// Returns a Proc interface that can be used to call the function.
NewProc(name string) Proc
}
Library represents a dynamically loaded library (DLL/SO/DYLIB). Platform-specific implementations handle the actual loading mechanism.
type Limits ¶
type Limits struct {
MaxTextureDimension1D uint32
MaxTextureDimension2D uint32
MaxTextureDimension3D uint32
MaxTextureArrayLayers uint32
MaxBindGroups uint32
MaxBindGroupsPlusVertexBuffers uint32
MaxBindingsPerBindGroup uint32
MaxDynamicUniformBuffersPerPipelineLayout uint32
MaxDynamicStorageBuffersPerPipelineLayout uint32
MaxSampledTexturesPerShaderStage uint32
MaxSamplersPerShaderStage uint32
MaxStorageBuffersPerShaderStage uint32
MaxStorageTexturesPerShaderStage uint32
MaxUniformBuffersPerShaderStage uint32
MaxUniformBufferBindingSize uint64
MaxStorageBufferBindingSize uint64
MaxVertexBuffers uint32
MaxBufferSize uint64
MaxVertexAttributes uint32
MaxVertexBufferArrayStride uint32
MaxInterStageShaderVariables uint32
MaxColorAttachments uint32
MaxColorAttachmentBytesPerSample uint32
MaxComputeWorkgroupStorageSize uint32
MaxComputeInvocationsPerWorkgroup uint32
MaxComputeWorkgroupSizeX uint32
MaxComputeWorkgroupSizeY uint32
MaxComputeWorkgroupSizeZ uint32
MaxComputeWorkgroupsPerDimension uint32
MinUniformBufferOffsetAlignment uint32
MinStorageBufferOffsetAlignment uint32
}
Limits describes resource limits for an adapter or device. This corresponds to WGPULimits in webgpu.h (no nextInChain field). Used inside SupportedLimits which wraps it with nextInChain for FFI calls.
type MapAsyncStatus ¶
type MapAsyncStatus uint32
MapAsyncStatus is the status returned by MapAsync callback.
const ( // MapAsyncStatusSuccess indicates the buffer was successfully mapped. MapAsyncStatusSuccess MapAsyncStatus = 0x00000001 // MapAsyncStatusInstanceDropped indicates the instance was dropped before completion. MapAsyncStatusInstanceDropped MapAsyncStatus = 0x00000002 // MapAsyncStatusError indicates a mapping error occurred. MapAsyncStatusError MapAsyncStatus = 0x00000003 // MapAsyncStatusAborted indicates the mapping was aborted (e.g., buffer destroyed). MapAsyncStatusAborted MapAsyncStatus = 0x00000004 // MapAsyncStatusUnknown indicates an unknown mapping error. MapAsyncStatusUnknown MapAsyncStatus = 0x00000005 )
type MapMode ¶
type MapMode uint64
MapMode specifies the mapping mode for MapAsync.
const ( // MapModeNone indicates no mapping mode (default). MapModeNone MapMode = 0x0000000000000000 // MapModeRead maps the buffer for reading via GetMappedRange. MapModeRead MapMode = 0x0000000000000001 // MapModeWrite maps the buffer for writing via GetMappedRange. MapModeWrite MapMode = 0x0000000000000002 )
type Mat4 ¶
type Mat4 [16]float32
Mat4 represents a 4x4 matrix in column-major order, compatible with WGSL mat4x4<f32>. Layout: [col0, col1, col2, col3] where each column is [x, y, z, w]. Element at column c, row r is at index c*4+r. This matches WebGPU/WGSL/OpenGL convention (column-major).
Example (Basic) ¶
ExampleMat4_basic demonstrates basic matrix operations
package main
import (
"fmt"
"github.com/go-webgpu/webgpu/wgpu"
)
func main() {
// Create transformation matrices
translate := wgpu.Mat4Translate(10, 0, 0)
scale := wgpu.Mat4Scale(2, 2, 2)
// Combine transformations (order matters: scale first, then translate)
combined := translate.Mul(scale)
// Transform a point
point := wgpu.Vec4{X: 1, Y: 0, Z: 0, W: 1}
result := combined.MulVec4(point)
fmt.Printf("Transformed point: (%.0f, %.0f, %.0f)\n", result.X, result.Y, result.Z)
}
Output: Transformed point: (12, 0, 0)
Example (Rotation) ¶
ExampleMat4_rotation demonstrates rotation matrices
package main
import (
"fmt"
"github.com/go-webgpu/webgpu/wgpu"
)
func main() {
// Rotate 90 degrees around Y axis
rotation := wgpu.Mat4RotateY(3.14159 / 2) // 90 degrees in radians
// Apply rotation to a point on X axis
point := wgpu.Vec4{X: 1, Y: 0, Z: 0, W: 1}
rotated := rotation.MulVec4(point)
// Right-hand rule: rotating +X around +Y by 90° gives -Z direction
fmt.Printf("Rotated point: X≈%.0f, Z≈%.0f\n", rotated.X, rotated.Z)
}
Output: Rotated point: X≈0, Z≈-1
func Mat4Identity ¶
func Mat4Identity() Mat4
Mat4Identity returns a 4x4 identity matrix. The identity matrix has 1s on the diagonal and 0s elsewhere.
func Mat4LookAt ¶
Mat4LookAt returns a view matrix that looks from eye position towards center. eye: camera position center: point the camera is looking at up: up direction vector (typically (0, 1, 0))
This creates a right-handed coordinate system view matrix.
func Mat4Perspective ¶
Mat4Perspective returns a perspective projection matrix. fovY: vertical field of view in radians aspect: aspect ratio (width/height) near: near clipping plane distance (must be > 0) far: far clipping plane distance (must be > near)
This uses right-handed coordinate system with Z in [-1, 1] (OpenGL/Vulkan style). For WebGPU with Z in [0, 1], post-multiply with depth range transform.
Example ¶
ExampleMat4Perspective demonstrates perspective projection setup
package main
import (
"fmt"
"github.com/go-webgpu/webgpu/wgpu"
)
func main() {
// Common 3D camera setup
fov := float32(45.0 * 3.14159 / 180.0) // 45 degrees in radians
aspect := float32(16.0 / 9.0) // 16:9 aspect ratio
near := float32(0.1)
far := float32(100.0)
projection := wgpu.Mat4Perspective(fov, aspect, near, far)
// Create view matrix (camera looking from (0, 0, 5) towards origin)
eye := wgpu.Vec3{X: 0, Y: 0, Z: 5}
center := wgpu.Vec3{X: 0, Y: 0, Z: 0}
up := wgpu.Vec3{X: 0, Y: 1, Z: 0}
view := wgpu.Mat4LookAt(eye, center, up)
// Combine projection and view
viewProj := projection.Mul(view)
fmt.Printf("View-Projection matrix ready: %v elements\n", len(viewProj))
}
Output: View-Projection matrix ready: 16 elements
func Mat4RotateX ¶
Mat4RotateX returns a rotation matrix around the X axis. Angle is in radians. Positive rotation follows right-hand rule.
func Mat4RotateY ¶
Mat4RotateY returns a rotation matrix around the Y axis. Angle is in radians. Positive rotation follows right-hand rule.
func Mat4RotateZ ¶
Mat4RotateZ returns a rotation matrix around the Z axis. Angle is in radians. Positive rotation follows right-hand rule.
func Mat4Scale ¶
Mat4Scale returns a scaling matrix for the given factors. Scales objects by (x, y, z) along each axis.
func Mat4Translate ¶
Mat4Translate returns a translation matrix for the given offset. Translates points by (x, y, z) in 3D space.
type MultisampleState ¶
MultisampleState describes multisampling.
type OptionalBool ¶
type OptionalBool uint32
OptionalBool is a tri-state boolean for WebGPU.
const ( // OptionalBoolFalse represents an explicit false value. OptionalBoolFalse OptionalBool = 0x00000000 // OptionalBoolTrue represents an explicit true value. OptionalBoolTrue OptionalBool = 0x00000001 // OptionalBoolUndefined represents an unset/default value. OptionalBoolUndefined OptionalBool = 0x00000002 )
type PipelineLayout ¶
type PipelineLayout struct {
// contains filtered or unexported fields
}
PipelineLayout defines the bind group layouts used by a pipeline. Create with Device.CreatePipelineLayout, release with PipelineLayout.Release.
func (*PipelineLayout) Handle ¶
func (pl *PipelineLayout) Handle() uintptr
Handle returns the underlying handle.
func (*PipelineLayout) Release ¶
func (pl *PipelineLayout) Release()
Release releases the pipeline layout.
type PipelineLayoutDescriptor ¶
type PipelineLayoutDescriptor struct {
NextInChain uintptr // *ChainedStruct
Label StringView
BindGroupLayoutCount uintptr // size_t
BindGroupLayouts uintptr // *WGPUBindGroupLayout
}
PipelineLayoutDescriptor describes a pipeline layout.
type PopErrorScopeStatus ¶
type PopErrorScopeStatus uint32
PopErrorScopeStatus describes the result of PopErrorScope operation.
const ( // PopErrorScopeStatusSuccess indicates the error scope was successfully popped. PopErrorScopeStatusSuccess PopErrorScopeStatus = 0x00000001 // PopErrorScopeStatusInstanceDropped indicates the instance was dropped. PopErrorScopeStatusInstanceDropped PopErrorScopeStatus = 0x00000002 // PopErrorScopeStatusEmptyStack indicates the error scope stack was empty. PopErrorScopeStatusEmptyStack PopErrorScopeStatus = 0x00000003 )
type PrimitiveState ¶
type PrimitiveState struct {
Topology gputypes.PrimitiveTopology
StripIndexFormat gputypes.IndexFormat
FrontFace gputypes.FrontFace
CullMode gputypes.CullMode
}
PrimitiveState describes how primitives are assembled.
type Proc ¶
type Proc interface {
// Call invokes the procedure with the given arguments.
// Returns the result value and error (if any).
// Arguments are passed as uintptr to match C ABI.
Call(args ...uintptr) (uintptr, uintptr, error)
}
Proc represents a procedure (function pointer) from a dynamically loaded library. It abstracts platform-specific function calling mechanisms.
type ProgrammableStageDescriptor ¶
type ProgrammableStageDescriptor struct {
NextInChain uintptr // *ChainedStruct
Module uintptr // WGPUShaderModule
EntryPoint StringView // Entry point function name
ConstantCount uintptr // size_t
Constants uintptr // *ConstantEntry
}
ProgrammableStageDescriptor describes a programmable shader stage.
type QuerySet ¶
type QuerySet struct {
// contains filtered or unexported fields
}
QuerySet holds a set of GPU queries (occlusion or timestamp). Create with Device.CreateQuerySet, release with QuerySet.Release.
func (*QuerySet) Destroy ¶
func (qs *QuerySet) Destroy()
Destroy destroys the QuerySet, making it invalid.
type QuerySetDescriptor ¶
QuerySetDescriptor describes a QuerySet to create.
type Queue ¶
type Queue struct {
// contains filtered or unexported fields
}
Queue is used to submit command buffers and write data to buffers/textures. Obtained via Device.GetQueue, release with Queue.Release.
func (*Queue) Submit ¶
func (q *Queue) Submit(commands ...*CommandBuffer)
Submit submits command buffers for execution.
func (*Queue) WriteBuffer ¶
WriteBuffer writes data to a buffer. This is a convenience method that stages data for upload to the GPU.
func (*Queue) WriteBufferRaw ¶
WriteBufferTyped writes typed data to a buffer. The data pointer should point to the first element, size is total byte size.
func (*Queue) WriteTexture ¶
func (q *Queue) WriteTexture(dest *TexelCopyTextureInfo, data []byte, layout *TexelCopyBufferLayout, size *gputypes.Extent3D)
WriteTexture writes data to a texture.
type RenderBundle ¶
type RenderBundle struct {
// contains filtered or unexported fields
}
RenderBundle is a pre-recorded set of render commands for efficient replay. Obtained from RenderBundleEncoder.Finish, release with RenderBundle.Release.
func (*RenderBundle) Handle ¶
func (rb *RenderBundle) Handle() uintptr
Handle returns the underlying handle.
func (*RenderBundle) Release ¶
func (rb *RenderBundle) Release()
Release releases the render bundle.
type RenderBundleDescriptor ¶
type RenderBundleDescriptor struct {
NextInChain uintptr // *ChainedStruct
Label StringView
}
RenderBundleDescriptor describes a render bundle.
type RenderBundleEncoder ¶
type RenderBundleEncoder struct {
// contains filtered or unexported fields
}
RenderBundleEncoder records render commands into a RenderBundle. Create with Device.CreateRenderBundleEncoder, finalize with RenderBundleEncoder.Finish.
func (*RenderBundleEncoder) Draw ¶
func (rbe *RenderBundleEncoder) Draw(vertexCount, instanceCount, firstVertex, firstInstance uint32)
Draw records a non-indexed draw call.
func (*RenderBundleEncoder) DrawIndexed ¶
func (rbe *RenderBundleEncoder) DrawIndexed(indexCount, instanceCount, firstIndex uint32, baseVertex int32, firstInstance uint32)
DrawIndexed records an indexed draw call.
func (*RenderBundleEncoder) DrawIndexedIndirect ¶
func (rbe *RenderBundleEncoder) DrawIndexedIndirect(indirectBuffer *Buffer, indirectOffset uint64)
DrawIndexedIndirect records an indirect indexed draw call.
func (*RenderBundleEncoder) DrawIndirect ¶
func (rbe *RenderBundleEncoder) DrawIndirect(indirectBuffer *Buffer, indirectOffset uint64)
DrawIndirect records an indirect draw call.
func (*RenderBundleEncoder) Finish ¶
func (rbe *RenderBundleEncoder) Finish(desc *RenderBundleDescriptor) *RenderBundle
Finish completes recording and returns the render bundle.
func (*RenderBundleEncoder) Handle ¶
func (rbe *RenderBundleEncoder) Handle() uintptr
Handle returns the underlying handle.
func (*RenderBundleEncoder) Release ¶
func (rbe *RenderBundleEncoder) Release()
Release releases the render bundle encoder.
func (*RenderBundleEncoder) SetBindGroup ¶
func (rbe *RenderBundleEncoder) SetBindGroup(groupIndex uint32, group *BindGroup, dynamicOffsets []uint32)
SetBindGroup sets a bind group at the given index.
func (*RenderBundleEncoder) SetIndexBuffer ¶
func (rbe *RenderBundleEncoder) SetIndexBuffer(buffer *Buffer, format gputypes.IndexFormat, offset, size uint64)
SetIndexBuffer sets the index buffer.
func (*RenderBundleEncoder) SetPipeline ¶
func (rbe *RenderBundleEncoder) SetPipeline(pipeline *RenderPipeline)
SetPipeline sets the render pipeline for subsequent draw calls.
func (*RenderBundleEncoder) SetVertexBuffer ¶
func (rbe *RenderBundleEncoder) SetVertexBuffer(slot uint32, buffer *Buffer, offset, size uint64)
SetVertexBuffer sets a vertex buffer at the given slot.
type RenderBundleEncoderDescriptor ¶
type RenderBundleEncoderDescriptor struct {
Label StringView
ColorFormatCount uintptr // size_t
ColorFormats *gputypes.TextureFormat
DepthStencilFormat gputypes.TextureFormat
SampleCount uint32
DepthReadOnly Bool
StencilReadOnly Bool
}
RenderBundleEncoderDescriptor describes a render bundle encoder.
type RenderPassColorAttachment ¶
type RenderPassColorAttachment struct {
View *TextureView
ResolveTarget *TextureView // For MSAA, nil otherwise
LoadOp gputypes.LoadOp
StoreOp gputypes.StoreOp
ClearValue Color
}
RenderPassColorAttachment describes a color attachment for a render pass.
type RenderPassDepthStencilAttachment ¶
type RenderPassDepthStencilAttachment struct {
View *TextureView
DepthLoadOp gputypes.LoadOp
DepthStoreOp gputypes.StoreOp
DepthClearValue float32
DepthReadOnly bool
StencilLoadOp gputypes.LoadOp
StencilStoreOp gputypes.StoreOp
StencilClearValue uint32
StencilReadOnly bool
}
RenderPassDepthStencilAttachment describes a depth/stencil attachment (user API).
type RenderPassDescriptor ¶
type RenderPassDescriptor struct {
Label string
ColorAttachments []RenderPassColorAttachment
DepthStencilAttachment *RenderPassDepthStencilAttachment
TimestampWrites *RenderPassTimestampWrites
}
RenderPassDescriptor describes a render pass.
type RenderPassEncoder ¶
type RenderPassEncoder struct {
// contains filtered or unexported fields
}
RenderPassEncoder records draw commands within a render pass. Begin with CommandEncoder.BeginRenderPass, end with RenderPassEncoder.End.
func (*RenderPassEncoder) Draw ¶
func (rpe *RenderPassEncoder) Draw(vertexCount, instanceCount, firstVertex, firstInstance uint32)
Draw draws primitives.
func (*RenderPassEncoder) DrawIndexed ¶
func (rpe *RenderPassEncoder) DrawIndexed(indexCount, instanceCount, firstIndex uint32, baseVertex int32, firstInstance uint32)
DrawIndexed draws indexed primitives.
func (*RenderPassEncoder) DrawIndexedIndirect ¶
func (rpe *RenderPassEncoder) DrawIndexedIndirect(indirectBuffer *Buffer, indirectOffset uint64)
DrawIndexedIndirect draws indexed primitives using parameters from a GPU buffer. indirectBuffer must contain a DrawIndexedIndirectArgs structure:
- indexCount (uint32)
- instanceCount (uint32)
- firstIndex (uint32)
- baseVertex (int32)
- firstInstance (uint32)
func (*RenderPassEncoder) DrawIndirect ¶
func (rpe *RenderPassEncoder) DrawIndirect(indirectBuffer *Buffer, indirectOffset uint64)
DrawIndirect draws primitives using parameters from a GPU buffer. indirectBuffer must contain a DrawIndirectArgs structure:
- vertexCount (uint32)
- instanceCount (uint32)
- firstVertex (uint32)
- firstInstance (uint32)
func (*RenderPassEncoder) ExecuteBundles ¶
func (rpe *RenderPassEncoder) ExecuteBundles(bundles []*RenderBundle)
ExecuteBundles executes pre-recorded render bundles in the render pass. This is useful for replaying static geometry without re-recording commands.
func (*RenderPassEncoder) Handle ¶
func (rpe *RenderPassEncoder) Handle() uintptr
Handle returns the underlying handle. For advanced use only.
func (*RenderPassEncoder) InsertDebugMarker ¶
func (rpe *RenderPassEncoder) InsertDebugMarker(markerLabel string)
InsertDebugMarker inserts a single debug marker label into the render pass. This is useful for GPU debugging tools to identify specific command points.
func (*RenderPassEncoder) PopDebugGroup ¶
func (rpe *RenderPassEncoder) PopDebugGroup()
PopDebugGroup ends the current debug group in the render pass. Must match a preceding PushDebugGroup call.
func (*RenderPassEncoder) PushDebugGroup ¶
func (rpe *RenderPassEncoder) PushDebugGroup(groupLabel string)
PushDebugGroup begins a labeled debug group in the render pass. Use PopDebugGroup to end the group. Groups can be nested.
func (*RenderPassEncoder) Release ¶
func (rpe *RenderPassEncoder) Release()
Release releases the render pass encoder.
func (*RenderPassEncoder) SetBindGroup ¶
func (rpe *RenderPassEncoder) SetBindGroup(groupIndex uint32, group *BindGroup, dynamicOffsets []uint32)
SetBindGroup sets a bind group for this pass.
func (*RenderPassEncoder) SetBlendConstant ¶
func (rpe *RenderPassEncoder) SetBlendConstant(color *Color)
SetBlendConstant sets the blend constant color used by blend operations. Errors are reported via Device error scopes.
func (*RenderPassEncoder) SetIndexBuffer ¶
func (rpe *RenderPassEncoder) SetIndexBuffer(buffer *Buffer, format gputypes.IndexFormat, offset, size uint64)
SetIndexBuffer sets the index buffer for this pass.
func (*RenderPassEncoder) SetPipeline ¶
func (rpe *RenderPassEncoder) SetPipeline(pipeline *RenderPipeline)
SetPipeline sets the render pipeline for this pass.
func (*RenderPassEncoder) SetScissorRect ¶
func (rpe *RenderPassEncoder) SetScissorRect(x, y, width, height uint32)
SetScissorRect sets the scissor rectangle used during the rasterization stage. Pixels outside the scissor rectangle will be discarded. x, y: top-left corner of the scissor rectangle in pixels width, height: dimensions of the scissor rectangle in pixels
func (*RenderPassEncoder) SetStencilReference ¶
func (rpe *RenderPassEncoder) SetStencilReference(reference uint32)
SetStencilReference sets the stencil reference value used by stencil operations.
func (*RenderPassEncoder) SetVertexBuffer ¶
func (rpe *RenderPassEncoder) SetVertexBuffer(slot uint32, buffer *Buffer, offset, size uint64)
SetVertexBuffer sets a vertex buffer for this pass.
func (*RenderPassEncoder) SetViewport ¶
func (rpe *RenderPassEncoder) SetViewport(x, y, width, height, minDepth, maxDepth float32)
SetViewport sets the viewport used during the rasterization stage. x, y: top-left corner of the viewport in pixels width, height: dimensions of the viewport in pixels minDepth, maxDepth: depth range for the viewport (typically 0.0 to 1.0)
type RenderPassTimestampWrites ¶
type RenderPassTimestampWrites struct {
QuerySet *QuerySet
BeginningOfPassWriteIndex uint32 // Use TimestampLocationUndefined to disable
EndOfPassWriteIndex uint32 // Use TimestampLocationUndefined to disable
}
RenderPassTimestampWrites describes timestamp writes for a render pass.
type RenderPipeline ¶
type RenderPipeline struct {
// contains filtered or unexported fields
}
RenderPipeline is a compiled render pipeline configuration (shaders, vertex layout, blend state). Create with Device.CreateRenderPipeline, release with RenderPipeline.Release.
func (*RenderPipeline) GetBindGroupLayout ¶
func (rp *RenderPipeline) GetBindGroupLayout(groupIndex uint32) *BindGroupLayout
GetBindGroupLayout returns the bind group layout for the given index.
func (*RenderPipeline) Handle ¶
func (rp *RenderPipeline) Handle() uintptr
Handle returns the underlying handle. For advanced use only.
func (*RenderPipeline) Release ¶
func (rp *RenderPipeline) Release()
Release releases the render pipeline.
type RenderPipelineDescriptor ¶
type RenderPipelineDescriptor struct {
Label string
Layout *PipelineLayout // nil for auto layout
Vertex VertexState
Primitive PrimitiveState
DepthStencil *DepthStencilState // nil for no depth/stencil
Multisample MultisampleState
Fragment *FragmentState // nil for no fragment stage (depth-only)
}
RenderPipelineDescriptor describes a render pipeline to create.
type RequestAdapterCallbackInfo ¶
type RequestAdapterCallbackInfo struct {
NextInChain uintptr // *ChainedStruct
Mode CallbackMode
Callback uintptr // Function pointer
Userdata1 uintptr
Userdata2 uintptr
}
RequestAdapterCallbackInfo holds callback configuration.
type RequestAdapterOptions ¶
type RequestAdapterOptions struct {
NextInChain uintptr // *ChainedStruct
FeatureLevel FeatureLevel
PowerPreference gputypes.PowerPreference
ForceFallbackAdapter Bool
CompatibilityMode Bool
CompatibleSurface uintptr // WGPUSurface
}
RequestAdapterOptions configures adapter selection.
type RequestAdapterStatus ¶
type RequestAdapterStatus uint32
RequestAdapterStatus is the status returned by RequestAdapter callback.
const ( // RequestAdapterStatusSuccess indicates the adapter was successfully obtained. RequestAdapterStatusSuccess RequestAdapterStatus = 0x00000001 // RequestAdapterStatusInstanceDropped indicates the instance was dropped before completion. RequestAdapterStatusInstanceDropped RequestAdapterStatus = 0x00000002 RequestAdapterStatusUnavailable RequestAdapterStatus = 0x00000003 // RequestAdapterStatusError indicates an error occurred during adapter request. RequestAdapterStatusError RequestAdapterStatus = 0x00000004 )
type RequestDeviceCallbackInfo ¶
type RequestDeviceCallbackInfo struct {
NextInChain uintptr // *ChainedStruct
Mode CallbackMode
Callback uintptr // Function pointer
Userdata1 uintptr
Userdata2 uintptr
}
RequestDeviceCallbackInfo holds callback configuration for RequestDevice.
type RequestDeviceStatus ¶
type RequestDeviceStatus uint32
RequestDeviceStatus is the status returned by RequestDevice callback.
const ( // RequestDeviceStatusSuccess indicates the device was successfully obtained. RequestDeviceStatusSuccess RequestDeviceStatus = 0x00000001 // RequestDeviceStatusInstanceDropped indicates the instance was dropped before completion. RequestDeviceStatusInstanceDropped RequestDeviceStatus = 0x00000002 // RequestDeviceStatusError indicates an error occurred during device request. RequestDeviceStatusError RequestDeviceStatus = 0x00000003 // RequestDeviceStatusUnknown indicates an unknown error occurred. RequestDeviceStatusUnknown RequestDeviceStatus = 0x00000004 )
type SType ¶
type SType uint32
SType identifies chained struct types.
const ( // STypeShaderSourceSPIRV identifies a SPIR-V shader source chained struct. STypeShaderSourceSPIRV SType = 0x00000001 // STypeShaderSourceWGSL identifies a WGSL shader source chained struct. STypeShaderSourceWGSL SType = 0x00000002 // STypeSurfaceSourceMetalLayer identifies a Metal layer surface source (macOS/iOS). STypeSurfaceSourceMetalLayer SType = 0x00000004 // STypeSurfaceSourceWindowsHWND identifies a Windows HWND surface source. STypeSurfaceSourceWindowsHWND SType = 0x00000005 // STypeSurfaceSourceXlibWindow identifies an Xlib window surface source (Linux). STypeSurfaceSourceXlibWindow SType = 0x00000006 // STypeSurfaceSourceWaylandSurface identifies a Wayland surface source (Linux). STypeSurfaceSourceWaylandSurface SType = 0x00000007 // STypeSurfaceSourceAndroidNativeWindow identifies an Android native window surface source. STypeSurfaceSourceAndroidNativeWindow SType = 0x00000008 // STypeSurfaceSourceXCBWindow identifies an XCB window surface source (Linux). STypeSurfaceSourceXCBWindow SType = 0x00000009 // STypeInstanceExtras identifies wgpu-native instance extras chained struct. STypeInstanceExtras SType = 0x00030006 )
type Sampler ¶
type Sampler struct {
// contains filtered or unexported fields
}
Sampler defines how a shader samples a Texture. Create with Device.CreateSampler, release with Sampler.Release.
type SamplerBindingLayout ¶
type SamplerBindingLayout struct {
NextInChain uintptr // *ChainedStruct
Type gputypes.SamplerBindingType
}
SamplerBindingLayout describes sampler binding properties.
type SamplerDescriptor ¶
type SamplerDescriptor struct {
NextInChain uintptr
Label StringView
AddressModeU gputypes.AddressMode
AddressModeV gputypes.AddressMode
AddressModeW gputypes.AddressMode
MagFilter gputypes.FilterMode
MinFilter gputypes.FilterMode
MipmapFilter gputypes.MipmapFilterMode
LodMinClamp float32
LodMaxClamp float32
Compare gputypes.CompareFunction
MaxAnisotropy uint16
// contains filtered or unexported fields
}
SamplerDescriptor describes a sampler to create.
type ShaderModule ¶
type ShaderModule struct {
// contains filtered or unexported fields
}
ShaderModule holds compiled shader code (WGSL or SPIR-V). Create with Device.CreateShaderModuleWGSL, release with ShaderModule.Release.
func (*ShaderModule) Handle ¶
func (s *ShaderModule) Handle() uintptr
Handle returns the underlying handle. For advanced use only.
func (*ShaderModule) Release ¶
func (s *ShaderModule) Release()
Release releases the shader module resources.
type ShaderModuleDescriptor ¶
type ShaderModuleDescriptor struct {
NextInChain uintptr // *ChainedStruct
Label StringView // Shader module label for debugging
}
ShaderModuleDescriptor describes a shader module to create.
type ShaderSourceWGSL ¶
type ShaderSourceWGSL struct {
Chain ChainedStruct
Code StringView
}
ShaderSourceWGSL provides WGSL source code for shader creation.
type StencilFaceState ¶
type StencilFaceState struct {
Compare gputypes.CompareFunction
FailOp gputypes.StencilOperation
DepthFailOp gputypes.StencilOperation
PassOp gputypes.StencilOperation
}
StencilFaceState describes stencil operations for a face.
type StorageTextureBindingLayout ¶
type StorageTextureBindingLayout struct {
NextInChain uintptr // *ChainedStruct
Access gputypes.StorageTextureAccess
Format gputypes.TextureFormat
ViewDimension gputypes.TextureViewDimension
}
StorageTextureBindingLayout describes storage texture binding properties.
type StringView ¶
type StringView struct {
Data uintptr // *char
Length uintptr // size_t, use SIZE_MAX for null-terminated
}
StringView represents a WebGPU string view (pointer + length).
func EmptyStringView ¶
func EmptyStringView() StringView
EmptyStringView returns an empty string view (null label).
type SupportedFeatures ¶ added in v0.3.0
SupportedFeatures contains features supported by adapter or device. This is the wire format for wgpuAdapterGetFeatures/wgpuDeviceGetFeatures.
type SupportedLimits ¶
SupportedLimits contains adapter limits.
type Surface ¶
type Surface struct {
// contains filtered or unexported fields
}
Surface represents a platform window surface for presenting rendered frames. Create with platform-specific CreateSurface, release with Surface.Release.
func (*Surface) Configure ¶
func (s *Surface) Configure(config *SurfaceConfiguration)
Configure configures the surface for rendering. This replaces the deprecated SwapChain API. Enum values are converted from gputypes to wgpu-native values before FFI call.
func (*Surface) GetCapabilities ¶ added in v0.3.0
func (s *Surface) GetCapabilities(adapter *Adapter) (*SurfaceCapabilities, error)
GetCapabilities queries the surface capabilities for the given adapter. This determines which texture formats, present modes, and alpha modes are supported. The caller must provide a valid adapter that will be used with this surface.
func (*Surface) GetCurrentTexture ¶
func (s *Surface) GetCurrentTexture() (*SurfaceTexture, error)
GetCurrentTexture gets the current texture to render to. Returns the texture and its status. Check status before using the texture.
func (*Surface) Present ¶
func (s *Surface) Present()
Present presents the current frame to the surface.
func (*Surface) Unconfigure ¶
func (s *Surface) Unconfigure()
Unconfigure removes the surface configuration.
type SurfaceCapabilities ¶ added in v0.3.0
type SurfaceCapabilities struct {
Usages gputypes.TextureUsage
Formats []gputypes.TextureFormat
PresentModes []gputypes.PresentMode
AlphaModes []gputypes.CompositeAlphaMode
}
SurfaceCapabilities describes the capabilities of a surface for presentation. Returned by Surface.GetCapabilities() to query supported formats, present modes, etc.
type SurfaceConfiguration ¶
type SurfaceConfiguration struct {
Device *Device
Format gputypes.TextureFormat
Usage gputypes.TextureUsage
Width uint32
Height uint32
AlphaMode gputypes.CompositeAlphaMode
PresentMode gputypes.PresentMode
}
SurfaceConfiguration describes how to configure a surface.
type SurfaceGetCurrentTextureStatus ¶
type SurfaceGetCurrentTextureStatus uint32
SurfaceGetCurrentTextureStatus describes the result of GetCurrentTexture.
const ( // SurfaceGetCurrentTextureStatusSuccessOptimal indicates the texture was obtained optimally. SurfaceGetCurrentTextureStatusSuccessOptimal SurfaceGetCurrentTextureStatus = 0x01 // SurfaceGetCurrentTextureStatusSuccessSuboptimal indicates the texture was obtained but may not be optimal. SurfaceGetCurrentTextureStatusSuccessSuboptimal SurfaceGetCurrentTextureStatus = 0x02 // SurfaceGetCurrentTextureStatusTimeout indicates the operation timed out. SurfaceGetCurrentTextureStatusTimeout SurfaceGetCurrentTextureStatus = 0x03 // SurfaceGetCurrentTextureStatusOutdated indicates the surface needs reconfiguration. SurfaceGetCurrentTextureStatusOutdated SurfaceGetCurrentTextureStatus = 0x04 // SurfaceGetCurrentTextureStatusLost indicates the surface was lost and must be recreated. SurfaceGetCurrentTextureStatusLost SurfaceGetCurrentTextureStatus = 0x05 // SurfaceGetCurrentTextureStatusOutOfMemory indicates GPU memory allocation failed. SurfaceGetCurrentTextureStatusOutOfMemory SurfaceGetCurrentTextureStatus = 0x06 // SurfaceGetCurrentTextureStatusDeviceLost indicates the GPU device was lost. SurfaceGetCurrentTextureStatusDeviceLost SurfaceGetCurrentTextureStatus = 0x07 // SurfaceGetCurrentTextureStatusError indicates an unspecified error occurred. SurfaceGetCurrentTextureStatusError SurfaceGetCurrentTextureStatus = 0x08 )
type SurfaceTexture ¶
type SurfaceTexture struct {
Texture *Texture
Status SurfaceGetCurrentTextureStatus
}
SurfaceTexture holds the result of GetCurrentTexture.
type TexelCopyBufferInfo ¶
type TexelCopyBufferInfo struct {
Layout TexelCopyBufferLayout
Buffer uintptr // Buffer handle
}
TexelCopyBufferInfo describes a buffer source/destination for copy operations.
type TexelCopyBufferLayout ¶
TexelCopyBufferLayout describes buffer layout for WriteTexture.
type TexelCopyTextureInfo ¶
type TexelCopyTextureInfo struct {
Texture uintptr
MipLevel uint32
Origin gputypes.Origin3D
Aspect TextureAspect
}
TexelCopyTextureInfo describes a texture for WriteTexture.
type Texture ¶
type Texture struct {
// contains filtered or unexported fields
}
Texture represents a GPU texture resource (1D, 2D, or 3D). Create with Device.CreateTexture, release with Texture.Release.
func (*Texture) CreateView ¶
func (t *Texture) CreateView(desc *TextureViewDescriptor) *TextureView
CreateView creates a view into this texture. Pass nil for default view parameters. Enum values are converted from gputypes to wgpu-native values before FFI call.
func (*Texture) GetDepthOrArrayLayers ¶
GetDepthOrArrayLayers returns the depth (for 3D textures) or array layer count.
func (*Texture) GetFormat ¶
func (t *Texture) GetFormat() gputypes.TextureFormat
GetFormat returns the texture format. The format is converted from wgpu-native enum to gputypes enum.
func (*Texture) GetMipLevelCount ¶
GetMipLevelCount returns the number of mip levels.
type TextureAspect ¶
type TextureAspect uint32
TextureAspect describes which aspect of a texture to access.
const ( // TextureAspectUndefined leaves the texture aspect unspecified. TextureAspectUndefined TextureAspect = 0x00 // TextureAspectAll accesses all aspects of the texture. TextureAspectAll TextureAspect = 0x01 // TextureAspectStencilOnly accesses only the stencil aspect of a depth-stencil texture. TextureAspectStencilOnly TextureAspect = 0x02 // TextureAspectDepthOnly accesses only the depth aspect of a depth-stencil texture. TextureAspectDepthOnly TextureAspect = 0x03 )
type TextureBindingLayout ¶
type TextureBindingLayout struct {
NextInChain uintptr // *ChainedStruct
SampleType gputypes.TextureSampleType
ViewDimension gputypes.TextureViewDimension
Multisampled Bool
}
TextureBindingLayout describes texture binding properties.
type TextureDescriptor ¶
type TextureDescriptor struct {
NextInChain uintptr
Label StringView
Usage gputypes.TextureUsage
Dimension gputypes.TextureDimension
Size gputypes.Extent3D
Format gputypes.TextureFormat
MipLevelCount uint32
SampleCount uint32
ViewFormatCount uintptr
ViewFormats uintptr
}
TextureDescriptor describes a texture to create.
type TextureView ¶
type TextureView struct {
// contains filtered or unexported fields
}
TextureView is a view into a subset of a Texture, used in bind groups and render passes. Create with Texture.CreateView, release with TextureView.Release.
func (*TextureView) Handle ¶
func (tv *TextureView) Handle() uintptr
Handle returns the underlying handle. For advanced use only.
func (*TextureView) Release ¶
func (tv *TextureView) Release()
Release releases the texture view reference.
type TextureViewDescriptor ¶
type TextureViewDescriptor struct {
NextInChain uintptr
Label StringView
Format gputypes.TextureFormat
Dimension gputypes.TextureViewDimension
BaseMipLevel uint32
MipLevelCount uint32
BaseArrayLayer uint32
ArrayLayerCount uint32
Aspect TextureAspect
Usage gputypes.TextureUsage
// contains filtered or unexported fields
}
TextureViewDescriptor describes a texture view to create.
type Vec3 ¶
type Vec3 struct {
X, Y, Z float32
}
Vec3 represents a 3D vector with X, Y, Z components.
Example (Cross) ¶
ExampleVec3_cross demonstrates cross product for normal calculation
package main
import (
"fmt"
"github.com/go-webgpu/webgpu/wgpu"
)
func main() {
// Calculate normal for a triangle (right-hand rule)
// Triangle vertices: v0, v1, v2
v0 := wgpu.Vec3{X: 0, Y: 0, Z: 0}
v1 := wgpu.Vec3{X: 1, Y: 0, Z: 0}
v2 := wgpu.Vec3{X: 0, Y: 1, Z: 0}
// Edge vectors
edge1 := v1.Sub(v0)
edge2 := v2.Sub(v0)
// Normal = edge1 × edge2
normal := edge1.Cross(edge2).Normalize()
fmt.Printf("Triangle normal: (%.0f, %.0f, %.0f)\n", normal.X, normal.Y, normal.Z)
}
Output: Triangle normal: (0, 0, 1)
func (Vec3) Cross ¶
Cross computes the cross product of this vector with another. Returns v × other (perpendicular to both vectors). Result follows right-hand rule.
func (Vec3) Dot ¶
Dot computes the dot product of this vector with another. Returns v · other (scalar projection).
type Vec4 ¶
type Vec4 struct {
X, Y, Z, W float32
}
Vec4 represents a 4D vector with X, Y, Z, W components. Compatible with WGSL vec4<f32>.
type VertexAttribute ¶
type VertexAttribute struct {
Format gputypes.VertexFormat
Offset uint64
ShaderLocation uint32
// contains filtered or unexported fields
}
VertexAttribute describes a vertex attribute.
type VertexBufferLayout ¶
type VertexBufferLayout struct {
ArrayStride uint64
StepMode gputypes.VertexStepMode
AttributeCount uintptr
Attributes *VertexAttribute
// contains filtered or unexported fields
}
VertexBufferLayout describes how vertex data is laid out in a buffer.
type VertexState ¶
type VertexState struct {
Module *ShaderModule
EntryPoint string
Buffers []VertexBufferLayout
}
VertexState describes the vertex stage of a render pipeline.
type WGPUError ¶ added in v0.3.0
type WGPUError struct {
// Op is the operation that failed (e.g., "CreateBuffer", "RequestAdapter").
Op string
// Type is the WebGPU error type (Validation, OutOfMemory, Internal).
Type ErrorType
// Message is the error message from wgpu-native.
Message string
}
WGPUError represents a WebGPU operation error with context. Supports errors.Is() and errors.As() for programmatic handling.
type WGPUStatus ¶
type WGPUStatus uint32
WGPUStatus describes the status returned from certain WebGPU operations.
const ( // WGPUStatusSuccess indicates the operation completed successfully. WGPUStatusSuccess WGPUStatus = 0x00000000 // WGPUStatusError indicates the operation failed. WGPUStatusError WGPUStatus = 0x00000001 )