ash

package module
v0.0.0-...-cea32f1 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2026 License: GPL-3.0 Imports: 24 Imported by: 1

README

Vulkan ash

Go Vulkan framework makes using Vulkan in Golang accessible. By solving basic boilerplate create a higher level abstract layer for building applications.

API

The overview of public API of the ash package is in separated file API.md.

Examples

Examples for usage of this framework are in the separate repository github.com/tomas-mraz/vulkan-example.

Dependencies

Force update dependencies

go get github.com/tomas-mraz/vulkan-ash@latest

Documentation

Index

Constants

View Source
const (
	OSMac     = "darwin"
	OSAndroid = "android"
)
View Source
const (
	SizeofMat4x4 = int(unsafe.Sizeof(Mat4x4{}))
	SizeofVec4   = int(unsafe.Sizeof(Vec4{}))
	SizeofVec3   = int(unsafe.Sizeof(Vec3{}))
	SizeofVec2   = int(unsafe.Sizeof(Vec2{}))
)

Variables

View Source
var ErrSurfaceNotReady = errors.New("surface not ready")

ErrSurfaceNotReady indicates that the platform surface exists but does not yet expose a usable extent for swapchain creation.

Functions

func AlignUp

func AlignUp(size, alignment uint32) uint32

AlignUp rounds size up to the nearest multiple of alignment.

func CheckDeviceExtensions

func CheckDeviceExtensions(gpu vk.PhysicalDevice, required []string) (ok bool, missing []string)

CheckDeviceExtensions returns true if the physical device supports all required extensions. Missing extensions are returned in the second value.

func DecodeGLTFTexture

func DecodeGLTFTexture(doc *gltf.Document, baseDir string, imageIndex int) ([]byte, uint32, uint32, error)

DecodeGLTFTexture decodes a glTF image to tightly packed RGBA pixels.

func DecodePNG

func DecodePNG(data []byte) (pixels []byte, width, height uint32, err error)

DecodePNG decodes a PNG image from raw bytes and returns RGBA pixels suitable for NewImageTexture.

func DegreesToRadians

func DegreesToRadians(angleDegrees float32) float32

DegreesToRadians converts degrees to radians.

func DumpMatrix

func DumpMatrix(m *Mat4x4, note string) string

func FindMemoryTypeIndex

func FindMemoryTypeIndex(dev vk.PhysicalDevice,
	typeBits uint32, reqMask vk.MemoryPropertyFlagBits) (uint32, bool)

FindMemoryTypeIndex finds a memory type index for the given type bits and required memory property flags. Returns the index and true if found.

func GetDeviceExtensions

func GetDeviceExtensions(gpu vk.PhysicalDevice) (extNames []string)

func LoadShaderFromBytes

func LoadShaderFromBytes(device vk.Device, data []byte) (vk.ShaderModule, error)

LoadShaderFromBytes creates a shader module from raw SPIR-V bytecode.

func NewDesktopSurface

func NewDesktopSurface(instance vk.Instance, window *glfw.Window) (vk.Surface, error)

NewDesktopSurface is a GLFW helper for creating a Vulkan surface.

func NewExtentSize

func NewExtentSize(width, height int) vk.Extent2D

NewExtentSize needs for Wayland

func NewTriangleGeometry

func NewTriangleGeometry(desc TriangleGeometryDesc) vk.AccelerationStructureGeometry

NewTriangleGeometry builds a vk.AccelerationStructureGeometry from a triangle description.

func QuatInnerProduct

func QuatInnerProduct(a, b *Quat) (p float32)

func QuatMultInner3

func QuatMultInner3(a, b *Quat) (p float32)

func RadiansToDegrees

func RadiansToDegrees(angleRadians float32) float32

RadiansToDegrees converts radians to degrees.

func RaytracingDeviceExtensions

func RaytracingDeviceExtensions() []string

func RequireInstanceApiVersion

func RequireInstanceApiVersion(minVersion uint32) error

RequireInstanceApiVersion ensures the installed Vulkan loader supports at least minVersion. Must be called after vk.Init — i.e. after Host.InitVulkan or its manual equivalent — because it depends on the dispatch table.

Returns a descriptive error when the loader is older, which gives callers a clearer failure mode than the raw VK_ERROR_INCOMPATIBLE_DRIVER that vkCreateInstance would otherwise produce if ApplicationInfo.ApiVersion is higher than the loader supports. Pre-1.1 loaders don't expose vkEnumerateInstanceVersion; in that case Result != Success and we fall back to reporting 1.0, which is the spec-defined default.

func SetDebug

func SetDebug(state bool)

func SetValidations

func SetValidations(state bool)

func StartPrintGCPauses

func StartPrintGCPauses(period time.Duration)

StartPrintGCPauses every 10 seconds prints to std output information about GC

func TransitionImageLayout

func TransitionImageLayout(device vk.Device, queue vk.Queue, cmdPool vk.CommandPool,
	image vk.Image, oldLayout, newLayout vk.ImageLayout)

TransitionImageLayout performs a one-time image layout transition using a temporary command buffer.

func Vec2MultInner

func Vec2MultInner(a, b *Vec2) (p float32)

func Vec3MultInner

func Vec3MultInner(a, b *Vec3) (p float32)

func Vec4MultInner

func Vec4MultInner(a, b *Vec4) (p float32)

func Vec4MultInner3

func Vec4MultInner3(a, b *Vec4) (p float32)

Types

type AccelerationStructure

type AccelerationStructure struct {
	AccelerationStructure vk.AccelerationStructure
	Type                  vk.AccelerationStructureType
	DeviceAddress         vk.DeviceAddress
	Buffer                BufferResource
	// contains filtered or unexported fields
}

AccelerationStructure owns a Manager acceleration structure handle, its backing buffer, and optional device address. Works for both BLAS (bottom-level) and TLAS (top-level).

func (*AccelerationStructure) Destroy

func (a *AccelerationStructure) Destroy()

Destroy releases the acceleration structure handle first, then the backing buffer. Order matters: the AS handle must be destroyed before the buffer it references.

func (*AccelerationStructure) GetDeviceAddress

func (a *AccelerationStructure) GetDeviceAddress() vk.DeviceAddress

GetDeviceAddress returns the cached device address, querying it on the first call.

type ArrayFloat32

type ArrayFloat32 []float32

func (ArrayFloat32) Data

func (a ArrayFloat32) Data() []byte

func (ArrayFloat32) Sizeof

func (a ArrayFloat32) Sizeof() int

type BindingAccelerationStructure

type BindingAccelerationStructure struct {
	StageFlags            vk.ShaderStageFlags
	AccelerationStructure vk.AccelerationStructure
	// contains filtered or unexported fields
}

BindingAccelerationStructure binds a top-level acceleration structure.

type BindingImageSampler

type BindingImageSampler struct {
	StageFlags        vk.ShaderStageFlags
	Resource          *ImageResource
	ImageView         vk.ImageView
	Sampler           vk.Sampler
	Layout            vk.ImageLayout // 0 defaults to ShaderReadOnlyOptimal
	ImmutableSamplers []vk.Sampler
}

BindingImageSampler binds a single combined image sampler.

func NewBindingImageSampler

func NewBindingImageSampler(stageFlags vk.ShaderStageFlags, resource *ImageResource, immutableSamplers []vk.Sampler) *BindingImageSampler

NewBindingImageSampler creates a combined-image-sampler descriptor binding from an ImageResource.

type BindingImageSamplerArray

type BindingImageSamplerArray struct {
	StageFlags        vk.ShaderStageFlags
	ImageInfos        []vk.DescriptorImageInfo
	ImmutableSamplers []vk.Sampler
}

BindingImageSamplerArray binds an array of combined image samplers (e.g. texture array for RT).

type BindingStorageBuffer

type BindingStorageBuffer struct {
	StageFlags vk.ShaderStageFlags
	Buffer     vk.Buffer
	Range      vk.DeviceSize // 0 = WholeSize
}

BindingStorageBuffer binds a storage buffer (e.g. geometry node SSBO).

type BindingStorageImage

type BindingStorageImage struct {
	StageFlags vk.ShaderStageFlags
	Resource   *ImageResource
	ImageView  vk.ImageView
	Layout     vk.ImageLayout // 0 defaults to General
}

BindingStorageImage binds a storage image (e.g. ray tracing output).

func NewBindingStorageImage

func NewBindingStorageImage(stageFlags vk.ShaderStageFlags, resource *ImageResource) *BindingStorageImage

NewBindingStorageImage creates a storage-image descriptor binding from an ImageResource.

type BindingUniformBuffer

type BindingUniformBuffer struct {
	StageFlags vk.ShaderStageFlags
	Uniforms   *UniformBuffers
}

BindingUniformBuffer binds per-frame uniform buffers. Each descriptor set gets the buffer at its swapchain index.

type BufferResource

type BufferResource struct {
	Buffer        vk.Buffer
	Memory        vk.DeviceMemory
	Size          uint64
	Usage         vk.BufferUsageFlags
	DeviceAddress vk.DeviceAddress
	// contains filtered or unexported fields
}

BufferResource is a generic Manager buffer allocation. It owns the VkBuffer, its backing VkDeviceMemory, and optional device address metadata.

func NewBufferDeviceLocal

func NewBufferDeviceLocal(device vk.Device, gpu vk.PhysicalDevice, size uint64, enableDeviceAddress bool, usage vk.BufferUsageFlags) (BufferResource, error)

NewBufferDeviceLocal creates a device-local buffer. Manager-local memory cannot be written from CPU, so size is specified in bytes directly.

func NewBufferHostVisible

func NewBufferHostVisible[T any](device vk.Device, gpu vk.PhysicalDevice, data []T, enableDeviceAddress bool, usage vk.BufferUsageFlags) (BufferResource, error)

NewBufferHostVisible creates a host-visible/coherent buffer from a typed slice. The buffer size is computed automatically from the slice length and element size.

func NewBufferResource

func NewBufferResource(device vk.Device, gpu vk.PhysicalDevice, size uint64, opts BufferResourceOptions) (BufferResource, error)

NewBufferResource creates a generic buffer resource with configurable usage, memory properties, initial data, and optional device address support.

func (*BufferResource) Destroy

func (r *BufferResource) Destroy()

func (*BufferResource) Update

func (r *BufferResource) Update(data []byte) error

Update overwrites the entire buffer contents. The resource must use host-visible memory.

type BufferResourceOptions

type BufferResourceOptions struct {
	Usage               vk.BufferUsageFlags
	MemoryProperties    vk.MemoryPropertyFlagBits
	EnableDeviceAddress bool
	InitialData         unsafe.Pointer
}

BufferResourceOptions configures BufferResource creation.

type Cleanup

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

Cleanup collects destroyable objects and runs them in LIFO order. Register cleanup right after object creation with Add, then call Destroy at shutdown to tear down everything in reverse order.

func (*Cleanup) Add

func (d *Cleanup) Add(object Destroyer)

Add registers a destroyable object. Objects run in reverse order on Destroy.

func (*Cleanup) Destroy

func (d *Cleanup) Destroy()

Destroy runs all registered destroyers in LIFO order and clears the list.

type CommandContext

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

CommandContext owns a command pool plus reusable frame command buffers. It also provides helpers for transient single-use command buffers.

func NewCommandContext

func NewCommandContext(device vk.Device, queueFamilyIndex, commandBufferCount uint32) (CommandContext, error)

NewCommandContext creates a resettable command pool and optionally allocates a fixed set of primary command buffers for per-frame recording.

func (*CommandContext) BeginOneTime

func (c *CommandContext) BeginOneTime() (vk.CommandBuffer, error)

BeginOneTime allocates and begins a transient primary command buffer.

func (*CommandContext) BindRTPipeline

func (c *CommandContext) BindRTPipeline(cmd vk.CommandBuffer, pipeline PipelineRaytracing, descriptorSet vk.DescriptorSet)

BindRTPipeline binds a ray tracing pipeline and a descriptor set to the command buffer.

func (*CommandContext) BindRasterPipeline

func (c *CommandContext) BindRasterPipeline(cmd vk.CommandBuffer, pipeline PipelineRasterization)

BindRasterPipeline binds a rasterization pipeline to the command buffer.

func (*CommandContext) BindVertexBuffers

func (c *CommandContext) BindVertexBuffers(cmd vk.CommandBuffer, firstBinding uint32, buffers []vk.Buffer, offsets []vk.DeviceSize)

BindVertexBuffers binds vertex buffers to the command buffer.

func (*CommandContext) Destroy

func (c *CommandContext) Destroy()

Destroy frees reusable command buffers and destroys the command pool.

func (*CommandContext) Draw

func (c *CommandContext) Draw(cmd vk.CommandBuffer, vertexCount, instanceCount, firstVertex, firstInstance uint32)

Draw records a non-indexed draw call.

func (*CommandContext) EndOneTime

func (c *CommandContext) EndOneTime(queue vk.Queue, cmd vk.CommandBuffer) error

EndOneTime ends, submits, waits, and frees a transient command buffer.

func (*CommandContext) GetCmdBuffers

func (c *CommandContext) GetCmdBuffers() []vk.CommandBuffer

func (*CommandContext) GetCmdPool

func (c *CommandContext) GetCmdPool() vk.CommandPool

func (*CommandContext) TraceRays

func (c *CommandContext) TraceRays(cmd vk.CommandBuffer, sbt *ShaderBindingTable, displaySize vk.Extent2D)

TraceRays records a ray tracing dispatch using the shader binding table regions.

type CreateSurfaceFunc

type CreateSurfaceFunc func(instance vk.Instance) (vk.Surface, error)

CreateSurfaceFunc creates a VkSurface from a Vulkan instance. On desktop (GLFW) this typically calls window.CreateWindowSurface; on Android it receives the native window pointer.

type DescriptorBinding

type DescriptorBinding interface {
	// contains filtered or unexported methods
}

DescriptorBinding describes a single binding in a descriptor set. Implement this interface with one of the concrete binding types: BindingAccelerationStructure, BindingStorageImage, BindingUniformBuffer, BindingStorageBuffer, BindingImageSampler, BindingImageSamplerArray.

type DescriptorInfo

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

DescriptorInfo manages a descriptor set layout, pool, and allocated sets.

func NewDescriptorSets

func NewDescriptorSets(device vk.Device, setCount uint32, bindings []DescriptorBinding) (DescriptorInfo, error)

NewDescriptorSets creates a descriptor set layout, pool, and sets from a slice of bindings. Binding indices are assigned sequentially (0, 1, 2, ...).

func (*DescriptorInfo) Destroy

func (d *DescriptorInfo) Destroy()

Destroy releases the descriptor pool and layout.

func (*DescriptorInfo) GetLayout

func (d *DescriptorInfo) GetLayout() vk.DescriptorSetLayout

GetLayout returns the descriptor set layout.

func (*DescriptorInfo) GetSets

func (d *DescriptorInfo) GetSets() []vk.DescriptorSet

GetSets returns all allocated descriptor sets.

type Destroyer

type Destroyer interface {
	Destroy()
}

Destroyer represents a type that can release its owned resources.

type DeviceOptions

type DeviceOptions struct {
	InstanceExtensions []string
	DeviceExtensions   []string
	PNextChain         unsafe.Pointer // pNext chain for VkDeviceCreateInfo
	EnabledFeatures    *vk.PhysicalDeviceFeatures
	ApiVersion         uint32 // Manager API version, e.g. vk.MakeVersion(1,2,0). 0 defaults to 1.0.
}

DeviceOptions configures instance and device creation for NewManager.

type DisplayTiming

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

DisplayTiming provides frame pacing using the VK_GOOGLE_display_timing extension. It queries actual display refresh rate and past presentation timestamps to calculate optimal target present times, eliminating stutter and unnecessary frame drops.

Usage:

  1. Enable VK_GOOGLE_display_timing as a device extension.
  2. After creating the swapchain, call NewDisplayTiming.
  3. Before each QueuePresent, call NextPresentInfo and chain it via PresentInfo.PNext.
  4. The extension gracefully degrades: when unsupported, IsEnabled returns false and NextPresentInfo returns nil (present without timing).

func NewDisplayTiming

func NewDisplayTiming(device vk.Device, swapchain vk.Swapchain) DisplayTiming

NewDisplayTiming creates a DisplayTiming for the given swapchain. The VK_GOOGLE_display_timing extension must be enabled on the device. If the extension is not available or the query fails, the returned DisplayTiming is disabled and all methods become no-ops.

func (*DisplayTiming) ChainPresentInfo

func (dt *DisplayTiming) ChainPresentInfo(presentInfo *vk.PresentInfo)

ChainPresentInfo is a convenience that sets presentInfo.PNext to the display timing info when enabled. It is a no-op when timing is disabled.

func (*DisplayTiming) GetRefreshDuration

func (dt *DisplayTiming) GetRefreshDuration() uint64

GetRefreshDuration returns the display refresh cycle in nanoseconds. Returns 0 when display timing is disabled.

func (*DisplayTiming) IsEnabled

func (dt *DisplayTiming) IsEnabled() bool

IsEnabled reports whether display timing is active.

func (*DisplayTiming) NextPresentInfo

func (dt *DisplayTiming) NextPresentInfo() *vk.PresentTimesInfoGOOGLE

NextPresentInfo returns a PresentTimesInfoGOOGLE to chain into PresentInfo.PNext. Returns nil when display timing is disabled — the caller can safely ignore it.

timingInfo := dt.NextPresentInfo()
if timingInfo != nil {
    presentInfo.PNext = unsafe.Pointer(timingInfo.Ref())
}

func (*DisplayTiming) Rebind

func (dt *DisplayTiming) Rebind(swapchain vk.Swapchain)

Rebind updates the swapchain handle after a swapchain recreation. Past-presentation timing state is reset because it belongs to the old swapchain.

func (*DisplayTiming) SyncPastTiming

func (dt *DisplayTiming) SyncPastTiming()

SyncPastTiming drains all pending past presentation results and uses the latest actual present time to recalculate the next target present time.

type Frame

type Frame struct {
	Cmd        vk.CommandBuffer
	ImageIndex uint32
	Extent     vk.Extent2D
	Swapchain  *Swapchain
}

Frame is a per-frame record handed to Renderer.Draw.

Cmd is already reset and begun by the Session; Draw just records commands into it. The Session ends and submits the command buffer after Draw returns.

type GLTFModel

type GLTFModel struct {
	Primitives     []GLTFPrimitive
	GeometryBuffer BufferResource
	BLAS           AccelerationStructure
	Textures       []ImageResource
	// contains filtered or unexported fields
}

GLTFModel owns primitive buffers, textures, a geometry buffer, and a single BLAS for the loaded glTF model.

func LoadGLTFModel

func LoadGLTFModel(rt *RaytracingContext, path string) (GLTFModel, error)

LoadGLTFModel loads a glTF scene into GPU buffers, creates the geometry SSBO, and builds a single BLAS containing one geometry per primitive.

func NewGLTFModel

func NewGLTFModel(device vk.Device, primitives []GLTFPrimitive, geometryBuffer BufferResource, blas AccelerationStructure, textures []ImageResource) GLTFModel

func (*GLTFModel) Destroy

func (m *GLTFModel) Destroy()

type GLTFPrimitive

type GLTFPrimitive struct {
	VertexBuffer  BufferResource
	IndexBuffer   BufferResource
	VertexCount   uint32
	TriangleCount uint32
	Transform     [12]float32
	BaseColorTex  int32
	OcclusionTex  int32
}

GLTFPrimitive holds per-primitive GPU resources and metadata used by the ray tracing examples.

type Host

type Host interface {
	// Start prepares the platform layer and begins delivering events on Events().
	// It must be called before any other method except Events().
	Start() error

	// InitVulkan performs platform-specific proc-address loader setup and vk.Init.
	// Called by NewSession before instance creation.
	InitVulkan() error

	// InstanceExtensions reports platform-specific instance extensions required
	// to build a working surface. Manager may add further generic extensions.
	InstanceExtensions() []string

	// CreateSurface creates a VkSurfaceKHR for the current platform window.
	// Returns an error when no window is currently available.
	CreateSurface(instance vk.Instance) (vk.Surface, error)

	// CurrentExtent reports the platform window's logical size.
	// ok=false when no surface is known yet (e.g. before first SurfaceAvailable).
	CurrentExtent() (vk.Extent2D, bool)

	// Events returns a channel of platform lifecycle events. Consumers must
	// drain it promptly to avoid blocking the demux goroutine.
	Events() <-chan HostEvent

	// Pump advances the platform event loop on the run-loop goroutine. It is a
	// no-op on platforms whose event loop runs independently.
	Pump()

	// Shutdown releases platform resources. Safe to call multiple times.
	Shutdown()
}

Host abstracts the platform/windowing layer (GLFW on desktop, app.NativeActivity on Android). A Host is created by the application entry point and handed to NewSession, which drives the entire Vulkan lifecycle on top of it.

Responsibilities split:

  • The Host owns the platform window / native surface handle and emits lifecycle events onto Events().
  • The Session owns Vulkan instance/device/swapchain and consumes events.

Thread model:

  • Run-loop methods (Pump) must be called from the same goroutine that runs the platform event pump. On desktop this is the OS main thread (locked via runtime.LockOSThread). On Android it is the app.Main callback goroutine, and Pump is a no-op.
  • CreateSurface and InitVulkan may be called from the run-loop goroutine.

func NewDesktopHost

func NewDesktopHost(width, height int, title string) Host

NewDesktopHost returns a Host that drives GLFW on the calling main thread.

type HostEvent

type HostEvent struct {
	Kind   HostEventKind
	Extent vk.Extent2D
}

HostEvent is a single platform-originated message on the Host events channel.

type HostEventKind

type HostEventKind int

HostEventKind enumerates platform lifecycle events the Session reacts to.

const (
	// HostEventSurfaceAvailable signals that a platform surface is ready for use.
	// Extent carries the initial window size. Emitted on first startup and again
	// after a previously-lost surface has been recreated.
	HostEventSurfaceAvailable HostEventKind = iota

	// HostEventSurfaceLost signals that the platform surface has been destroyed.
	// Any Vulkan swapchain or device tied to it must be torn down before the next
	// HostEventSurfaceAvailable can be honored.
	HostEventSurfaceLost

	// HostEventSurfaceInvalidated signals that the current surface is still valid
	// but its size or orientation has changed. Extent carries the new size. The
	// Session responds by requesting a swapchain recreation at the next frame.
	HostEventSurfaceInvalidated

	// HostEventPause signals that the app has been backgrounded and must stop
	// issuing GPU work. The Vulkan device and swapchain remain valid — this is
	// a soft signal, orthogonal to surface lifetime. Android emits it on
	// onPause; the Session waits for the device to become idle and then gates
	// the render loop until HostEventResume arrives. If the platform later
	// destroys the surface while paused, HostEventSurfaceLost follows normally.
	HostEventPause

	// HostEventResume signals that the app has been foregrounded. The Session
	// un-gates the render loop. If the swapchain changed during the pause
	// (e.g. rotation while backgrounded), a HostEventSurfaceInvalidated is
	// emitted separately.
	HostEventResume

	// HostEventClose signals that the user or OS asked the app to exit.
	HostEventClose
)

type ImageResource

type ImageResource struct {
	Image   vk.Image
	Memory  vk.DeviceMemory
	View    vk.ImageView
	Sampler vk.Sampler
	Format  vk.Format
	Extent  vk.Extent3D
	Layout  vk.ImageLayout
	// contains filtered or unexported fields
}

ImageResource is a generic Manager image allocation. It owns the VkImage, its backing VkDeviceMemory, VkImageView, and optional VkSampler.

func LoadGLTFTextures

func LoadGLTFTextures(dev vk.Device, gpu vk.PhysicalDevice, queue vk.Queue, cmdCtx *CommandContext, doc *gltf.Document, baseDir string) ([]ImageResource, error)

LoadGLTFTextures loads glTF textures into Manager image resources. Index 0 always contains a 1x1 white fallback texture.

func NewImageDepth

func NewImageDepth(device vk.Device, gpu vk.PhysicalDevice, width, height uint32, format vk.Format) (ImageResource, error)

NewImageDepth creates a depth buffer with the given dimensions and format.

func NewImageResourceFromHandles

func NewImageResourceFromHandles(device vk.Device, image vk.Image, memory vk.DeviceMemory, view vk.ImageView, sampler vk.Sampler, format vk.Format) ImageResource

NewImageResourceFromHandles wraps pre-existing Manager handles into a ImageResource. Use this when image creation is done manually (e.g. staging buffer upload with optimal tiling). Layout defaults to Undefined because the caller owns the synchronization contract.

func NewImageStorage

func NewImageStorage(device vk.Device, gpu vk.PhysicalDevice, queue vk.Queue, cmdPool vk.CommandPool, width, height uint32, format vk.Format) (ImageResource, error)

NewImageStorage creates a device-local storage image and transitions it to General layout.

func NewImageTexture

func NewImageTexture(device vk.Device, gpu vk.PhysicalDevice, width, height uint32, rgbaPixels []byte) (ImageResource, error)

NewImageTexture creates a texture from RGBA pixel data with a nearest-filter sampler. After creation, call TransitionImageLayout to transition from PreInitialized to ShaderReadOnlyOptimal.

func NewImageTextureWithSampler

func NewImageTextureWithSampler(device vk.Device, gpu vk.PhysicalDevice, queue vk.Queue, cmdCtx *CommandContext, width, height uint32, rgbaPixels []byte, samplerInfo vk.SamplerCreateInfo) (ImageResource, error)

NewImageTextureWithSampler uploads RGBA pixels through a staging buffer into an optimal-tiled sampled image and creates a sampler from samplerInfo.

func (*ImageResource) Destroy

func (r *ImageResource) Destroy()

func (*ImageResource) GetExtent

func (r *ImageResource) GetExtent() vk.Extent3D

func (*ImageResource) GetFormat

func (r *ImageResource) GetFormat() vk.Format

func (*ImageResource) GetImage

func (r *ImageResource) GetImage() vk.Image

func (*ImageResource) GetLayout

func (r *ImageResource) GetLayout() vk.ImageLayout

func (*ImageResource) GetSampler

func (r *ImageResource) GetSampler() vk.Sampler

func (*ImageResource) GetView

func (r *ImageResource) GetView() vk.ImageView

func (*ImageResource) SampledDescriptorInfo

func (r *ImageResource) SampledDescriptorInfo() vk.DescriptorImageInfo

SampledDescriptorInfo returns descriptor info for sampled image bindings.

func (*ImageResource) StorageDescriptorInfo

func (r *ImageResource) StorageDescriptorInfo() vk.DescriptorImageInfo

StorageDescriptorInfo returns descriptor info for storage image bindings.

func (*ImageResource) TransitionLayout

func (r *ImageResource) TransitionLayout(queue vk.Queue, cmdPool vk.CommandPool, newLayout vk.ImageLayout)

TransitionLayout updates the resource to the requested layout using the stored current state.

type Manager

type Manager struct {
	Device   vk.Device
	Instance vk.Instance
	Surface  vk.Surface
	Gpu      vk.PhysicalDevice
	Queue    vk.Queue
	// contains filtered or unexported fields
}

func NewManager

func NewManager(appName string, createSurfaceFn CreateSurfaceFunc, opts *DeviceOptions) (Manager, error)

NewManager creates a Manager device with custom options for extensions and features.

func (*Manager) Destroy

func (v *Manager) Destroy()

Destroy waits for the device to be idle and tears down the device, debug callback, surface, and instance.

func (*Manager) GetDebugCallback

func (v *Manager) GetDebugCallback() vk.DebugReportCallback

func (*Manager) QuerySurfaceExtent

func (v *Manager) QuerySurfaceExtent(fallback vk.Extent2D) vk.Extent2D

QuerySurfaceExtent returns the current platform surface extent reported by the driver. On Android this reflects rotation-induced size changes after a config change event. Falls back to the provided extent when the capabilities query fails or when the driver returns the Wayland-style "undefined" extent (all-ones) or a zero extent.

type Mat4x4

type Mat4x4 [4]Vec4

func InvertMatrix

func InvertMatrix(m *Mat4x4) Mat4x4

InvertMatrix computes the inverse of a 4x4 matrix using cofactor expansion. Returns the identity matrix if the input is singular.

func (*Mat4x4) Add

func (m *Mat4x4) Add(a, b *Mat4x4)

func (*Mat4x4) Data

func (m *Mat4x4) Data() []byte

func (*Mat4x4) Dup

func (m *Mat4x4) Dup(n *Mat4x4)

func (*Mat4x4) Fill

func (m *Mat4x4) Fill(d float32)

func (*Mat4x4) FromQuat

func (m *Mat4x4) FromQuat(q *Quat)

func (*Mat4x4) FromVec3MultOuter

func (m *Mat4x4) FromVec3MultOuter(a, b *Vec3)

func (*Mat4x4) Frustum

func (m *Mat4x4) Frustum(l, r, b, t, n, f float32)

func (*Mat4x4) Identity

func (m *Mat4x4) Identity()

func (*Mat4x4) Invert

func (t *Mat4x4) Invert(m *Mat4x4)

func (*Mat4x4) LookAt

func (m *Mat4x4) LookAt(eye, center, up *Vec3)

func (*Mat4x4) Mult

func (m *Mat4x4) Mult(a, b *Mat4x4)

func (*Mat4x4) MultQuat

func (r *Mat4x4) MultQuat(m *Mat4x4, q *Quat)

func (*Mat4x4) Ortho

func (m *Mat4x4) Ortho(l, r, b, t, n, f float32)

func (*Mat4x4) OrthoNormalize

func (r *Mat4x4) OrthoNormalize(m *Mat4x4)

func (*Mat4x4) Perspective

func (m *Mat4x4) Perspective(y_fov, aspect, n, f float32)

func (*Mat4x4) Rotate

func (r *Mat4x4) Rotate(m *Mat4x4, x, y, z, angle float32)

func (*Mat4x4) RotateX

func (q *Mat4x4) RotateX(m *Mat4x4, angle float32)

func (*Mat4x4) RotateY

func (q *Mat4x4) RotateY(m *Mat4x4, angle float32)

func (*Mat4x4) RotateZ

func (q *Mat4x4) RotateZ(m *Mat4x4, angle float32)

func (*Mat4x4) Scale

func (m *Mat4x4) Scale(a *Mat4x4, k float32)

func (*Mat4x4) ScaleAniso

func (m *Mat4x4) ScaleAniso(a *Mat4x4, x, y, z float32)

func (*Mat4x4) Sub

func (m *Mat4x4) Sub(a, b *Mat4x4)

func (*Mat4x4) Translate

func (m *Mat4x4) Translate(x, y, z float32)

func (*Mat4x4) TranslateInPlace

func (m *Mat4x4) TranslateInPlace(x, y, z float32)

func (*Mat4x4) Transpose

func (m *Mat4x4) Transpose(n *Mat4x4)

type Model

type Model struct {
	Vertices        []float32 // interleaved: pos3 + norm3 = 6 floats per vertex
	FloatsPerVertex int
	Indices         []uint32
}

Model holds parsed glTF model data with interleaved position(3) + normal(3) vertices.

func LoadModel

func LoadModel(path string) (Model, error)

LoadModel loads a glTF/GLB file and returns a Model with interleaved vertex data (pos3+norm3).

func (*Model) IndexCount

func (m *Model) IndexCount() int

IndexCount returns the number of indices.

func (*Model) VertexCount

func (m *Model) VertexCount() int

VertexCount returns the number of vertices.

type PipelineOptions

type PipelineOptions struct {
	// VertShaderData is raw SPIR-V bytecode for the vertex shader.
	// If nil, error happens
	VertShaderData []byte
	// FragShaderData is raw SPIR-V bytecode for the fragment shader.
	// If nil, error happens
	FragShaderData []byte
	// PushConstantRanges defines push constant ranges for the pipeline layout.
	// If nil, no push constants are used.
	PushConstantRanges []vk.PushConstantRange
	// VertexBindings defines custom vertex input bindings.
	// If nil, a default single binding (stride 12, vec3 position) is used.
	VertexBindings []vk.VertexInputBindingDescription
	// VertexAttributes defines custom vertex input attributes.
	// If nil, the default single attribute (location 0, R32G32B32Sfloat) is used.
	VertexAttributes []vk.VertexInputAttributeDescription
	// DescriptorSetLayouts defines descriptor set layouts for the pipeline layout.
	// If nil, no descriptor sets are used.
	DescriptorSetLayouts []vk.DescriptorSetLayout
	// DepthTestEnable enables depth testing and writing.
	DepthTestEnable bool
}

PipelineOptions configures optional pipeline parameters.

type PipelineRasterization

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

func NewPipelineRasterization

func NewPipelineRasterization(device vk.Device, displaySize vk.Extent2D, renderPass vk.RenderPass, opts PipelineOptions) (PipelineRasterization, error)

NewPipelineRasterization creates a graphics pipeline with custom shaders and push constants.

func (*PipelineRasterization) Destroy

func (gfx *PipelineRasterization) Destroy()

func (*PipelineRasterization) GetLayout

func (gfx *PipelineRasterization) GetLayout() vk.PipelineLayout

func (*PipelineRasterization) GetPipeline

func (gfx *PipelineRasterization) GetPipeline() vk.Pipeline

type PipelineRaytracing

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

PipelineRaytracing holds a ray tracing pipeline and its layout.

func NewRTPipeline

func NewRTPipeline(device vk.Device, opts RTPipelineOptions) (PipelineRaytracing, error)

NewRTPipeline creates a ray tracing pipeline from shader group definitions. Shader modules are created internally and destroyed after pipeline creation.

func (*PipelineRaytracing) Destroy

func (p *PipelineRaytracing) Destroy()

func (*PipelineRaytracing) GetLayout

func (p *PipelineRaytracing) GetLayout() vk.PipelineLayout

func (*PipelineRaytracing) GetPipeline

func (p *PipelineRaytracing) GetPipeline() vk.Pipeline

type Quat

type Quat [4]float32

func (*Quat) Add

func (r *Quat) Add(a, b *Quat)

func (*Quat) AddVec3

func (r *Quat) AddVec3(a *Quat, v *Vec3)

func (*Quat) Conj

func (r *Quat) Conj(q *Quat)

func (*Quat) FromMat4x4

func (q *Quat) FromMat4x4(m *Mat4x4)

func (*Quat) Identity

func (q *Quat) Identity()

func (*Quat) Len

func (q *Quat) Len() float32

func (*Quat) Mult

func (r *Quat) Mult(p, q *Quat)

func (*Quat) MultCross3

func (r *Quat) MultCross3(a, b *Quat)

func (*Quat) Norm

func (r *Quat) Norm(q *Quat)

func (*Quat) Scale

func (r *Quat) Scale(q *Quat, s float32)

func (*Quat) Sub

func (r *Quat) Sub(a, b *Quat)

type RTPipelineOptions

type RTPipelineOptions struct {
	Groups                       []RTShaderGroup
	DescriptorSetLayouts         []vk.DescriptorSetLayout
	PushConstantRanges           []vk.PushConstantRange
	MaxPipelineRayRecursionDepth uint32 // 0 defaults to 1
}

RTPipelineOptions configures a ray tracing pipeline.

type RTShaderGroup

type RTShaderGroup struct {
	RaygenShader       []byte // SPIR-V — implies General group, ShaderStageRaygenBit
	MissShader         []byte // SPIR-V — implies General group, ShaderStageMissBit
	CallableShader     []byte // SPIR-V — implies General group, ShaderStageCallableBit
	ClosestHitShader   []byte // SPIR-V — ShaderStageClosestHitBit
	AnyHitShader       []byte // SPIR-V — ShaderStageAnyHitBit
	IntersectionShader []byte // SPIR-V — implies Procedural hit group, ShaderStageIntersectionBit
}

RTShaderGroup defines one shader group for a ray tracing pipeline. The group type is inferred from which shader fields are set. Set exactly one of RaygenShader/MissShader/CallableShader for General groups, or ClosestHitShader (with optional AnyHitShader) for triangle hit groups, or IntersectionShader (with optional ClosestHitShader/AnyHitShader) for procedural hit groups.

type RasterizationPass

type RasterizationPass struct {
	RenderPass vk.RenderPass
	// contains filtered or unexported fields
}

RasterizationPass owns a render pass used by rasterization pipelines. Framebuffers remain owned by Swapchain and command buffers by CommandContext.

func NewRasterPass

func NewRasterPass(device vk.Device, displayFormat vk.Format) (RasterizationPass, error)

NewRasterPass creates a render pass with a single color attachment.

func NewRasterPassWithDepth

func NewRasterPassWithDepth(device vk.Device, displayFormat vk.Format, depthFormat vk.Format) (RasterizationPass, error)

NewRasterPassWithDepth creates a render pass with color + depth attachments.

func (*RasterizationPass) Destroy

func (r *RasterizationPass) Destroy()

func (*RasterizationPass) GetRenderPass

func (r *RasterizationPass) GetRenderPass() vk.RenderPass

type RaytracingContext

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

RaytracingContext is a lightweight orchestration object for ray tracing helpers. It does not own Manager resources; it only groups dependencies commonly needed to build acceleration structures and other RT resources.

func NewRaytracingContext

func NewRaytracingContext(manager *Manager, cmdCtx *CommandContext) RaytracingContext

NewRaytracingContext groups the common RT dependencies without taking ownership.

func (*RaytracingContext) Destroy

func (rt *RaytracingContext) Destroy()

Destroy releases all acceleration structures created by this context.

func (*RaytracingContext) NewBottomLevelAccelerationStructure

func (rt *RaytracingContext) NewBottomLevelAccelerationStructure(
	geometries []vk.AccelerationStructureGeometry,
	primitiveCounts []uint32,
	flags vk.BuildAccelerationStructureFlags,
) (AccelerationStructure, error)

NewBottomLevelAccelerationStructure builds a BLAS from pre-configured geometry slices. The caller is responsible for setting up the geometry and primitive counts; this method handles size queries, buffer allocation, scratch, build, and cleanup.

func (*RaytracingContext) NewTopLevelAccelerationStructure

func (rt *RaytracingContext) NewTopLevelAccelerationStructure(instances []TLASInstance, flags vk.BuildAccelerationStructureFlags) (AccelerationStructure, error)

NewTopLevelAccelerationStructure builds a TLAS from the provided BLAS instances.

type Renderer

type Renderer interface {
	// CreateOnce builds resources that stay valid for the lifetime of the device:
	// textures, descriptor set layouts, static vertex/index buffers, shaders,
	// uniforms whose layout does not depend on swapchain length.
	CreateOnce(s *Session) error

	// DestroyOnce releases CreateOnce resources. Must be idempotent.
	DestroyOnce()

	// CreateSized builds resources that depend on the swapchain extent:
	// depth image, render pass (if its attachments encode extent-linked choices),
	// framebuffers, and graphics pipelines whose viewport/scissor is baked in.
	// Called once per swapchain generation.
	CreateSized(s *Session, extent vk.Extent2D) error

	// DestroySized releases CreateSized resources. Must be idempotent.
	DestroySized()

	// Draw records one frame into f.Cmd. The Session has already begun the
	// command buffer; Draw issues CmdBeginRenderPass, draw calls,
	// CmdEndRenderPass, and returns. Session handles end + submit + present.
	Draw(s *Session, f *Frame) error
}

Renderer is the application-supplied object that owns all size-dependent and size-independent graphics resources and records frame commands.

Lifecycle, as driven by Session.Run:

CreateOnce(s)                                   // device is live
CreateSized(s, extent0)                         // first swapchain built
    Draw(s, f)   ...   Draw(s, f)               // steady state
    [rotation / resize observed]
    DestroySized()
    CreateSized(s, extentN)                     // new swapchain built
    Draw(s, f)   ...
[surface lost]
DestroySized()
DestroyOnce()                                   // device torn down

All methods run on the Session's run goroutine. DestroySized / DestroyOnce must be idempotent — Run calls them in its shutdown path even if CreateSized / CreateOnce failed partway through.

type Session

type Session struct {
	Host    Host
	AppName string
	Opts    SessionOptions

	// Populated while the device is alive.
	Manager       *Manager
	Swapchain     *Swapchain
	CmdCtx        *CommandContext
	Sync          *SyncInfo
	DisplayTiming *DisplayTiming
	// contains filtered or unexported fields
}

Session owns the whole Vulkan stack (instance, device, swapchain, command pool, sync objects, display timing) and orchestrates the render loop on top of a Host. It is the single object a Renderer talks to.

Typical usage:

host := ash.NewDesktopHost(...)   // or ash.NewAndroidHost(a)
sess := ash.NewSession(host, "MyApp", nil)
sess.Run(&myRenderer{})

Session.Run is a blocking state machine. It reacts to HostEvents to build and tear down Vulkan resources, and drives the Renderer's lifecycle callbacks at the corresponding moments.

func NewSession

func NewSession(host Host, appName string, opts *SessionOptions) *Session

NewSession returns a Session bound to the given Host. NewSession does not touch the platform; all platform I/O happens inside Run.

func (*Session) AckRecreate

func (s *Session) AckRecreate()

AckRecreate clears the recreate flag after a rebuild is complete. Called by recreateSwapchain; exposed for renderers that need a hand-rolled rebuild.

func (*Session) AcquireNextImage

func (s *Session) AcquireNextImage(timeout uint64, semaphore vk.Semaphore, fence vk.Fence) (imageIndex uint32, acquired bool, err error)

AcquireNextImage acquires the next swapchain image and classifies WSI warnings. SUBOPTIMAL: acquisition succeeds and NeedsRecreate flips true. OUT_OF_DATE: no image is acquired and NeedsRecreate flips true.

func (*Session) BeginFrame

func (s *Session) BeginFrame(imageIndex uint32) (vk.CommandBuffer, error)

BeginFrame resets and begins the command buffer for the given swapchain image.

func (*Session) EndFrame

func (s *Session) EndFrame(cmd vk.CommandBuffer) error

EndFrame finalizes command buffer recording.

func (*Session) NeedsRecreate

func (s *Session) NeedsRecreate() bool

NeedsRecreate reports whether AcquireNextImage or PresentImage observed that the swapchain is suboptimal/out-of-date, or whether recreation was requested explicitly via RequestRecreate. Safe to call from any goroutine.

func (*Session) PresentImage

func (s *Session) PresentImage(imageIndex uint32, waitSemaphores []vk.Semaphore) (presented bool, err error)

PresentImage presents the rendered image and classifies WSI warnings. SUBOPTIMAL: presents successfully but requests recreation. OUT_OF_DATE: skips presentation and requests recreation.

func (*Session) RequestRecreate

func (s *Session) RequestRecreate()

RequestRecreate marks the swapchain as needing recreation on the next frame boundary. Safe to call from any goroutine; typically invoked by the platform event loop when it observes a window size / orientation change (Android NativeWindowRedrawNeeded).

func (*Session) Run

func (s *Session) Run(r Renderer) error

Run starts the platform Host, drives the Renderer lifecycle, and blocks until HostEventClose is received or a fatal error occurs.

func (*Session) SubmitRender

func (s *Session) SubmitRender(cmd vk.CommandBuffer, fence vk.Fence, waitSemaphores []vk.Semaphore) error

SubmitRender submits the recorded command buffer and waits for the fence.

type SessionOptions

type SessionOptions struct {
	DeviceOptions *DeviceOptions
	EnableTiming  bool // enable VK_GOOGLE_display_timing when available
}

SessionOptions configures device creation for NewSession.

type ShaderBindingTable

type ShaderBindingTable struct {
	Buffer   BufferResource
	Raygen   vk.StridedDeviceAddressRegion
	Miss     vk.StridedDeviceAddressRegion
	Hit      vk.StridedDeviceAddressRegion
	Callable vk.StridedDeviceAddressRegion
	// contains filtered or unexported fields
}

ShaderBindingTable holds a shader binding table buffer and the strided device address regions for each shader group type (raygen, miss, hit, callable).

func NewShaderBindingTable

func NewShaderBindingTable(device vk.Device, gpu vk.PhysicalDevice, pipeline vk.Pipeline,
	handleSize, handleAlignment uint32,
	raygenCount, missCount, hitCount, callableCount uint32,
) (ShaderBindingTable, error)

NewShaderBindingTable creates a shader binding table from a ray tracing pipeline. Groups are laid out sequentially: raygen, miss, hit, callable. handleSize and handleAlignment come from VkPhysicalDeviceRayTracingPipelinePropertiesKHR.

func (*ShaderBindingTable) Destroy

func (s *ShaderBindingTable) Destroy()

type Swapchain

type Swapchain struct {
	Swapchains   []vk.Swapchain
	SwapchainLen []uint32

	DisplaySize   vk.Extent2D
	DisplayFormat vk.Format
	PreTransform  vk.SurfaceTransformFlagBits

	Framebuffers []vk.Framebuffer
	DisplayViews []vk.ImageView
	// contains filtered or unexported fields
}

func NewSwapchain

func NewSwapchain(manager *Manager, windowSize vk.Extent2D) (Swapchain, error)

func (*Swapchain) CmdCopyToSwapchain

func (s *Swapchain) CmdCopyToSwapchain(cmd vk.CommandBuffer, srcImage vk.Image, imageIndex uint32)

CmdCopyToSwapchain records commands to copy a storage image to a swapchain image. It transitions the swapchain image to TransferDst, the source image from General to TransferSrc, performs the copy, then transitions back (swapchain to PresentSrc, source to General).

func (*Swapchain) CreateFramebuffers

func (s *Swapchain) CreateFramebuffers(renderPass vk.RenderPass, depthView vk.ImageView) error

func (*Swapchain) DefaultSwapchain

func (s *Swapchain) DefaultSwapchain() vk.Swapchain

func (*Swapchain) DefaultSwapchainLen

func (s *Swapchain) DefaultSwapchainLen() uint32

func (*Swapchain) Destroy

func (s *Swapchain) Destroy()

func (*Swapchain) PreRotationMatrix

func (s *Swapchain) PreRotationMatrix() Mat4x4

PreRotationMatrix returns a rotation matrix around the Z axis that matches the swapchain's preTransform. Multiply this into the projection matrix to handle Android surface rotation without compositor overhead.

func (*Swapchain) Recreate

func (s *Swapchain) Recreate(windowSize vk.Extent2D) error

Recreate rebuilds this Swapchain in place with a new target size. The previous swapchain handle is passed to the driver as oldSwapchain for an efficient handover of underlying images, then destroyed. On success the receiver's fields (Swapchains, DisplaySize, DisplayFormat, PreTransform, framebuffers) reflect the newly created swapchain.

The caller is responsible for ensuring no command buffer in flight still references the old swapchain's framebuffers (typically vk.DeviceWaitIdle before calling) and for rebuilding any size-dependent resources (framebuffers, depth image, pipelines) after return.

type SyncInfo

type SyncInfo struct {
	Fence     vk.Fence
	Semaphore vk.Semaphore
	// contains filtered or unexported fields
}

SyncInfo manages a fence and semaphore pair for frame synchronization.

func NewSyncObjects

func NewSyncObjects(device vk.Device) (SyncInfo, error)

NewSyncObjects creates a fence and a semaphore for frame synchronization.

func (*SyncInfo) Destroy

func (s *SyncInfo) Destroy()

Destroy releases the fence and semaphore.

type TLASInstance

type TLASInstance struct {
	Transform           [12]float32
	InstanceCustomIndex uint32
	Mask                uint8
	SBTRecordOffset     uint32
	Flags               vk.GeometryInstanceFlags
	BLAS                *AccelerationStructure
}

TLASInstance describes one TLAS instance referencing an already built BLAS.

type TexturedModel

type TexturedModel struct {
	Vertices        []float32 // interleaved: pos3 + norm3 + uv2 = 8 floats per vertex
	FloatsPerVertex int
	Indices         []uint32
	TextureRGBA     []byte
	TextureWidth    uint32
	TextureHeight   uint32
}

TexturedModel holds parsed glTF model data with interleaved position(3) + normal(3) + texcoord(2) vertices and a base color texture.

func LoadGLBModel

func LoadGLBModel(path string) (TexturedModel, error)

LoadGLBModel loads a glTF/GLB file and returns a TexturedModel with interleaved vertex data (pos3+norm3+uv2), indices, and the base color texture.

func (*TexturedModel) IndexCount

func (m *TexturedModel) IndexCount() int

IndexCount returns the number of indices.

func (*TexturedModel) VertexCount

func (m *TexturedModel) VertexCount() int

VertexCount returns the number of vertices.

type TriangleGeometryDesc

type TriangleGeometryDesc struct {
	VertexAddress vk.DeviceAddress
	VertexFormat  vk.Format // e.g. vk.FormatR32g32b32Sfloat
	VertexStride  uint32    // e.g. 12 for 3×float32
	MaxVertex     uint32
	IndexAddress  vk.DeviceAddress
	IndexType     vk.IndexType // e.g. vk.IndexTypeUint32
	Flags         vk.GeometryFlags
}

TriangleGeometryDesc describes a triangle geometry for BLAS construction.

type UniformBuffers

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

UniformBuffers manages a set of uniform buffers (typically one per swapchain image).

func NewUniformBuffers

func NewUniformBuffers(device vk.Device, gpu vk.PhysicalDevice, count uint32, dataSize int) (UniformBuffers, error)

NewUniformBuffers creates count uniform buffers of the given byte size. Typically count matches the swapchain image count.

func (*UniformBuffers) Destroy

func (u *UniformBuffers) Destroy()

Destroy frees all uniform buffers and their memory.

func (*UniformBuffers) GetBuffer

func (u *UniformBuffers) GetBuffer(index uint32) vk.Buffer

GetBuffer returns the buffer at the given index.

func (*UniformBuffers) GetBuffers

func (u *UniformBuffers) GetBuffers() []vk.Buffer

GetBuffers returns all buffers.

func (*UniformBuffers) GetSize

func (u *UniformBuffers) GetSize() int

GetSize returns the byte size of each uniform buffer.

func (*UniformBuffers) Update

func (u *UniformBuffers) Update(index uint32, data []byte)

Update writes data into the uniform buffer at the given index.

type Vec2

type Vec2 [2]float32

func (*Vec2) Add

func (r *Vec2) Add(a, b *Vec2)

func (*Vec2) Len

func (v *Vec2) Len() float32

func (*Vec2) Max

func (r *Vec2) Max(a, b *Vec2)

func (*Vec2) Min

func (r *Vec2) Min(a, b *Vec2)

func (*Vec2) Norm

func (r *Vec2) Norm(v *Vec2)

func (*Vec2) Scale

func (r *Vec2) Scale(v *Vec2, s float32)

func (*Vec2) Sub

func (r *Vec2) Sub(a, b *Vec2)

type Vec3

type Vec3 [3]float32

func (*Vec3) Add

func (r *Vec3) Add(a, b *Vec3)

func (*Vec3) Len

func (v *Vec3) Len() float32

func (*Vec3) Max

func (r *Vec3) Max(a, b *Vec3)

func (*Vec3) Min

func (r *Vec3) Min(a, b *Vec3)

func (*Vec3) MultCross

func (r *Vec3) MultCross(a, b *Vec3)

func (*Vec3) Norm

func (r *Vec3) Norm(v *Vec3)

func (*Vec3) QuatMultVec3

func (r *Vec3) QuatMultVec3(q *Quat, v *Vec3)

func (*Vec3) Reflect

func (r *Vec3) Reflect(v, n *Vec3)

func (*Vec3) Scale

func (r *Vec3) Scale(v *Vec3, s float32)

func (*Vec3) ScaleQuat

func (r *Vec3) ScaleQuat(q *Quat, s float32)

func (*Vec3) ScaleVec4

func (r *Vec3) ScaleVec4(v *Vec4, s float32)

func (*Vec3) Sub

func (r *Vec3) Sub(a, b *Vec3)

type Vec4

type Vec4 [4]float32

func (*Vec4) Add

func (r *Vec4) Add(a, b *Vec4)

func (*Vec4) Len

func (v *Vec4) Len() float32

func (*Vec4) Mat4x4Col

func (r *Vec4) Mat4x4Col(m *Mat4x4, i int)

func (*Vec4) Mat4x4MultVec4

func (r *Vec4) Mat4x4MultVec4(m *Mat4x4, v Vec4)

func (*Vec4) Mat4x4Row

func (r *Vec4) Mat4x4Row(m *Mat4x4, i int)

func (*Vec4) Max

func (r *Vec4) Max(a, b *Vec4)

func (*Vec4) Min

func (r *Vec4) Min(a, b *Vec4)

func (*Vec4) MultCross

func (r *Vec4) MultCross(a, b *Vec4)

func (*Vec4) Norm

func (r *Vec4) Norm(v *Vec4)

func (*Vec4) QuatMultVec4

func (r *Vec4) QuatMultVec4(q *Quat, v *Vec4)

func (*Vec4) Reflect

func (r *Vec4) Reflect(v, n *Vec4)

func (*Vec4) Scale

func (r *Vec4) Scale(v *Vec4, s float32)

func (*Vec4) Sub

func (r *Vec4) Sub(a, b *Vec4)

func (*Vec4) SubVec3

func (r *Vec4) SubVec3(a *Vec4, b *Vec3)

type VulkanIndexBufferInfo

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

VulkanIndexBufferInfo manages an index buffer for indexed drawing.

func NewIndexBuffer

func NewIndexBuffer(device vk.Device, gpu vk.PhysicalDevice, indices []uint16) (VulkanIndexBufferInfo, error)

NewIndexBuffer creates an index buffer from uint16 index data.

func NewIndexBuffer32

func NewIndexBuffer32(device vk.Device, gpu vk.PhysicalDevice, indices []uint32) (VulkanIndexBufferInfo, error)

NewIndexBuffer32 creates an index buffer from uint32 index data.

func (*VulkanIndexBufferInfo) Destroy

func (ib *VulkanIndexBufferInfo) Destroy()

func (*VulkanIndexBufferInfo) GetBuffer

func (ib *VulkanIndexBufferInfo) GetBuffer() vk.Buffer

func (*VulkanIndexBufferInfo) GetCount

func (ib *VulkanIndexBufferInfo) GetCount() uint32

GetCount returns the number of indices.

Jump to

Keyboard shortcuts

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