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.Limits, Adapter.Info, Adapter.Features, Adapter.HasFeature
- Read-only queries: Device.Limits, Device.Features, 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) Features() []FeatureName
- func (a *Adapter) Handle() uintptr
- func (a *Adapter) HasFeature(feature FeatureName) bool
- func (a *Adapter) Info() (*AdapterInfoGo, error)
- func (a *Adapter) Limits() Limits
- func (a *Adapter) Release()
- func (a *Adapter) RequestDevice(options *DeviceDescriptor) (*Device, error)
- type AdapterInfo
- type AdapterInfoGo
- type AdapterType
- type AddressMode
- type BackendType
- type BindGroup
- type BindGroupDescriptor
- type BindGroupDescriptorGo
- type BindGroupEntry
- type BindGroupEntryGo
- type BindGroupLayout
- type BindGroupLayoutDescriptor
- type BindGroupLayoutDescriptorGo
- type BindGroupLayoutEntry
- type BlendComponent
- type BlendFactor
- type BlendOperation
- type BlendState
- type Bool
- type Buffer
- func (b *Buffer) Destroy()
- func (b *Buffer) GetMappedRange(offset, size uint64) unsafe.Pointer
- func (b *Buffer) Handle() uintptr
- func (b *Buffer) Map(ctx context.Context, mode MapMode, offset, size uint64) error
- func (b *Buffer) MapAsync(mode MapMode, offset, size uint64) (*MapPending, error)
- func (b *Buffer) MapAsyncBlocking(device *Device, mode MapMode, offset, size uint64) error
- func (b *Buffer) MapState() BufferMapState
- func (b *Buffer) MappedRange(offset, size uint64) (*MappedRange, error)
- func (b *Buffer) Release()
- func (b *Buffer) Size() uint64
- func (b *Buffer) Unmap() error
- func (b *Buffer) Usage() gputypes.BufferUsage
- type BufferBindingLayout
- type BufferBindingType
- type BufferDescriptor
- type BufferMapCallbackInfo
- type BufferMapState
- type BufferTextureCopy
- type BufferUsage
- type CallbackMode
- type ChainedStruct
- type ChainedStructOut
- type Color
- type ColorTargetState
- type ColorWriteMask
- type CommandBuffer
- type CommandBufferDescriptor
- type CommandEncoder
- func (enc *CommandEncoder) BeginComputePass(desc *ComputePassDescriptor) (*ComputePassEncoder, error)
- func (enc *CommandEncoder) BeginRenderPass(desc *RenderPassDescriptor) (*RenderPassEncoder, error)
- 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(src *Texture, dst *Buffer, regions []BufferTextureCopy)
- func (enc *CommandEncoder) CopyTextureToBufferRaw(source *TexelCopyTextureInfo, destination *TexelCopyBufferInfo, ...)
- func (enc *CommandEncoder) CopyTextureToTexture(src, dst *Texture, regions []TextureCopy)
- func (enc *CommandEncoder) CopyTextureToTextureRaw(source *TexelCopyTextureInfo, destination *TexelCopyTextureInfo, ...)
- func (enc *CommandEncoder) Finish(desc ...*CommandBufferDescriptor) (*CommandBuffer, error)
- 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 CommandEncoderDescriptorGo
- type CompareFunction
- type ComponentSwizzle
- type CompositeAlphaMode
- 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 ComputePassTimestampWrites
- type ComputePipeline
- type ComputePipelineDescriptor
- type ComputePipelineDescriptorGo
- type CullMode
- type DepthStencilState
- type Device
- func (d *Device) CreateBindGroup(desc *BindGroupDescriptor) (*BindGroup, error)
- func (d *Device) CreateBindGroupLayout(desc *BindGroupLayoutDescriptor) (*BindGroupLayout, error)
- func (d *Device) CreateBindGroupLayoutSimple(entries []BindGroupLayoutEntry) (*BindGroupLayout, error)
- func (d *Device) CreateBindGroupSimple(layout *BindGroupLayout, entries []BindGroupEntry) (*BindGroup, error)
- func (d *Device) CreateBuffer(desc *BufferDescriptor) (*Buffer, error)
- func (d *Device) CreateCommandEncoder(desc *CommandEncoderDescriptor) (*CommandEncoder, error)
- func (d *Device) CreateComputePipeline(desc *ComputePipelineDescriptor) (*ComputePipeline, error)
- func (d *Device) CreateComputePipelineSimple(layout *PipelineLayout, shader *ShaderModule, entryPoint string) (*ComputePipeline, error)
- func (d *Device) CreateDepthTexture(width, height uint32, format gputypes.TextureFormat) *Texture
- func (d *Device) CreateLinearSampler() (*Sampler, error)
- func (d *Device) CreateNearestSampler() (*Sampler, error)
- func (d *Device) CreatePipelineLayout(desc *PipelineLayoutDescriptor) (*PipelineLayout, error)
- func (d *Device) CreatePipelineLayoutSimple(layouts []*BindGroupLayout) (*PipelineLayout, error)
- func (d *Device) CreateQuerySet(desc *QuerySetDescriptor) (*QuerySet, error)
- func (d *Device) CreateRenderBundleEncoder(desc *RenderBundleEncoderDescriptor) (*RenderBundleEncoder, error)
- func (d *Device) CreateRenderBundleEncoderSimple(colorFormats []gputypes.TextureFormat, depthFormat gputypes.TextureFormat, ...) *RenderBundleEncoder
- func (d *Device) CreateRenderPipeline(desc *RenderPipelineDescriptor) (*RenderPipeline, error)
- func (d *Device) CreateRenderPipelineSimple(layout *PipelineLayout, vertexShader *ShaderModule, vertexEntryPoint string, ...) (*RenderPipeline, error)
- func (d *Device) CreateSampler(desc *SamplerDescriptor) (*Sampler, error)
- func (d *Device) CreateShaderModule(desc *ShaderModuleDescriptor) (*ShaderModule, error)
- func (d *Device) CreateShaderModuleFromDesc(desc *ShaderDescriptor) (*ShaderModule, error)
- func (d *Device) CreateShaderModuleFromDescriptor(desc *ShaderDescriptor) (*ShaderModule, error)deprecated
- func (d *Device) CreateShaderModuleSPIRV(label string, spirv []uint32) (*ShaderModule, error)
- func (d *Device) CreateShaderModuleWGSL(code string) (*ShaderModule, error)
- func (d *Device) CreateTexture(desc *TextureDescriptor) (*Texture, error)
- func (d *Device) Features() []FeatureName
- func (d *Device) Handle() uintptr
- func (d *Device) HasFeature(feature FeatureName) bool
- func (d *Device) Limits() Limits
- 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) Queue() *Queue
- func (d *Device) Release()
- type DeviceDescriptor
- type DeviceLostCallbackInfo
- type DeviceLostReason
- type DispatchIndirectArgs
- type DrawIndexedIndirectArgs
- type DrawIndirectArgs
- type ErrorFilter
- type ErrorType
- type Extent3D
- type FeatureLevel
- type FeatureName
- type Features
- type FilterMode
- type FragmentState
- type FrontFace
- type Future
- type ImageCopyTexture
- type ImageDataLayout
- type IndexFormat
- 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 InstanceBackend
- type InstanceDescriptor
- type InstanceFeatureName
- type InstanceFlag
- type InstanceLimits
- type LeakReport
- type Library
- type Limits
- type LoadOp
- type MapAsyncStatus
- type MapMode
- type MapPending
- type MappedRange
- 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 MipmapFilterMode
- type MultisampleState
- type NativeDisplayHandleType
- type NativeFeature
- type NativeLimits
- type OptionalBool
- type Origin3D
- type PassTimestampWrites
- type PipelineLayout
- type PipelineLayoutDescriptor
- type PipelineLayoutDescriptorGo
- type PipelineLayoutExtras
- type PopErrorScopeStatus
- type PowerPreference
- type PredefinedColorSpace
- type PresentMode
- type PrimitiveState
- type PrimitiveTopology
- 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) (uint64, error)
- func (q *Queue) WriteBuffer(buffer *Buffer, offset uint64, data []byte) error
- func (q *Queue) WriteBufferRaw(buffer *Buffer, offset uint64, data unsafe.Pointer, size uint64)
- func (q *Queue) WriteTexture(dest *ImageCopyTexture, data []byte, layout *ImageDataLayout, ...) error
- func (q *Queue) WriteTextureRaw(dest *TexelCopyTextureInfo, data []byte, layout *TexelCopyBufferLayout, ...) error
- type QueueDescriptor
- 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 RenderBundleEncoderDescriptorGo
- 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 SamplerBindingType
- type SamplerDescriptor
- type ShaderDescriptor
- type ShaderModule
- type ShaderModuleDescriptor
- type ShaderModuleDescriptorGo
- type ShaderSourceWGSL
- type ShaderStage
- type ShaderStages
- type StencilFaceState
- type StencilOperation
- type StorageTextureBindingLayout
- type StoreOp
- type StringView
- type SupportedFeatures
- type Surface
- func (s *Surface) Configure(device *Device, config *SurfaceConfiguration) error
- func (s *Surface) ConfigureLegacy(config *SurfaceConfiguration)
- func (s *Surface) GetCapabilities(adapter *Adapter) (*SurfaceCapabilities, error)
- func (s *Surface) GetCurrentTexture() (*SurfaceTexture, bool, error)
- func (s *Surface) Handle() uintptr
- func (s *Surface) Present(texture ...*SurfaceTexture) error
- 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, error)
- func (t *Texture) DepthOrArrayLayers() uint32
- func (t *Texture) Destroy()
- func (t *Texture) Format() gputypes.TextureFormat
- func (t *Texture) Handle() uintptr
- func (t *Texture) Height() uint32
- func (t *Texture) MipLevelCount() uint32
- func (t *Texture) Release()
- func (t *Texture) Width() uint32
- type TextureAspect
- type TextureBindingLayout
- type TextureCopy
- type TextureDescriptor
- type TextureDimension
- type TextureFormat
- type TextureSampleType
- type TextureUsage
- type TextureView
- type TextureViewDescriptor
- type TextureViewDimension
- type ToneMappingMode
- type UncapturedErrorCallbackInfo
- type Vec3
- type Vec4
- type VertexAttribute
- type VertexBufferLayout
- type VertexFormat
- type VertexState
- type VertexStepMode
- type WGPUError
- type WGPUStatus
Examples ¶
Constants ¶
const ( BufferUsageNone = gputypes.BufferUsageNone BufferUsageMapRead = gputypes.BufferUsageMapRead BufferUsageMapWrite = gputypes.BufferUsageMapWrite BufferUsageCopySrc = gputypes.BufferUsageCopySrc BufferUsageCopyDst = gputypes.BufferUsageCopyDst BufferUsageIndex = gputypes.BufferUsageIndex BufferUsageVertex = gputypes.BufferUsageVertex BufferUsageUniform = gputypes.BufferUsageUniform BufferUsageStorage = gputypes.BufferUsageStorage BufferUsageIndirect = gputypes.BufferUsageIndirect BufferUsageQueryResolve = gputypes.BufferUsageQueryResolve )
const ( TextureUsageNone = gputypes.TextureUsageNone TextureUsageCopySrc = gputypes.TextureUsageCopySrc TextureUsageCopyDst = gputypes.TextureUsageCopyDst TextureUsageTextureBinding = gputypes.TextureUsageTextureBinding TextureUsageStorageBinding = gputypes.TextureUsageStorageBinding TextureUsageRenderAttachment = gputypes.TextureUsageRenderAttachment )
const ( TextureFormatUndefined = gputypes.TextureFormatUndefined TextureFormatR8Unorm = gputypes.TextureFormatR8Unorm TextureFormatR8Snorm = gputypes.TextureFormatR8Snorm TextureFormatR8Uint = gputypes.TextureFormatR8Uint TextureFormatR8Sint = gputypes.TextureFormatR8Sint TextureFormatR16Uint = gputypes.TextureFormatR16Uint TextureFormatR16Sint = gputypes.TextureFormatR16Sint TextureFormatR16Float = gputypes.TextureFormatR16Float TextureFormatRG8Unorm = gputypes.TextureFormatRG8Unorm TextureFormatRG8Snorm = gputypes.TextureFormatRG8Snorm TextureFormatRG8Uint = gputypes.TextureFormatRG8Uint TextureFormatRG8Sint = gputypes.TextureFormatRG8Sint TextureFormatR32Float = gputypes.TextureFormatR32Float TextureFormatR32Uint = gputypes.TextureFormatR32Uint TextureFormatR32Sint = gputypes.TextureFormatR32Sint TextureFormatRG16Uint = gputypes.TextureFormatRG16Uint TextureFormatRG16Sint = gputypes.TextureFormatRG16Sint TextureFormatRG16Float = gputypes.TextureFormatRG16Float TextureFormatRGBA8Unorm = gputypes.TextureFormatRGBA8Unorm TextureFormatRGBA8UnormSrgb = gputypes.TextureFormatRGBA8UnormSrgb TextureFormatRGBA8Snorm = gputypes.TextureFormatRGBA8Snorm TextureFormatRGBA8Uint = gputypes.TextureFormatRGBA8Uint TextureFormatRGBA8Sint = gputypes.TextureFormatRGBA8Sint TextureFormatBGRA8Unorm = gputypes.TextureFormatBGRA8Unorm TextureFormatBGRA8UnormSrgb = gputypes.TextureFormatBGRA8UnormSrgb TextureFormatRGB10A2Uint = gputypes.TextureFormatRGB10A2Uint TextureFormatRGB10A2Unorm = gputypes.TextureFormatRGB10A2Unorm TextureFormatRG11B10Ufloat = gputypes.TextureFormatRG11B10Ufloat TextureFormatRG32Float = gputypes.TextureFormatRG32Float TextureFormatRG32Uint = gputypes.TextureFormatRG32Uint TextureFormatRG32Sint = gputypes.TextureFormatRG32Sint TextureFormatRGBA16Uint = gputypes.TextureFormatRGBA16Uint TextureFormatRGBA16Sint = gputypes.TextureFormatRGBA16Sint TextureFormatRGBA16Float = gputypes.TextureFormatRGBA16Float TextureFormatRGBA32Float = gputypes.TextureFormatRGBA32Float TextureFormatRGBA32Uint = gputypes.TextureFormatRGBA32Uint TextureFormatRGBA32Sint = gputypes.TextureFormatRGBA32Sint TextureFormatDepth32Float = gputypes.TextureFormatDepth32Float TextureFormatDepth24Plus = gputypes.TextureFormatDepth24Plus TextureFormatDepth24PlusStencil8 = gputypes.TextureFormatDepth24PlusStencil8 TextureFormatDepth16Unorm = gputypes.TextureFormatDepth16Unorm )
const ( TextureDimension1D = gputypes.TextureDimension1D TextureDimension2D = gputypes.TextureDimension2D TextureDimension3D = gputypes.TextureDimension3D )
const ( ShaderStageNone = gputypes.ShaderStageNone ShaderStageVertex = gputypes.ShaderStageVertex ShaderStageFragment = gputypes.ShaderStageFragment ShaderStageCompute = gputypes.ShaderStageCompute )
const ( PrimitiveTopologyPointList = gputypes.PrimitiveTopologyPointList PrimitiveTopologyLineList = gputypes.PrimitiveTopologyLineList PrimitiveTopologyLineStrip = gputypes.PrimitiveTopologyLineStrip PrimitiveTopologyTriangleList = gputypes.PrimitiveTopologyTriangleList PrimitiveTopologyTriangleStrip = gputypes.PrimitiveTopologyTriangleStrip )
const ( FrontFaceCCW = gputypes.FrontFaceCCW FrontFaceCW = gputypes.FrontFaceCW )
const ( CullModeNone = gputypes.CullModeNone CullModeFront = gputypes.CullModeFront CullModeBack = gputypes.CullModeBack )
const ( IndexFormatUint16 = gputypes.IndexFormatUint16 IndexFormatUint32 = gputypes.IndexFormatUint32 )
const ( LoadOpLoad = gputypes.LoadOpLoad LoadOpClear = gputypes.LoadOpClear )
const ( StoreOpStore = gputypes.StoreOpStore StoreOpDiscard = gputypes.StoreOpDiscard )
const ( FilterModeNearest = gputypes.FilterModeNearest FilterModeLinear = gputypes.FilterModeLinear )
const ( AddressModeRepeat = gputypes.AddressModeRepeat AddressModeMirrorRepeat = gputypes.AddressModeMirrorRepeat AddressModeClampToEdge = gputypes.AddressModeClampToEdge )
const ( CompareFunctionUndefined = gputypes.CompareFunctionUndefined CompareFunctionNever = gputypes.CompareFunctionNever CompareFunctionLess = gputypes.CompareFunctionLess CompareFunctionEqual = gputypes.CompareFunctionEqual CompareFunctionLessEqual = gputypes.CompareFunctionLessEqual CompareFunctionGreater = gputypes.CompareFunctionGreater CompareFunctionNotEqual = gputypes.CompareFunctionNotEqual CompareFunctionGreaterEqual = gputypes.CompareFunctionGreaterEqual CompareFunctionAlways = gputypes.CompareFunctionAlways )
const ( PresentModeImmediate = gputypes.PresentModeImmediate PresentModeMailbox = gputypes.PresentModeMailbox PresentModeFifo = gputypes.PresentModeFifo PresentModeFifoRelaxed = gputypes.PresentModeFifoRelaxed )
const ( CompositeAlphaModeAuto = gputypes.CompositeAlphaModeAuto CompositeAlphaModeOpaque = gputypes.CompositeAlphaModeOpaque CompositeAlphaModePremultiplied = gputypes.CompositeAlphaModePremultiplied CompositeAlphaModeUnpremultiplied = gputypes.CompositeAlphaModeUnpremultiplied CompositeAlphaModeInherit = gputypes.CompositeAlphaModeInherit )
const ( PowerPreferenceNone = gputypes.PowerPreferenceNone PowerPreferenceLowPower = gputypes.PowerPreferenceLowPower PowerPreferenceHighPerformance = gputypes.PowerPreferenceHighPerformance )
const ( ColorWriteMaskNone = gputypes.ColorWriteMaskNone ColorWriteMaskRed = gputypes.ColorWriteMaskRed ColorWriteMaskGreen = gputypes.ColorWriteMaskGreen ColorWriteMaskBlue = gputypes.ColorWriteMaskBlue ColorWriteMaskAlpha = gputypes.ColorWriteMaskAlpha ColorWriteMaskAll = gputypes.ColorWriteMaskAll )
const ( VertexFormatUint8x2 = gputypes.VertexFormatUint8x2 VertexFormatUint8x4 = gputypes.VertexFormatUint8x4 VertexFormatSint8x2 = gputypes.VertexFormatSint8x2 VertexFormatSint8x4 = gputypes.VertexFormatSint8x4 VertexFormatFloat32 = gputypes.VertexFormatFloat32 VertexFormatFloat32x2 = gputypes.VertexFormatFloat32x2 VertexFormatFloat32x3 = gputypes.VertexFormatFloat32x3 VertexFormatFloat32x4 = gputypes.VertexFormatFloat32x4 VertexFormatUint32 = gputypes.VertexFormatUint32 VertexFormatUint32x2 = gputypes.VertexFormatUint32x2 VertexFormatUint32x3 = gputypes.VertexFormatUint32x3 VertexFormatUint32x4 = gputypes.VertexFormatUint32x4 VertexFormatSint32 = gputypes.VertexFormatSint32 VertexFormatSint32x2 = gputypes.VertexFormatSint32x2 VertexFormatSint32x3 = gputypes.VertexFormatSint32x3 VertexFormatSint32x4 = gputypes.VertexFormatSint32x4 )
const ( VertexStepModeVertex = gputypes.VertexStepModeVertex VertexStepModeInstance = gputypes.VertexStepModeInstance )
const ( BufferBindingTypeUndefined = gputypes.BufferBindingTypeUndefined BufferBindingTypeUniform = gputypes.BufferBindingTypeUniform BufferBindingTypeStorage = gputypes.BufferBindingTypeStorage BufferBindingTypeReadOnlyStorage = gputypes.BufferBindingTypeReadOnlyStorage )
const ( SamplerBindingTypeUndefined = gputypes.SamplerBindingTypeUndefined SamplerBindingTypeFiltering = gputypes.SamplerBindingTypeFiltering SamplerBindingTypeNonFiltering = gputypes.SamplerBindingTypeNonFiltering SamplerBindingTypeComparison = gputypes.SamplerBindingTypeComparison )
const ( TextureSampleTypeUndefined = gputypes.TextureSampleTypeUndefined TextureSampleTypeFloat = gputypes.TextureSampleTypeFloat TextureSampleTypeUnfilterableFloat = gputypes.TextureSampleTypeUnfilterableFloat TextureSampleTypeDepth = gputypes.TextureSampleTypeDepth TextureSampleTypeSint = gputypes.TextureSampleTypeSint TextureSampleTypeUint = gputypes.TextureSampleTypeUint )
const ( TextureViewDimensionUndefined = gputypes.TextureViewDimensionUndefined TextureViewDimension1D = gputypes.TextureViewDimension1D TextureViewDimension2D = gputypes.TextureViewDimension2D TextureViewDimension2DArray = gputypes.TextureViewDimension2DArray TextureViewDimensionCube = gputypes.TextureViewDimensionCube TextureViewDimensionCubeArray = gputypes.TextureViewDimensionCubeArray TextureViewDimension3D = gputypes.TextureViewDimension3D )
const ( StencilOperationUndefined = gputypes.StencilOperationUndefined StencilOperationKeep = gputypes.StencilOperationKeep StencilOperationZero = gputypes.StencilOperationZero StencilOperationReplace = gputypes.StencilOperationReplace StencilOperationInvert = gputypes.StencilOperationInvert StencilOperationIncrementClamp = gputypes.StencilOperationIncrementClamp StencilOperationDecrementClamp = gputypes.StencilOperationDecrementClamp StencilOperationIncrementWrap = gputypes.StencilOperationIncrementWrap StencilOperationDecrementWrap = gputypes.StencilOperationDecrementWrap )
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"} // ErrSurfaceOccluded is returned on macOS Metal when the window is minimized or fully covered. // Applications should skip rendering for the current frame and try again when unoccluded. // New in wgpu-native v29. ErrSurfaceOccluded = &WGPUError{Op: "Surface.GetCurrentTexture", Message: "surface occluded (window minimized or covered)"} // ErrSurfaceOutOfMemory is kept for backward compatibility. // Deprecated: In v29 this is reported as generic Error status. ErrSurfaceOutOfMemory = &WGPUError{Op: "Surface.GetCurrentTexture", Message: "out of memory"} // ErrSurfaceDeviceLost is kept for backward compatibility. // Deprecated: In v29 this is reported as generic Error status. 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.
The library is located using the following strategy (first match wins):
- WGPU_NATIVE_PATH environment variable (explicit full path)
- ./lib/<name> — default location installed by cmd/setup
- ./<name> — current directory
- OS default search (PATH on Windows, LD_LIBRARY_PATH/DYLD_LIBRARY_PATH on Unix)
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 is a deprecated alias for Features. Deprecated: Use Features instead. This method was renamed in wgpu-native v29.
func (*Adapter) Features ¶ added in v0.5.0
func (a *Adapter) Features() []FeatureName
Features retrieves all features supported by this adapter. v29: Uses single-call wgpuAdapterGetFeatures with SupportedFeatures struct (replaces two-call EnumerateFeatures). The returned slice is copied from C memory; the underlying C allocation is freed automatically.
func (*Adapter) HasFeature ¶
func (a *Adapter) HasFeature(feature FeatureName) bool
HasFeature checks if the adapter supports a specific feature.
func (*Adapter) Info ¶ added in v0.5.0
func (a *Adapter) Info() (*AdapterInfoGo, error)
Info 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) Limits ¶ added in v0.5.0
Limits returns the resource limits of this adapter.
Limits are cached at adapter creation time and returned by value. No FFI call is made. Returns zero-value Limits if the adapter is nil. This matches the gogpu/wgpu API signature for cross-project compatibility.
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 // *ChainedStruct (was *ChainedStructOut in v27)
Vendor StringView
Architecture StringView
Device StringView
Description StringView
BackendType BackendType
AdapterType AdapterType
VendorID uint32
DeviceID uint32
SubgroupMinSize uint32 // NEW in v29
SubgroupMaxSize uint32 // NEW in v29
}
AdapterInfo contains information about the adapter. v29: NextInChain type changed from *ChainedStructOut to *ChainedStruct. v29: SubgroupMinSize and SubgroupMaxSize fields added.
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 AddressMode ¶
type AddressMode = gputypes.AddressMode
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 {
Label string
Layout *BindGroupLayout
Entries []BindGroupEntry
}
BindGroupDescriptor describes a bind group.
type BindGroupDescriptorGo ¶ added in v0.5.0
type BindGroupDescriptorGo = BindGroupDescriptor
BindGroupDescriptorGo is kept for backward compatibility. Deprecated: Use BindGroupDescriptor directly (now Go-idiomatic).
type BindGroupEntry ¶
type BindGroupEntry struct {
Binding uint32
Buffer *Buffer // For buffer bindings (nil if not used)
Offset uint64 // Buffer offset (ignored for non-buffer bindings)
Size uint64 // Buffer binding size; 0 = whole buffer
Sampler *Sampler // For sampler bindings (nil if not used)
TextureView *TextureView // For texture view bindings (nil if not used)
}
BindGroupEntry describes a single binding in a bind group. Exactly one of Buffer, Sampler, or TextureView must be non-nil.
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 BindGroupEntryGo ¶ added in v0.5.0
type BindGroupEntryGo = BindGroupEntry
BindGroupEntryGo is kept for backward compatibility. Deprecated: Use BindGroupEntry directly (now Go-idiomatic).
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 {
Label string
Entries []BindGroupLayoutEntry
}
BindGroupLayoutDescriptor describes a bind group layout.
type BindGroupLayoutDescriptorGo ¶ added in v0.5.0
type BindGroupLayoutDescriptorGo = BindGroupLayoutDescriptor
BindGroupLayoutDescriptorGo is kept for backward compatibility. Deprecated: Use BindGroupLayoutDescriptor directly (now Go-idiomatic).
type BindGroupLayoutEntry ¶
type BindGroupLayoutEntry struct {
// Binding is the binding number (must match @binding in shader).
Binding uint32
// Visibility specifies which shader stages can access this binding.
Visibility gputypes.ShaderStage
// Buffer describes a buffer binding (nil if not a buffer binding).
Buffer *BufferBindingLayout
// Sampler describes a sampler binding (nil if not a sampler binding).
Sampler *SamplerBindingLayout
// Texture describes a texture binding (nil if not a texture binding).
Texture *TextureBindingLayout
// StorageTexture describes a storage texture binding (nil if not a storage texture binding).
StorageTexture *StorageTextureBindingLayout
}
BindGroupLayoutEntry describes a single binding in a bind group layout.
Exactly one of Buffer, Sampler, Texture, or StorageTexture must be non-nil. This matches the gogpu/wgpu API for cross-project compatibility.
type BlendComponent ¶
type BlendComponent struct {
Operation gputypes.BlendOperation
SrcFactor gputypes.BlendFactor
DstFactor gputypes.BlendFactor
}
BlendComponent describes blend state for a color component.
type BlendOperation ¶
type BlendOperation = gputypes.BlendOperation
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) 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) Map ¶ added in v0.5.0
Map blocks until a CPU-visible mapping is established for the given byte range, or until ctx is canceled.
The buffer must have been created with BufferUsageMapRead or BufferUsageMapWrite matching mode. offset must be a multiple of 8 and size must be a multiple of 4 (WebGPU MAP_ALIGNMENT).
After Map succeeds, call MappedRange to obtain a byte view and Unmap when finished:
if err := buf.Map(ctx, wgpu.MapModeRead, 0, size); err != nil {
return err
}
defer buf.Unmap()
rng, _ := buf.MappedRange(0, size)
data := rng.Bytes()
Matches gogpu/wgpu Buffer.Map(ctx, mode, offset, size) error.
func (*Buffer) MapAsync ¶
func (b *Buffer) MapAsync(mode MapMode, offset, size uint64) (*MapPending, error)
MapAsync initiates an asynchronous buffer map without blocking. Returns a *MapPending that resolves once the GPU completes the operation.
The caller must periodically drive Device.Poll(false) so the mapping resolves. For a blocking variant use Buffer.Map.
Matches gogpu/wgpu Buffer.MapAsync(mode, offset, size) (*MapPending, error).
func (*Buffer) MapAsyncBlocking ¶ added in v0.5.0
MapAsyncBlocking maps a buffer for reading or writing, blocking until complete. Deprecated: Use Buffer.Map for blocking mapping or Buffer.MapAsync for non-blocking. This method is retained for backward compatibility.
func (*Buffer) MapState ¶ added in v0.5.0
func (b *Buffer) MapState() BufferMapState
MapState returns the current mapping state of this buffer.
func (*Buffer) MappedRange ¶ added in v0.5.0
func (b *Buffer) MappedRange(offset, size uint64) (*MappedRange, error)
MappedRange returns a safe view over the mapped region [offset, offset+size).
The buffer must be in the Mapped state (Buffer.Map or Buffer.MapAsync resolved to success). The returned MappedRange.Bytes() slice is invalidated by Buffer.Unmap.
Matches gogpu/wgpu Buffer.MappedRange(offset, size) (*MappedRange, error).
func (*Buffer) Unmap ¶
Unmap unmaps the buffer, making the mapped memory inaccessible. For buffers created with MappedAtCreation, this commits the data to the GPU. Returns nil on success. Matches gogpu/wgpu Buffer.Unmap() error signature.
func (*Buffer) Usage ¶ added in v0.5.0
func (b *Buffer) Usage() gputypes.BufferUsage
Usage returns the usage flags of this buffer.
type BufferBindingLayout ¶
type BufferBindingLayout = gputypes.BufferBindingLayout
BufferBindingLayout describes buffer binding properties.
This type matches gputypes.BufferBindingLayout for cross-project compatibility. Used as a pointer field in BindGroupLayoutEntry; nil means "not a buffer binding".
type BufferDescriptor ¶
type BufferDescriptor struct {
Label string // 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 GPU 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 BufferTextureCopy ¶ added in v0.5.0
type BufferTextureCopy struct {
// BufferLayout describes the memory layout of the buffer data.
BufferLayout ImageDataLayout
// TextureBase describes the texture subresource and origin.
TextureBase ImageCopyTexture
// Size is the extent of the copy operation.
Size gputypes.Extent3D
}
BufferTextureCopy defines a buffer-texture copy region. Matches gogpu/wgpu BufferTextureCopy.
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 (both input and output). In v29 ChainedStructOut was unified with ChainedStruct — use ChainedStruct everywhere.
type ChainedStructOut ¶
type ChainedStructOut = ChainedStruct
ChainedStructOut is kept for backward compatibility. Deprecated: Use ChainedStruct. In v29 there is no separate ChainedStructOut in C header.
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 ColorWriteMask ¶
type ColorWriteMask = gputypes.ColorWriteMask
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, error)
BeginComputePass begins a compute pass. Returns an error if the FFI call fails or the encoder is nil.
func (*CommandEncoder) BeginRenderPass ¶
func (enc *CommandEncoder) BeginRenderPass(desc *RenderPassDescriptor) (*RenderPassEncoder, error)
BeginRenderPass begins a render pass. Returns an error if the FFI call fails, encoder is nil, or desc has no color attachments.
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 using low-level wire types. Errors are reported via Device error scopes, not as return values.
func (*CommandEncoder) CopyTextureToBuffer ¶
func (enc *CommandEncoder) CopyTextureToBuffer(src *Texture, dst *Buffer, regions []BufferTextureCopy)
CopyTextureToBuffer copies data from a texture to a buffer. Accepts gogpu/wgpu-compatible types: src *Texture, dst *Buffer, regions []BufferTextureCopy. Each region specifies the buffer layout, texture subresource origin, and copy extent. Errors are reported via Device error scopes, not as return values.
func (*CommandEncoder) CopyTextureToBufferRaw ¶ added in v0.5.0
func (enc *CommandEncoder) CopyTextureToBufferRaw(source *TexelCopyTextureInfo, destination *TexelCopyBufferInfo, copySize *gputypes.Extent3D)
CopyTextureToBufferRaw copies data from a texture to a buffer using low-level wire types. Prefer [CopyTextureToBuffer] for new code.
func (*CommandEncoder) CopyTextureToTexture ¶
func (enc *CommandEncoder) CopyTextureToTexture(src, dst *Texture, regions []TextureCopy)
CopyTextureToTexture copies data from one texture to another. Accepts gogpu/wgpu-compatible types: src *Texture, dst *Texture, regions []TextureCopy. Each region specifies the source and destination subresource origins and copy extent. Errors are reported via Device error scopes, not as return values.
func (*CommandEncoder) CopyTextureToTextureRaw ¶ added in v0.5.0
func (enc *CommandEncoder) CopyTextureToTextureRaw(source *TexelCopyTextureInfo, destination *TexelCopyTextureInfo, copySize *gputypes.Extent3D)
CopyTextureToTextureRaw copies data from one texture to another using low-level wire types. Prefer [CopyTextureToTexture] for new code.
func (*CommandEncoder) Finish ¶
func (enc *CommandEncoder) Finish(desc ...*CommandBufferDescriptor) (*CommandBuffer, error)
Finish finishes recording and returns a command buffer. The optional desc argument allows setting a label; pass nothing for defaults. This variadic signature matches the gogpu/wgpu API for compatibility. Returns an error if the FFI call fails or the encoder is nil.
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 {
Label string
}
CommandEncoderDescriptor describes a command encoder to create.
type CommandEncoderDescriptorGo ¶ added in v0.5.0
type CommandEncoderDescriptorGo = CommandEncoderDescriptor
CommandEncoderDescriptorGo is kept for backward compatibility. Deprecated: Use CommandEncoderDescriptor directly (now Go-idiomatic).
type ComponentSwizzle ¶ added in v0.5.0
type ComponentSwizzle uint32
ComponentSwizzle describes texture component swizzle mapping. New in v29.
const ( // ComponentSwizzleUndefined indicates no value is passed. ComponentSwizzleUndefined ComponentSwizzle = 0x00000000 // ComponentSwizzleZero forces the component value to 0. ComponentSwizzleZero ComponentSwizzle = 0x00000001 // ComponentSwizzleOne forces the component value to 1. ComponentSwizzleOne ComponentSwizzle = 0x00000002 // ComponentSwizzleR takes from the red channel. ComponentSwizzleR ComponentSwizzle = 0x00000003 // ComponentSwizzleG takes from the green channel. ComponentSwizzleG ComponentSwizzle = 0x00000004 // ComponentSwizzleB takes from the blue channel. ComponentSwizzleB ComponentSwizzle = 0x00000005 // ComponentSwizzleA takes from the alpha channel. ComponentSwizzleA ComponentSwizzle = 0x00000006 )
type CompositeAlphaMode ¶
type CompositeAlphaMode = gputypes.CompositeAlphaMode
type ComputePassDescriptor ¶
type ComputePassDescriptor struct {
Label string
TimestampWrites *PassTimestampWrites // optional; use PassTimestampWrites (was ComputePassTimestampWrites)
}
ComputePassDescriptor describes a compute pass (user-facing API).
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 ComputePassTimestampWrites ¶ added in v0.5.0
type ComputePassTimestampWrites = PassTimestampWrites
ComputePassTimestampWrites is a deprecated alias for PassTimestampWrites. Deprecated: Use PassTimestampWrites. Renamed in wgpu-native v29.
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 {
Label string
Layout *PipelineLayout // nil for auto layout
Module *ShaderModule
EntryPoint string
}
ComputePipelineDescriptor describes a compute pipeline to create. Layout is nil for auto layout.
type ComputePipelineDescriptorGo ¶ added in v0.5.0
type ComputePipelineDescriptorGo = ComputePipelineDescriptor
ComputePipelineDescriptorGo is kept for backward compatibility. Deprecated: Use ComputePipelineDescriptor directly (now Go-idiomatic).
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, error)
CreateBindGroup creates a bind group. Returns an error if the FFI call fails or the device/descriptor is nil.
func (*Device) CreateBindGroupLayout ¶
func (d *Device) CreateBindGroupLayout(desc *BindGroupLayoutDescriptor) (*BindGroupLayout, error)
CreateBindGroupLayout creates a bind group layout. Entries are converted from gputypes to wgpu-native enum values before FFI call. Returns an error if the FFI call fails or the device/descriptor is nil.
func (*Device) CreateBindGroupLayoutSimple ¶
func (d *Device) CreateBindGroupLayoutSimple(entries []BindGroupLayoutEntry) (*BindGroupLayout, error)
CreateBindGroupLayoutSimple creates a bind group layout with the given entries. Returns an error if the FFI call fails or the device is nil.
func (*Device) CreateBindGroupSimple ¶
func (d *Device) CreateBindGroupSimple(layout *BindGroupLayout, entries []BindGroupEntry) (*BindGroup, error)
CreateBindGroupSimple creates a bind group with the given entries. Returns an error if the FFI call fails or the device/layout is nil.
func (*Device) CreateBuffer ¶
func (d *Device) CreateBuffer(desc *BufferDescriptor) (*Buffer, error)
CreateBuffer creates a new GPU buffer. Returns an error if the FFI call fails or the device/descriptor is nil.
func (*Device) CreateCommandEncoder ¶
func (d *Device) CreateCommandEncoder(desc *CommandEncoderDescriptor) (*CommandEncoder, error)
CreateCommandEncoder creates a command encoder. Returns an error if the FFI call fails or the device is nil.
func (*Device) CreateComputePipeline ¶
func (d *Device) CreateComputePipeline(desc *ComputePipelineDescriptor) (*ComputePipeline, error)
CreateComputePipeline creates a compute pipeline. Returns an error if the FFI call fails or the device/descriptor is nil.
func (*Device) CreateComputePipelineSimple ¶
func (d *Device) CreateComputePipelineSimple(layout *PipelineLayout, shader *ShaderModule, entryPoint string) (*ComputePipeline, error)
CreateComputePipelineSimple creates a compute pipeline with the given shader and entry point. If layout is nil, auto layout is used. Returns an error if the FFI call fails or the device/shader is nil.
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. Returns nil on error (use CreateTexture directly for full error handling).
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, error)
CreatePipelineLayout creates a pipeline layout. Returns an error if the FFI call fails or the device/descriptor is nil.
func (*Device) CreatePipelineLayoutSimple ¶
func (d *Device) CreatePipelineLayoutSimple(layouts []*BindGroupLayout) (*PipelineLayout, error)
CreatePipelineLayoutSimple creates a pipeline layout with the given bind group layouts. Returns an error if the FFI call fails or the device is nil.
func (*Device) CreateQuerySet ¶
func (d *Device) CreateQuerySet(desc *QuerySetDescriptor) (*QuerySet, error)
CreateQuerySet creates a new QuerySet for GPU profiling/timestamps.
func (*Device) CreateRenderBundleEncoder ¶
func (d *Device) CreateRenderBundleEncoder(desc *RenderBundleEncoderDescriptor) (*RenderBundleEncoder, error)
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, error)
CreateRenderPipeline creates a render pipeline. Returns an error if the FFI call fails or the device/descriptor is nil.
func (*Device) CreateRenderPipelineSimple ¶
func (d *Device) CreateRenderPipelineSimple( layout *PipelineLayout, vertexShader *ShaderModule, vertexEntryPoint string, fragmentShader *ShaderModule, fragmentEntryPoint string, targetFormat gputypes.TextureFormat, ) (*RenderPipeline, error)
CreateRenderPipelineSimple creates a simple render pipeline with common defaults. Returns an error if the FFI call fails or the device/shaders are nil.
func (*Device) CreateSampler ¶
func (d *Device) CreateSampler(desc *SamplerDescriptor) (*Sampler, error)
CreateSampler creates a sampler with the specified descriptor.
func (*Device) CreateShaderModule ¶
func (d *Device) CreateShaderModule(desc *ShaderModuleDescriptor) (*ShaderModule, error)
CreateShaderModule creates a shader module from a descriptor. For WGSL shaders, prefer CreateShaderModuleWGSL or use ShaderDescriptor. Returns an error if the FFI call fails or the device/descriptor is nil.
func (*Device) CreateShaderModuleFromDesc ¶ added in v0.5.0
func (d *Device) CreateShaderModuleFromDesc(desc *ShaderDescriptor) (*ShaderModule, error)
CreateShaderModule creates a shader module from a Go-idiomatic ShaderDescriptor. This is the preferred method name matching the gogpu/wgpu API. If both WGSL and SPIRV are set, WGSL takes precedence. Returns an error if the FFI call fails, the device is nil, or both sources are empty.
Note: there is also a lower-level CreateShaderModule(*ShaderModuleDescriptor) that accepts the wire-level descriptor with a chained struct for direct FFI use.
func (*Device) CreateShaderModuleFromDescriptor
deprecated
added in
v0.5.0
func (d *Device) CreateShaderModuleFromDescriptor(desc *ShaderDescriptor) (*ShaderModule, error)
CreateShaderModuleFromDescriptor creates a shader module from a Go-idiomatic ShaderDescriptor. If both WGSL and SPIRV are set, WGSL takes precedence. Returns an error if the FFI call fails, the device is nil, or both sources are empty.
Deprecated: use CreateShaderModule which has the same signature.
func (*Device) CreateShaderModuleSPIRV ¶ added in v0.5.0
func (d *Device) CreateShaderModuleSPIRV(label string, spirv []uint32) (*ShaderModule, error)
CreateShaderModuleSPIRV creates a shader module from SPIR-V bytecode. Returns an error if the FFI call fails, the device is nil, or the bytecode is empty.
func (*Device) CreateShaderModuleWGSL ¶
func (d *Device) CreateShaderModuleWGSL(code string) (*ShaderModule, error)
CreateShaderModuleWGSL creates a shader module from WGSL source code. Returns an error if the FFI call fails or the device is nil.
func (*Device) CreateTexture ¶
func (d *Device) CreateTexture(desc *TextureDescriptor) (*Texture, error)
CreateTexture creates a texture with the specified descriptor. Enum values are converted from gputypes to wgpu-native values before FFI call. Returns an error if the FFI call fails or the device/descriptor is nil.
func (*Device) Features ¶ added in v0.5.0
func (d *Device) Features() []FeatureName
Features retrieves all features enabled on this device. Returns a slice of FeatureName values.
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) Limits ¶ added in v0.5.0
Limits returns the resource limits of this device.
Limits are cached at device creation time and returned by value. No FFI call is made. Returns zero-value Limits if the device is nil. This matches the gogpu/wgpu API signature for cross-project compatibility.
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 {
// Label is an optional debug label for the device.
Label string
// RequiredFeatures lists GPU features that the device must support.
RequiredFeatures []FeatureName
// RequiredLimits, if non-nil, specifies minimum resource limits the device must meet.
// Pass nil to use the adapter's default limits.
RequiredLimits *Limits
}
DeviceDescriptor configures device creation. Matches the gogpu/wgpu API for cross-project compatibility.
type DeviceLostCallbackInfo ¶ added in v0.5.0
type DeviceLostCallbackInfo struct {
NextInChain uintptr // *ChainedStruct
Mode CallbackMode
Callback uintptr // Function pointer
Userdata1 uintptr
Userdata2 uintptr
}
DeviceLostCallbackInfo configures the device-lost callback.
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 // DeviceLostReasonCallbackCancelled indicates the operation was cancelled (e.g. instance dropped). // Renamed from InstanceDropped in v29. DeviceLostReasonCallbackCancelled DeviceLostReason = 0x00000003 // DeviceLostReasonFailedCreation indicates device creation failed. DeviceLostReasonFailedCreation DeviceLostReason = 0x00000004 // DeviceLostReasonInstanceDropped is a deprecated alias for CallbackCancelled. // Deprecated: Use DeviceLostReasonCallbackCancelled. DeviceLostReasonInstanceDropped = DeviceLostReasonCallbackCancelled )
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 ( // FeatureLevelUndefined indicates no value is passed. Added in v29. FeatureLevelUndefined FeatureLevel = 0x00000000 // 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 ( // FeatureNameCoreFeaturesAndLimits indicates core features and limits support. FeatureNameCoreFeaturesAndLimits FeatureName = 0x00000001 // FeatureNameDepthClipControl enables depth clip control. FeatureNameDepthClipControl FeatureName = 0x00000002 // FeatureNameDepth32FloatStencil8 enables depth32float-stencil8 texture format. FeatureNameDepth32FloatStencil8 FeatureName = 0x00000003 // FeatureNameTextureCompressionBC enables BC texture compression. FeatureNameTextureCompressionBC FeatureName = 0x00000004 // FeatureNameTextureCompressionBCSliced3D enables sliced 3D BC compression. FeatureNameTextureCompressionBCSliced3D FeatureName = 0x00000005 // FeatureNameTextureCompressionETC2 enables ETC2 texture compression. FeatureNameTextureCompressionETC2 FeatureName = 0x00000006 // FeatureNameTextureCompressionASTC enables ASTC texture compression. FeatureNameTextureCompressionASTC FeatureName = 0x00000007 // FeatureNameTextureCompressionASTCSliced3D enables sliced 3D ASTC compression. FeatureNameTextureCompressionASTCSliced3D FeatureName = 0x00000008 // FeatureNameTimestampQuery enables timestamp query support. FeatureNameTimestampQuery FeatureName = 0x00000009 // FeatureNameIndirectFirstInstance enables indirect first instance. FeatureNameIndirectFirstInstance FeatureName = 0x0000000A // FeatureNameShaderF16 enables f16 in shaders. FeatureNameShaderF16 FeatureName = 0x0000000B // FeatureNameRG11B10UfloatRenderable enables RG11B10Ufloat as render target. FeatureNameRG11B10UfloatRenderable FeatureName = 0x0000000C // FeatureNameBGRA8UnormStorage enables BGRA8Unorm storage textures. FeatureNameBGRA8UnormStorage FeatureName = 0x0000000D // FeatureNameFloat32Filterable enables filterable float32 textures. FeatureNameFloat32Filterable FeatureName = 0x0000000E // FeatureNameFloat32Blendable enables blendable float32 textures. FeatureNameFloat32Blendable FeatureName = 0x0000000F // FeatureNameClipDistances enables clip distances in shaders. FeatureNameClipDistances FeatureName = 0x00000010 // FeatureNameDualSourceBlending enables dual source blending. FeatureNameDualSourceBlending FeatureName = 0x00000011 // FeatureNameSubgroups enables subgroup operations. FeatureNameSubgroups FeatureName = 0x00000012 // FeatureNameTextureFormatsTier1 enables tier 1 texture formats. FeatureNameTextureFormatsTier1 FeatureName = 0x00000013 // FeatureNameTextureFormatsTier2 enables tier 2 texture formats. FeatureNameTextureFormatsTier2 FeatureName = 0x00000014 // FeatureNamePrimitiveIndex enables primitive index in shaders. FeatureNamePrimitiveIndex FeatureName = 0x00000015 // FeatureNameTextureComponentSwizzle enables texture component swizzle. FeatureNameTextureComponentSwizzle FeatureName = 0x00000016 )
type Features ¶ added in v0.5.0
Features is a bitmask of enabled GPU features. Note: Limits is defined as a native FFI struct in adapter.go (matches wgpu-native ABI).
type FragmentState ¶
type FragmentState struct {
Module *ShaderModule
EntryPoint string
Targets []ColorTargetState
}
FragmentState describes the fragment stage of a render pipeline.
type ImageCopyTexture ¶ added in v0.5.0
type ImageCopyTexture struct {
Texture *Texture
MipLevel uint32
Origin gputypes.Origin3D
Aspect TextureAspect
}
ImageCopyTexture describes a texture subresource and origin for copy/write operations. Matches gogpu/wgpu ImageCopyTexture.
type ImageDataLayout ¶ added in v0.5.0
ImageDataLayout describes the layout of image data in a buffer. Matches gogpu/wgpu ImageDataLayout.
type IndexFormat ¶
type IndexFormat = gputypes.IndexFormat
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 (all primary backends enabled).
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 InstanceBackend ¶ added in v0.5.0
type InstanceBackend uint64
InstanceBackend is a bitflag selecting which graphics backends to enable. Used in InstanceExtras.Backends.
const ( // InstanceBackendAll enables all available backends (default when zero). InstanceBackendAll InstanceBackend = 0x00000000 // InstanceBackendVulkan enables the Vulkan backend. InstanceBackendVulkan InstanceBackend = 1 << 0 // InstanceBackendGL enables the OpenGL/OpenGL ES backend. InstanceBackendGL InstanceBackend = 1 << 1 // InstanceBackendMetal enables the Metal backend (macOS/iOS). InstanceBackendMetal InstanceBackend = 1 << 2 // InstanceBackendDX12 enables the Direct3D 12 backend (Windows). InstanceBackendDX12 InstanceBackend = 1 << 3 // InstanceBackendBrowserWebGPU enables the browser WebGPU backend (WASM). InstanceBackendBrowserWebGPU InstanceBackend = 1 << 5 // InstanceBackendPrimary enables primary tier backends: Vulkan, Metal, DX12, BrowserWebGPU. InstanceBackendPrimary InstanceBackend = (1 << 0) | (1 << 2) | (1 << 3) | (1 << 5) // InstanceBackendSecondary enables secondary tier backends: GL only. // BREAKING: v27 had Secondary = GL | DX11; DX11 was removed in v29. InstanceBackendSecondary InstanceBackend = (1 << 1) )
type InstanceDescriptor ¶
type InstanceDescriptor struct {
// Backends selects which GPU backends to enable.
// Use gputypes.BackendsPrimary (default) or specific backends.
Backends gputypes.Backends
// Flags controls instance features like debug layers and validation.
// Use gputypes.InstanceFlagsDebug to enable GPU debug layer.
Flags gputypes.InstanceFlags
}
InstanceDescriptor configures instance creation. Matches the gogpu/wgpu API for cross-project compatibility.
Pass nil to CreateInstance for default configuration (all primary backends enabled).
type InstanceFeatureName ¶ added in v0.5.0
type InstanceFeatureName uint32
InstanceFeatureName describes features that can be required at instance creation. New in v29.
const ( // InstanceFeatureNameTimedWaitAny enables wgpuInstanceWaitAny with timeoutNS > 0. InstanceFeatureNameTimedWaitAny InstanceFeatureName = 0x00000001 // InstanceFeatureNameShaderSourceSPIRV enables SPIR-V shader sources. InstanceFeatureNameShaderSourceSPIRV InstanceFeatureName = 0x00000002 // InstanceFeatureNameMultipleDevicesPerAdapter allows multiple devices per adapter. InstanceFeatureNameMultipleDevicesPerAdapter InstanceFeatureName = 0x00000003 )
type InstanceFlag ¶ added in v0.5.0
type InstanceFlag uint64
InstanceFlag is a bitflag controlling instance debugging and validation behavior. Used in InstanceExtras.Flags.
const ( // InstanceFlagEmpty has no flags set. Zero-initialization default. // BREAKING: v27 had Default=0; v29 renamed to Empty=0, Default moved to 1<<24. InstanceFlagEmpty InstanceFlag = 0x00000000 // InstanceFlagDebug generates debug information in shaders and objects. InstanceFlagDebug InstanceFlag = 1 << 0 // InstanceFlagValidation enables validation in the backend API. InstanceFlagValidation InstanceFlag = 1 << 1 // InstanceFlagDiscardHalLabels suppresses label passing to backend HAL. InstanceFlagDiscardHalLabels InstanceFlag = 1 << 2 // InstanceFlagAllowUnderlyingNoncompliantAdapter exposes adapters on non-compliant drivers. InstanceFlagAllowUnderlyingNoncompliantAdapter InstanceFlag = 1 << 3 // InstanceFlagGPUBasedValidation enables GPU-based validation (implies Validation). InstanceFlagGPUBasedValidation InstanceFlag = 1 << 4 // InstanceFlagValidationIndirectCall validates indirect buffer content before indirect draws. InstanceFlagValidationIndirectCall InstanceFlag = 1 << 5 // InstanceFlagAutomaticTimestampNormalization normalizes timestamps to nanoseconds. InstanceFlagAutomaticTimestampNormalization InstanceFlag = 1 << 6 // InstanceFlagDefault uses the default flags for the current build configuration. // BREAKING: v27 had Default=0; v29 Default=1<<24 (debug builds enable Debug+Validation). InstanceFlagDefault InstanceFlag = 1 << 24 // InstanceFlagDebugging enables Debug and Validation. InstanceFlagDebugging InstanceFlag = 1 << 25 // InstanceFlagAdvancedDebugging enables Debug, Validation, and GPUBasedValidation. InstanceFlagAdvancedDebugging InstanceFlag = 1 << 26 // InstanceFlagWithEnv reads flag overrides from environment variables. InstanceFlagWithEnv InstanceFlag = 1 << 27 )
type InstanceLimits ¶ added in v0.5.0
type InstanceLimits struct {
NextInChain uintptr // *ChainedStruct (nullable)
TimedWaitAnyMaxCount uint64
}
InstanceLimits describes the limits required at instance creation. New in v29 — passed as RequiredLimits in instanceDescriptorWire.
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 is the maximum 1D texture dimension.
MaxTextureDimension1D uint32
// MaxTextureDimension2D is the maximum 2D texture dimension.
MaxTextureDimension2D uint32
// MaxTextureDimension3D is the maximum 3D texture dimension.
MaxTextureDimension3D uint32
// MaxTextureArrayLayers is the maximum texture array layer count.
MaxTextureArrayLayers uint32
// MaxBindGroups is the maximum number of bind groups.
MaxBindGroups uint32
// MaxBindGroupsPlusVertexBuffers is the max bind groups + vertex buffers.
MaxBindGroupsPlusVertexBuffers uint32
// MaxBindingsPerBindGroup is the max bindings per bind group.
MaxBindingsPerBindGroup uint32
// MaxDynamicUniformBuffersPerPipelineLayout is the max dynamic uniform buffers.
MaxDynamicUniformBuffersPerPipelineLayout uint32
// MaxDynamicStorageBuffersPerPipelineLayout is the max dynamic storage buffers.
MaxDynamicStorageBuffersPerPipelineLayout uint32
// MaxSampledTexturesPerShaderStage is the max sampled textures per shader stage.
MaxSampledTexturesPerShaderStage uint32
// MaxSamplersPerShaderStage is the max samplers per shader stage.
MaxSamplersPerShaderStage uint32
// MaxStorageBuffersPerShaderStage is the max storage buffers per shader stage.
MaxStorageBuffersPerShaderStage uint32
// MaxStorageTexturesPerShaderStage is the max storage textures per shader stage.
MaxStorageTexturesPerShaderStage uint32
// MaxUniformBuffersPerShaderStage is the max uniform buffers per shader stage.
MaxUniformBuffersPerShaderStage uint32
// MaxUniformBufferBindingSize is the max uniform buffer binding size in bytes.
MaxUniformBufferBindingSize uint64
// MaxStorageBufferBindingSize is the max storage buffer binding size in bytes.
MaxStorageBufferBindingSize uint64
// MinUniformBufferOffsetAlignment is the minimum uniform buffer offset alignment.
MinUniformBufferOffsetAlignment uint32
// MinStorageBufferOffsetAlignment is the minimum storage buffer offset alignment.
MinStorageBufferOffsetAlignment uint32
// MaxVertexBuffers is the max vertex buffers in a pipeline.
MaxVertexBuffers uint32
// MaxBufferSize is the max buffer size in bytes.
MaxBufferSize uint64
// MaxVertexAttributes is the max vertex attributes in a pipeline.
MaxVertexAttributes uint32
// MaxVertexBufferArrayStride is the max vertex buffer array stride.
MaxVertexBufferArrayStride uint32
// MaxInterStageShaderVariables is the max inter-stage shader variables.
MaxInterStageShaderVariables uint32
// MaxColorAttachments is the max color attachments in a render pass.
MaxColorAttachments uint32
// MaxColorAttachmentBytesPerSample is the max bytes per sample for color attachments.
MaxColorAttachmentBytesPerSample uint32
// MaxComputeWorkgroupStorageSize is the max compute workgroup storage in bytes.
MaxComputeWorkgroupStorageSize uint32
// MaxComputeInvocationsPerWorkgroup is the max compute invocations per workgroup.
MaxComputeInvocationsPerWorkgroup uint32
// MaxComputeWorkgroupSizeX is the max compute workgroup size in X dimension.
MaxComputeWorkgroupSizeX uint32
// MaxComputeWorkgroupSizeY is the max compute workgroup size in Y dimension.
MaxComputeWorkgroupSizeY uint32
// MaxComputeWorkgroupSizeZ is the max compute workgroup size in Z dimension.
MaxComputeWorkgroupSizeZ uint32
// MaxComputeWorkgroupsPerDimension is the max compute workgroups per dimension.
MaxComputeWorkgroupsPerDimension uint32
}
Limits describes GPU resource limits for an adapter or device.
This type matches the gogpu/wgpu API for cross-project compatibility. Limits are cached at creation time (RequestAdapter/RequestDevice) and returned by value — no FFI call is made on each access.
Note: wgpu-native-specific fields (MaxImmediateSize, MaxNonSamplerBindings) are not exposed here. Use NativeLimits for native extensions.
type MapAsyncStatus ¶
type MapAsyncStatus uint32
MapAsyncStatus is the status returned by MapAsync callback.
const ( // MapAsyncStatusSuccess indicates the buffer was successfully mapped. MapAsyncStatusSuccess MapAsyncStatus = 0x00000001 // MapAsyncStatusCallbackCancelled indicates the callback was cancelled. MapAsyncStatusCallbackCancelled MapAsyncStatus = 0x00000002 // MapAsyncStatusError indicates a mapping error occurred. MapAsyncStatusError MapAsyncStatus = 0x00000003 // MapAsyncStatusAborted indicates the mapping was aborted (e.g., buffer destroyed). MapAsyncStatusAborted MapAsyncStatus = 0x00000004 // Deprecated: use MapAsyncStatusCallbackCancelled. MapAsyncStatusInstanceDropped = MapAsyncStatusCallbackCancelled )
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 MapPending ¶ added in v0.5.0
type MapPending struct {
// contains filtered or unexported fields
}
MapPending represents an in-flight buffer map request. Created by Buffer.MapAsync; poll Status() or call Wait() to resolve.
The caller must not access the mapped buffer data until Status() returns ready=true with err=nil, or Wait() returns nil.
func (*MapPending) Release ¶ added in v0.5.0
func (p *MapPending) Release()
Release discards the pending handle. Safe to call after Wait/Status resolved.
func (*MapPending) Status ¶ added in v0.5.0
func (p *MapPending) Status() (ready bool, err error)
Status reports whether the map request has completed. Non-blocking — returns (false, nil) if still pending. Once it returns (true, ...), subsequent calls return the same value.
type MappedRange ¶ added in v0.5.0
type MappedRange struct {
// contains filtered or unexported fields
}
MappedRange provides safe access to a mapped buffer region. Obtained via Buffer.MappedRange after a successful Buffer.Map or Buffer.MapAsync. The data slice is invalidated by Buffer.Unmap.
Matches gogpu/wgpu MappedRange.
func (*MappedRange) Bytes ¶ added in v0.5.0
func (m *MappedRange) Bytes() []byte
Bytes returns the mapped memory as a byte slice. Returns nil if the buffer is not mapped or the range has been invalidated.
The slice is valid only while the buffer remains mapped. Calling Buffer.Unmap or Buffer.Release after this will cause undefined behavior if the slice is still accessed.
func (*MappedRange) Len ¶ added in v0.5.0
func (m *MappedRange) Len() int
Len returns the size of the mapped range in bytes.
func (*MappedRange) Offset ¶ added in v0.5.0
func (m *MappedRange) Offset() uint64
Offset returns the byte offset of this range within the buffer.
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 MipmapFilterMode ¶
type MipmapFilterMode = gputypes.MipmapFilterMode
type MultisampleState ¶
MultisampleState describes multisampling.
type NativeDisplayHandleType ¶ added in v0.5.0
type NativeDisplayHandleType uint32
NativeDisplayHandleType identifies the platform display connection type. Used in NativeDisplayHandle.Type. New in v29.
const ( // NativeDisplayHandleTypeNone indicates no display handle. Default (zero-init). NativeDisplayHandleTypeNone NativeDisplayHandleType = 0x00000000 // NativeDisplayHandleTypeXlib is an X11 display via Xlib. NativeDisplayHandleTypeXlib NativeDisplayHandleType = 0x00000001 // NativeDisplayHandleTypeXcb is an X11 display via XCB. NativeDisplayHandleTypeXcb NativeDisplayHandleType = 0x00000002 // NativeDisplayHandleTypeWayland is a Wayland display connection. NativeDisplayHandleTypeWayland NativeDisplayHandleType = 0x00000003 )
type NativeFeature ¶ added in v0.5.0
type NativeFeature uint32
NativeFeature describes a wgpu-native extension feature.
const ( // NativeFeatureImmediates enables immediate data (push constants replacement). // Renamed from PushConstants in v29. NativeFeatureImmediates NativeFeature = 0x00030001 // NativeFeaturePushConstants is a deprecated alias for Immediates. // Deprecated: Use NativeFeatureImmediates. NativeFeaturePushConstants = NativeFeatureImmediates // NativeFeatureTextureAdapterSpecificFormatFeatures enables device-specific texture format features. NativeFeatureTextureAdapterSpecificFormatFeatures NativeFeature = 0x00030002 // NativeFeatureMultiDrawIndirectCount enables indirect draw count. NativeFeatureMultiDrawIndirectCount NativeFeature = 0x00030004 // NativeFeatureVertexWritableStorage enables vertex shader writable storage. NativeFeatureVertexWritableStorage NativeFeature = 0x00030005 // NativeFeatureTextureBindingArray enables texture binding arrays. NativeFeatureTextureBindingArray NativeFeature = 0x00030006 // NativeFeatureSampledTextureAndStorageBufferArrayNonUniformIndexing enables non-uniform indexing. NativeFeatureSampledTextureAndStorageBufferArrayNonUniformIndexing NativeFeature = 0x00030007 // NativeFeaturePipelineStatisticsQuery enables pipeline statistics queries. NativeFeaturePipelineStatisticsQuery NativeFeature = 0x00030008 // NativeFeatureStorageResourceBindingArray enables storage resource binding arrays. NativeFeatureStorageResourceBindingArray NativeFeature = 0x00030009 // NativeFeaturePartiallyBoundBindingArray enables partially bound binding arrays. NativeFeaturePartiallyBoundBindingArray NativeFeature = 0x0003000A // NativeFeatureTextureFormat16bitNorm enables normalized 16-bit texture formats. NativeFeatureTextureFormat16bitNorm NativeFeature = 0x0003000B // NativeFeatureTextureCompressionAstcHdr enables ASTC HDR compression. NativeFeatureTextureCompressionAstcHdr NativeFeature = 0x0003000C // NativeFeatureMappablePrimaryBuffers enables mappable primary buffers. NativeFeatureMappablePrimaryBuffers NativeFeature = 0x0003000E // NativeFeatureBufferBindingArray enables buffer binding arrays. NativeFeatureBufferBindingArray NativeFeature = 0x0003000F // NativeFeatureUniformBufferAndStorageTextureArrayNonUniformIndexing enables non-uniform indexing for these types. NativeFeatureUniformBufferAndStorageTextureArrayNonUniformIndexing NativeFeature = 0x00030010 // NativeFeaturePolygonModeLine enables polygon line mode. NativeFeaturePolygonModeLine NativeFeature = 0x00030013 // NativeFeaturePolygonModePoint enables polygon point mode. NativeFeaturePolygonModePoint NativeFeature = 0x00030014 // NativeFeatureConservativeRasterization enables conservative rasterization. NativeFeatureConservativeRasterization NativeFeature = 0x00030015 // NativeFeatureSpirvShaderPassthrough enables SPIR-V shader passthrough. NativeFeatureSpirvShaderPassthrough NativeFeature = 0x00030017 // NativeFeatureVertexAttribute64bit enables 64-bit vertex attributes. NativeFeatureVertexAttribute64bit NativeFeature = 0x00030019 // NativeFeatureTextureFormatNv12 enables NV12 texture format. NativeFeatureTextureFormatNv12 NativeFeature = 0x0003001A // NativeFeatureRayQuery enables ray query in shaders. NativeFeatureRayQuery NativeFeature = 0x0003001C // NativeFeatureShaderF64 enables f64 in shaders. NativeFeatureShaderF64 NativeFeature = 0x0003001D // NativeFeatureShaderI16 enables i16 in shaders. NativeFeatureShaderI16 NativeFeature = 0x0003001E // NativeFeatureShaderEarlyDepthTest enables early depth test attribute in shaders. NativeFeatureShaderEarlyDepthTest NativeFeature = 0x00030020 // NativeFeatureSubgroup enables subgroup operations in compute/fragment shaders. NativeFeatureSubgroup NativeFeature = 0x00030021 // NativeFeatureSubgroupVertex enables subgroup operations in vertex shaders. NativeFeatureSubgroupVertex NativeFeature = 0x00030022 // NativeFeatureSubgroupBarrier enables subgroup barrier in compute shaders. NativeFeatureSubgroupBarrier NativeFeature = 0x00030023 // NativeFeatureTimestampQueryInsideEncoders enables timestamp queries on command encoders. NativeFeatureTimestampQueryInsideEncoders NativeFeature = 0x00030024 // NativeFeatureTimestampQueryInsidePasses enables timestamp queries inside render/compute passes. NativeFeatureTimestampQueryInsidePasses NativeFeature = 0x00030025 // NativeFeatureShaderInt64 enables i64/u64 in shaders. NativeFeatureShaderInt64 NativeFeature = 0x00030026 )
type NativeLimits ¶ added in v0.5.0
type NativeLimits struct {
Chain ChainedStruct // chain.SType must be STypeNativeLimits
MaxImmediateSize uint32 // was maxPushConstantSize in v27
MaxNonSamplerBindings uint32 // max live non-sampler bindings (DX12 only)
MaxBindingArrayElementsPerShaderStage uint32 // max resources in binding arrays per shader stage
}
NativeLimits extends WGPULimits with wgpu-native specific limits. Chain via NextInChain in Limits with SType = STypeNativeLimits. v29 BREAKING: maxPushConstantSize renamed to maxImmediateSize; maxNonSamplerBindings and maxBindingArrayElementsPerShaderStage added.
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 PassTimestampWrites ¶ added in v0.5.0
type PassTimestampWrites struct {
QuerySet *QuerySet
BeginningOfPassWriteIndex uint32 // Use TimestampLocationUndefined to disable
EndOfPassWriteIndex uint32 // Use TimestampLocationUndefined to disable
}
PassTimestampWrites describes timestamp writes for a render or compute pass. v29: Unified struct — replaces separate RenderPassTimestampWrites and ComputePassTimestampWrites.
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 {
Label string
BindGroupLayouts []*BindGroupLayout
}
PipelineLayoutDescriptor describes a pipeline layout to create. BindGroupLayouts is a slice of *BindGroupLayout; nil for auto layout.
type PipelineLayoutDescriptorGo ¶ added in v0.5.0
type PipelineLayoutDescriptorGo = PipelineLayoutDescriptor
PipelineLayoutDescriptorGo is kept for backward compatibility. Deprecated: Use PipelineLayoutDescriptor directly (now Go-idiomatic).
type PipelineLayoutExtras ¶ added in v0.5.0
type PipelineLayoutExtras struct {
Chain ChainedStruct // chain.SType must be STypePipelineLayoutExtras
ImmediateDataSize uint32 // bytes of immediate data for shaders (requires NativeFeatureImmediates)
}
PipelineLayoutExtras provides wgpu-native specific pipeline layout extensions. Chain via NextInChain in PipelineLayoutDescriptor with SType = STypePipelineLayoutExtras. v29 BREAKING: pushConstantRangeCount/pushConstantRanges replaced by immediateDataSize.
type PopErrorScopeStatus ¶
type PopErrorScopeStatus uint32
PopErrorScopeStatus describes the result of PopErrorScope operation.
const ( // PopErrorScopeStatusSuccess indicates the error scope was successfully popped. PopErrorScopeStatusSuccess PopErrorScopeStatus = 0x00000001 // PopErrorScopeStatusCallbackCancelled indicates the operation was cancelled (e.g. instance dropped). // Renamed from InstanceDropped in v29. PopErrorScopeStatusCallbackCancelled PopErrorScopeStatus = 0x00000002 // PopErrorScopeStatusError indicates the error scope stack was empty or another error occurred. // Renamed from EmptyStack in v29. PopErrorScopeStatusError PopErrorScopeStatus = 0x00000003 // PopErrorScopeStatusInstanceDropped is a deprecated alias for CallbackCancelled. // Deprecated: Use PopErrorScopeStatusCallbackCancelled. PopErrorScopeStatusInstanceDropped = PopErrorScopeStatusCallbackCancelled // PopErrorScopeStatusEmptyStack is a deprecated alias for Error. // Deprecated: Use PopErrorScopeStatusError. PopErrorScopeStatusEmptyStack = PopErrorScopeStatusError )
type PredefinedColorSpace ¶ added in v0.5.0
type PredefinedColorSpace uint32
PredefinedColorSpace describes a color space for surface color management. New in v29.
const ( // PredefinedColorSpaceSRGB is the standard sRGB color space. PredefinedColorSpaceSRGB PredefinedColorSpace = 0x00000001 // PredefinedColorSpaceDisplayP3 is the Display P3 wide-gamut color space. PredefinedColorSpaceDisplayP3 PredefinedColorSpace = 0x00000002 )
type PrimitiveState ¶
type PrimitiveState struct {
Topology gputypes.PrimitiveTopology
StripIndexFormat gputypes.IndexFormat
FrontFace gputypes.FrontFace
CullMode gputypes.CullMode
}
PrimitiveState describes how primitives are assembled.
type PrimitiveTopology ¶
type PrimitiveTopology = gputypes.PrimitiveTopology
Primitive assembly types.
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.Queue, release with Queue.Release.
func (*Queue) Submit ¶
func (q *Queue) Submit(commands ...*CommandBuffer) (uint64, error)
Submit submits command buffers for execution. Returns the submission index (uint64) and nil on success. The submission index can be used with Device.Poll to track when work completes. Matches gogpu/wgpu Queue.Submit(commands ...*CommandBuffer) (uint64, error).
func (*Queue) WriteBuffer ¶
WriteBuffer writes data to a buffer. Returns nil on success. In this FFI implementation errors are surfaced through the Device uncaptured-error callback; the signature matches gogpu/wgpu for API compatibility.
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 *ImageCopyTexture, data []byte, layout *ImageDataLayout, size *gputypes.Extent3D) error
WriteTexture writes data to a texture. Returns nil on success. In this FFI implementation errors are surfaced through the Device uncaptured-error callback; the signature matches gogpu/wgpu for API compatibility.
Accepts either ImageCopyTexture or TexelCopyTextureInfo as dest (via overloads below). This overload takes the high-level ImageCopyTexture type.
func (*Queue) WriteTextureRaw ¶ added in v0.5.0
func (q *Queue) WriteTextureRaw(dest *TexelCopyTextureInfo, data []byte, layout *TexelCopyBufferLayout, size *gputypes.Extent3D) error
WriteTextureRaw writes data to a texture using the low-level wire types. Prefer [WriteTexture] for new code.
type QueueDescriptor ¶ added in v0.5.0
type QueueDescriptor struct {
NextInChain uintptr // *ChainedStruct
Label StringView
}
QueueDescriptor configures queue creation.
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. The optional desc parameter allows specifying a label; if omitted, nil is used.
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 string
ColorFormats []gputypes.TextureFormat
DepthStencilFormat gputypes.TextureFormat
SampleCount uint32
DepthReadOnly bool
StencilReadOnly bool
}
RenderBundleEncoderDescriptor describes a render bundle encoder to create.
type RenderBundleEncoderDescriptorGo ¶ added in v0.5.0
type RenderBundleEncoderDescriptorGo = RenderBundleEncoderDescriptor
RenderBundleEncoderDescriptorGo is kept for backward compatibility. Deprecated: Use RenderBundleEncoderDescriptor directly (now Go-idiomatic).
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 = PassTimestampWrites
RenderPassTimestampWrites is a deprecated alias for PassTimestampWrites. Deprecated: Use PassTimestampWrites. Renamed in wgpu-native v29.
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 {
// PowerPreference indicates power consumption preference.
PowerPreference gputypes.PowerPreference
// ForceFallbackAdapter forces the use of a software adapter.
ForceFallbackAdapter bool
// CompatibleSurface, if non-nil, restricts adapter selection to those
// compatible with rendering to the given surface.
CompatibleSurface *Surface
}
RequestAdapterOptions configures adapter selection. Matches the gogpu/wgpu API for cross-project compatibility.
type RequestAdapterStatus ¶
type RequestAdapterStatus uint32
RequestAdapterStatus is the status returned by RequestAdapter callback.
const ( // RequestAdapterStatusSuccess indicates the adapter was successfully obtained. RequestAdapterStatusSuccess RequestAdapterStatus = 0x00000001 // RequestAdapterStatusCallbackCancelled indicates the operation was cancelled (e.g. instance dropped). // Renamed from InstanceDropped in v29. RequestAdapterStatusCallbackCancelled RequestAdapterStatus = 0x00000002 RequestAdapterStatusUnavailable RequestAdapterStatus = 0x00000003 // RequestAdapterStatusError indicates an error occurred during adapter request. RequestAdapterStatusError RequestAdapterStatus = 0x00000004 // RequestAdapterStatusInstanceDropped is a deprecated alias for CallbackCancelled. // Deprecated: Use RequestAdapterStatusCallbackCancelled. RequestAdapterStatusInstanceDropped = RequestAdapterStatusCallbackCancelled )
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 // RequestDeviceStatusCallbackCancelled indicates the operation was cancelled (e.g. instance dropped). // Renamed from InstanceDropped in v29. RequestDeviceStatusCallbackCancelled RequestDeviceStatus = 0x00000002 // RequestDeviceStatusError indicates an error occurred during device request. RequestDeviceStatusError RequestDeviceStatus = 0x00000003 // RequestDeviceStatusInstanceDropped is a deprecated alias for CallbackCancelled. // Deprecated: Use RequestDeviceStatusCallbackCancelled. RequestDeviceStatusInstanceDropped = RequestDeviceStatusCallbackCancelled )
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 // STypeRenderPassMaxDrawCount identifies the max draw count chained struct. STypeRenderPassMaxDrawCount SType = 0x00000003 // 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 // STypeSurfaceColorManagement identifies a surface color management chained struct. New in v29. STypeSurfaceColorManagement SType = 0x0000000A // STypeRequestAdapterWebXROptions identifies WebXR adapter options. New in v29. STypeRequestAdapterWebXROptions SType = 0x0000000B // STypeTextureComponentSwizzleDescriptor identifies a texture component swizzle descriptor. New in v29. STypeTextureComponentSwizzleDescriptor SType = 0x0000000C // STypeExternalTextureBindingLayout identifies an external texture binding layout. New in v29. STypeExternalTextureBindingLayout SType = 0x0000000D // STypeExternalTextureBindingEntry identifies an external texture binding entry. New in v29. STypeExternalTextureBindingEntry SType = 0x0000000E // STypeCompatibilityModeLimits identifies compat-mode limits. New in v29. STypeCompatibilityModeLimits SType = 0x0000000F // STypeTextureBindingViewDimension identifies a texture binding view dimension. New in v29. STypeTextureBindingViewDimension SType = 0x00000010 // STypeDeviceExtras identifies wgpu-native device extras chained struct. STypeDeviceExtras SType = 0x00030001 // STypeNativeLimits identifies wgpu-native native limits chained struct. STypeNativeLimits SType = 0x00030002 // STypePipelineLayoutExtras identifies wgpu-native pipeline layout extras chained struct. STypePipelineLayoutExtras SType = 0x00030003 // STypeShaderSourceGLSL identifies a GLSL shader source chained struct (wgpu-native extension). STypeShaderSourceGLSL SType = 0x00030004 // STypeInstanceExtras identifies wgpu-native instance extras chained struct. STypeInstanceExtras SType = 0x00030006 // STypeBindGroupEntryExtras identifies wgpu-native bind group entry extras. STypeBindGroupEntryExtras SType = 0x00030007 // STypeBindGroupLayoutEntryExtras identifies wgpu-native bind group layout entry extras. STypeBindGroupLayoutEntryExtras SType = 0x00030008 // STypeQuerySetDescriptorExtras identifies wgpu-native query set descriptor extras. STypeQuerySetDescriptorExtras SType = 0x00030009 // STypeSurfaceConfigurationExtras identifies wgpu-native surface configuration extras. STypeSurfaceConfigurationExtras SType = 0x0003000A // STypeSurfaceSourceSwapChainPanel identifies a WinUI SwapChainPanel surface source. STypeSurfaceSourceSwapChainPanel SType = 0x0003000B // STypePrimitiveStateExtras identifies wgpu-native primitive state extras. STypePrimitiveStateExtras SType = 0x0003000C )
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 = gputypes.SamplerBindingLayout
SamplerBindingLayout describes sampler binding properties.
This type matches gputypes.SamplerBindingLayout for cross-project compatibility. Used as a pointer field in BindGroupLayoutEntry; nil means "not a sampler binding".
type SamplerBindingType ¶
type SamplerBindingType = gputypes.SamplerBindingType
type SamplerDescriptor ¶
type SamplerDescriptor struct {
Label string
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
// Anisotropy is the maximum anisotropy level for anisotropic filtering.
// wgpu-native requires a value >= 1; 0 is automatically clamped to 1.
Anisotropy uint16
}
SamplerDescriptor describes a sampler to create.
type ShaderDescriptor ¶ added in v0.5.0
type ShaderDescriptor struct {
Label string
WGSL string // WGSL source code
SPIRV []uint32 // SPIR-V bytecode (alternative to WGSL)
}
ShaderDescriptor is the Go-idiomatic descriptor for creating a shader module. Use WGSL to specify WGSL source, or SPIRV for SPIR-V bytecode. If both are set, WGSL takes precedence. Use Device.CreateShaderModule or Device.CreateShaderModuleFromDescriptor to create from this.
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 ShaderModuleDescriptorGo ¶ added in v0.5.0
type ShaderModuleDescriptorGo = ShaderDescriptor
ShaderModuleDescriptorGo is an alias for ShaderDescriptor. Use this name when matching the gogpu/wgpu naming convention.
type ShaderSourceWGSL ¶
type ShaderSourceWGSL struct {
Chain ChainedStruct
Code StringView
}
ShaderSourceWGSL provides WGSL source code for shader creation.
type ShaderStage ¶
type ShaderStage = gputypes.ShaderStage
Shader stage type. ShaderStage is the uint32 bitflag for individual stages (vertex/fragment/compute). ShaderStages is an alias for the same type for use in pipeline descriptors.
type ShaderStages ¶ added in v0.5.0
type ShaderStages = gputypes.ShaderStages
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 StencilOperation ¶
type StencilOperation = gputypes.StencilOperation
type StorageTextureBindingLayout ¶
type StorageTextureBindingLayout = gputypes.StorageTextureBindingLayout
StorageTextureBindingLayout describes storage texture binding properties.
This type matches gputypes.StorageTextureBindingLayout for cross-project compatibility. Used as a pointer field in BindGroupLayoutEntry; nil means "not a storage texture binding".
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
type SupportedFeatures struct {
FeatureCount uintptr // size_t
Features uintptr // *FeatureName (C-allocated, must free with SupportedFeaturesFreeMembers)
}
SupportedFeatures contains features supported by adapter or device. This is the wire format for wgpuAdapterGetFeatures/wgpuDeviceGetFeatures (v29 single-call API). Call SupportedFeaturesFreeMembers after use to release C-allocated memory.
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(device *Device, config *SurfaceConfiguration) error
Configure configures the surface for rendering. The device argument specifies which logical device to use for the surface. If config.Device is also set (deprecated usage), it takes precedence over the device arg. Returns nil on success. Errors are surfaced through the Device uncaptured-error callback in this FFI implementation; the error return matches the gogpu/wgpu API signature. This replaces the deprecated SwapChain API. Enum values are converted from gputypes to wgpu-native values before FFI call.
func (*Surface) ConfigureLegacy ¶ added in v0.5.0
func (s *Surface) ConfigureLegacy(config *SurfaceConfiguration)
ConfigureLegacy configures the surface using only the config struct (legacy API). Deprecated: use Configure(device, config) instead.
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, bool, error)
GetCurrentTexture gets the current texture to render to. Returns the texture, a suboptimal flag (true if the surface needs reconfiguration but is still usable this frame), and any error. This matches the gogpu/wgpu API.
func (*Surface) Present ¶
func (s *Surface) Present(texture ...*SurfaceTexture) error
Present presents the current frame to the surface. The texture argument is accepted for API compatibility with gogpu/wgpu but is unused in the FFI implementation (wgpuSurfacePresent takes no texture arg). Returns nil on success.
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 is deprecated: pass the device to Configure() directly instead.
// Kept for backward compatibility. If non-nil, overrides the explicit device argument.
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. Note: the Device field is deprecated — pass the device as a separate argument to Configure. It remains here for backward compatibility; if non-nil it takes precedence over the explicit arg.
type SurfaceGetCurrentTextureStatus ¶
type SurfaceGetCurrentTextureStatus uint32
SurfaceGetCurrentTextureStatus describes the result of GetCurrentTexture.
const ( // SurfaceGetCurrentTextureStatusSuccessOptimal indicates the texture was obtained optimally. SurfaceGetCurrentTextureStatusSuccessOptimal SurfaceGetCurrentTextureStatus = 0x00000001 // SurfaceGetCurrentTextureStatusSuccessSuboptimal indicates the texture was obtained but may not be optimal. SurfaceGetCurrentTextureStatusSuccessSuboptimal SurfaceGetCurrentTextureStatus = 0x00000002 // SurfaceGetCurrentTextureStatusTimeout indicates the operation timed out. SurfaceGetCurrentTextureStatusTimeout SurfaceGetCurrentTextureStatus = 0x00000003 // SurfaceGetCurrentTextureStatusOutdated indicates the surface needs reconfiguration. SurfaceGetCurrentTextureStatusOutdated SurfaceGetCurrentTextureStatus = 0x00000004 // SurfaceGetCurrentTextureStatusLost indicates the surface was lost and must be recreated. SurfaceGetCurrentTextureStatusLost SurfaceGetCurrentTextureStatus = 0x00000005 // SurfaceGetCurrentTextureStatusError indicates a deterministic error (e.g. surface not configured). // BREAKING: v27 had OutOfMemory=0x06, DeviceLost=0x07, Error=0x08; v29 collapsed to Error=0x06. SurfaceGetCurrentTextureStatusError SurfaceGetCurrentTextureStatus = 0x00000006 // NativeSurfaceGetCurrentTextureStatusOccluded is a wgpu-native extension status. // Returned on macOS Metal when the window is occluded/minimized. NativeSurfaceGetCurrentTextureStatusOccluded SurfaceGetCurrentTextureStatus = 0x00030001 )
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 (low-level wire type). Prefer ImageDataLayout for new code.
type TexelCopyTextureInfo ¶
type TexelCopyTextureInfo struct {
Texture uintptr
MipLevel uint32
Origin gputypes.Origin3D
Aspect TextureAspect
}
TexelCopyTextureInfo describes a texture for WriteTexture (low-level wire type). Prefer ImageCopyTexture for new code — it holds a *Texture handle.
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, error)
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. Returns an error if the FFI call fails or the texture is nil.
func (*Texture) DepthOrArrayLayers ¶ added in v0.5.0
DepthOrArrayLayers returns the depth (for 3D textures) or array layer count.
func (*Texture) Format ¶ added in v0.5.0
func (t *Texture) Format() gputypes.TextureFormat
Format returns the texture format. TextureFormat values match between gputypes v0.3.0 and wgpu-native v29 exactly.
func (*Texture) MipLevelCount ¶ added in v0.5.0
MipLevelCount 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 = gputypes.TextureBindingLayout
TextureBindingLayout describes texture binding properties.
This type matches gputypes.TextureBindingLayout for cross-project compatibility. Used as a pointer field in BindGroupLayoutEntry; nil means "not a texture binding".
type TextureCopy ¶ added in v0.5.0
type TextureCopy struct {
// Source describes the source texture subresource and origin.
Source ImageCopyTexture
// Destination describes the destination texture subresource and origin.
Destination ImageCopyTexture
// Size is the extent of the copy operation.
Size gputypes.Extent3D
}
TextureCopy describes a texture-to-texture copy region. Matches gogpu/wgpu TextureCopy.
type TextureDescriptor ¶
type TextureDescriptor struct {
Label string
Usage gputypes.TextureUsage
Dimension gputypes.TextureDimension
Size gputypes.Extent3D
Format gputypes.TextureFormat
MipLevelCount uint32
SampleCount uint32
ViewFormats []gputypes.TextureFormat
}
TextureDescriptor describes a texture to create.
type TextureDimension ¶
type TextureDimension = gputypes.TextureDimension
type TextureFormat ¶
type TextureFormat = gputypes.TextureFormat
Texture types. TextureAspect is defined as a native enum in enums.go.
type TextureSampleType ¶
type TextureSampleType = gputypes.TextureSampleType
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 {
Label string
Format gputypes.TextureFormat
Dimension gputypes.TextureViewDimension
BaseMipLevel uint32
MipLevelCount uint32
BaseArrayLayer uint32
ArrayLayerCount uint32
Aspect TextureAspect
Usage gputypes.TextureUsage
}
TextureViewDescriptor describes a texture view to create.
type TextureViewDimension ¶
type TextureViewDimension = gputypes.TextureViewDimension
type ToneMappingMode ¶ added in v0.5.0
type ToneMappingMode uint32
ToneMappingMode describes tone mapping for HDR surfaces. New in v29.
const ( // ToneMappingModeStandard is standard tone mapping (sRGB). ToneMappingModeStandard ToneMappingMode = 0x00000001 // ToneMappingModeExtended is extended (HDR) tone mapping. ToneMappingModeExtended ToneMappingMode = 0x00000002 )
type UncapturedErrorCallbackInfo ¶ added in v0.5.0
type UncapturedErrorCallbackInfo struct {
NextInChain uintptr // *ChainedStruct
Callback uintptr // Function pointer
Userdata1 uintptr
Userdata2 uintptr
}
UncapturedErrorCallbackInfo configures the uncaptured-error callback.
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 VertexStepMode ¶
type VertexStepMode = gputypes.VertexStepMode
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. Note: v29 changed Success from 0x00 to 0x01 and Error from 0x01 to 0x02.
const ( // WGPUStatusSuccess indicates the operation completed successfully. WGPUStatusSuccess WGPUStatus = 0x00000001 // WGPUStatusError indicates the operation failed. WGPUStatusError WGPUStatus = 0x00000002 )
Source Files
¶
- adapter.go
- bindgroup.go
- buffer.go
- command.go
- convert.go
- debug.go
- descriptors.go
- device.go
- doc.go
- enums.go
- errors.go
- gputypes_aliases.go
- instance.go
- loader.go
- loader_unix.go
- map_pending.go
- mapped_range.go
- math.go
- pipeline.go
- queryset.go
- render.go
- render_bundle.go
- render_pipeline.go
- sampler.go
- shader.go
- surface.go
- surface_linux.go
- texture.go
- types.go
- wgpu.go
- wgpu_errors.go