shader

package
v0.34.8 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package shader provides shader execution for the software backend.

Two execution paths are supported:

  • SPIR-V interpreter: parses and executes SPIR-V bytecode (compiled from WGSL via naga). This enables rendering shaders that use @builtin(vertex_index) with no vertex buffers (e.g. the gogpu triangle example). See Module, ParseModule, and Module.Execute.

  • Callback shaders: Go functions implementing VertexShaderFunc / FragmentShaderFunc for programmatic shader definition without SPIR-V. Useful for testing and built-in effects (solid color, vertex color, textured).

Shader Types

There are two main shader stages:

  • Vertex Shader: Transforms vertices from object space to clip space. Receives vertex position and attributes, outputs clip-space position and interpolated attributes.

  • Fragment Shader: Computes the final color for each fragment (pixel candidate). Receives interpolated fragment data and outputs RGBA color.

Built-in Shaders

The package provides several built-in shaders for common use cases:

  • SolidColor: Renders geometry with a uniform color.
  • VertexColor: Interpolates per-vertex colors across the triangle.

Usage

// Create a shader program
program := shader.ShaderProgram{
    Vertex:   shader.SolidColorVertexShader,
    Fragment: shader.SolidColorFragmentShader,
}

// Prepare uniforms
uniforms := &shader.SolidColorUniforms{
    MVP:   myMVPMatrix,
    Color: [4]float32{1, 0, 0, 1}, // Red
}

// Use with the rasterization pipeline
// (integration code varies based on pipeline implementation)

Custom Shaders

To create custom shaders, implement the VertexShaderFunc and FragmentShaderFunc signatures:

func MyVertexShader(
    vertexIndex int,
    position [3]float32,
    attributes []float32,
    uniforms any,
) raster.ClipSpaceVertex {
    // Transform position and prepare attributes
}

func MyFragmentShader(
    fragment raster.Fragment,
    uniforms any,
) [4]float32 {
    // Compute and return RGBA color
}

Index

Constants

View Source
const (
	GLSLRound     = 1
	GLSLRoundEven = 2
	GLSLTrunc     = 3
	GLSLFAbs      = 4
	GLSLSAbs      = 5
	GLSLFSign     = 6
	GLSLSSign     = 7
	GLSLFloor     = 8
	GLSLCeil      = 9
	GLSLFract     = 10

	GLSLRadians = 11
	GLSLDegrees = 12
	GLSLSin     = 13
	GLSLCos     = 14
	GLSLTan     = 15
	GLSLAsin    = 16
	GLSLAcos    = 17
	GLSLAtan    = 18
	GLSLSinh    = 19
	GLSLCosh    = 20
	GLSLTanh    = 21
	GLSLAsinh   = 22
	GLSLAcosh   = 23
	GLSLAtanh   = 24
	GLSLAtan2   = 25

	GLSLPow         = 26
	GLSLExp         = 27
	GLSLLog         = 28
	GLSLExp2        = 29
	GLSLLog2        = 30
	GLSLSqrt        = 31
	GLSLInverseSqrt = 32

	GLSLDeterminant   = 33
	GLSLMatrixInverse = 34

	GLSLModf       = 35
	GLSLModfStruct = 36
	GLSLFMin       = 37
	GLSLUMin       = 38
	GLSLSMin       = 39
	GLSLFMax       = 40
	GLSLUMax       = 41
	GLSLSMax       = 42
	GLSLFClamp     = 43
	GLSLUClamp     = 44
	GLSLSClamp     = 45
	GLSLFMix       = 46
	GLSLIMix       = 47 // Reserved; treated as FMix.
	GLSLStep       = 48
	GLSLSmoothStep = 49

	GLSLFma         = 50
	GLSLFrexp       = 51
	GLSLFrexpStruct = 52
	GLSLLdexp       = 53

	GLSLPackSnorm4x8     = 54
	GLSLPackUnorm4x8     = 55
	GLSLPackSnorm2x16    = 56
	GLSLPackUnorm2x16    = 57
	GLSLPackHalf2x16     = 58
	GLSLPackDouble2x32   = 59
	GLSLUnpackSnorm2x16  = 60
	GLSLUnpackUnorm2x16  = 61
	GLSLUnpackHalf2x16   = 62
	GLSLUnpackSnorm4x8   = 63
	GLSLUnpackUnorm4x8   = 64
	GLSLUnpackDouble2x32 = 65

	GLSLLength      = 66
	GLSLDistance    = 67
	GLSLCross       = 68
	GLSLNormalize   = 69
	GLSLFaceForward = 70
	GLSLReflect     = 71
	GLSLRefract     = 72

	GLSLFindILsb = 73
	GLSLFindSMsb = 74
	GLSLFindUMsb = 75

	GLSLInterpolateAtCentroid = 76
	GLSLInterpolateAtSample   = 77
	GLSLInterpolateAtOffset   = 78

	GLSLNMin   = 79
	GLSLNMax   = 80
	GLSLNClamp = 81
)

GLSL.std.450 instruction numbers. Reference: https://github.com/KhronosGroup/SPIRV-Headers/blob/main/include/spirv/unified1/GLSL.std.450.h

View Source
const (
	OpNop                  = 0
	OpExtInstImport        = 11
	OpMemoryModel          = 14
	OpEntryPoint           = 15
	OpExecutionMode        = 16
	OpCapability           = 17
	OpTypeVoid             = 19
	OpTypeBool             = 20
	OpTypeInt              = 21
	OpTypeFloat            = 22
	OpTypeVector           = 23
	OpTypeMatrix           = 24
	OpTypeArray            = 28
	OpTypeRuntimeArray     = 29
	OpTypeStruct           = 30
	OpTypePointer          = 32
	OpTypeFunction         = 33
	OpConstant             = 43
	OpConstantComposite    = 44
	OpConstantNull         = 46
	OpFunction             = 54
	OpFunctionParameter    = 55
	OpFunctionEnd          = 56
	OpVariable             = 59
	OpLoad                 = 61
	OpStore                = 62
	OpAccessChain          = 65
	OpArrayLength          = 68
	OpDecorate             = 71
	OpMemberDecorate       = 72
	OpCompositeExtract     = 81
	OpCompositeConstruct   = 80
	OpCompositeInsert      = 82
	OpVectorExtractDynamic = 77
	OpVectorInsertDynamic  = 78
	OpReturn               = 253
	OpReturnValue          = 254
	OpLabel                = 248
	OpBranch               = 249
	OpSource               = 3
	OpSourceExtension      = 4
	OpName                 = 5
	OpMemberName           = 6
	OpString               = 7
	OpLine                 = 8
	OpNoLine               = 317
	OpModuleProcessed      = 330
	OpUndef                = 1
	OpExtInst              = 12
	OpBitcast              = 124
	OpConvertUToF          = 112
	OpConvertFToU          = 109
	OpConvertSToF          = 111
	OpIAdd                 = 128
	OpISub                 = 130
	OpIMul                 = 132
	OpFAdd                 = 129
	OpFSub                 = 131
	OpFMul                 = 133
	OpFDiv                 = 136
	OpSDiv                 = 135
	OpUDiv                 = 134
	OpFNegate              = 127
	OpSelect               = 169
	OpBranchConditional    = 250
	OpSelectionMerge       = 247
	OpLoopMerge            = 246
	OpPhi                  = 245
	OpIEqual               = 170
	OpINotEqual            = 171
	OpFOrdEqual            = 180
	OpFOrdLessThan         = 184
	OpFOrdGreaterThan      = 186
	OpFOrdLessThanEqual    = 188
	OpFOrdGreaterThanEqual = 190

	// Additional opcodes for Phases 2-6.
	OpDot               = 148
	OpVectorTimesScalar = 142
	OpMatrixTimesVector = 145
	OpMatrixTimesScalar = 143
	OpMatrixTimesMatrix = 146
	OpTranspose         = 84
	OpVectorShuffle     = 79

	OpFunctionCall = 57

	OpSwitch              = 251
	OpKill                = 252
	OpUnreachable         = 255
	OpTerminateInvocation = 4416 // SPV_KHR_terminate_invocation, core in SPIR-V 1.6

	// Comparison ops (integer, unsigned).
	OpULessThan         = 176
	OpUGreaterThan      = 172
	OpULessThanEqual    = 178
	OpUGreaterThanEqual = 174
	OpSLessThan         = 177
	OpSGreaterThan      = 173
	OpSLessThanEqual    = 179
	OpSGreaterThanEqual = 175

	// Logical ops.
	OpLogicalAnd      = 167
	OpLogicalOr       = 166
	OpLogicalNot      = 168
	OpLogicalEqual    = 164
	OpLogicalNotEqual = 165

	// Float inequality, ordered (false with a NaN) and unordered (true).
	OpFOrdNotEqual   = 182
	OpFUnordNotEqual = 183

	// Bit field ops.
	OpBitFieldInsert   = 201
	OpBitFieldSExtract = 202
	OpBitFieldUExtract = 203
	OpBitReverse       = 204
	OpBitCount         = 205

	// Derivatives (fragment stage).
	OpDPdx         = 207
	OpDPdy         = 208
	OpFwidth       = 209
	OpDPdxFine     = 210
	OpDPdyFine     = 211
	OpFwidthFine   = 212
	OpDPdxCoarse   = 213
	OpDPdyCoarse   = 214
	OpFwidthCoarse = 215

	// Bitwise ops.
	OpBitwiseAnd           = 199
	OpBitwiseOr            = 197
	OpBitwiseXor           = 198
	OpNot                  = 200
	OpShiftLeftLogical     = 196
	OpShiftRightLogical    = 194
	OpShiftRightArithmetic = 195

	// Image / sampler ops.
	OpTypeImage              = 25
	OpTypeSampler            = 26
	OpTypeSampledImage       = 27
	OpSampledImage           = 86
	OpImageSampleImplicitLod = 87
	OpImageSampleExplicitLod = 88
	OpImageFetch             = 95
	OpImageRead              = 98
	OpImageWrite             = 99
	OpImageQuerySizeLod      = 103
	OpImageQuerySize         = 104
	OpImageQueryLevels       = 106
	OpImageQuerySamples      = 107

	// Atomic ops.
	OpAtomicLoad            = 227
	OpAtomicStore           = 228
	OpAtomicExchange        = 229
	OpAtomicCompareExchange = 230
	OpAtomicIIncrement      = 232
	OpAtomicIDecrement      = 233
	OpAtomicIAdd            = 234
	OpAtomicISub            = 235
	OpAtomicSMin            = 236
	OpAtomicUMin            = 237
	OpAtomicSMax            = 238
	OpAtomicUMax            = 239

	// Barrier ops.
	OpControlBarrier = 224
	OpMemoryBarrier  = 225

	// Type conversion ops.
	OpConvertFToS = 110
	OpSConvert    = 114
	OpUConvert    = 113
	OpFConvert    = 115

	// Misc ops.
	OpCopyObject = 83
	OpFMod       = 141
	OpSMod       = 139
	OpUMod       = 137
	OpSRem       = 138
	OpFRem       = 140
	OpSNegate    = 126

	// Constant ops.
	OpConstantTrue      = 41
	OpConstantFalse     = 42
	OpSpecConstant      = 48
	OpSpecConstantTrue  = 49
	OpSpecConstantFalse = 50

	// Image operand masks.
	ImageOperandBiasMask = 0x1
	ImageOperandLodMask  = 0x2
	ImageOperandGradMask = 0x4
	// ImageOperandConstOffsetMask and ImageOperandOffsetMask add a texel
	// offset to the coordinate; ConstOffsets, Sample and MinLod follow them.
	ImageOperandConstOffsetMask = 0x8
	ImageOperandOffsetMask      = 0x10
)

SPIR-V opcodes relevant to the triangle shader. Reference: SPIR-V Specification v1.6, section 3.32 (Instructions).

View Source
const (
	StorageClassUniformConstant = 0
	StorageClassInput           = 1
	StorageClassUniform         = 2
	StorageClassOutput          = 3
	StorageClassWorkgroup       = 4
	StorageClassCrossWorkgroup  = 5
	StorageClassPrivate         = 6
	StorageClassFunction        = 7
	StorageClassGeneric         = 8
	StorageClassPushConstant    = 9
	StorageClassAtomicCounter   = 10
	StorageClassImage           = 11
	StorageClassStorageBuffer   = 12
)

SPIR-V storage classes.

View Source
const (
	DecorationArrayStride   = 6
	DecorationBuiltIn       = 11
	DecorationBinding       = 33
	DecorationDescriptorSet = 34
	DecorationLocation      = 30
	DecorationOffset        = 35
	DecorationBlock         = 2
	DecorationBufferBlock   = 3
	DecorationColMajor      = 5
	DecorationMatrixStride  = 7
	DecorationNonWritable   = 24
	DecorationNonReadable   = 25
)

SPIR-V decoration constants.

View Source
const (
	BuiltInPosition           = 0
	BuiltInPointSize          = 1
	BuiltInVertexIndex        = 42
	BuiltInInstanceIndex      = 43
	BuiltInFragCoord          = 15
	BuiltInFrontFacing        = 17
	BuiltInSampleID           = 18
	BuiltInSampleMask         = 20
	BuiltInFragDepth          = 22
	BuiltInGlobalInvocationID = 28
	BuiltInLocalInvocationID  = 27
	BuiltInWorkgroupID        = 26
	BuiltInNumWorkgroups      = 24
	BuiltInLocalInvocationIdx = 29
	BuiltInWorkgroupSize      = 25
)

SPIR-V BuiltIn values.

View Source
const (
	ExecutionModelVertex    = 0
	ExecutionModelFragment  = 4
	ExecutionModelGLCompute = 5
)

SPIR-V execution model constants.

View Source
const (
	// DepthStencilTexelSize is the stored texel size of a combined format.
	DepthStencilTexelSize = 8
	// StencilPlaneOffset is the byte offset of the stencil in such a texel.
	StencilPlaneOffset = 4
)

Combined depth-stencil storage (the software backend's own layout): a texel of Depth24PlusStencil8 or Depth32FloatStencil8 is 8 bytes, the depth as a float32 at offset 0 and the stencil as a uint8 at offset 4. Depth24Plus stores the float32 depth alone; Stencil8 the stencil byte alone.

View Source
const (
	TexDim2D        = 0
	TexDim1D        = 1
	TexDim2DArray   = 2
	TexDimCube      = 3
	TexDimCubeArray = 4
	TexDim3D        = 5
)

Texture view dimensions (Texture2D.Dimension).

View Source
const (
	WrapRepeat         = 0
	WrapClampToEdge    = 1
	WrapMirroredRepeat = 2
)

Wrap mode constants.

View Source
const (
	FilterNearest = 0
	FilterLinear  = 1
)

Filter constants.

View Source
const (
	ExecutionModeLocalSize = 17
)

Execution mode constants.

View Source
const LodClampNone = 32

LodClampNone is the WebGPU default LodMaxClamp (32): no upper clamp. The fallback samplers used when no sampler is bound set it; a Sampler's LodMaxClamp is otherwise taken literally, as the HAL descriptor's is.

Variables

View Source
var ErrDiscarded = errors.New("spirv: fragment invocation discarded")

ErrDiscarded is returned by Execute, ExecuteWithContext and ExecuteWithDebug when a fragment invocation executed OpKill or OpTerminateInvocation (WGSL discard). The caller must write no color, depth or stencil for the fragment.

Functions

func BarycentricFragmentShader

func BarycentricFragmentShader(fragment raster.Fragment, _ any) [4]float32

BarycentricFragmentShader returns a color based on barycentric coordinates. Useful for debugging triangle rasterization.

func DepthFragmentShader

func DepthFragmentShader(fragment raster.Fragment, _ any) [4]float32

DepthFragmentShader returns a grayscale color based on fragment depth. Useful for visualizing the depth buffer.

func Float32BitsToUint32 added in v0.27.0

func Float32BitsToUint32(f float32) uint32

Float32BitsToUint32 converts a float32 to its bit representation as uint32. Used for SPIR-V constant encoding in tests.

func Mat4Identity

func Mat4Identity() [16]float32

Mat4Identity returns a 4x4 identity matrix.

func Mat4Mul

func Mat4Mul(a, b [16]float32) [16]float32

Mat4Mul multiplies two 4x4 matrices (column-major order).

func Mat4MulVec4

func Mat4MulVec4(m [16]float32, v [4]float32) [4]float32

Mat4MulVec4 multiplies a 4x4 matrix by a vec4 (column-major order). This is the standard OpenGL/WebGPU matrix-vector multiplication.

func Mat4Ortho

func Mat4Ortho(left, right, bottom, top, near, far float32) [16]float32

Mat4Ortho creates an orthographic projection matrix. Parameters define the view volume: left, right, bottom, top, near, far.

func Mat4Scale

func Mat4Scale(x, y, z float32) [16]float32

Mat4Scale creates a scale matrix.

func Mat4Translate

func Mat4Translate(x, y, z float32) [16]float32

Mat4Translate creates a translation matrix.

func PassthroughVertexShader

func PassthroughVertexShader(
	vertexIndex int,
	position [3]float32,
	attributes []float32,
	_ any,
) raster.ClipSpaceVertex

PassthroughVertexShader is a simple vertex shader that passes position through without transformation. Useful for screen-space rendering.

func SolidColorFragmentShader

func SolidColorFragmentShader(frag raster.Fragment, _ any) [4]float32

SolidColorFragmentShader returns the uniform color for all fragments.

func SolidColorVertexShader

func SolidColorVertexShader(
	_ int,
	position [3]float32,
	_ []float32,
	uniforms any,
) raster.ClipSpaceVertex

SolidColorVertexShader transforms vertices using the MVP matrix. The color is passed through as attributes for the fragment shader.

func TexturedFragmentShader

func TexturedFragmentShader(frag raster.Fragment, uniforms any) [4]float32

TexturedFragmentShader samples a texture using interpolated UV coordinates.

func TexturedVertexShader

func TexturedVertexShader(
	_ int,
	position [3]float32,
	attributes []float32,
	uniforms any,
) raster.ClipSpaceVertex

TexturedVertexShader transforms vertices and passes UV coordinates as attributes. Expects attrs[0:2] to be UV coordinates.

func Vec4ToFloat32 added in v0.27.0

func Vec4ToFloat32(val Value) [4]float32

Vec4ToFloat32 extracts a Vec4 from a Value, returning zeros if type doesn't match.

func VertexColorFragmentShader

func VertexColorFragmentShader(frag raster.Fragment, _ any) [4]float32

VertexColorFragmentShader returns the interpolated vertex color.

func VertexColorVertexShader

func VertexColorVertexShader(
	_ int,
	position [3]float32,
	attributes []float32,
	uniforms any,
) raster.ClipSpaceVertex

VertexColorVertexShader transforms vertices and passes vertex colors as attributes. Expects attrs[0:4] to be RGBA color values in [0, 1].

func WhiteFragmentShader

func WhiteFragmentShader(_ raster.Fragment, _ any) [4]float32

WhiteFragmentShader returns white for all fragments. Useful for testing and debugging.

Types

type Array added in v0.27.0

type Array = []Value

Type aliases kept for backward compatibility with external code and tests. These are the underlying Go types used for construction only.

type BindingKey added in v0.27.0

type BindingKey struct {
	Group   uint32
	Binding uint32
}

BindingKey identifies a resource binding by descriptor set and binding number.

type BufferPointer added in v0.27.0

type BufferPointer struct {
	Buffer []byte    // raw buffer data
	Offset uint32    // byte offset within the buffer
	Type   *TypeInfo // type of the pointed-to element
	// MatrixStride is the column stride of the matrices in Type, from the
	// MatrixStride decoration of the struct member the access chain went
	// through (SPIR-V decorates the member, not the matrix type). 0 when
	// Type holds no matrix or the member is not decorated.
	MatrixStride uint32
}

BufferPointer provides direct read/write access to a position within a raw byte buffer. Used for storage buffer access chains where OpStore must write back to the buffer.

type ColorCodec

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

ColorCodec reads and writes the texels of one color attachment format in linear values: the color writes and clears of the software rasterizer go through it. An sRGB format decodes and encodes the sRGB transfer function on red, green and blue; alpha is linear.

func NewColorCodec

func NewColorCodec(f gputypes.TextureFormat) (ColorCodec, bool)

NewColorCodec returns the codec of color format f, or false for a format that is not an uncompressed color format the backend stores (depth-stencil, compressed, rgb9e5ufloat, Undefined).

func (ColorCodec) Decode

func (c ColorCodec) Decode(b []byte) [4]float32

Decode reads the texel at b[0] as linear RGBA, the channels the format lacks filled with (0, 0, 0, 1).

func (ColorCodec) Encode

func (c ColorCodec) Encode(b []byte, v [4]float32)

Encode writes linear RGBA v into the texel at b[0].

func (ColorCodec) EncodeClear

func (c ColorCodec) EncodeClear(b []byte, v [4]float64)

EncodeClear writes the clear value v, given in float64 as GPURenderPassColorAttachment.clearValue is, into the texel at b[0]. The 32-bit integer formats convert from float64 directly, so every uint32 and int32 clears exactly; the other formats convert as Encode.

func (ColorCodec) EncodeIntMasked

func (c ColorCodec) EncodeIntMasked(b []byte, v [4]uint32, mask gputypes.ColorWriteMask)

EncodeIntMasked writes the integer channels v, each the 32 bits of the shader's u32 or i32 output, into the texel at b[0] of an integer format, the channels mask selects only. A narrower channel keeps the low bits, as the float path (encodeAt) truncates; a 32-bit channel stores v exactly, which a float32 cannot carry above 2^24.

func (ColorCodec) EncodeMasked

func (c ColorCodec) EncodeMasked(b []byte, v [4]float32, mask gputypes.ColorWriteMask)

EncodeMasked writes the channels of v that mask (gputypes.ColorWriteMask bits: red 1, green 2, blue 4, alpha 8) selects into the texel at b[0] and keeps the stored bits of the others exactly.

func (ColorCodec) Integer

func (c ColorCodec) Integer() bool

Integer reports whether the format stores integers: such targets never blend (WebGPU rejects a blend state on them).

func (ColorCodec) Range

func (c ColorCodec) Range() (lo, hi float32, ok bool)

Range returns the range a normalized format clamps blend inputs and results to: [0, 1] for unorm (sRGB included), [-1, 1] for snorm. ok is false for float and integer formats, which WebGPU does not clamp.

func (ColorCodec) Signed

func (c ColorCodec) Signed() bool

Signed reports whether the format stores signed integers.

func (ColorCodec) TexelSize

func (c ColorCodec) TexelSize() int

TexelSize returns the bytes of one texel.

type DebugAction added in v0.27.0

type DebugAction int

DebugAction controls execution flow after a debug callback.

const (
	// DebugContinue resumes execution until the next breakpoint or watch trigger.
	DebugContinue DebugAction = iota

	// DebugStep executes one instruction, then fires the OnInstruction callback.
	DebugStep

	// DebugAbort stops execution immediately. ExecuteWithDebug returns
	// a nil output map and an ErrDebugAbort error.
	DebugAbort
)

type DebugContext added in v0.27.0

type DebugContext struct {
	// OnInstruction is called before each instruction executes (when stepping
	// or when a watched variable changed). The returned DebugAction controls
	// whether to continue, step, or abort.
	OnInstruction func(event InstructionEvent) DebugAction

	// OnBreakpoint is called when execution reaches a breakpoint instruction
	// index. If both OnBreakpoint and OnInstruction are set, OnBreakpoint fires
	// first, then OnInstruction fires and its return value controls flow.
	OnBreakpoint func(event InstructionEvent)

	// OnError is called when an instruction produces a runtime error (e.g.,
	// exceeding max iterations). The error is still returned from ExecuteWithDebug.
	OnError func(event ErrorEvent)

	// Breakpoints maps instruction index (0-based within the function) to
	// a boolean indicating whether a breakpoint is set. The instruction at
	// the given index triggers the OnBreakpoint callback before execution.
	Breakpoints map[int]bool

	// WatchVariables maps SSA result IDs to watch status. When a watched
	// variable's value changes after an instruction, OnInstruction is called
	// with DebugStep regardless of breakpoints.
	WatchVariables map[uint32]bool

	// TraceEnabled enables JSON-lines trace output. Each instruction that
	// produces a result writes one JSON line to TraceWriter after execution.
	TraceEnabled bool

	// TraceWriter receives JSON-lines trace output when TraceEnabled is true.
	// Each line is a self-contained JSON object terminated by a newline.
	TraceWriter io.Writer
}

DebugContext configures shader debugging for a single ExecuteWithDebug call.

All fields are optional. When DebugContext is nil, the interpreter runs at full speed with zero debug overhead.

type EntryPoint added in v0.27.0

type EntryPoint struct {
	ExecutionModel uint32
	FunctionID     uint32
	Name           string
	InterfaceIDs   []uint32 // IDs of interface variables
}

EntryPoint describes a SPIR-V entry point.

type ErrorEvent added in v0.27.0

type ErrorEvent struct {
	// PC is the instruction index where the error occurred.
	PC int

	// Instruction is the instruction that caused the error.
	Instruction Instruction

	// Err is the runtime error.
	Err error
}

ErrorEvent provides information about a runtime error during debug execution.

type ExecutionContext added in v0.27.0

type ExecutionContext struct {
	// Inputs maps variable ID to its value (builtin inputs like vertex_index).
	Inputs map[uint32]Value

	// Buffers maps (group, binding) to raw buffer data for uniform/storage buffers.
	Buffers map[BindingKey][]byte

	// Textures maps (group, binding) to a 2D texture.
	Textures map[BindingKey]*Texture2D

	// Samplers maps (group, binding) to sampler parameters.
	Samplers map[BindingKey]*Sampler

	// WorkgroupSharedMemory is shared memory for compute shader workgroups.
	// Maps variable ID to a byte slice shared across all invocations: a
	// workgroup variable's loads and stores read and write it directly.
	// DispatchCompute sets it for each workgroup.
	WorkgroupSharedMemory map[uint32][]byte

	// ComputeBuiltins provides compute shader built-in values.
	GlobalInvocationID   [3]uint32
	LocalInvocationID    [3]uint32
	WorkgroupID          [3]uint32
	NumWorkgroups        [3]uint32
	WorkgroupSize        [3]uint32
	LocalInvocationIndex uint32
	// contains filtered or unexported fields
}

ExecutionContext provides bound resources for shader execution. Shaders read uniform/storage buffers, textures, and samplers through this context.

type Float32 added in v0.27.0

type Float32 = float32

Type aliases kept for backward compatibility with external code and tests. These are the underlying Go types used for construction only.

type FragmentShaderFunc

type FragmentShaderFunc func(
	fragment raster.Fragment,
	uniforms any,
) [4]float32

FragmentShaderFunc computes the final color for a fragment. It receives interpolated fragment data and returns an RGBA color.

Parameters:

  • fragment: The fragment with interpolated position, depth, and attributes.
  • uniforms: User-defined uniform data (textures, colors, etc.).

Returns:

  • [4]float32: RGBA color values in the range [0, 1].

type Function added in v0.27.0

type Function struct {
	ID           uint32
	ReturnType   uint32
	FunctionType uint32
	Instructions []Instruction

	// Labels maps label ID to instruction index. Built once during ParseModule
	// to avoid rebuilding on every Execute call. OpBranch and OpBranchConditional
	// use this for control flow.
	Labels map[uint32]int
}

Function is a parsed SPIR-V function body.

type Instruction added in v0.27.0

type Instruction struct {
	Opcode   uint16
	ResultID uint32   // 0 if instruction produces no result
	TypeID   uint32   // 0 if instruction has no result type
	Operands []uint32 // remaining operands after result/type
}

Instruction represents a decoded SPIR-V instruction.

type InstructionEvent added in v0.27.0

type InstructionEvent struct {
	// PC is the 0-based instruction index within the current function.
	PC int

	// Instruction is the SPIR-V instruction about to execute (for OnInstruction
	// and OnBreakpoint) or just executed (for watch triggers).
	Instruction Instruction

	// Values is the current SSA value slice indexed by SPIR-V ID. This is a
	// direct reference to the interpreter's live values -- callers should
	// treat it as read-only.
	Values []Value

	// BlockLabel is the result ID of the current basic block's OpLabel.
	BlockLabel uint32
}

InstructionEvent provides information about the current instruction during a debug callback. The Values slice is a read-only snapshot -- modifications are ignored by the interpreter.

type Int32 added in v0.27.0

type Int32 = int32

Type aliases kept for backward compatibility with external code and tests. These are the underlying Go types used for construction only.

type Mat4 added in v0.27.0

type Mat4 = [4]Vec4

Mat4 is a 4x4 column-major matrix stored as an Array of 4 Vec4 columns. SPIR-V represents matrices as arrays of column vectors.

type Module added in v0.27.0

type Module struct {
	// Types maps result ID to type information.
	Types map[uint32]*TypeInfo

	// Constants maps result ID to constant value.
	Constants map[uint32]Value

	// Functions maps entry point name to function body.
	Functions map[string]*Function

	// EntryPoints maps entry point name to its metadata.
	EntryPoints map[string]*EntryPoint

	// Decorations maps (target ID, decoration kind) to decoration value.
	Decorations map[decorationKey]uint32

	// MemberDecorations maps (struct type ID, member index, decoration kind) to value.
	// Used for OpMemberDecorate, primarily for struct member Offset decorations.
	MemberDecorations map[memberDecorationKey]uint32

	// Variables maps result ID to variable metadata.
	Variables map[uint32]*VariableInfo

	// FunctionsByID maps function result ID to function body.
	// Used by OpFunctionCall to dispatch to non-entry-point functions.
	FunctionsByID map[uint32]*Function

	// ExtInstImports maps result ID to the imported instruction set name.
	// The primary use is "GLSL.std.450" for math intrinsics.
	ExtInstImports map[uint32]string

	// ExecutionModes maps (function ID, execution mode) to operands.
	// Used for LocalSize in compute shaders.
	ExecutionModes map[executionModeKey][]uint32

	// ResultTypes maps the result ID of a constant or a typed function
	// instruction to its result type ID. Runtime values do not carry their
	// SPIR-V type (an integer vector component is held as a float32), so an
	// instruction whose meaning depends on its operand's type, such as
	// OpBitcast, looks the type up here.
	ResultTypes map[uint32]uint32

	// Bound is the upper bound of all IDs in the module.
	Bound uint32
	// contains filtered or unexported fields
}

Module is a parsed SPIR-V module ready for interpretation.

func ParseModule added in v0.27.0

func ParseModule(words []uint32) (*Module, error)

ParseModule parses SPIR-V binary (as []uint32 words) into a Module.

The SPIR-V format is: 5-word header (magic, version, generator, bound, reserved) followed by a stream of instructions. Each instruction's first word encodes (wordCount << 16 | opcode).

func (*Module) DispatchCompute added in v0.27.0

func (m *Module) DispatchCompute(entryPoint string, ctx *ExecutionContext,
	groupCountX, groupCountY, groupCountZ uint32) error

DispatchCompute executes a compute shader for all invocations in the dispatch. groupCountX/Y/Z specify the number of workgroups to dispatch. The entry point's LocalSize execution mode determines the workgroup dimensions.

The workgroups run one after another, each with its own zero-initialized workgroup memory, which all its invocations share. The invocations of a workgroup run on one goroutine, round-robin from barrier to barrier: each runs until it reaches a workgroup barrier (OpControlBarrier with Workgroup execution scope) or returns, and the invocations at the barrier go on past it only once all of them have run (see workgroupRun).

func (*Module) Execute added in v0.27.0

func (m *Module) Execute(entryPoint string, inputs map[uint32]Value) (map[uint32]Value, error)

Execute runs the named entry point with the given input variable values.

inputs maps variable ID (decorated with BuiltIn or Location) to its value. Returns a map of output variable ID to its value after execution.

For a vertex shader, inputs typically contain:

  • vertex_index variable ID -> Uint32 value

Outputs typically contain:

  • position variable ID -> Vec4 value

func (*Module) ExecuteCompute added in v0.27.0

func (m *Module) ExecuteCompute(entryPoint string, ctx *ExecutionContext) error

ExecuteCompute runs a compute shader entry point for a single invocation.

The context must have ComputeBuiltins (GlobalInvocationID, LocalInvocationID, WorkgroupID, NumWorkgroups, WorkgroupSize, LocalInvocationIndex) populated by the caller for each invocation.

Storage buffer writes are reflected in the context's Buffers map. A workgroup variable lives in its WorkgroupSharedMemory buffer when the context has one of the variable's size, and in zeroed memory of its own otherwise. The invocation runs alone, so it does not wait at a barrier: use DispatchCompute to run the invocations of a workgroup together.

func (*Module) ExecuteWithContext added in v0.27.0

func (m *Module) ExecuteWithContext(entryPoint string, ctx *ExecutionContext) (map[uint32]Value, error)

ExecuteWithContext runs the named entry point with full resource context. The context provides bound buffers, textures, and samplers for the shader.

func (*Module) ExecuteWithDebug added in v0.27.0

func (m *Module) ExecuteWithDebug(entryPoint string, ctx *ExecutionContext, debug *DebugContext) (map[uint32]Value, error)

ExecuteWithDebug runs the named entry point with full resource context and optional debug support. When debug is nil, execution proceeds at full speed with zero overhead -- the existing Execute and ExecuteWithContext methods call this with debug=nil.

When debug is non-nil, the interpreter fires callbacks for breakpoints, variable watches, and instruction tracing. See DebugContext for details.

func (*Module) GetBinding added in v0.27.0

func (m *Module) GetBinding(varID uint32) (BindingKey, bool)

GetBinding returns the (group, binding) for a variable, or ok=false if not decorated.

func (*Module) GetBuiltIn added in v0.27.0

func (m *Module) GetBuiltIn(varID uint32) int

GetBuiltIn returns the BuiltIn decoration value for a variable ID, or -1 if none.

func (*Module) GetLocation added in v0.27.0

func (m *Module) GetLocation(varID uint32) int

GetLocation returns the Location decoration value for a variable ID, or -1 if none.

func (*Module) GetMemberOffset added in v0.27.0

func (m *Module) GetMemberOffset(structTypeID, memberIndex uint32) uint32

GetMemberOffset returns the byte offset of a struct member, or 0 if not decorated.

func (*Module) GetTypeComponentCount added in v0.27.0

func (m *Module) GetTypeComponentCount(varID uint32) int

GetTypeComponentCount returns the number of scalar components for the type pointed to by a variable. For vec2 returns 2, vec3 returns 3, vec4 returns 4, scalars return 1. Returns 0 if the variable or type is unknown.

func (*Module) GetWorkgroupSize added in v0.27.0

func (m *Module) GetWorkgroupSize(entryPoint string) [3]uint32

GetWorkgroupSize returns the workgroup size declared via OpExecutionMode LocalSize. Returns (1, 1, 1) if not specified.

func (*Module) MayDiscard

func (m *Module) MayDiscard() bool

MayDiscard reports whether any function of the module contains OpKill or OpTerminateInvocation, so a fragment entry point may discard. The answer is conservative: it does not check that the function is reachable from the entry point.

func (*Module) PointeeType added in v0.27.0

func (m *Module) PointeeType(ptrTypeID uint32) *TypeInfo

PointeeType dereferences a pointer type, returning the type it points to.

type Pointer added in v0.27.0

type Pointer struct {
	Val Value
}

Pointer wraps a mutable reference to a Value stored in a variable. SPIR-V OpVariable creates a Pointer; OpLoad dereferences it; OpStore writes to it.

type SampledImageValue added in v0.27.0

type SampledImageValue struct {
	Image   Value // BindingKey or *Texture2D (stored as Value)
	Sampler Value // BindingKey or *Sampler (stored as Value)
}

SampledImageValue combines a texture reference and a sampler reference. Created by OpSampledImage, consumed by OpImageSample* opcodes.

type Sampler added in v0.27.0

type Sampler struct {
	MinFilter    uint32 // 0 = Nearest, 1 = Linear.
	MagFilter    uint32 // 0 = Nearest, 1 = Linear.
	MipmapFilter uint32 // 0 = Nearest, 1 = Linear.
	WrapU        uint32 // 0 = Repeat, 1 = ClampToEdge, 2 = MirroredRepeat.
	WrapV        uint32 // 0 = Repeat, 1 = ClampToEdge, 2 = MirroredRepeat.
	WrapW        uint32 // 0 = Repeat, 1 = ClampToEdge, 2 = MirroredRepeat.
	// LodMinClamp and LodMaxClamp clamp the level of detail, taken
	// literally: a zero LodMaxClamp pins sampling to the base level. Use
	// LodClampNone for no upper clamp.
	LodMinClamp float32
	LodMaxClamp float32
}

Sampler describes texture sampling parameters.

type ShaderProgram

type ShaderProgram struct {
	// Vertex is the vertex shader function.
	Vertex VertexShaderFunc

	// Fragment is the fragment shader function.
	Fragment FragmentShaderFunc
}

ShaderProgram combines vertex and fragment shaders into a complete program.

func (ShaderProgram) IsValid

func (p ShaderProgram) IsValid() bool

IsValid returns true if the shader program has both vertex and fragment shaders.

type SolidColorUniforms

type SolidColorUniforms struct {
	// MVP is the Model-View-Projection matrix in column-major order.
	MVP [16]float32

	// Color is the RGBA color to render with values in [0, 1].
	Color [4]float32
}

SolidColorUniforms contains uniform data for the solid color shader.

type SubPointer added in v0.27.0

type SubPointer struct {
	Parent  *Pointer // root variable pointer
	Indexes []uint32 // index path from parent to sub-element (literal values, not SSA IDs)
}

SubPointer provides write-through access to a member of a composite value stored in a parent Pointer. When SPIR-V uses OpAccessChain on a function-local variable (e.g. var p: Particle; p.pos), OpStore to the resulting pointer must update the parent composite -- not just a disconnected copy.

Without SubPointer, accessChain creates a new Pointer wrapping a copy of the sub-element, so OpStore modifies the copy but not the original struct. This bug caused compute shaders with struct member updates (p.pos += ...) to silently discard writes.

SubPointer solves this by storing a reference to the parent Pointer and the index path. OpLoad reads the current value through the parent. OpStore writes back through the parent, rebuilding the composite at each level.

type Texture2D added in v0.27.0

type Texture2D struct {
	Width  uint32
	Height uint32
	Data   []byte // Pixel data, row-major, BytesPerPixel bytes per texel.
	// Format is the view's format, the gputypes.TextureFormat texels are
	// read and written in (0 = RGBA8 by BytesPerPixel). It may differ from
	// the stored texture's format by the sRGB suffix only.
	Format uint32
	// Aspect is the view's gputypes.TextureAspect: StencilOnly reads the
	// stencil plane of a depth-stencil format; any other value reads the
	// depth plane or the color.
	Aspect uint32
	// BytesPerPixel is the storage size of a single texel (1 for R8, 2 for
	// RG8/R16, 4 for RGBA8/BGRA8). When zero, sampling assumes 4 (RGBA8) for
	// backward compatibility. Single-channel formats unpack as (r, 0, 0, 1).
	BytesPerPixel uint32
	// MipLevels, SampleCount and Layers answer the image queries
	// (OpImageQueryLevels, OpImageQuerySamples, the array size of
	// OpImageQuerySize[Lod]); zero reads as 1. MipLevels and Layers are the
	// view's: Layers counts the six faces of each cube.
	MipLevels   uint32
	SampleCount uint32
	Layers      uint32
	// Dimension is the view dimension, one of the TexDim constants; zero is
	// 2D.
	Dimension uint32
	// Depth is the depth of the base level of a 3D view; zero reads as 1.
	Depth uint32
	// Levels holds the view's mip levels, base level first. When nil the
	// view has the one level Width, Height and Data describe.
	Levels []TextureLevel
}

Texture2D is a texture view bound to a shader in the SPIR-V interpreter: one or more mip levels of a 1D, 2D, 2D-array, cube, cube-array or 3D view. The name predates the other dimensions.

Width, Height and Data describe the view's base mip level: Data holds its images back to back (the view's array layers, or the depth slices of a 3D view), each Height rows of Width texels, BytesPerPixel bytes per texel. Levels, when set, holds every mip level of the view from the base level on, and Levels[0] is the base level again.

type TextureLevel

type TextureLevel struct {
	Width  uint32
	Height uint32
	Images uint32
	Data   []byte
}

TextureLevel is one mip level of a texture view: Images images of Height rows of Width texels back to back in Data (array layers, or depth slices of a 3D view).

type TexturedUniforms

type TexturedUniforms struct {
	// MVP is the Model-View-Projection matrix in column-major order.
	MVP [16]float32

	// TextureData is the RGBA8 texture data.
	TextureData []byte

	// TextureWidth is the width of the texture in pixels.
	TextureWidth int

	// TextureHeight is the height of the texture in pixels.
	TextureHeight int
}

TexturedUniforms contains uniform data for the textured shader.

type TypeInfo added in v0.27.0

type TypeInfo struct {
	Kind       TypeKind
	Width      uint32   // bit width for int/float
	Signed     bool     // for OpTypeInt
	Components uint32   // for OpTypeVector
	ElemType   uint32   // element type ID for vector/array/pointer
	Length     uint32   // for OpTypeArray (number of elements)
	Storage    uint32   // for OpTypePointer (storage class)
	ParamIDs   []uint32 // for OpTypeFunction (parameter type IDs)
	ReturnType uint32   // for OpTypeFunction
	MemberIDs  []uint32 // for OpTypeStruct

	// ArrayStride is the ArrayStride decoration of an array type: the byte
	// distance between its elements in an explicitly laid-out buffer. 0 when
	// the array is not decorated (Function, Private and Workgroup arrays).
	ArrayStride uint32
}

TypeInfo describes a SPIR-V type.

type TypeKind added in v0.27.0

type TypeKind int

TypeKind classifies SPIR-V types.

const (
	TypeVoid TypeKind = iota
	TypeBool
	TypeInt
	TypeFloat
	TypeVector
	TypeMatrix
	TypeArray
	TypePointer
	TypeFunction
	TypeStruct
	TypeImage
	TypeSampler
	TypeSampledImage
)

type Uint32 added in v0.27.0

type Uint32 = uint32

Type aliases kept for backward compatibility with external code and tests. These are the underlying Go types used for construction only.

type Value added in v0.27.0

type Value struct {
	Tag ValueTag
	F   [4]float32     // float scalars + vectors
	U   [4]uint32      // uint/int scalars, bool, binding key
	Ref unsafe.Pointer // Array, Pointer, SubPointer, BufferPointer, SampledImageValue
}

Value is a tagged union representing a runtime value in the SPIR-V interpreter. Scalars and vectors (up to vec4) are stored inline with zero heap allocation. Composite types (arrays, pointers) use the Ref field.

Size: 40 bytes (1 tag + 3 pad + 16 F + 16 U + 8 Ref = 44, but compiler may align to 48). This is intentionally larger than an interface (16 bytes) because it eliminates the heap allocation that every interface boxing requires.

func ValArray added in v0.27.0

func ValArray(a []Value) Value

ValArray returns an Array Value. The slice is stored on the heap via Ref.

func ValBindingKey added in v0.27.0

func ValBindingKey(bk BindingKey) Value

ValBindingKey returns a BindingKey Value stored inline in U[0..1].

func ValBool added in v0.27.0

func ValBool(b bool) Value

ValBool returns a boolean Value.

func ValBufferPointer added in v0.27.0

func ValBufferPointer(bp *BufferPointer) Value

ValBufferPointer returns a BufferPointer Value.

func ValFloat added in v0.27.0

func ValFloat(f float32) Value

ValFloat returns a float32 scalar Value.

func ValFloat64 added in v0.34.4

func ValFloat64(f float64) Value

ValFloat64 returns a float64 scalar Value stored as IEEE-754 bits in U[0..1].

func ValInt added in v0.27.0

func ValInt(i int32) Value

ValInt returns an int32 scalar Value.

func ValNone added in v0.27.0

func ValNone() Value

ValNone returns the zero/nil Value.

func ValPointer added in v0.27.0

func ValPointer(p *Pointer) Value

ValPointer returns a Pointer Value.

func ValSampledImage added in v0.27.0

func ValSampledImage(si *SampledImageValue) Value

ValSampledImage returns a SampledImageValue.

func ValSubPointer added in v0.27.0

func ValSubPointer(sp *SubPointer) Value

ValSubPointer returns a SubPointer Value.

func ValUint added in v0.27.0

func ValUint(u uint32) Value

ValUint returns a uint32 scalar Value.

func ValVec2 added in v0.27.0

func ValVec2(x, y float32) Value

ValVec2 returns a 2-component float vector Value.

func ValVec2From added in v0.27.0

func ValVec2From(v Vec2) Value

ValVec2From returns a Value from a Vec2 array.

func ValVec3 added in v0.27.0

func ValVec3(x, y, z float32) Value

ValVec3 returns a 3-component float vector Value.

func ValVec3From added in v0.27.0

func ValVec3From(v Vec3) Value

ValVec3From returns a Value from a Vec3 array.

func ValVec4 added in v0.27.0

func ValVec4(x, y, z, w float32) Value

ValVec4 returns a 4-component float vector Value.

func ValVec4From added in v0.27.0

func ValVec4From(v Vec4) Value

ValVec4From returns a Value from a Vec4 array.

func (Value) AsArray added in v0.27.0

func (v Value) AsArray() []Value

AsArray extracts a []Value from the Ref field.

func (Value) AsBindingKey added in v0.27.0

func (v Value) AsBindingKey() BindingKey

AsBindingKey extracts a BindingKey from U[0..1].

func (Value) AsBool added in v0.27.0

func (v Value) AsBool() bool

AsBool extracts a bool. Returns false for non-bool tags.

func (Value) AsBufferPointer added in v0.27.0

func (v Value) AsBufferPointer() *BufferPointer

AsBufferPointer extracts a *BufferPointer from the Ref field.

func (Value) AsFloat32 added in v0.27.0

func (v Value) AsFloat32() float32

AsFloat32 extracts a float32. Returns 0 for non-float tags.

func (Value) AsFloat64 added in v0.34.4

func (v Value) AsFloat64() float64

AsFloat64 extracts a float64 from TagFloat64 bits. Returns 0 for other tags.

func (Value) AsInt32 added in v0.27.0

func (v Value) AsInt32() int32

AsInt32 extracts an int32. Returns 0 for non-int tags.

func (Value) AsPointer added in v0.27.0

func (v Value) AsPointer() *Pointer

AsPointer extracts a *Pointer from the Ref field.

func (Value) AsSampledImage added in v0.27.0

func (v Value) AsSampledImage() *SampledImageValue

AsSampledImage extracts a *SampledImageValue from the Ref field.

func (Value) AsSubPointer added in v0.27.0

func (v Value) AsSubPointer() *SubPointer

AsSubPointer extracts a *SubPointer from the Ref field.

func (Value) AsUint32 added in v0.27.0

func (v Value) AsUint32() uint32

AsUint32 extracts a uint32. Returns 0 for non-uint tags.

func (Value) AsVec2 added in v0.27.0

func (v Value) AsVec2() Vec2

AsVec2 extracts a [2]float32.

func (Value) AsVec3 added in v0.27.0

func (v Value) AsVec3() Vec3

AsVec3 extracts a [3]float32.

func (Value) AsVec4 added in v0.27.0

func (v Value) AsVec4() Vec4

AsVec4 extracts a [4]float32.

func (Value) IsNone added in v0.27.0

func (v Value) IsNone() bool

IsNone returns true if the value is uninitialized/nil.

type ValueTag added in v0.27.0

type ValueTag byte

ValueTag identifies the concrete type stored in a Value.

const (
	TagNone          ValueTag = iota
	TagFloat32                // scalar float32 in F[0]
	TagUint32                 // scalar uint32 in U[0]
	TagInt32                  // scalar int32 (stored as uint32 in U[0])
	TagBool                   // boolean (U[0]: 0=false, 1=true)
	TagVec2                   // [2]float32 in F[0..1]
	TagVec3                   // [3]float32 in F[0..2]
	TagVec4                   // [4]float32 in F[0..3]
	TagArray                  // []Value stored via Ref
	TagPointer                // *Pointer stored via Ref
	TagSubPointer             // *SubPointer stored via Ref
	TagBufferPointer          // *BufferPointer stored via Ref
	TagSampledImage           // *SampledImageValue stored via Ref
	TagBindingKey             // BindingKey stored in U[0..1]
	TagFloat64                // IEEE-754 binary64 bits in U[0]=lo, U[1]=hi
)

type VariableInfo added in v0.27.0

type VariableInfo struct {
	TypeID       uint32 // pointer type ID
	StorageClass uint32
	Initializer  uint32 // constant ID of the initializer; 0 for none
}

VariableInfo describes an OpVariable.

type Vec2 added in v0.27.0

type Vec2 = [2]float32

Type aliases kept for backward compatibility with external code and tests. These are the underlying Go types used for construction only.

type Vec3 added in v0.27.0

type Vec3 = [3]float32

Type aliases kept for backward compatibility with external code and tests. These are the underlying Go types used for construction only.

type Vec4 added in v0.27.0

type Vec4 = [4]float32

Type aliases kept for backward compatibility with external code and tests. These are the underlying Go types used for construction only.

type Vertex

type Vertex struct {
	// Position in object/model space.
	Position [3]float32

	// Attributes are additional per-vertex data (colors, UVs, normals, etc.).
	Attributes []float32
}

Vertex represents input vertex data for processing.

func NewVertex

func NewVertex(x, y, z float32) Vertex

NewVertex creates a vertex with position only.

func NewVertexWithColor

func NewVertexWithColor(x, y, z, r, g, b, a float32) Vertex

NewVertexWithColor creates a vertex with position and RGBA color.

func NewVertexWithColorAndUV

func NewVertexWithColorAndUV(x, y, z, r, g, b, a, u, v float32) Vertex

NewVertexWithColorAndUV creates a vertex with position, RGBA color, and UV coordinates.

func NewVertexWithUV

func NewVertexWithUV(x, y, z, u, v float32) Vertex

NewVertexWithUV creates a vertex with position and UV texture coordinates.

type VertexColorUniforms

type VertexColorUniforms struct {
	// MVP is the Model-View-Projection matrix in column-major order.
	MVP [16]float32
}

VertexColorUniforms contains uniform data for the per-vertex color shader.

type VertexShaderFunc

type VertexShaderFunc func(
	vertexIndex int,
	position [3]float32,
	attributes []float32,
	uniforms any,
) raster.ClipSpaceVertex

VertexShaderFunc transforms a vertex from object space to clip space. It receives vertex data and returns a clip-space vertex with position and attributes.

Parameters:

  • vertexIndex: The index of the vertex being processed.
  • position: The 3D position of the vertex in object/world space.
  • attributes: Additional vertex attributes (colors, UVs, normals, etc.).
  • uniforms: User-defined uniform data (matrices, colors, etc.).

Returns:

  • ClipSpaceVertex: The transformed vertex with clip-space position and attributes to be interpolated across the triangle.

Jump to

Keyboard shortcuts

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