vgpu

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2024 License: BSD-3-Clause Imports: 27 Imported by: 0

README

vGPU: Vulkan GPU Framework for Graphics and Compute, in Go

Mac Installation prerequisite: https://vulkan.lunarg.com/sdk/home -- download the Vulkan SDK installer for the mac. Unfortunately there does not appear to be a full version of this on homebrew -- the molten-vk package is not enough by itself.

vGPU is a Vulkan-based framework for both Graphics and Compute Engine use of GPU hardware, in the Go langauge. It uses the basic cgo-based Go bindings to Vulkan in vulkan-go and was developed starting with the associated example code surrounding that project. Vulkan is a relatively new, essentially universally supported interface to GPU hardware across all types of systems from mobile phones to massive GPU-based compute hardware, and it provides high-performance "bare metal" access to the hardware, for both graphics and computational uses.

Vulkan is very low-level and demands a higher-level framework to manage the complexity and verbosity. While there are many helpful tutorials covering the basic API, many of the tutorials don't provide much of a pathway for how to organize everything at a higher level of abstraction. vGPU represents one attempt that enforces some reasonable choices that enable a significantly simpler programming model, while still providing considerable flexibility and high levels of performance. Everything is a tradeoff, and simplicity definitely was prioritized over performance in a few cases, but in practical use-cases, the performance differences should be minimal.

  • The gosl sub-package provides a way to translate Go code into GPU shader language code for running under vGPU, playing the role of NVIDIA's "cuda" language in other frameworks.

Platforms

  • On desktop (mac, windows, linux), glfw is used for initializing the GPU.
  • Mobile (android, ios)...
    • When developing for Android on macOS, it is critical to set Emulated Performance -> Graphics to Software in the Android Virtual Device Manager (AVD); otherwise, the app will crash on startup. This is because macOS does not support direct access to the underlying hardware GPU in the Android Emulator. You can see more information how to do this in the Android developer documentation. Please note that this issue will not affect end-users of your app, only you while you develop it. Also, due to the typically bad performance of the emulated device GPU on macOS, it is recommended that you use a more modern emulated device than the default Pixel 3a. Finally, you should always test your app on a real mobile device if possible to see what it is actually like.

Selecting a GPU Device

For systems with multiple GPU devices, by default the discrete device is selected, and if multiple of those are present, the one with the most RAM is used. To see what is available and their properties, use:

$ vulkaninfo --summary

The following environment variables can be set to specifically select a particular device by name (deviceName):

  • MESA_VK_DEVICE_SELECT (standard for mesa-based drivers) or VK_DEVICE_SELECT -- for graphics or compute usage.
  • VK_COMPUTE_DEVICE_SELECT -- only used for compute, if present -- will override above, so you can use different GPUs for graphics vs compute.

vPhong and vShape

The vPhong package provides a complete rendering implementation with different pipelines for different materials, and support for 4 different types of light sources based on the classic Blinn-Phong lighting model. See the examples/phong example for how to use it. It does not assume any kind of organization of the rendering elements, and just provides name and index-based access to all the resources needed to render a scene.

vShape generates standard 3D shapes (sphere, cylinder, box, etc), with all the normals and texture coordinates. You can compose shape elements into more complex groups of shapes, programmatically. It separates the calculation of the number of vertex and index elements from actually setting those elements, so you can allocate everything in one pass, and then configure the shape data in a second pass, consistent with the most efficient memory model provided by vgpu. It only has a dependency on the math32 package and could be used for anything.

Basic Elements and Organization

  • GPU represents the hardware Device and maintains global settings, info about the hardware.

    • Device is a logical device and associated Queue info -- each such device can function in parallel.
    • CmdPool manages a command pool and buffer, associated with a specific logical device, for submitting commands to the GPU.
  • System manages multiple vulkan Pipelines and associated variables, variable values, and memory, to accomplish a complete overall rendering / computational job. The Memory with Vars and Values are shared across all pipelines within a System.

    • Pipeline performs a specific chain of operations, using Shader program(s). In a graphics context, each pipeline typically handles a different type of material or other variation in rendering (textured vs. not, transparent vs. solid, etc).
    • Memory manages the memory, organized by Vars variables that are referenced in the shader programs, with each Var having any number of associated values in Values. Vars are organized into Sets that manage their bindings distinctly, and can be updated at different time scales. It has 4 different MemBuff buffers for different types of memory. It is assumed that the sizes of all the Values do not change frequently, so everything is Alloc'd afresh if any size changes. This avoids the need for complex de-fragmentation algorithms, and is maximally efficient, but is not good if sizes change (which is rare in most rendering cases).
  • Image manages a vulkan Image and associated ImageView, including potential host staging buffer (shared as in a Value or owned separately).

  • Texture extends the Image with a Sampler that defines how pixels are accessed in a shader.

  • Framebuffer manages an Image along with a RenderPass configuration for managing a Render target (shared for rendering onto a window Surface or an offscreen RenderFrame)

  • Surface represents the full hardware-managed Images associated with an actual on-screen Window. One can associate a System with a Surface to manage the Swapchain updating for effective double or triple buffering.

  • RenderFrame is an offscreen render target with Framebuffers and a logical device if being used without any Surface -- otherwise it should use the Surface device so images can be copied across them.

  • Unlike most game-oriented GPU setups, vGPU is designed to be used in an event-driven manner where render updates arise from user input or other events, instead of requiring a constant render loop taking place at all times (which can optionally be established too). The event-driven model is vastly more energy efficient for non-game applications.

Memory organization

Memory maintains a host-visible, mapped staging buffer, and a corresponding device-local memory buffer that the GPU uses to compute on (the latter of which is optional for unified memory architectures). Each Value records when it is modified, and a global Sync step efficiently transfers only what has changed. You must allocate and sync update a unique Value for each different value you will need for the entire render pass -- although you can dynamically select which Value to use for each draw command, you cannot in general update the actual data associated with these values during the course of a single rendering pass.

  • Vars variables define the Type and Role of data used in the shaders. There are 3 major categories of Var roles:
    • Vertex and Index represent mesh points etc that provide input to Vertex shader -- these are handled very differently from the others, and must be located in a VertexSet which has a set index of -2. The offsets into allocated Values are updated dynamically for each render Draw command, so you can Bind different Vertex Values as you iterate through objects within a single render pass (again, the underlying vals must be sync'd prior).
    • PushConst are push constants that can only be 128 bytes total that can be directly copied from CPU ram to the GPU via a command -- it is the most high-performance way to update dynamically changing content, such as view matricies or indexes into other data structures. Must be located in PushConstSet set (index -1).
    • Uniform (read-only "constants") and Storage (read-write) data that contain misc other data, e.g., transformation matricies. These are also updated dynamically using dynamic offsets, so you can also call BindDynValue methods to select different such vals as you iterate through objects. The original binding is done automatically in the Memory Config (via BindDynVarsAll) and usually does not need to be redone.
    • Texture vars that provide the raw Image data, the ImageView through which that is accessed, and a Sampler that parametrizes how the pixels are mapped onto coordinates in the Fragment shader. Each texture object is managed as a distinct item in device memory, and they cannot be accessed through a dynamic offset. Thus, a unique descriptor is provided for each texture Value, and your shader should describe them as an array. All such textures must be in place at the start of the render pass, and cannot be updated on the fly during rendering! Thus, you must dynamically bind a uniform variable or push constant to select which texture item from the array to use on a given step of rendering.
      • There is a low maximum number of Texture descriptors (vals) available within one descriptor set on many platforms, including the Mac, only 16, which is enforced via the MaxTexturesPerSet const. There are two (non mutually exclusive) strategies for increasing the number of available textures:
      • Each individual Texture can have up to 128 (again a low limit present on the Mac) layers in a 2d Array of images, in addition to all the separate texture vals being in an Array -- arrays of arrays. Each of the array layers must be the same size -- they are allocated and managed as a unit. The szalloc package provides manager for efficiently allocating images of various sizes to these 16 x 128 (or any N's) groups of layer arrays. This is integrated into the Values value manager and can be engaged by calling AllocTexBySize there. The texture UV coordinates need to be processed by the actual pct size of a given texture relative to the allocated group size -- this is all done in the vphong package and the texture_frag.frag file there can be consulted for a working example.
      • If you allocate more than 16 texture Values, then multiple entire collections of these descriptors will be allocated, as indicated by the NTextureDescs on VarSet and Vars (see that for more info, and the vdraw Draw method for an example). You can use Vars.BindAllTextureValues to bind all texture vals (iterating over NTextureDescs), and System.CmdBindTextureVarIndex to automatically bind the correct set. +, here's some glsl shader code showing how to use the sampler2DArray, as used in the vdraw draw_frag.frag fragment shader code:
#version 450
#extension GL_EXT_nonuniform_qualifier : require

// must use mat4 -- mat3 alignment issues are horrible.
// each mat4 = 64 bytes, so full 128 byte total, but only using mat3.
// pack the tex index into [0][3] of mvp,
// and the fill color into [3][0-3] of uvp
layout(push_constant) uniform Mtxs {
	mat4 mvp;
	mat4 uvp;
};

layout(set = 0, binding = 0) uniform sampler2DArray Tex[]; //
layout(location = 0) in vector2 uv;
layout(location = 0) out vector4 outputColor;

void main() {
	int idx = int(mvp[3][0]);   // packing into unused part of mat4 matrix push constant
	int layer = int(mvp[3][1]);
	outputColor = texture(Tex[idx], vector3(uv,layer)); // layer selection as 3rd dim here
}
  • Vars are accessed at a given location or binding number by the shader code, and these bindings can be organized into logical sets called DescriptorSets (see Graphics Rendering example below). In HLSL, these are specified like this: [[vk::binding(5, 1)]] Texture2D MyTexture2; for descriptor 5 in set 1 (set 0 is the first set).
    • You manage these sets explicitly by calling AddSet or AddVertexSet / AddPushConstSet to create new VarSets, and then add Vars directly to each set.
    • Values represent the values of Vars, with each Value representing a distinct value of a corresponding Var. The ConfigValues call on a given VarSet specifies how many Values to create per each Var within a Set -- this is a shared property of the Set, and should be a consideration in organizing the sets. For example, Sets that are per object should contain one Value per object, etc, while others that are per material would have one Value per material.
    • There is no support for interleaved arrays -- if you want to achieve such a thing, you need to use an array of structs, but the main use-case is for VertexInput, which actually works faster with non-interleaved simple arrays of vector4 points in most cases (e.g., for the points and their normals).
    • You can allocate multiple bindings of all the variables, with each binding being used for a different parallel threaded rendering pass. However, there is only one shared set of Values, so your logic will have to take that into account (e.g., allocating 2x Values per object to allow 2 separate threads to each update and bind their own unique subset of these Values for their own render pass). See discussion under Texture about how this is done in that case. The number of such DescriptorSets is configured in Memory.Vars.NDescs (defaults to 1). Note that these are orthogonal to the number of VarSets -- the terminology is confusing. Various methods take a descIndex to determine which such descriptor set to use -- typically in a threaded swapchain logic you would use the acquired frame index as the descIndex to determine what binding to use.

Naming conventions

  • New returns a new object
  • Init operates on existing object, doing initialization needed for subsequent setting of options
  • Config operates on an existing object and settings, and does everything to get it configured for use.
  • Destroy destroys allocated vulkan objects
  • Alloc is for allocating memory (vs. making a new object)
  • Free is for freeing memory (vs. destroying an object)

Graphics Rendering

See https://developer.nvidia.com/vulkan-shader-resource-binding for a clear description of DescriptorSets etc.

Here's a widely used rendering logic, supported by the Cogent Core Scene (and tbd std Pipeline), and how you should organize the Uniform data into different sets at each level, to optimize the binding overhead:

for each view {
  bind view resources [Set 0]         // camera, environment...
  for each shader type (based on material type: textured, transparent..) {
    bind shader pipeline  
    bind shader resources [Set 1]    // shader control values (maybe none)
    for each specific material {
      bind material resources  [Set 2] // material parameters and textures
      for each object {
        bind object resources  [Set 3] // object transforms
        draw object [VertexInput binding to locations]
        (only finally calls Pipeline here!)
      }
    }
  }
}

It is common practice to use different DescriptorSets for each level in the swapchain, for maintaining high FPS rates by rendering the next frame while the current one is still cooking along itself -- this is the NDescs parameter mentioned above.

Because everything is all packed into big buffers organized by different broad categories, in Memory, we exclusively use the Dynamic mode for Uniform and Storage binding, where the offset into the buffer is specified at the time of the binding call, not in advance in the descriptor set itself. This has only very minor performance implications and makes everything much more flexible and simple: just bind whatever variables you want and that data will be used.

The examples and provided vPhong package retain the Y-is-up coordinate system from OpenGL, which is more "natural" for the physical world, where the Y axis is the height dimension, and up is up, after all. Some of the defaults reflect this choice, but it is easy to use the native Vulkan Y-is-down coordinate system too.

Combining many pipeline renders per RenderPass

The various introductory tutorials all seem to focus on just a single simple render pass with one draw operation, but any realistic scene needs different settings for each object! As noted above, this requires dynamic binding, which is good for Uniforms and Vertex data, but you might not appreciate that this also requires that you pre-allocate and sync up to device memory all the Values that you will need for the entire render pass -- the dynamic binding only selects different offsets into memory buffers, but the actual contents of those buffers should not change during a single render pass (otherwise things will get very slow and lots of bad sync steps might be required, etc). The Memory system makes it easy to allocate, update, and dynamically bind these vals.

Here's some info on the logical issues:

This blog has a particularly clear discussion of the need for Texture arrays for managing textures within a render pass. This is automatically how Texture vars are managed .

GPU Accelerated Compute Engine

See examples/compute1 for a very simple compute shader, and compute.go for Compute* methods specifically useful for this case.

See the gosl repository for a tool that converts Go code into HLSL shader code, so you can effectively run Go on the GPU.

Here's how it works:

  • Each Vulkan Pipeline holds 1 compute shader program, which is equivalent to a kernel in CUDA -- this is the basic unit of computation, accomplishing one parallel sweep of processing across some number of identical data structures.

  • You must organize at the outset your Vars and Values in the System Memory to hold the data structures your shaders operate on. In general, you want to have a single static set of Vars that cover everything you'll need, and different shaders can operate on different subsets of these. You want to minimize the amount of memory transfer.

  • Because the vkQueueSubmit call is by far the most expensive call in Vulkan, you want to minimize those. This means you want to combine as much of your computation into one big Command sequence, with calls to various different Pipeline shaders (which can all be put in one command buffer) that gets submitted once, rather than submitting separate commands for each shader. Ideally this also involves combining memory transfers to / from the GPU in the same command buffer as well.

  • Although rarely used in graphics, the most important tool for synchronizing commands within a single command stream is the vkEvent, which is described a bit in the Khronos Blog. Much of vulkan discussion centers instead around Semaphores, but these are only used for synchronization between different commands --- each of which requires a different vkQueueSubmit (and is therefore suboptimal).

  • Thus, you should create named events in your compute System, and inject calls to set and wait on those events in your command stream.

Gamma Correction (sRGB vs Linear) and Headless / Offscreen Rendering

It is hard to find this info very clearly stated:

  • All internal computation in shaders is done in a linear color space.
  • Image textures are assumed to be sRGB and are automatically converted to linear on upload.
  • Other colors that are passed in should be converted from sRGB to linear (the Phong shaders do this).
  • The Surface automatically converts from Linear to sRGB for actual rendering.
  • A RenderFrame for offscreen / headless rendering must use vk.FormatR8g8b8a8Srgb for the format, in order to get back an image that is automatically converted back to sRGB format.

Mac Platform

To have the mac use the libMoltenVK.dylib installed by brew install molten-vk, you need to change the LDFLAGS here:

github.com/goki/vulkan/vulkan_darwin.go

#cgo darwin LDFLAGS: -L/opt/homebrew/lib -Wl,-rpath,/opt/homebrew/lib -F/Library/Frameworks -framework Cocoa -framework IOKit -framework IOSurface -framework QuartzCore -framework Metal -lMoltenVK -lc++

However it does not find the libvulkan which is not included in molten-vk.

Platform properties

See MACOS.md file for full report of properties on Mac.

These are useful for deciding what kinds of limits are likely to work in practice:

This is a significant constraint! need to work around it.

Note that this constraint is largely irrelevant because each dynamic descriptor can have an unlimited number of offset values used for it.

Documentation

Overview

Package vgpu implements a convenient interface to the Vulkan GPU-based graphics and compute framework, in Go, using the https://github.com/goki/vulkan Go bindings.

The Cogent Core GUI framework runs on top if this, replacing the previous OpenGL-based framework, and the compute engine is used for the emergent neural network simulation framework.

Index

Constants

View Source
const (
	// FlipY used as named arg for flipping the Y axis of images, etc
	FlipY = true

	// NoFlipY used as named arg for not flipping the Y axis of images
	NoFlipY = false
)
View Source
const (
	// CullBack is for SetCullFace function
	CullBack = true

	// CullFront is for SetCullFace function
	CullFront = false

	// CCW is for SetFrontFace function
	CCW = true

	// CW is for SetFrontFace function
	CW = false
)
View Source
const (
	// MaxTexturesPerSet is the maximum number of image variables that can be used
	// in one descriptor set.  This value is a lowest common denominator across
	// platforms.  To overcome this limitation, when more Texture vals are allocated,
	// multiple NDescs are used, setting the and switch
	// across those -- each such Desc set can hold this many textures.
	// NValuesPer on a Texture var can be set higher and only this many will be
	// allocated in the descriptor set, with bindings of values wrapping
	// around across as many such sets as are vals, with a warning if insufficient
	// numbers are present.
	MaxTexturesPerSet = 16

	// MaxImageLayers is the maximum number of layers per image
	MaxImageLayers = 128
)
View Source
const (
	VertexSet = -2
	PushSet   = -1
)
View Source
const ByteCopyMemoryLimit int = 0x7fffffffffff

ByteCopyMemoryLimit represents the total number of bytes that can be copied from a Vulkan Memory Buffer to a byte slice.

Variables

BuffUsages maps BuffTypes into buffer usage flags

View Source
var Debug = false

Debug is a global flag for turning on debug mode Set to true prior to GPU.Config to get validation debugging.

FormatSizes gives size of known vulkan formats in bytes

View Source
var ImageFormatNames = map[vk.Format]string{
	vk.FormatR8g8b8a8Srgb:           "RGBA 8bit sRGB colorspace",
	vk.FormatR8g8b8a8Unorm:          "RGBA 8bit unsigned linear colorspace",
	vk.FormatR5g6b5UnormPack16:      "RGB 5bit (pack 16bit total) unsigned linear colorspace",
	vk.FormatA2b10g10r10UnormPack32: "ABGR 10bit, 2bit alpha (pack 32bit total), unsigned linear colorspace",
	vk.FormatB8g8r8a8Srgb:           "BGRA 8bit sRGB colorspace",
	vk.FormatB8g8r8a8Unorm:          "BGRA 8bit unsigned linear colorspace",
	vk.FormatR16g16b16a16Sfloat:     "RGBA 16bit signed floating point linear colorspace",
	vk.FormatA2r10g10b10UnormPack32: "ARGB 10bit, 2bit alpha (pack 32bit total), unsigned linear colorspace",
}

ImageFormatNames translates image format into human-readable string for most commonly available formats

RoleBuffers maps VarRoles onto type of memory buffer

For static variable binding

VulkanTypes maps vgpu.Types to vulkan types

Functions

func AllocBuffMem

func AllocBuffMem(gp *GPU, dev vk.Device, buffer vk.Buffer, properties vk.MemoryPropertyFlagBits) vk.DeviceMemory

AllocBuffMem allocates memory for given buffer, with given properties

func CheckErr

func CheckErr(err *error)

func CheckExisting

func CheckExisting(actual, required []string) (existing []string, missing int)

func CleanString

func CleanString(s string) string

func CmdBegin

func CmdBegin(cmd vk.CommandBuffer)

CmdBegin does BeginCommandBuffer on buffer

func CmdBeginOneTime

func CmdBeginOneTime(cmd vk.CommandBuffer)

CmdBeginOneTime does BeginCommandBuffer with OneTimeSubmit set on buffer

func CmdEnd

func CmdEnd(cmd vk.CommandBuffer)

CmdEnd does EndCommandBuffer on buffer

func CmdEndSubmitWait

func CmdEndSubmitWait(cmd vk.CommandBuffer, dev *Device)

CmdEndSubmitWait does End, Submit, WaitIdle on command Buffer

func CmdReset

func CmdReset(cmd vk.CommandBuffer)

CmdReset resets the command buffer so it is ready for recording new commands.

func CmdResetBegin

func CmdResetBegin(cmd vk.CommandBuffer)

CmdResetBegin resets the command buffer so it is ready for recording new commands. and then calls CmdBegin to begin recording

func CmdSubmit

func CmdSubmit(cmd vk.CommandBuffer, dev *Device)

CmdSubmit submits commands in buffer to given device queue, without any semaphore logic -- suitable for a WaitIdle logic.

func CmdSubmitFence

func CmdSubmitFence(cmd vk.CommandBuffer, dev *Device, fence vk.Fence)

CmdSubmitFence submits commands in buffer to given device queue using given fence.

func CmdSubmitSignal

func CmdSubmitSignal(cmd vk.CommandBuffer, dev *Device, signal vk.Semaphore, fence vk.Fence)

CmdSubmitSignal submits command in buffer to given device queue with given signal semaphore when done, and with given fence (use vk.NullFence for none). The optional fence is used typically at the end of a block of such commands, whenever the CPU needs to be sure the submitted GPU commands have completed.

func CmdSubmitWait

func CmdSubmitWait(cmd vk.CommandBuffer, dev *Device)

CmdSubmitWait does Submit, WaitIdle on command Buffer

func CmdSubmitWaitSignal

func CmdSubmitWaitSignal(cmd vk.CommandBuffer, dev *Device, wait, signal vk.Semaphore, fence vk.Fence)

CmdSubmitWaitSignal submits command in buffer to given device queue with given wait semaphore and given signal semaphore when done, and with given fence (use vk.NullFence for none). This will cause the GPU to wait until the wait semphaphore is signaled by a previous command with that semaphore as its signal. The optional fence is used typically at the end of a block of such commands, whenever the CPU needs to be sure the submitted GPU commands have completed.

func CmdWait

func CmdWait(dev *Device)

CmdWait does WaitIdle on given device

func DestroyBuffer

func DestroyBuffer(dev vk.Device, buff *vk.Buffer)

DestroyBuffer destroys given buffer and nils the pointer

func DeviceExts

func DeviceExts(gpu vk.PhysicalDevice) (names []string, err error)

DeviceExts gets a list of instance extensions available on the provided physical device.

func FindRequiredMemoryType

func FindRequiredMemoryType(properties vk.PhysicalDeviceMemoryProperties,
	deviceRequirements, hostRequirements vk.MemoryPropertyFlagBits) (uint32, bool)

func FindRequiredMemoryTypeFallback

func FindRequiredMemoryTypeFallback(properties vk.PhysicalDeviceMemoryProperties,
	deviceRequirements, hostRequirements vk.MemoryPropertyFlagBits) (uint32, bool)

func FindString

func FindString(str string, strs []string) int

FindString returns index of string if in list, else -1

func FreeBuffMem

func FreeBuffMem(dev vk.Device, memory *vk.DeviceMemory)

FreeBuffMem frees given device memory to nil

func HasAllStrings

func HasAllStrings(s string, strs []string) bool

func IfPanic

func IfPanic(err error, finalizers ...func())

func ImageSRGBFromLinear added in v0.0.10

func ImageSRGBFromLinear(img *image.RGBA) *image.RGBA

ImageSRGBFromLinear returns a sRGB colorspace version of given linear colorspace image

func ImageSRGBToLinear

func ImageSRGBToLinear(img *image.RGBA) *image.RGBA

ImageSRGBToLinear returns a linear colorspace version of sRGB colorspace image

func ImageToRGBA

func ImageToRGBA(img image.Image) *image.RGBA

ImageToRGBA returns image.RGBA version of given image either because it already is one, or by converting it.

func ImgCompToUint8

func ImgCompToUint8(val float32) uint8

func Init

func Init() error

Init initializes vulkan system for Display-enabled use, using glfw. Must call before doing any vgpu stuff. Calls glfw.Init and sets the Vulkan instance proc addr and calls Init. IMPORTANT: must be called on the main initial thread!

func InitNoDisplay

func InitNoDisplay() error

InitNoDisplay initializes vulkan system for a purely compute-based or headless operation, without any display (i.e., without using glfw). Call before doing any vgpu stuff. Loads the vulkan library and sets the Vulkan instance proc addr and calls Init. IMPORTANT: must be called on the main initial thread!

func InstanceExts

func InstanceExts() (names []string, err error)

InstanceExts gets a list of instance extensions available on the platform.

func IsError

func IsError(ret vk.Result) bool

func MapMemory

func MapMemory(dev vk.Device, mem vk.DeviceMemory, size int) unsafe.Pointer

MapMemory maps the buffer memory, returning a pointer into start of buffer memory

func MapMemoryAll

func MapMemoryAll(dev vk.Device, mem vk.DeviceMemory) unsafe.Pointer

MapMemoryAll maps the WholeSize of buffer memory, returning a pointer into start of buffer memory

func MemSizeAlign

func MemSizeAlign(size, align int) int

MemSizeAlign returns the size aligned according to align byte increments e.g., if align = 16 and size = 12, it returns 16

func NDescForTextures

func NDescForTextures(nvals int) int

NDescForTextures returns number of descriptors (NDesc) required for given number of texture values.

func NewBuffer

func NewBuffer(dev vk.Device, size int, usage vk.BufferUsageFlagBits) vk.Buffer

NewBuffer makes a buffer of given size, usage

func NewError

func NewError(ret vk.Result) error

func NewEvent

func NewEvent(dev vk.Device) vk.Event

New Event creates a new Event, setting the DeviceOnly bit flag because we typically only use events for within-device communication. and presumably this is faster if so-scoped.

func NewFence

func NewFence(dev vk.Device) vk.Fence

func NewSemaphore

func NewSemaphore(dev vk.Device) vk.Semaphore

func NoDisplayGPU

func NoDisplayGPU(nm string) (*GPU, *Device, error)

NoDisplayGPU Initializes the Vulkan GPU and returns that and the graphics GPU device, with given name, without connecting to the display.

func PlatformDefaults

func PlatformDefaults(gp *GPU)

func SRGBFromLinear added in v0.0.10

func SRGBFromLinear(rl, gl, bl float32) (r, g, b float32)

SRGBFromLinear converts set of sRGB components from linear values, adding gamma correction.

func SRGBFromLinearComp added in v0.0.10

func SRGBFromLinearComp(lin float32) float32

SRGBFromLinearComp converts an sRGB rgb linear component to non-linear (gamma corrected) sRGB value Used in converting from XYZ to sRGB.

func SRGBToLinear

func SRGBToLinear(r, g, b float32) (rl, gl, bl float32)

SRGBToLinear converts set of sRGB components to linear values, removing gamma correction.

func SRGBToLinearComp

func SRGBToLinearComp(srgb float32) float32

SRGBToLinearComp converts an sRGB rgb component to linear space (removes gamma). Used in converting from sRGB to XYZ colors.

func SafeString

func SafeString(s string) string

func SafeStrings

func SafeStrings(list []string) []string

func SetImageSRGBFromLinear added in v0.0.10

func SetImageSRGBFromLinear(img *image.RGBA)

SetImageSRGBFromLinear sets in place the pixel values to sRGB colorspace version of given linear colorspace image. This directly modifies the given image!

func SetImageSRGBToLinear

func SetImageSRGBToLinear(img *image.RGBA)

SetImageSRGBToLinear sets in place the pixel values to linear colorspace version of sRGB colorspace image. This directly modifies the given image!

func SliceUint32

func SliceUint32(data []byte) []uint32

func Terminate

func Terminate()

Terminate shuts down the vulkan system -- call as last thing before quitting. IMPORTANT: must be called on the main initial thread!

func ValidationLayers

func ValidationLayers() (names []string, err error)

ValidationLayers gets a list of validation layers available on the platform.

func Warps

func Warps(n, threads int) int

Warps returns the number of warps (thread groups) that is sufficient to compute n elements, given specified number of threads per this dimension. It just rounds up to nearest even multiple of n divided by threads: Ceil(n / threads)

Types

type BorderColors

type BorderColors int32 //enums:enum -trim-prefix Border

Texture image sampler modes

const (
	// Repeat the texture when going beyond the image dimensions.
	BorderTrans BorderColors = iota
	BorderBlack
	BorderWhite
)
const BorderColorsN BorderColors = 3

BorderColorsN is the highest valid value for type BorderColors, plus one.

func BorderColorsValues

func BorderColorsValues() []BorderColors

BorderColorsValues returns all possible values for the type BorderColors.

func (BorderColors) Desc

func (i BorderColors) Desc() string

Desc returns the description of the BorderColors value.

func (BorderColors) Int64

func (i BorderColors) Int64() int64

Int64 returns the BorderColors value as an int64.

func (BorderColors) MarshalText

func (i BorderColors) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*BorderColors) SetInt64

func (i *BorderColors) SetInt64(in int64)

SetInt64 sets the BorderColors value from an int64.

func (*BorderColors) SetString

func (i *BorderColors) SetString(s string) error

SetString sets the BorderColors value from its string representation, and returns an error if the string is invalid.

func (BorderColors) String

func (i BorderColors) String() string

String returns the string representation of this BorderColors value.

func (*BorderColors) UnmarshalText

func (i *BorderColors) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (BorderColors) Values

func (i BorderColors) Values() []enums.Enum

Values returns all possible values for the type BorderColors.

func (BorderColors) VkColor

func (bc BorderColors) VkColor() vk.BorderColor

type BuffTypes

type BuffTypes int32 //enums:enum

BuffTypes are memory buffer types managed by the Memory object

const (
	// VtxIndexBuff is a buffer holding Vertex and Index values
	VtxIndexBuff BuffTypes = iota

	// UniformBuff holds Uniform and UniformTexel objects: read-only, small footprint
	UniformBuff

	// StorageBuff holds Storage and StorageTexel: read-write, larger
	// mostly for compute shaders
	StorageBuff

	// TextureBuff holds Images / Textures -- hardware optimizes allocation
	// on device side, and staging-side is general
	TextureBuff
)
const BuffTypesN BuffTypes = 4

BuffTypesN is the highest valid value for type BuffTypes, plus one.

func BuffTypesValues

func BuffTypesValues() []BuffTypes

BuffTypesValues returns all possible values for the type BuffTypes.

func (BuffTypes) AlignBytes

func (bt BuffTypes) AlignBytes(gp *GPU) int

AlignBytes returns alignment bytes for offsets into given buffer

func (BuffTypes) Desc

func (i BuffTypes) Desc() string

Desc returns the description of the BuffTypes value.

func (BuffTypes) Int64

func (i BuffTypes) Int64() int64

Int64 returns the BuffTypes value as an int64.

func (BuffTypes) IsReadOnly

func (bt BuffTypes) IsReadOnly() bool

IsReadOnly returns true if buffer is read-only (most), else read-write (Storage)

func (BuffTypes) MarshalText

func (i BuffTypes) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*BuffTypes) SetInt64

func (i *BuffTypes) SetInt64(in int64)

SetInt64 sets the BuffTypes value from an int64.

func (*BuffTypes) SetString

func (i *BuffTypes) SetString(s string) error

SetString sets the BuffTypes value from its string representation, and returns an error if the string is invalid.

func (BuffTypes) String

func (i BuffTypes) String() string

String returns the string representation of this BuffTypes value.

func (*BuffTypes) UnmarshalText

func (i *BuffTypes) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (BuffTypes) Values

func (i BuffTypes) Values() []enums.Enum

Values returns all possible values for the type BuffTypes.

type CPUOptions

type CPUOptions int32 //enums:enum -trim-prefix Opt

GPUOptions specifies supported options for the vgpu device upon initialization. Several vulkan device features are automatically enabled, which are required for the basic functionality of vgpu supported graphics, but these are optional and may be required for other uses (e.g., compute shaders). See also InstanceExts, DeviceExts, and ValidationLayers.

const (
	// OptRobustBufferAccess specifies that accesses to buffers are bounds-checked against the range of the buffer descriptor (as determined by VkDescriptorBufferInfo::range, VkBufferViewCreateInfo::range, or the size of the buffer). Out of bounds accesses must not cause application termination, and the effects of shader loads, stores, and atomics must conform to an implementation-dependent behavior as described below.
	OptRobustBufferAccess CPUOptions = iota

	// OptFullDrawIndexUint32 specifies the full 32-bit range of indices is supported for indexed draw calls when using a VkIndexType of VK_INDEX_TYPE_UINT32. maxDrawIndexedIndexValue is the maximum index value that may be used (aside from the primitive restart index, which is always 232-1 when the VkIndexType is VK_INDEX_TYPE_UINT32). If this feature is supported, maxDrawIndexedIndexValue must be 232-1; otherwise it must be no smaller than 224-1. See maxDrawIndexedIndexValue.
	OptFullDrawIndexUint32

	// OptImageCubeArray specifies whether image views with a VkImageViewType of VK_IMAGE_VIEW_TYPE_CUBE_ARRAY can be created, and that the corresponding SampledCubeArray and ImageCubeArray SPIR-V capabilities can be used in shader code.
	OptImageCubeArray

	// OptIndependentBlend specifies whether the VkPipelineColorBlendAttachmentState settings are controlled independently per-attachment. If this feature is not enabled, the VkPipelineColorBlendAttachmentState settings for all color attachments must be identical. Otherwise, a different VkPipelineColorBlendAttachmentState can be provided for each bound color attachment.
	OptIndependentBlend

	// OptGeometryShader specifies whether geometry shaders are supported. If this feature is not enabled, the VK_SHADER_STAGE_GEOMETRY_BIT and VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT enum values must not be used. This also specifies whether shader modules can declare the Geometry capability.
	OptGeometryShader

	// OptTessellationShader specifies whether tessellation control and evaluation shaders are supported. If this feature is not enabled, the VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT, VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT, and VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO enum values must not be used. This also specifies whether shader modules can declare the Tessellation capability.
	OptTessellationShader

	// OptSampleRateShading specifies whether Sample Shading and multisample interpolation are supported. If this feature is not enabled, the sampleShadingEnable member of the VkPipelineMultisampleStateCreateInfo structure must be set to VK_FALSE and the minSampleShading member is ignored. This also specifies whether shader modules can declare the SampleRateShading capability.
	OptSampleRateShading

	// OptDualSrcBlend specifies whether blend operations which take two sources are supported. If this feature is not enabled, the VK_BLEND_FACTOR_SRC1_COLOR, VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR, VK_BLEND_FACTOR_SRC1_ALPHA, and VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA enum values must not be used as source or destination blending factors. See https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html#framebuffer-dsb.
	OptDualSrcBlend

	// OptLogicOp specifies whether logic operations are supported. If this feature is not enabled, the logicOpEnable member of the VkPipelineColorBlendStateCreateInfo structure must be set to VK_FALSE, and the logicOp member is ignored.
	OptLogicOp

	// OptMultiDrawIndirect specifies whether multiple draw indirect is supported. If this feature is not enabled, the drawCount parameter to the vkCmdDrawIndirect and vkCmdDrawIndexedIndirect commands must be 0 or 1. The maxDrawIndirectCount member of the VkPhysicalDeviceLimits structure must also be 1 if this feature is not supported. See maxDrawIndirectCount.
	OptMultiDrawIndirect

	// OptDrawIndirectFirstInstance specifies whether indirect drawing calls support the firstInstance parameter. If this feature is not enabled, the firstInstance member of all VkDrawIndirectCommand and VkDrawIndexedIndirectCommand structures that are provided to the vkCmdDrawIndirect and vkCmdDrawIndexedIndirect commands must be 0.
	OptDrawIndirectFirstInstance

	// OptDepthClamp specifies whether depth clamping is supported. If this feature is not enabled, the depthClampEnable member of the VkPipelineRasterizationStateCreateInfo structure must be set to VK_FALSE. Otherwise, setting depthClampEnable to VK_TRUE will enable depth clamping.
	OptDepthClamp

	// OptDepthBiasClamp specifies whether depth bias clamping is supported. If this feature is not enabled, the depthBiasClamp member of the VkPipelineRasterizationStateCreateInfo structure must be set to 0.0 unless the VK_DYNAMIC_STATE_DEPTH_BIAS dynamic state is enabled, and the depthBiasClamp parameter to vkCmdSetDepthBias must be set to 0.0.
	OptDepthBiasClamp

	// OptFillModeNonSolid specifies whether point and wireframe fill modes are supported. If this feature is not enabled, the VK_POLYGON_MODE_POINT and VK_POLYGON_MODE_LINE enum values must not be used.
	OptFillModeNonSolid

	// OptDepthBounds specifies whether depth bounds tests are supported. If this feature is not enabled, the depthBoundsTestEnable member of the VkPipelineDepthStencilStateCreateInfo structure must be set to VK_FALSE. When depthBoundsTestEnable is set to VK_FALSE, the minDepthBounds and maxDepthBounds members of the VkPipelineDepthStencilStateCreateInfo structure are ignored.
	OptDepthBounds

	// OptWideLines specifies whether lines with width other than 1.0 are supported. If this feature is not enabled, the lineWidth member of the VkPipelineRasterizationStateCreateInfo structure must be set to 1.0 unless the VK_DYNAMIC_STATE_LINE_WIDTH dynamic state is enabled, and the lineWidth parameter to vkCmdSetLineWidth must be set to 1.0. When this feature is supported, the range and granularity of supported line widths are indicated by the lineWidthRange and lineWidthGranularity members of the VkPhysicalDeviceLimits structure, respectively.
	OptWideLines

	// OptLargePoints specifies whether points with size greater than 1.0 are supported. If this feature is not enabled, only a point size of 1.0 written by a shader is supported. The range and granularity of supported point sizes are indicated by the pointSizeRange and pointSizeGranularity members of the VkPhysicalDeviceLimits structure, respectively.
	OptLargePoints

	// OptAlphaToOne specifies whether the implementation is able to replace the alpha value of the fragment shader color output in the Multisample Coverage fragment operation. If this feature is not enabled, then the alphaToOneEnable member of the VkPipelineMultisampleStateCreateInfo structure must be set to VK_FALSE. Otherwise setting alphaToOneEnable to VK_TRUE will enable alpha-to-one behavior.
	OptAlphaToOne

	// OptMultiViewport specifies whether more than one viewport is supported. If this feature is not enabled: The viewportCount and scissorCount members of the VkPipelineViewportStateCreateInfo structure must be set to 1. The firstViewport and viewportCount parameters to the vkCmdSetViewport command must be set to 0 and 1, respectively. The firstScissor and scissorCount parameters to the vkCmdSetScissor command must be set to 0 and 1, respectively. The exclusiveScissorCount member of the VkPipelineViewportExclusiveScissorStateCreateInfoNV structure must be set to 0 or 1. The firstExclusiveScissor and exclusiveScissorCount parameters to the vkCmdSetExclusiveScissorNV command must be set to 0 and 1, respectively.
	OptMultiViewport

	// OptSamplerAnisotropy specifies whether anisotropic filtering is supported. If this feature is not enabled, the anisotropyEnable member of the VkSamplerCreateInfo structure must be VK_FALSE.
	OptSamplerAnisotropy

	// OptTextureCompressionETC2 specifies whether all of the ETC2 and EAC compressed texture formats are supported. If this feature is enabled, then the VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT, VK_FORMAT_FEATURE_BLIT_SRC_BIT and VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT features must be supported in optimalTilingFeatures for various formats -- see the Vulkan Spec at https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkPhysicalDeviceFeatures.html
	OptTextureCompressionETC2

	// OptTextureCompressionASTC_LDR specifies whether all of the ASTC LDR compressed texture formats are supported. If this feature is enabled, then the VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT, VK_FORMAT_FEATURE_BLIT_SRC_BIT and VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT features must be supported in optimalTilingFeatures for various formats -- see the Vulkan Spec at https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkPhysicalDeviceFeatures.html
	OptTextureCompressionASTC_LDR

	// OptTextureCompressionBC specifies whether all of the BC compressed texture formats are supported. If this feature is enabled, then the VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT, VK_FORMAT_FEATURE_BLIT_SRC_BIT and VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT features must be supported in optimalTilingFeatures for various formats -- see the Vulkan Spec at https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkPhysicalDeviceFeatures.html
	OptTextureCompressionBC

	// OptOcclusionQueryPrecise specifies whether occlusion queries returning actual sample counts are supported. Occlusion queries are created in a VkQueryPool by specifying the queryType of VK_QUERY_TYPE_OCCLUSION in the VkQueryPoolCreateInfo structure which is passed to vkCreateQueryPool. If this feature is enabled, queries of this type can enable VK_QUERY_CONTROL_PRECISE_BIT in the flags parameter to vkCmdBeginQuery. If this feature is not supported, the implementation supports only boolean occlusion queries. When any samples are passed, boolean queries will return a non-zero result value, otherwise a result value of zero is returned. When this feature is enabled and VK_QUERY_CONTROL_PRECISE_BIT is set, occlusion queries will report the actual number of samples passed.
	OptOcclusionQueryPrecise

	// OptPipelineStatisticsQuery specifies whether the pipeline statistics queries are supported. If this feature is not enabled, queries of type VK_QUERY_TYPE_PIPELINE_STATISTICS cannot be created, and none of the VkQueryPipelineStatisticFlagBits bits can be set in the pipelineStatistics member of the VkQueryPoolCreateInfo structure.
	OptPipelineStatisticsQuery

	// OptVertexPipelineStoresAndAtomics specifies whether storage buffers and images support stores and atomic operations in the vertex, tessellation, and geometry shader stages. If this feature is not enabled, all storage image, storage texel buffer, and storage buffer variables used by these stages in shader modules must be decorated with the NonWritable decoration (or the readonly memory qualifier in GLSL).
	OptVertexPipelineStoresAndAtomics

	// OptFragmentStoresAndAtomics specifies whether storage buffers and images support stores and atomic operations in the fragment shader stage. If this feature is not enabled, all storage image, storage texel buffer, and storage buffer variables used by the fragment stage in shader modules must be decorated with the NonWritable decoration (or the readonly memory qualifier in GLSL).
	OptFragmentStoresAndAtomics

	// OptShaderTessellationAndGeometryPointSize specifies whether the PointSize built-in decoration is available in the tessellation control, tessellation evaluation, and geometry shader stages. If this feature is not enabled, members decorated with the PointSize built-in decoration must not be read from or written to and all points written from a tessellation or geometry shader will have a size of 1.0. This also specifies whether shader modules can declare the TessellationPointSize capability for tessellation control and evaluation shaders, or if the shader modules can declare the GeometryPointSize capability for geometry shaders. An implementation supporting this feature must also support one or both of the tessellationShader or geometryShader features.
	OptShaderTessellationAndGeometryPointSize

	// OptShaderImageGatherExtended specifies whether the extended set of image gather instructions are available in shader code. If this feature is not enabled, the OpImage*Gather instructions do not support the Offset and ConstOffsets operands. This also specifies whether shader modules can declare the ImageGatherExtended capability.
	OptShaderImageGatherExtended

	// OptShaderStorageImageExtendedFormats specifies whether all the “storage image extended formats” below are supported; if this feature is supported, then the VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT must be supported in optimalTilingFeatures various formats -- see the Vulkan Spec at https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkPhysicalDeviceFeatures.html
	OptShaderStorageImageExtendedFormats

	// OptShaderStorageImageMultisample specifies whether multisampled storage images are supported. If this feature is not enabled, images that are created with a usage that includes VK_IMAGE_USAGE_STORAGE_BIT must be created with samples equal to VK_SAMPLE_COUNT_1_BIT. This also specifies whether shader modules can declare the StorageImageMultisample and ImageMSArray capabilities.
	OptShaderStorageImageMultisample

	// OptShaderStorageImageReadWithoutFormat specifies whether storage images and storage texel buffers require a format qualifier to be specified when reading. shaderStorageImageReadWithoutFormat applies only to formats listed in the storage without format list.
	OptShaderStorageImageReadWithoutFormat

	// OptShaderStorageImageWriteWithoutFormat specifies whether storage images and storage texel buffers require a format qualifier to be specified when writing. shaderStorageImageWriteWithoutFormat applies only to formats listed in the storage without format list.
	OptShaderStorageImageWriteWithoutFormat

	// OptShaderUniformBufferArrayDynamicIndexing specifies whether arrays of uniform buffers can be indexed by dynamically uniform integer expressions in shader code. If this feature is not enabled, resources with a descriptor type of VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER or VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC must be indexed only by constant integral expressions when aggregated into arrays in shader code. This also specifies whether shader modules can declare the UniformBufferArrayDynamicIndexing capability.
	OptShaderUniformBufferArrayDynamicIndexing

	// OptShaderSampledImageArrayDynamicIndexing specifies whether arrays of samplers or sampled images can be indexed by dynamically uniform integer expressions in shader code. If this feature is not enabled, resources with a descriptor type of VK_DESCRIPTOR_TYPE_SAMPLER, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, or VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE must be indexed only by constant integral expressions when aggregated into arrays in shader code. This also specifies whether shader modules can declare the SampledImageArrayDynamicIndexing capability.
	OptShaderSampledImageArrayDynamicIndexing

	// OptShaderStorageBufferArrayDynamicIndexing specifies whether arrays of storage buffers can be indexed by dynamically uniform integer expressions in shader code. If this feature is not enabled, resources with a descriptor type of VK_DESCRIPTOR_TYPE_STORAGE_BUFFER or VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC must be indexed only by constant integral expressions when aggregated into arrays in shader code. This also specifies whether shader modules can declare the StorageBufferArrayDynamicIndexing capability.
	OptShaderStorageBufferArrayDynamicIndexing

	// OptShaderStorageImageArrayDynamicIndexing specifies whether arrays of storage images can be indexed by dynamically uniform integer expressions in shader code. If this feature is not enabled, resources with a descriptor type of VK_DESCRIPTOR_TYPE_STORAGE_IMAGE must be indexed only by constant integral expressions when aggregated into arrays in shader code. This also specifies whether shader modules can declare the StorageImageArrayDynamicIndexing capability.
	OptShaderStorageImageArrayDynamicIndexing

	// OptShaderClipDistance specifies whether clip distances are supported in shader code. If this feature is not enabled, any members decorated with the ClipDistance built-in decoration must not be read from or written to in shader modules. This also specifies whether shader modules can declare the ClipDistance capability.
	OptShaderClipDistance

	// OptShaderCullDistance specifies whether cull distances are supported in shader code. If this feature is not enabled, any members decorated with the CullDistance built-in decoration must not be read from or written to in shader modules. This also specifies whether shader modules can declare the CullDistance capability.
	OptShaderCullDistance

	// OptShaderFloat64 specifies whether 64-bit floats (doubles) are supported in shader code. If this feature is not enabled, 64-bit floating-point types must not be used in shader code. This also specifies whether shader modules can declare the Float64 capability. Declaring and using 64-bit floats is enabled for all storage classes that SPIR-V allows with the Float64 capability.
	OptShaderFloat64

	// OptShaderInt64 specifies whether 64-bit integers (signed and unsigned) are supported in shader code. If this feature is not enabled, 64-bit integer types must not be used in shader code. This also specifies whether shader modules can declare the Int64 capability. Declaring and using 64-bit integers is enabled for all storage classes that SPIR-V allows with the Int64 capability.
	OptShaderInt64

	// OptShaderInt16 specifies whether 16-bit integers (signed and unsigned) are supported in shader code. If this feature is not enabled, 16-bit integer types must not be used in shader code. This also specifies whether shader modules can declare the Int16 capability. However, this only enables a subset of the storage classes that SPIR-V allows for the Int16 SPIR-V capability: Declaring and using 16-bit integers in the Private, Workgroup (for non-Block variables), and Function storage classes is enabled, while declaring them in the interface storage classes (e.g., UniformConstant, Uniform, StorageBuffer, Input, Output, and PushConstant) is not enabled.
	OptShaderInt16

	// OptShaderResourceResidency specifies whether image operations that return resource residency information are supported in shader code. If this feature is not enabled, the OpImageSparse* instructions must not be used in shader code. This also specifies whether shader modules can declare the SparseResidency capability. The feature requires at least one of the sparseResidency* features to be supported.
	OptShaderResourceResidency

	// OptShaderResourceMinLod specifies whether image operations specifying the minimum resource LOD are supported in shader code. If this feature is not enabled, the MinLod image operand must not be used in shader code. This also specifies whether shader modules can declare the MinLod capability.
	OptShaderResourceMinLod

	// OptSparseBinding specifies whether resource memory can be managed at opaque sparse block level instead of at the object level. If this feature is not enabled, resource memory must be bound only on a per-object basis using the vkBindBufferMemory and vkBindImageMemory commands. In this case, buffers and images must not be created with VK_BUFFER_CREATE_SPARSE_BINDING_BIT and VK_IMAGE_CREATE_SPARSE_BINDING_BIT set in the flags member of the VkBufferCreateInfo and VkImageCreateInfo structures, respectively. Otherwise resource memory can be managed as described in Sparse Resource Features.
	OptSparseBinding

	// OptSparseResidencyBuffer specifies whether the device can access partially resident buffers. If this feature is not enabled, buffers must not be created with VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT set in the flags member of the VkBufferCreateInfo structure.
	OptSparseResidencyBuffer

	// OptSparseResidencyImage2D specifies whether the device can access partially resident 2D images with 1 sample per pixel. If this feature is not enabled, images with an imageType of VK_IMAGE_TYPE_2D and samples set to VK_SAMPLE_COUNT_1_BIT must not be created with VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT set in the flags member of the VkImageCreateInfo structure.
	OptSparseResidencyImage2D

	// OptSparseResidencyImage3D specifies whether the device can access partially resident 3D images. If this feature is not enabled, images with an imageType of VK_IMAGE_TYPE_3D must not be created with VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT set in the flags member of the VkImageCreateInfo structure.
	OptSparseResidencyImage3D

	// OptSparseResidency2Samples specifies whether the physical device can access partially resident 2D images with 2 samples per pixel. If this feature is not enabled, images with an imageType of VK_IMAGE_TYPE_2D and samples set to VK_SAMPLE_COUNT_2_BIT must not be created with VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT set in the flags member of the VkImageCreateInfo structure.
	OptSparseResidency2Samples

	// OptSparseResidency4Samples specifies whether the physical device can access partially resident 2D images with 4 samples per pixel. If this feature is not enabled, images with an imageType of VK_IMAGE_TYPE_2D and samples set to VK_SAMPLE_COUNT_4_BIT must not be created with VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT set in the flags member of the VkImageCreateInfo structure.
	OptSparseResidency4Samples

	// OptSparseResidency8Samples specifies whether the physical device can access partially resident 2D images with 8 samples per pixel. If this feature is not enabled, images with an imageType of VK_IMAGE_TYPE_2D and samples set to VK_SAMPLE_COUNT_8_BIT must not be created with VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT set in the flags member of the VkImageCreateInfo structure.
	OptSparseResidency8Samples

	// OptSparseResidency16Samples specifies whether the physical device can access partially resident 2D images with 16 samples per pixel. If this feature is not enabled, images with an imageType of VK_IMAGE_TYPE_2D and samples set to VK_SAMPLE_COUNT_16_BIT must not be created with VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT set in the flags member of the VkImageCreateInfo structure.
	OptSparseResidency16Samples

	// OptSparseResidencyAliased specifies whether the physical device can correctly access data aliased into multiple locations. If this feature is not enabled, the VK_BUFFER_CREATE_SPARSE_ALIASED_BIT and VK_IMAGE_CREATE_SPARSE_ALIASED_BIT enum values must not be used in flags members of the VkBufferCreateInfo and VkImageCreateInfo structures, respectively.
	OptSparseResidencyAliased

	// OptVariableMultisampleRate specifies whether all pipelines that will be bound to a command buffer during a subpass which uses no attachments must have the same value for VkPipelineMultisampleStateCreateInfo::rasterizationSamples. If set to VK_TRUE, the implementation supports variable multisample rates in a subpass which uses no attachments. If set to VK_FALSE, then all pipelines bound in such a subpass must have the same multisample rate. This has no effect in situations where a subpass uses any attachments.
	OptVariableMultisampleRate

	// OptInheritedQueries specifies whether a secondary command buffer may be executed while a query is active.
	OptInheritedQueries
)
const CPUOptionsN CPUOptions = 55

CPUOptionsN is the highest valid value for type CPUOptions, plus one.

func CPUOptionsValues

func CPUOptionsValues() []CPUOptions

CPUOptionsValues returns all possible values for the type CPUOptions.

func (CPUOptions) Desc

func (i CPUOptions) Desc() string

Desc returns the description of the CPUOptions value.

func (CPUOptions) Int64

func (i CPUOptions) Int64() int64

Int64 returns the CPUOptions value as an int64.

func (CPUOptions) MarshalText

func (i CPUOptions) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*CPUOptions) SetInt64

func (i *CPUOptions) SetInt64(in int64)

SetInt64 sets the CPUOptions value from an int64.

func (*CPUOptions) SetString

func (i *CPUOptions) SetString(s string) error

SetString sets the CPUOptions value from its string representation, and returns an error if the string is invalid.

func (CPUOptions) String

func (i CPUOptions) String() string

String returns the string representation of this CPUOptions value.

func (*CPUOptions) UnmarshalText

func (i *CPUOptions) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (CPUOptions) Values

func (i CPUOptions) Values() []enums.Enum

Values returns all possible values for the type CPUOptions.

type CmdPool

type CmdPool struct {
	Pool vk.CommandPool
	Buff vk.CommandBuffer
}

CmdPool is a command pool and buffer

func (*CmdPool) BeginCmd

func (cp *CmdPool) BeginCmd() vk.CommandBuffer

BeginCmd does BeginCommandBuffer on buffer

func (*CmdPool) BeginCmdOneTime

func (cp *CmdPool) BeginCmdOneTime() vk.CommandBuffer

BeginCmdOneTime does BeginCommandBuffer with OneTimeSubmit set on buffer

func (*CmdPool) ConfigResettable

func (cp *CmdPool) ConfigResettable(dv *Device)

ConfigResettable configures the pool for persistent, resettable command buffers, used for rendering commands.

func (*CmdPool) ConfigTransient

func (cp *CmdPool) ConfigTransient(dv *Device)

ConfigTransient configures the pool for transient command buffers, which are best used for random functions, such as memory copying. Use EndSubmitWaitFree logic.

func (*CmdPool) Destroy

func (cp *CmdPool) Destroy(dev vk.Device)

Destroy

func (*CmdPool) EndCmd

func (cp *CmdPool) EndCmd()

EndCmd does EndCommandBuffer on buffer

func (*CmdPool) EndSubmitWait

func (cp *CmdPool) EndSubmitWait(dev *Device)

EndSubmitWait does End, Submit, WaitIdle on Buffer

func (*CmdPool) EndSubmitWaitFree

func (cp *CmdPool) EndSubmitWaitFree(dev *Device)

EndSubmitWaitFree does End, Submit, WaitIdle, Free on Buffer

func (*CmdPool) FreeBuffer

func (cp *CmdPool) FreeBuffer(dev *Device)

FreeBuffer frees the current Buff buffer

func (*CmdPool) NewBuffer

func (cp *CmdPool) NewBuffer(dv *Device) vk.CommandBuffer

NewBuffer makes a buffer in pool, setting Buff to point to it if Buff == nil, returning the buffer.

func (*CmdPool) Reset

func (cp *CmdPool) Reset()

Reset resets the command buffer so it is ready for recording new commands.

func (*CmdPool) Submit

func (cp *CmdPool) Submit(dev *Device)

Submit submits commands in buffer to given device queue, without any semaphore logic -- suitable for a WaitIdle logic.

func (*CmdPool) SubmitWait

func (cp *CmdPool) SubmitWait(dev *Device)

SubmitWait does Submit, WaitIdle on Buffer

type Device

type Device struct {

	// logical device
	Device vk.Device

	// queue index for device
	QueueIndex uint32

	// queue for device
	Queue vk.Queue
}

Device holds Device and associated Queue info

func NewGraphicsDevice

func NewGraphicsDevice(gp *GPU) (*Device, error)

NewGraphicsDevice returns a new Graphics Device, on given GPU. This is suitable for no display offscreen rendering. Typically use the Surface Device for rendering to a display window.

func (*Device) Destroy

func (dv *Device) Destroy()

func (*Device) DeviceWaitIdle

func (dv *Device) DeviceWaitIdle()

DeviceWaitIdle waits until the device is idle and ready for commands -- maybe useful to call if getting not ready errors in particular situations

func (*Device) FindQueue

func (dv *Device) FindQueue(gp *GPU, flags vk.QueueFlagBits) error

FindQueue finds queue for given flag bits, sets in QueueIndex returns error if not found.

func (*Device) Init

func (dv *Device) Init(gp *GPU, flags vk.QueueFlagBits) error

Init initializes a device based on QueueFlagBits

func (*Device) MakeDevice

func (dv *Device) MakeDevice(gp *GPU)

MakeDevice and Queue based on QueueIndex

type Framebuffer

type Framebuffer struct {

	// target framebuffer format -- if multisampling is active then Image has samples = 1, Render.Multi has full samples
	Format ImageFormat

	// the image behind the framebuffer, includes the format -- this
	Image Image

	// pointer to the associated renderpass and depth buffer
	Render *Render

	// vulkan framebuffer
	Framebuffer vk.Framebuffer

	// has this framebuffer been cleared yet?  if not, must be prior to use as a non-clearing Load case
	HasCleared bool
}

Framebuffer combines an Image and Render info (which has a depth buffer)

func (*Framebuffer) Config

func (fb *Framebuffer) Config()

Config configures a new vulkan framebuffer object with current settings, destroying any existing

func (*Framebuffer) ConfigRender

func (fb *Framebuffer) ConfigRender(rp *Render)

ConfigRender configures for Render, assuming image is already set and Configs the Framebuffer based on that.

func (*Framebuffer) ConfigRenderImage

func (fb *Framebuffer) ConfigRenderImage(gp *GPU, dev vk.Device, fmt ImageFormat)

ConfigRenderImage configures a new image for a standalone framebuffer not associated with an existing surface, for RenderFrame target. In general it is recommended to use vk.SampleCount4Bit to avoid aliasing. Does not yet make the Framebuffer because it still needs the Render (see ConfigRender)

func (*Framebuffer) ConfigSurfaceImage

func (fb *Framebuffer) ConfigSurfaceImage(gp *GPU, dev vk.Device, fmt ImageFormat, img vk.Image)

ConfigSurfaceImage configures settings for given existing surface image and format. Does not yet make the Framebuffer because it still needs the Render (see ConfigAll for all)

func (*Framebuffer) CopyToImage

func (fb *Framebuffer) CopyToImage(toImg *Image, dev vk.Device, cmd vk.CommandBuffer)

CopyToImage copies the current framebuffer image to given image dest using given command buffer which must have the cmdBegin called already.

func (*Framebuffer) Destroy

func (fb *Framebuffer) Destroy()

Destroy destroys everything

func (*Framebuffer) DestroyFrame

func (fb *Framebuffer) DestroyFrame()

DestroyFrame destroys the framebuffer if non-nil

func (*Framebuffer) GrabImage

func (fb *Framebuffer) GrabImage(dev vk.Device, cmd vk.CommandBuffer)

GrabImage grabs the current framebuffer image, using given command buffer which must have the cmdBegin called already. call this after: sys.MemCmdEndSubmitWaitFree()

type GPU

type GPU struct {

	// handle for the vulkan driver instance
	Instance vk.Instance

	// handle for the vulkan physical GPU hardware
	GPU vk.PhysicalDevice

	// options passed in during config
	UserOpts *GPUOpts

	// set of enabled options set post-Config
	EnabledOpts GPUOpts

	// name of the physical GPU device
	DeviceName string

	// name of application -- set during Config and used in init of GPU
	AppName string

	// version of vulkan API to target
	APIVersion vk.Version

	// version of application -- optional
	AppVersion vk.Version

	// use Add method to add required instance extentions prior to calling Config
	InstanceExts []string

	// use Add method to add required device extentions prior to calling Config
	DeviceExts []string

	// set Add method to add required validation layers prior to calling Config
	ValidationLayers []string

	// physical device features required -- set per platform as needed
	DeviceFeaturesNeeded *vk.PhysicalDeviceVulkan12Features

	// this is used for computing, not graphics
	Compute bool

	// our custom debug callback
	DebugCallback vk.DebugReportCallback

	// properties of physical hardware -- populated after Config
	GPUProperties vk.PhysicalDeviceProperties

	// features of physical hardware -- populated after Config
	GPUFeats vk.PhysicalDeviceFeatures

	// properties of device memory -- populated after Config
	MemoryProperties vk.PhysicalDeviceMemoryProperties

	// maximum number of compute threads per compute shader invokation, for a 1D number of threads per Warp, which is generally greater than MaxComputeWorkGroup, which allows for the and maxima as well.  This is not defined anywhere in the formal spec, unfortunately, but has been determined empirically for Mac and NVIDIA which are two of the most relevant use-cases.  If not a known case, the MaxComputeWorkGroupvalue is used, which can significantly slow down compute processing if more could actually be used.  Please file an issue or PR for other GPUs with known larger values.
	MaxComputeWorkGroupCount1D int
}

GPU represents the GPU hardware

func NewComputeGPU

func NewComputeGPU() *GPU

NewComputeGPU returns a new GPU struct with Compute Defaults set configure any additional defaults before calling Config. Use NewGPU for a graphics enabled GPU.

func NewGPU

func NewGPU() *GPU

NewGPU returns a new GPU struct with Graphics Defaults set configure any additional defaults before calling Config. Use NewComputeGPU for a compute-only GPU that doesn't load graphics extensions.

func (*GPU) AddDeviceExt

func (gp *GPU) AddDeviceExt(ext ...string) bool

AddDeviceExt adds given extension(s), only if not already set returns true if added.

func (*GPU) AddInstanceExt

func (gp *GPU) AddInstanceExt(ext ...string) bool

AddInstanceExt adds given extension(s), only if not already set returns true if added.

func (*GPU) AddValidationLayer

func (gp *GPU) AddValidationLayer(ext string) bool

AddValidationLayer adds given validation layer, only if not already set returns true if added.

func (*GPU) CheckGPUOpts

func (gp *GPU) CheckGPUOpts(feats *vk.PhysicalDeviceFeatures, opts *GPUOpts, report bool) bool

CheckGPUOpts checks if the required options are present. if report is true, a message is printed about missing features, and the state of the actual

func (*GPU) Config

func (gp *GPU) Config(name string, opts ...*GPUOpts) error

Config configures the GPU given the extensions set in InstanceExts, DeviceExts, and ValidationLayers, and the given GPUOpts options. Only the first such opts will be used -- the variable args is used to enable no options to be passed by default.

func (*GPU) Defaults

func (gp *GPU) Defaults(graphics bool)

Defaults sets up default parameters, with the graphics flag determining whether graphics-relevant items are added.

func (*GPU) Destroy

func (gp *GPU) Destroy()

Destroy destroys GPU resources -- call after everything else has been destroyed

func (*GPU) GetDeviceName

func (gp *GPU) GetDeviceName(properties *vk.PhysicalDeviceProperties, idx int) string

func (*GPU) NewComputeSystem

func (gp *GPU) NewComputeSystem(name string) *System

NewComputeSystem returns a new system initialized for this GPU, for Compute, not graphics functionality.

func (*GPU) NewGraphicsSystem

func (gp *GPU) NewGraphicsSystem(name string, dev *Device) *System

NewGraphicsSystem returns a new system initialized for this GPU, for graphics functionality, using Device from the Surface or RenderFrame depending on the target of rendering.

func (*GPU) PropertiesString added in v0.0.10

func (gp *GPU) PropertiesString(print bool) string

PropertiesString returns a human-readable summary of the GPU properties.

func (*GPU) SelectGPU

func (gp *GPU) SelectGPU(gpus []vk.PhysicalDevice, gpuCount int) int

func (*GPU) SetGPUOpts

func (gp *GPU) SetGPUOpts(feats *vk.PhysicalDeviceFeatures, opts GPUOpts)

SetGPUOpts sets the Enabled optional features in given features struct

type GPUOpts

type GPUOpts map[CPUOptions]OptionStates

GPUOpts is the collection of CPUOption states

var DefaultOpts *GPUOpts

DefaultOpts are default GPU config options that can be set by any app prior to initializing the GPU object -- this may be easier than passing options in from the app during the Config call. Any such options take precedence over these options (usually best to avoid direct conflits -- monitor Debug output to see).

func NewRequiredOpts

func NewRequiredOpts(opts ...CPUOptions) GPUOpts

NewRequiredOpts returns a new GPUOpts with all of the given options as Required.

func (*GPUOpts) Add

func (co *GPUOpts) Add(opt CPUOptions, state OptionStates)

Add adds the given option state

func (*GPUOpts) CopyFrom

func (co *GPUOpts) CopyFrom(fm *GPUOpts)

CopyFrom copies options from another opts collection, overwriting any existing in this map.

func (*GPUOpts) Init

func (co *GPUOpts) Init()

func (*GPUOpts) State

func (co *GPUOpts) State(opt CPUOptions) OptionStates

State returns the state of the given option. Any option not explicitly set is assumed to be Disabled.

type HostImage

type HostImage struct {

	// size in bytes allocated for host representation of image
	Size int

	// buffer for host CPU-visible memory, for staging -- can be owned by us or managed by Memory (for Value)
	Buff vk.Buffer `display:"-"`

	// offset into host buffer, when Buff is Memory managed
	Offset int

	// host CPU-visible memory, for staging, when we manage our own memory
	Mem vk.DeviceMemory `display:"-"`

	// memory mapped pointer into host memory -- remains mapped
	Ptr unsafe.Pointer `display:"-"`
}

HostImage is the host representation of an Image

func (*HostImage) Pixels

func (hi *HostImage) Pixels() []byte

Pixels returns the byte slice of the pixels for host image Only valid if host is active! No error checking is performed here.

func (*HostImage) SetNil

func (hi *HostImage) SetNil()

type Image

type Image struct {

	// name of the image -- e.g., same as Value name if used that way -- helpful for debugging -- set to filename if loaded from a file and otherwise empty
	Name string

	// bit flags for image state, for indicating nature of ownership and state
	Flags ImageFlags

	// format & size of image
	Format ImageFormat

	// vulkan image handle, in device memory
	Image vk.Image `display:"-"`

	// vulkan image view
	View vk.ImageView `display:"-"`

	// memory for image when we allocate it
	Mem vk.DeviceMemory `display:"-"`

	// keep track of device for destroying view
	Dev vk.Device `display:"-"`

	// host memory buffer representation of the image
	Host HostImage

	// pointer to our GPU
	GPU *GPU
}

Image represents a vulkan image with an associated ImageView. The vulkan Image is in device memory, in an optimized format. There can also be an optional host-visible, plain pixel buffer which can be a pointer into a larger buffer or owned by the Image.

func (*Image) AllocHost

func (im *Image) AllocHost()

AllocHost allocates a staging buffer on the host for the image on the device (must set first), based on the current Format info, and other flags. If the existing host buffer is sufficient to hold the image, then nothing happens.

func (*Image) AllocImage

func (im *Image) AllocImage()

AllocImage allocates the VkImage on the device (must set first), based on the current Format info, and other flags.

func (*Image) ConfigDepth

func (im *Image) ConfigDepth(gp *GPU, dev vk.Device, depthType Types, imgFmt *ImageFormat)

ConfigDepth configures this image as a depth image using given depth image format, and other on format information from the render image format.

func (*Image) ConfigDepthView

func (im *Image) ConfigDepthView()

ConfigDepthView configures a depth view image

func (*Image) ConfigFramebuffer

func (im *Image) ConfigFramebuffer(gp *GPU, dev vk.Device, imgFmt *ImageFormat)

ConfigFramebuffer configures this image as a framebuffer image using format. Sets multisampling to 1, layers to 1. Only makes a device image -- no host rep.

func (*Image) ConfigGoImage

func (im *Image) ConfigGoImage(sz image.Point, layers int)

ConfigGoImage configures the image for storing an image of the given size, for images allocated in a shared host buffer. (i.e., not Var.TextureOwns). Image format will be set to default unless format is already set. Layers is number of separate images of given size allocated in a texture array. Once memory is allocated then SetGoImage can be called in a second pass.

func (*Image) ConfigMulti

func (im *Image) ConfigMulti(gp *GPU, dev vk.Device, imgFmt *ImageFormat)

ConfigMulti configures this image as a mutisampling image using format. Only makes a device image -- no host rep.

func (*Image) ConfigStdView

func (im *Image) ConfigStdView()

ConfigStdView configures a standard 2D image view, for current image, format, and device.

func (*Image) ConfigValueHost added in v0.0.10

func (im *Image) ConfigValueHost(buff *MemBuff, buffPtr unsafe.Pointer, offset int)

ConfigValueHost configures host staging buffer from memory buffer for val-owned image

func (*Image) CopyImageRec

func (im *Image) CopyImageRec() vk.ImageCopy

CopyImageRec returns info for this Image for the ImageCopy operations

func (*Image) CopyRec

func (im *Image) CopyRec() vk.BufferImageCopy

CopyRec returns info for this Image for the BufferImageCopy operations

func (*Image) Destroy

func (im *Image) Destroy()

Destroy destroys any existing view, nils fields

func (*Image) DestroyView

func (im *Image) DestroyView()

DestroyView destroys any existing view

func (*Image) DevGoImage

func (im *Image) DevGoImage() (*image.RGBA, error)

DevGoImage returns an image.RGBA standard Go image version of the HostOnly Device memory representation, directly pointing to the source memory. This will be valid only as long as that memory is valid, and modifications will directly write into the source memory. You MUST call UnmapDev once done using that image memory, at which point it will become invalid. This is only for immediate, transitory use of the image (e.g., saving or then drawing it into another image). See [DevGoImageCopy] for a version that copies into an image.RGBA. Only works if ImageOnHostOnly and Format is default vk.FormatR8g8b8a8Srgb.

func (*Image) DevGoImageCopy

func (im *Image) DevGoImageCopy(rgba *image.RGBA) error

DevGoImageCopy sets the given image.RGBA standard Go image to a copy of the HostOnly Device memory representation, re-sizing the pixel memory as needed. If the image pixels are sufficiently sized, no memory allocation occurs. Only works if ImageOnHostOnly, and works best if Format is default vk.FormatR8g8b8a8Srgb (strongly recommended in any case). If format is vk.FormatR8g8b8a8Unorm, it will be converted to srgb.

func (*Image) FreeHost

func (im *Image) FreeHost()

FreeHost frees memory in host buffer representation of image Only if we own the host buffer.

func (*Image) FreeImage

func (im *Image) FreeImage()

FreeImage frees device memory version of image that we own

func (*Image) GoImage

func (im *Image) GoImage(layer int) (*image.RGBA, error)

GoImage returns an *image.RGBA standard Go image, of the Host memory representation at given layer. Only works if IsHostActive and Format is default vk.FormatR8g8b8a8Srgb (strongly recommended in any case)

func (*Image) HasFlag

func (im *Image) HasFlag(flag ImageFlags) bool

HasFlag checks if flag is set using atomic, safe for concurrent access

func (*Image) HostPixels

func (im *Image) HostPixels(layer int) []byte

HostPixels returns host staging pixels at given layer

func (*Image) IsActive

func (im *Image) IsActive() bool

IsActive returns true if the image is set and has a view

func (*Image) IsHostActive

func (im *Image) IsHostActive() bool

IsHostActive returns true if the Host accessible version of image is active and ready to use

func (*Image) IsHostOwner

func (im *Image) IsHostOwner() bool

IsHostOwner returns true if the host buffer is owned by us

func (*Image) IsImageOwner

func (im *Image) IsImageOwner() bool

IsImageOwner returns true if the vk.Image is owned by us

func (*Image) IsValue added in v0.0.10

func (im *Image) IsValue() bool

IsValue returns true if the image belongs to a Value

func (*Image) SetFlag

func (im *Image) SetFlag(on bool, flag ...enums.BitFlag)

SetFlag sets flag(s) using atomic, safe for concurrent access

func (*Image) SetGoImage

func (im *Image) SetGoImage(img image.Image, layer int, flipY bool) error

SetGoImage sets staging image data from a standard Go image at given layer. This is most efficiently done using an image.RGBA, but other formats will be converted as necessary. If flipY is true then the Image Y axis is flipped when copying into the image data, so that images will appear upright in the standard OpenGL Y-is-up coordinate system. If using the Y-is-down Vulkan coordinate system, don't flip. Only works if IsHostActive and Image Format is default vk.FormatR8g8b8a8Srgb, Must still call AllocImage to have image allocated on the device, and copy from this host staging data to the device.

func (*Image) SetNil

func (im *Image) SetNil()

SetNil sets everything to nil, for shared image

func (*Image) SetSize

func (im *Image) SetSize(size image.Point) bool

SetSize sets the size. If the size is not the same as current, and Image owns the Host and / or Image, then those are resized. returns true if resized.

func (*Image) SetVkImage

func (im *Image) SetVkImage(gp *GPU, dev vk.Device, img vk.Image)

SetVkImage sets a Vk Image and configures a default 2D view based on existing format information (which must be set properly). Any exiting view is destroyed first. Must pass the relevant device.

func (*Image) Transition

func (im *Image) Transition(cmd vk.CommandBuffer, format vk.Format, oldLayout, NewLayout vk.ImageLayout, srcStage, dstStage vk.PipelineStageFlagBits)

Transition transitions image to new layout

func (*Image) TransitionDstToGeneral

func (im *Image) TransitionDstToGeneral(cmd vk.CommandBuffer)

TransitionDstToGeneral transitions from Dst to General, in prep for copy from dev to host

func (*Image) TransitionDstToShader

func (im *Image) TransitionDstToShader(cmd vk.CommandBuffer)

TransitionDstToShader transitions from TransferDstOptimal to TransferShaderReadOnly

func (*Image) TransitionForDst

func (im *Image) TransitionForDst(cmd vk.CommandBuffer, srcStage vk.PipelineStageFlagBits)

TransitionForDst transitions to TransferDstOptimal to prepare device image to be copied to. source stage is as specified.

func (*Image) UnmapDev

func (im *Image) UnmapDev()

UnmapDev calls UnmapMemory on the mapped memory for this image, set by MapMemoryAll. This must be called after image is used in DevGoImage (only if you use it immediately!)

type ImageFlags

type ImageFlags int64 //enums:bitflag -trim-prefix Image

ImageFlags are bitflags for Image state

const (
	// ImageActive: the Image and ImageView are configured and ready to use
	ImageActive ImageFlags = iota

	// ImageHostActive: the Host representation of the image is present and
	// ready to be accessed
	ImageHostActive

	// ImageOwnsImage: we own the Vk.Image
	ImageOwnsImage

	// ImageOwnsHost: we own the Host buffer (and it is initialized)
	ImageOwnsHost

	// ImageIsValue: we are a Value image and our Host buffer is shared, with offset.
	// this is incompatible with ImageOwnsHost
	ImageIsValue

	// DepthImage indicates that this is a Depth buffer image
	DepthImage

	// FramebufferImage indicates that this is a Framebuffer image
	FramebufferImage

	// ImageOnHostOnly causes the image to be created only on host visible
	// memory, not on device memory -- no additional host buffer should be created.
	// this is for an ImageGrab image.  layout is LINEAR
	ImageOnHostOnly
)
const ImageFlagsN ImageFlags = 8

ImageFlagsN is the highest valid value for type ImageFlags, plus one.

func ImageFlagsValues

func ImageFlagsValues() []ImageFlags

ImageFlagsValues returns all possible values for the type ImageFlags.

func (ImageFlags) BitIndexString

func (i ImageFlags) BitIndexString() string

BitIndexString returns the string representation of this ImageFlags value if it is a bit index value (typically an enum constant), and not an actual bit flag value.

func (ImageFlags) Desc

func (i ImageFlags) Desc() string

Desc returns the description of the ImageFlags value.

func (ImageFlags) HasFlag

func (i ImageFlags) HasFlag(f enums.BitFlag) bool

HasFlag returns whether these bit flags have the given bit flag set.

func (ImageFlags) Int64

func (i ImageFlags) Int64() int64

Int64 returns the ImageFlags value as an int64.

func (ImageFlags) MarshalText

func (i ImageFlags) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*ImageFlags) SetFlag

func (i *ImageFlags) SetFlag(on bool, f ...enums.BitFlag)

SetFlag sets the value of the given flags in these flags to the given value.

func (*ImageFlags) SetInt64

func (i *ImageFlags) SetInt64(in int64)

SetInt64 sets the ImageFlags value from an int64.

func (*ImageFlags) SetString

func (i *ImageFlags) SetString(s string) error

SetString sets the ImageFlags value from its string representation, and returns an error if the string is invalid.

func (*ImageFlags) SetStringOr

func (i *ImageFlags) SetStringOr(s string) error

SetStringOr sets the ImageFlags value from its string representation while preserving any bit flags already set, and returns an error if the string is invalid.

func (ImageFlags) String

func (i ImageFlags) String() string

String returns the string representation of this ImageFlags value.

func (*ImageFlags) UnmarshalText

func (i *ImageFlags) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (ImageFlags) Values

func (i ImageFlags) Values() []enums.Enum

Values returns all possible values for the type ImageFlags.

type ImageFormat

type ImageFormat struct {

	// Size of image
	Size image.Point

	// Image format -- FormatR8g8b8a8Srgb is a standard default
	Format vk.Format

	// number of samples -- set higher for Framebuffer rendering but otherwise default of SampleCount1Bit
	Samples vk.SampleCountFlagBits

	// number of layers for texture arrays
	Layers int
}

ImageFormat describes the size and vulkan format of an Image If Layers > 1, all must be the same size.

func NewImageFormat

func NewImageFormat(width, height, layers int) *ImageFormat

NewImageFormat returns a new ImageFormat with default format and given size and number of layers

func (*ImageFormat) Aspect

func (im *ImageFormat) Aspect() float32

Aspect returns the aspect ratio X / Y

func (*ImageFormat) Bounds

func (im *ImageFormat) Bounds() image.Rectangle

Bounds returns the rectangle defining this image: 0,0,w,h

func (*ImageFormat) BytesPerPixel

func (im *ImageFormat) BytesPerPixel() int

BytesPerPixel returns number of bytes required to represent one Pixel (in Host memory at least). TODO only works for known formats -- need to add more as needed.

func (*ImageFormat) Defaults

func (im *ImageFormat) Defaults()

func (*ImageFormat) IsRGBAUnorm

func (im *ImageFormat) IsRGBAUnorm() bool

IsRGBAUnorm returns true if image format is the vk.FormatR8g8b8a8Unorm format which is compatible with go image.RGBA format with colorspace conversion.

func (*ImageFormat) IsStdRGBA

func (im *ImageFormat) IsStdRGBA() bool

IsStdRGBA returns true if image format is the standard vk.FormatR8g8b8a8Srgb format which is compatible with go image.RGBA format.

func (*ImageFormat) LayerByteSize

func (im *ImageFormat) LayerByteSize() int

LayerByteSize returns number of bytes required to represent one layer of image in Host memory. TODO only works for known formats -- need to add more as needed.

func (*ImageFormat) NSamples

func (im *ImageFormat) NSamples() int

NSamples returns the integer number of samples based on Samples flag setting

func (*ImageFormat) Set

func (im *ImageFormat) Set(w, h int, ft vk.Format)

Set sets width, height and format

func (*ImageFormat) SetFormat

func (im *ImageFormat) SetFormat(ft Types)

SetFormat sets the format using vgpu standard Types

func (*ImageFormat) SetMultisample

func (im *ImageFormat) SetMultisample(nsamp int)

SetMultisample sets the number of multisampling to decrease aliasing 4 is typically sufficient. Values must be power of 2.

func (*ImageFormat) SetSize

func (im *ImageFormat) SetSize(w, h int)

SetSize sets the width, height

func (*ImageFormat) Size32

func (im *ImageFormat) Size32() (width, height uint32)

Size32 returns size as uint32 values

func (*ImageFormat) Stride

func (im *ImageFormat) Stride() int

Stride returns number of bytes per image row. TODO only works for known formats -- need to add more as needed.

func (*ImageFormat) String

func (im *ImageFormat) String() string

String returns human-readable version of format

func (*ImageFormat) TotalByteSize

func (im *ImageFormat) TotalByteSize() int

TotalByteSize returns total number of bytes required to represent all layers of images in Host memory. TODO only works for known formats -- need to add more as needed.

type MemBuff

type MemBuff struct {
	GPU *GPU

	// type of memory in this buffer
	Type BuffTypes

	// allocated buffer size
	Size int

	// logical descriptor for host CPU-visible memory, for staging
	Host vk.Buffer `display:"-"`

	// host CPU-visible memory, for staging
	HostMem vk.DeviceMemory `display:"-"`

	// logical descriptor for device GPU-local memory, for computation
	Dev vk.Buffer `display:"-"`

	// device GPU-local memory, for computation
	DevMem vk.DeviceMemory `display:"-"`

	// memory mapped pointer into host memory -- remains mapped
	HostPtr unsafe.Pointer `display:"-"`

	// alignment of offsets into this buffer
	AlignBytes int

	// true if memory has been allocated, copied, transfered
	Active bool `edit:"-"`
}

MemBuff is a memory buffer holding a particular type of memory with staging Host-based memory and Device memory

func (*MemBuff) AllocDev

func (mb *MemBuff) AllocDev(dev vk.Device)

AllocDev allocates device local memory for this buffer.

func (*MemBuff) AllocHost

func (mb *MemBuff) AllocHost(dev vk.Device, bsz int) bool

AllocHost allocates memory for this buffer of given size in bytes, freeing any existing memory allocated first. Host and Dev buffers are made, and host memory is allocated and mapped for staging purposes. Call AllocDev to allocate device memory. Returns true if new memory was allocated.

func (*MemBuff) Free

func (mb *MemBuff) Free(dev vk.Device)

Free frees all memory for this buffer, including destroying buffers which have size associated with them.

type MemReg

type MemReg struct {
	Offset    int
	Size      int
	BuffType  BuffTypes
	BuffIndex int // for storage buffers, storage buffer index
}

MemReg is a region of memory for transferring to / from GPU

type Memory

type Memory struct {
	GPU *GPU

	// logical device that this memory is managed for -- set from System
	Device Device

	// command pool for memory transfers
	CmdPool CmdPool

	// Vars variables used in shaders, which manage associated Values containing specific value instances of each var
	Vars Vars

	// memory buffers, organized by different Roles of vars.  Storage is managed separately in StorageBuffs
	Buffs [BuffTypesN]*MemBuff

	// memory buffers for storage -- vals are allocated to buffers during AllocHost, grouping based on what fits within GPU limits
	StorageBuffs []*MemBuff

	// memory allocation records for storage buffer allocation, per variable
	StorageMems []*VarMem
}

Memory manages memory for the GPU, using separate buffers for different roles, defined in the BuffTypes and managed by a MemBuff. Memory is organized by Vars with associated Values.

func (*Memory) AllocBuffMem

func (mm *Memory) AllocBuffMem(buffer vk.Buffer, properties vk.MemoryPropertyFlagBits) vk.DeviceMemory

AllocBuffMem allocates memory for given buffer, with given properties

func (*Memory) AllocDev

func (mm *Memory) AllocDev()

AllocDev allocates device memory for all bufers

func (*Memory) AllocDevBuff

func (mm *Memory) AllocDevBuff(bt BuffTypes)

AllocDevBuff allocates memory on the device for given buffer

func (*Memory) AllocHost

func (mm *Memory) AllocHost()

AllocHost allocates memory for all buffers

func (*Memory) AllocHostBuff

func (mm *Memory) AllocHostBuff(bt BuffTypes)

AllocHostBuff allocates host memory for given buffer

func (*Memory) AllocHostStorageBuff

func (mm *Memory) AllocHostStorageBuff()

AllocHostStorageBuff allocates host memory for all storage buffers

func (*Memory) CmdTransferRegsFromGPU added in v0.0.10

func (mm *Memory) CmdTransferRegsFromGPU(cmd vk.CommandBuffer, buff *MemBuff, regs []MemReg)

CmdTransferRegsFromGPU transfers memory from GPU to CPU for given regions by recording command to given buffer.

func (*Memory) CmdTransferRegsToGPU

func (mm *Memory) CmdTransferRegsToGPU(cmd vk.CommandBuffer, buff *MemBuff, regs []MemReg)

CmdTransferRegsToGPU transfers memory from CPU to GPU for given regions by recording command to given buffer.

func (*Memory) CmdTransferStorageBuffRegsFromGPU added in v0.0.10

func (mm *Memory) CmdTransferStorageBuffRegsFromGPU(cmd vk.CommandBuffer, buff *MemBuff, buffIndex int, regs []MemReg)

CmdTransferStorageBuffRegsFromGPU transfers memory from GPU to CPU for given regions by recording command to given storage buffer of given index.

func (*Memory) CmdTransferStorageBuffRegsToGPU

func (mm *Memory) CmdTransferStorageBuffRegsToGPU(cmd vk.CommandBuffer, buff *MemBuff, buffIndex int, regs []MemReg)

CmdTransferStorageBuffRegsToGPU transfers memory from CPU to GPU for given regions by recording command to given storage buffer of given index.

func (*Memory) CmdTransferStorageRegsFromGPU added in v0.0.10

func (mm *Memory) CmdTransferStorageRegsFromGPU(cmd vk.CommandBuffer, regs []MemReg)

CmdTransferStorageRegsFromGPU transfers memory from GPU to CPU for given storage regions by recording command to given command buffer.

func (*Memory) CmdTransferStorageRegsToGPU

func (mm *Memory) CmdTransferStorageRegsToGPU(cmd vk.CommandBuffer, regs []MemReg)

CmdTransferStorageRegsToGPU transfers memory from CPU to GPU for given storage regions by recording command to given command buffer.

func (*Memory) Config

func (mm *Memory) Config(dev vk.Device)

Config should be called after all Values have been configured and are ready to go with their initial data. Does: AllocHost(), AllocDev(). Note: dynamic binding must be called separately after this.

func (*Memory) Deactivate

func (mm *Memory) Deactivate()

Deactivate deactivates device memory for all buffs

func (*Memory) DeactivateBuff

func (mm *Memory) DeactivateBuff(bt BuffTypes)

DeactivateBuff deactivates device memory in given buffer

func (*Memory) Destroy

func (mm *Memory) Destroy(dev vk.Device)

Destroy destroys all vulkan allocations, using given dev

func (*Memory) Free

func (mm *Memory) Free() bool

Free frees memory for all buffers -- returns true if any freed

func (*Memory) FreeBuff

func (mm *Memory) FreeBuff(bt BuffTypes) bool

FreeBuff frees any allocated memory in buffer -- returns true if freed

func (*Memory) FreeBuffMem

func (mm *Memory) FreeBuffMem(memory *vk.DeviceMemory)

FreeBuffMem frees given device memory to nil

func (*Memory) Init

func (mm *Memory) Init(gp *GPU, device *Device)

Init configures the Memory for use with given gpu, device, and associated queueindex

func (*Memory) NewBuffer

func (mm *Memory) NewBuffer(size int, usage vk.BufferUsageFlagBits) vk.Buffer

NewBuffer makes a buffer of given size, usage

func (*Memory) SyncRegionValueIndex added in v0.0.10

func (mm *Memory) SyncRegionValueIndex(set int, varNm string, valIndex int) (MemReg, error)

SyncRegionValueIndex returns memory region for syncing given value from GPU device memory to CPU host memory, specifying value by index for given named variable, in given set. Variable can only only be Storage memory -- otherwise an error is returned. Multiple regions can be combined into one transfer call for greater efficiency.

func (*Memory) SyncRegionValueName added in v0.0.10

func (mm *Memory) SyncRegionValueName(set int, varNm, valNm string) (MemReg, error)

SyncRegionValueName returns memory region for syncing given value from GPU device memory to CPU host memory, specifying value by name for given named variable in given set. Variable can only only be Storage memory -- otherwise an error is returned. Multiple regions can be combined into one transfer call for greater efficiency.

func (*Memory) SyncStorageRegionsFromGPU added in v0.0.10

func (mm *Memory) SyncStorageRegionsFromGPU(regs ...MemReg)

SyncStorageRegionsFromGPU syncs given regions from the Storage buffer memory from GPU to CPU, in one call. Use SyncRegValueIndexFromCPU to get the regions.

func (*Memory) SyncToGPU

func (mm *Memory) SyncToGPU()

SyncToGPU syncs all modified Value regions from CPU to GPU device memory, for all buffs

func (*Memory) SyncToGPUBuff

func (mm *Memory) SyncToGPUBuff(bt BuffTypes)

SyncToGPUBuff syncs all modified Value regions from CPU to GPU device memory, for given buff

func (*Memory) SyncValueIndexFromGPU added in v0.0.10

func (mm *Memory) SyncValueIndexFromGPU(set int, varNm string, valIndex int) error

SyncValueIndexFromGPU syncs given value from GPU device memory to CPU host memory, specifying value by index for given named variable, in given set. Variable can only only be Storage memory -- otherwise an error is returned.

func (*Memory) SyncValueNameFromGPU added in v0.0.10

func (mm *Memory) SyncValueNameFromGPU(set int, varNm, valNm string) error

SyncValueNameFromGPU syncs given value from GPU device memory to CPU host memory, specifying value by name for given named variable in given set. Variable can only only be Storage memory -- otherwise an error is returned.

func (*Memory) SyncValuesTextures added in v0.0.10

func (mm *Memory) SyncValuesTextures(buff *MemBuff)

SyncValuesTextures syncs all changed vals images from host buffer to device memory

func (*Memory) TransferAllValuesTextures added in v0.0.10

func (mm *Memory) TransferAllValuesTextures(buff *MemBuff)

TransferAllValuesTextures copies all vals images from host buffer to device memory

func (*Memory) TransferImagesFromGPU added in v0.0.10

func (mm *Memory) TransferImagesFromGPU(buff vk.Buffer, imgs ...*Image)

TransferImagesFromGPU transfers image memory from GPU to CPU for given images. the image Host.Offset *must* be accurate for the given buffer, whether its own individual buffer or the shared memory-managed buffer.

func (*Memory) TransferRegsFromGPU added in v0.0.10

func (mm *Memory) TransferRegsFromGPU(regs []MemReg)

TransferRegsFromGPU transfers memory from GPU to CPU for given regions, using a one-time memory command buffer. All buffs must be of the same type.

func (*Memory) TransferRegsToGPU

func (mm *Memory) TransferRegsToGPU(regs []MemReg)

TransferRegsToGPU transfers memory from CPU to GPU for given regions, using a one-time memory command buffer. All buffs must be of the same type.

func (*Memory) TransferStorageRegsFromGPU added in v0.0.10

func (mm *Memory) TransferStorageRegsFromGPU(regs []MemReg)

TransferStorageRegsFromGPU transfers memory from GPU to CPU for given regions, using a one-time memory command buffer, for Storage

func (*Memory) TransferStorageRegsToGPU

func (mm *Memory) TransferStorageRegsToGPU(regs []MemReg)

TransferStorageRegsToGPU transfers memory from CPU to GPU for given regions, using a one-time memory command buffer, for Storage

func (*Memory) TransferTexturesToGPU

func (mm *Memory) TransferTexturesToGPU(buff vk.Buffer, imgs ...*Image)

TransferTexturesToGPU transfers texture image memory from CPU to GPU for given images. Transitions device image as destination, then to Shader read only source, for use in fragment shader texture sampling. The image Host.Offset *must* be accurate for the given buffer, whether its own individual buffer or the shared memory-managed buffer.

func (*Memory) TransferToGPU

func (mm *Memory) TransferToGPU()

TransferToGPU transfers entire staging to GPU for all buffs

func (*Memory) TransferToGPUBuff

func (mm *Memory) TransferToGPUBuff(bt BuffTypes)

TransferToGPUBuff transfers entire staging to GPU for given buffer

type OptionStates

type OptionStates int32 //enums:enum

OptionStates are options for the physical device features

const (
	// Disabled -- option is not enabled
	Disabled OptionStates = iota

	// Optional -- option is enabled if possible
	// and code checks for actual state providing
	// workaround if not supported
	Optional

	// Required -- option is required and GPU.Config
	// fails if not supported by the hardware
	Required

	// Enabled is the state of all options specified
	// during Config, and supported bythe hardware
	Enabled
)
const OptionStatesN OptionStates = 4

OptionStatesN is the highest valid value for type OptionStates, plus one.

func OptionStatesValues

func OptionStatesValues() []OptionStates

OptionStatesValues returns all possible values for the type OptionStates.

func (OptionStates) Desc

func (i OptionStates) Desc() string

Desc returns the description of the OptionStates value.

func (OptionStates) Int64

func (i OptionStates) Int64() int64

Int64 returns the OptionStates value as an int64.

func (OptionStates) MarshalText

func (i OptionStates) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*OptionStates) SetInt64

func (i *OptionStates) SetInt64(in int64)

SetInt64 sets the OptionStates value from an int64.

func (*OptionStates) SetString

func (i *OptionStates) SetString(s string) error

SetString sets the OptionStates value from its string representation, and returns an error if the string is invalid.

func (OptionStates) String

func (i OptionStates) String() string

String returns the string representation of this OptionStates value.

func (*OptionStates) UnmarshalText

func (i *OptionStates) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (OptionStates) Values

func (i OptionStates) Values() []enums.Enum

Values returns all possible values for the type OptionStates.

type Pipeline

type Pipeline struct {

	// unique name of this pipeline
	Name string

	// system that we belong to and manages all shared resources (Memory, Vars, Values, etc), etc
	Sys *System

	// shaders in order added -- should be execution order
	Shaders []*Shader

	// shaders loaded for this pipeline
	ShaderMap map[string]*Shader

	// vulkan pipeline configuration options
	VkConfig vk.GraphicsPipelineCreateInfo

	// the created vulkan pipeline
	VkPipeline vk.Pipeline

	// cache
	VkCache vk.PipelineCache
}

Pipeline manages Shader program(s) that accomplish a specific type of rendering or compute function, using Vars / Values defined by the overall System. In the graphics context, each pipeline could handle a different class of materials (textures, Phong lighting, etc).

func (*Pipeline) AddShader

func (pl *Pipeline) AddShader(name string, typ ShaderTypes) *Shader

AddShader adds Shader with given name and type to the pipeline

func (*Pipeline) AddShaderCode

func (pl *Pipeline) AddShaderCode(name string, typ ShaderTypes, code []byte) *Shader

AddShaderCode adds Shader with given name and type to the pipeline, Loading SPV code from given bytes

func (*Pipeline) AddShaderEmbed

func (pl *Pipeline) AddShaderEmbed(name string, typ ShaderTypes, efs embed.FS, fname string) *Shader

AddShaderEmbed adds Shader with given name and type to the pipeline, Loading SPV code from given file name in embed.FS filesystem.

func (*Pipeline) AddShaderFile

func (pl *Pipeline) AddShaderFile(name string, typ ShaderTypes, fname string) *Shader

AddShaderFile adds Shader with given name and type to the pipeline, Opening SPV code from given filename

func (*Pipeline) BindDrawVertex

func (pl *Pipeline) BindDrawVertex(cmd vk.CommandBuffer, descIndex int)

BindDrawVertex adds commands to the given command buffer to bind this pipeline, and then bind vertex / index values and Draw based on current vals for any Vertex (and associated Index) Vars. for given descIndex set of descriptors (see Vars NDescs for info). This is the standard unit of drawing between Begin and End.

func (*Pipeline) BindPipeline

func (pl *Pipeline) BindPipeline(cmd vk.CommandBuffer)

BindPipeline adds commands to the given command buffer to bind this pipeline to command buffer. System BeginRenderPass must have been called at some point before this.

func (*Pipeline) ComputeDispatch

func (pl *Pipeline) ComputeDispatch(cmd vk.CommandBuffer, nx, ny, nz int)

ComputeDispatch adds commands to given cmd buffer to run the compute shader for given number of *warps* (groups of threads) along 3 dimensions, which then generate indexes passed into the shader. In HLSL, the [numthreads(x, y, z)] directive specifies the number of threads allocated per warp -- the actual number of elements processed is threads * warps per each dimension. See Warps function. The hardware typically has 32 (NVIDIA, M1, M2) or 64 (AMD) hardware threads per warp, and so 64 is typically used as a default sum of threads per warp across all of the dimensions. Can use subsets of dimensions by using 1 for the other dimensions, and see ComputeDispatch1D for a convenience method that automatically computes the number of warps for a 1D compute shader (everthing in x). Must have a CmdBegin already executed, either via ComputeBindVars or ComputeResetBegin call. Must call CommandSubmit[Wait] to execute the command.

func (*Pipeline) ComputeDispatch1D

func (pl *Pipeline) ComputeDispatch1D(cmd vk.CommandBuffer, n, threads int)

ComputeDispatch1D adds commands to run the compute shader for given number of computational elements along the first (X) dimension, for given number *elements* and threads per warp (typically 64). See ComputeDispatch for full info. This is just a convenience method for common 1D case that calls the Warps method for you.

func (*Pipeline) Config

func (pl *Pipeline) Config(rebuild bool)

Config is called once all the VkConfig options have been set using Set* methods, and the shaders have been loaded. The parent System has already done what it can for its config. The rebuild flag indicates whether pipelines should rebuild, e.g., based on NTextures changing.

func (*Pipeline) ConfigCompute

func (pl *Pipeline) ConfigCompute()

ConfigCompute does the configuration for a Compute pipeline

func (*Pipeline) ConfigStages

func (pl *Pipeline) ConfigStages()

ConfigStages configures the shader stages

func (*Pipeline) Destroy

func (pl *Pipeline) Destroy()

func (*Pipeline) DestroyPipeline

func (pl *Pipeline) DestroyPipeline()

func (*Pipeline) Draw

func (pl *Pipeline) Draw(cmd vk.CommandBuffer, vtxCount, instanceCount, firstVtx, firstInstance int)

Draw adds CmdDraw command to the given command buffer BindPipeline must have been called before this. SeeDrawVertex for more typical case using Vertex (and Index) variables.

func (*Pipeline) DrawVertex

func (pl *Pipeline) DrawVertex(cmd vk.CommandBuffer, descIndex int)

DrawVertex adds commands to the given command buffer to bind vertex / index values and Draw based on current BindVertexValue setting for any Vertex (and associated Index) Vars, for given descIndex set of descriptors (see Vars NDescs for info).

func (*Pipeline) FreeShaders

func (pl *Pipeline) FreeShaders()

FreeShaders is called after successful pipeline creation, to unload shader modules as they are no longer needed

func (*Pipeline) Init

func (pl *Pipeline) Init(sy *System)

Init initializes pipeline as part of given System

func (*Pipeline) InitPipeline

func (pl *Pipeline) InitPipeline()

func (*Pipeline) Push

func (pl *Pipeline) Push(cmd vk.CommandBuffer, vr *Var, val unsafe.Pointer)

Push pushes given value as a push constant for given registered push constant variable. Note: it is *essential* to use a local, stack variable for the push value as cgo will likely complain if it is inside some other structure. BindPipeline must have been called before this.

func (*Pipeline) SetColorBlend

func (pl *Pipeline) SetColorBlend(alphaBlend bool)

SetColorBlend determines the color blending function: either 1-source alpha (alphaBlend) or no blending: new color overwrites old. Default is alphaBlend = true

func (*Pipeline) SetCullFace

func (pl *Pipeline) SetCullFace(back bool)

SetCullFace sets the face culling mode: true = back, false = front use CullBack, CullFront constants

func (*Pipeline) SetDynamicState

func (pl *Pipeline) SetDynamicState()

SetDynamicState sets dynamic state (Scissor, Viewport, what else?)

func (*Pipeline) SetFrontFace

func (pl *Pipeline) SetFrontFace(ccw bool)

SetFrontFace sets the winding order for what counts as a front face true = CCW, false = CW

func (*Pipeline) SetGraphicsDefaults

func (pl *Pipeline) SetGraphicsDefaults()

SetGraphicsDefaults configures all the default settings for a graphics rendering pipeline (not for a compute pipeline)

func (*Pipeline) SetLineWidth

func (pl *Pipeline) SetLineWidth(lineWidth float32)

SetLineWidth sets the rendering line width -- 1 is default.

func (*Pipeline) SetRasterization

func (pl *Pipeline) SetRasterization(polygonMode vk.PolygonMode, cullMode vk.CullModeFlagBits, frontFace vk.FrontFace, lineWidth float32)

SetRasterization sets various options for how to rasterize shapes: Defaults are: vk.PolygonModeFill, vk.CullModeBackBit, vk.FrontFaceCounterClockwise, 1.0 There are also separate methods for CullFace, FrontFace, and LineWidth Note: must enable OptFillModeNonSolid option for Line or Point fill mode.

func (*Pipeline) SetTopology

func (pl *Pipeline) SetTopology(topo Topologies, restartEnable bool)

SetTopology sets the topology of vertex position data. TriangleList is the default. Also for Strip modes, restartEnable allows restarting a new strip by inserting a ??

func (*Pipeline) ShaderByName

func (pl *Pipeline) ShaderByName(name string) *Shader

ShaderByName returns Shader by name. Returns nil if not found (error auto logged).

func (*Pipeline) Vars

func (pl *Pipeline) Vars() *Vars

Vars returns a pointer to the vars for this pipeline, which has vals within it

type Render

type Render struct {

	// system that we belong to and manages all shared resources (Memory, Vars, Values, etc), etc
	Sys *System

	// the device we're associated with -- this must be the same device that owns the Framebuffer -- e.g., the Surface
	Dev vk.Device

	// image format information for the framebuffer we render to
	Format ImageFormat

	// the associated depth buffer, if set
	Depth Image

	// is true if configured with depth buffer
	HasDepth bool

	// for multisampling, this is the multisampled image that is the actual render target
	Multi Image

	// is true if multsampled image configured
	HasMulti bool

	// host-accessible image that is used to transfer back from a render color attachment to host memory -- requires a different format than color attachment, and is ImageOnHostOnly flagged.
	Grab Image

	// host-accessible buffer for grabbing the depth map -- must go to a buffer and not an image
	GrabDepth MemBuff

	// set this to true if it is not using a Surface render target (i.e., it is a RenderFrame)
	NotSurface bool

	// values for clearing image when starting render pass
	ClearValues []vk.ClearValue

	// the vulkan renderpass config that clears target first
	VkClearPass vk.RenderPass

	// the vulkan renderpass config that does not clear target first (loads previous)
	VkLoadPass vk.RenderPass
}

Render manages various elements needed for rendering, including a vulkan RenderPass object, which specifies parameters for rendering to a Framebuffer. It holds the Depth buffer if one is used, and a multisampling image too. The Render object lives on the System, and any associated Surface, RenderFrame, and Framebuffers point to it.

func (*Render) BeginRenderPass

func (rp *Render) BeginRenderPass(cmd vk.CommandBuffer, fr *Framebuffer)

BeginRenderPass adds commands to the given command buffer to start the render pass on given framebuffer. Clears the frame first, according to the ClearValues See BeginRenderPassNoClear for non-clearing version.

func (*Render) BeginRenderPassImpl

func (rp *Render) BeginRenderPassImpl(cmd vk.CommandBuffer, fr *Framebuffer, clear bool)

BeginRenderPassImpl adds commands to the given command buffer to start the render pass on given framebuffer. If clear = true, clears the frame according to the ClearValues.

func (*Render) BeginRenderPassNoClear

func (rp *Render) BeginRenderPassNoClear(cmd vk.CommandBuffer, fr *Framebuffer)

BeginRenderPassNoClear adds commands to the given command buffer to start the render pass on given framebuffer. does NOT clear the frame first -- loads prior state.

func (*Render) Config

func (rp *Render) Config(dev vk.Device, imgFmt *ImageFormat, depthFmt Types, notSurface bool)

Config configures the render pass for given device, Using standard parameters for graphics rendering, based on the given image format and depth image format (pass UndefinedType for no depth buffer).

func (*Render) ConfigGrab

func (rp *Render) ConfigGrab(dev vk.Device)

ConfigGrab configures the Grab for copying rendered image back to host memory. Uses format of current Image.

func (*Render) ConfigGrabDepth

func (rp *Render) ConfigGrabDepth(dev vk.Device)

ConfigGrabDepth configures the GrabDepth for copying depth image back to host memory. Uses format of current Depth image.

func (*Render) ConfigImpl

func (rp *Render) ConfigImpl(dev vk.Device, imgFmt *ImageFormat, depthFmt Types, clear bool) vk.RenderPass

func (*Render) DepthImageArray

func (rp *Render) DepthImageArray() ([]float32, error)

DepthImageArray returns the float values from the last GrabDepthImage call automatically handles down-sampling from multisampling.

func (*Render) Destroy

func (rp *Render) Destroy()

func (*Render) GrabDepthImage

func (rp *Render) GrabDepthImage(dev vk.Device, cmd vk.CommandBuffer) error

GrabDepthImage grabs the current render depth image, using given command buffer which must have the cmdBegin called already. Uses the GrabDepth Storage Buffer. call this after: sys.MemCmdEndSubmitWaitFree()

func (*Render) SetClearColor

func (rp *Render) SetClearColor(r, g, b, a float32)

SetClearColor sets the RGBA colors to set when starting new render

func (*Render) SetClearDepthStencil

func (rp *Render) SetClearDepthStencil(depth float32, stencil uint32)

SetClearDepthStencil sets the depth and stencil values when starting new render

func (*Render) SetSize

func (rp *Render) SetSize(size image.Point)

SetSize sets updated size of the render target -- resizes depth and multi buffers as needed

type RenderFrame

type RenderFrame struct {

	// pointer to gpu device, for convenience
	GPU *GPU

	// device for this surface -- each window surface has its own device, configured for that surface
	Device Device

	// the Render for this RenderFrame, typically from a System
	Render *Render

	// has the current image format and dimensions
	Format ImageFormat

	// number of frames to maintain in the swapchain -- e.g., 2 = double-buffering, 3 = triple-buffering -- initially set to a requested amount, and after Init reflects actual number
	NFrames int

	// Framebuffers representing the Image owned by the RenderFrame -- we iterate through these in rendering subsequent frames
	Frames []*Framebuffer

	// semaphore used internally for waiting on acquisition of next frame
	ImageAcquired vk.Semaphore `display:"-"`

	// semaphore that surface user can wait on, will be activated when image has been acquired in AcquireNextFrame method
	RenderDone vk.Semaphore `display:"-"`

	// fence for rendering command running
	RenderFence vk.Fence `display:"-"`

	// do we own the device?
	OwnDevice bool
}

RenderFrame is an offscreen, non-window-backed rendering target, functioning like a Surface

func NewRenderFrame

func NewRenderFrame(gp *GPU, dev *Device, size image.Point) *RenderFrame

NewRenderFrame returns a new renderframe initialized for given GPU, of given size. using given device, e.g., from a Surface -- to transition images from renderframe to surface, they must use the same device. if device is nil, own device is created.

func NewRenderFrameOwnDevice

func NewRenderFrameOwnDevice(gp *GPU, size image.Point) *RenderFrame

NewRenderFrameOwnDevice returns a new renderframe initialized for given GPU, of given size. This version creates a new Graphics device -- for purely offscreen usage.

func (*RenderFrame) Config

func (rf *RenderFrame) Config()

Config configures the framebuffers etc

func (*RenderFrame) Defaults

func (rf *RenderFrame) Defaults()

func (*RenderFrame) Destroy

func (rf *RenderFrame) Destroy()

func (*RenderFrame) Free

func (rf *RenderFrame) Free()

Free frees any existing (for ReInit or Destroy)

func (*RenderFrame) GrabDepthImage

func (rf *RenderFrame) GrabDepthImage(cmd vk.CommandBuffer)

GrabDepthImage grabs rendered depth image from the Render, must have waited for render already.

func (*RenderFrame) GrabImage

func (rf *RenderFrame) GrabImage(cmd vk.CommandBuffer, idx int)

GrabImage grabs rendered image of given index to Framebuffer.ImageGrab. must have waited for render already.

func (*RenderFrame) Init

func (rf *RenderFrame) Init(gp *GPU, makeDevice bool) error

Init initializes the device and all other resources for the renderframe.

func (*RenderFrame) ReConfig

func (rf *RenderFrame) ReConfig()

ReConfig reconfigures rendering

func (*RenderFrame) ReConfigFrames

func (rf *RenderFrame) ReConfigFrames()

ReConfigFrames re-configures the Famebuffers using exiting settings. Assumes Config has been called.

func (*RenderFrame) SetRender

func (rf *RenderFrame) SetRender(rp *Render)

SetRender sets the Render and updates frames accordingly

func (*RenderFrame) SetSize

func (rf *RenderFrame) SetSize(size image.Point) bool

SetSize sets the size for the render frame, doesn't do anything if already that size (returns fale)

func (*RenderFrame) SubmitRender

func (rf *RenderFrame) SubmitRender(cmd vk.CommandBuffer)

SubmitRender submits a rendering command that must have been added to the given command buffer, calling CmdEnd on the buffer first. This buffer triggers the associated Fence logic to control the sequencing of render commands over time. The ImageAcquired semaphore before the command is run.

func (*RenderFrame) WaitForRender

func (rf *RenderFrame) WaitForRender()

WaitForRender waits until the last submitted render completes

type Sampler

type Sampler struct {
	Name string

	// for U (horizontal) axis -- what to do when going off the edge
	UMode SamplerModes

	// for V (vertical) axis -- what to do when going off the edge
	VMode SamplerModes

	// for W (horizontal) axis -- what to do when going off the edge
	WMode SamplerModes

	// border color for Clamp modes
	Border BorderColors

	// the vulkan sampler
	VkSampler vk.Sampler
}

Sampler represents a vulkan image sampler

func (*Sampler) Config

func (sm *Sampler) Config(gp *GPU, dev vk.Device)

Config configures sampler on device

func (*Sampler) Defaults

func (sm *Sampler) Defaults()

func (*Sampler) Destroy

func (sm *Sampler) Destroy(dev vk.Device)

type SamplerModes

type SamplerModes int32 //enums:enum

Texture image sampler modes

const (
	// Repeat the texture when going beyond the image dimensions.
	Repeat SamplerModes = iota

	// Like repeat, but inverts the coordinates to mirror the image when going beyond the dimensions.
	MirroredRepeat

	// Take the color of the edge closest to the coordinate beyond the image dimensions.
	ClampToEdge

	// Return a solid color when sampling beyond the dimensions of the image.
	ClampToBorder

	// Like clamp to edge, but instead uses the edge opposite to the closest edge.
	MirrorClampToEdge
)
const SamplerModesN SamplerModes = 5

SamplerModesN is the highest valid value for type SamplerModes, plus one.

func SamplerModesValues

func SamplerModesValues() []SamplerModes

SamplerModesValues returns all possible values for the type SamplerModes.

func (SamplerModes) Desc

func (i SamplerModes) Desc() string

Desc returns the description of the SamplerModes value.

func (SamplerModes) Int64

func (i SamplerModes) Int64() int64

Int64 returns the SamplerModes value as an int64.

func (SamplerModes) MarshalText

func (i SamplerModes) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*SamplerModes) SetInt64

func (i *SamplerModes) SetInt64(in int64)

SetInt64 sets the SamplerModes value from an int64.

func (*SamplerModes) SetString

func (i *SamplerModes) SetString(s string) error

SetString sets the SamplerModes value from its string representation, and returns an error if the string is invalid.

func (SamplerModes) String

func (i SamplerModes) String() string

String returns the string representation of this SamplerModes value.

func (*SamplerModes) UnmarshalText

func (i *SamplerModes) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (SamplerModes) Values

func (i SamplerModes) Values() []enums.Enum

Values returns all possible values for the type SamplerModes.

func (SamplerModes) VkMode

func (sm SamplerModes) VkMode() vk.SamplerAddressMode

type Shader

type Shader struct {
	Name     string
	Type     ShaderTypes
	VkModule vk.ShaderModule
}

Shader manages a single Shader program

func (*Shader) Free

func (sh *Shader) Free(dev vk.Device)

Free deletes the shader module, which can be done after the pipeline is created.

func (*Shader) Init

func (sh *Shader) Init(name string, typ ShaderTypes)

Init initializes the shader

func (*Shader) OpenCode

func (sh *Shader) OpenCode(dev vk.Device, code []byte) error

OpenCode loads given SPIR-V ".spv" code for the Shader.

func (*Shader) OpenFile

func (sh *Shader) OpenFile(dev vk.Device, fname string) error

OpenFile loads given SPIR-V ".spv" code from file for the Shader.

type ShaderTypes

type ShaderTypes int32

ShaderTypes is a list of GPU shader types

const (
	VertexShader ShaderTypes = iota
	TessCtrlShader
	TessEvalShader
	GeometryShader
	FragmentShader
	ComputeShader
	AllShaders
)

type StackFrame

type StackFrame struct {
	File           string
	LineNumber     int
	Name           string
	Package        string
	ProgramCounter uintptr
}

A StackFrame contains all necessary information about to generate a line in a callstack.

func (*StackFrame) Func

func (frame *StackFrame) Func() *runtime.Func

Func returns the function that this stackframe corresponds to

func (*StackFrame) SourceLine

func (frame *StackFrame) SourceLine() (string, error)

SourceLine gets the line of code (from File and Line) of the original source if possible

func (*StackFrame) String

func (frame *StackFrame) String() string

String returns the stackframe formatted in the same way as go does in runtime/debug.Stack()

type Surface

type Surface struct {

	// pointer to gpu device, for convenience
	GPU *GPU

	// device for this surface -- each window surface has its own device, configured for that surface
	Device Device

	// the Render for this Surface, typically from a System
	Render *Render

	// has the current swapchain image format and dimensions
	Format ImageFormat

	// ordered list of surface formats to select
	DesiredFormats []vk.Format

	// number of frames to maintain in the swapchain -- e.g., 2 = double-buffering, 3 = triple-buffering -- initially set to a requested amount, and after Init reflects actual number
	NFrames int

	// Framebuffers representing the visible Image owned by the Surface -- we iterate through these in rendering subsequent frames
	Frames []*Framebuffer

	// vulkan handle for surface
	Surface vk.Surface `display:"-"`

	// vulkan handle for swapchain
	Swapchain vk.Swapchain `display:"-"`

	// semaphore used internally for waiting on acquisition of next frame
	ImageAcquired vk.Semaphore `display:"-"`

	// semaphore that surface user can wait on, will be activated when image has been acquired in AcquireNextFrame method
	RenderDone vk.Semaphore `display:"-"`

	// fence for rendering command running
	RenderFence vk.Fence `display:"-"`

	// NeedsConfig is whether the surface needs to be configured again without freeing the swapchain.
	// This is set internally to allow for correct recovery from sudden minimization events that are
	// only detected at the point of swapchain reconfiguration.
	NeedsConfig bool
}

Surface manages the physical device for the visible image of a window surface, and the swapchain for presenting images.

func NewSurface

func NewSurface(gp *GPU, vsurf vk.Surface) *Surface

NewSurface returns a new surface initialized for given GPU and vulkan Surface handle, obtained from a valid window.

func (*Surface) AcquireNextImage

func (sf *Surface) AcquireNextImage() (uint32, bool)

AcquireNextImage gets the next frame index to render to. It automatically handles any issues with out-of-date swapchain. It triggers the ImageAcquired semaphore when image actually acquired. Must call SubmitRender with command to launch command contingent on that semaphore. It returns false if the swapchain size is zero.

func (*Surface) ConfigSwapchain

func (sf *Surface) ConfigSwapchain() bool

ConfigSwapchain configures the swapchain for surface. This assumes that all existing items have been destroyed. It returns false if the swapchain size is zero.

func (*Surface) Defaults

func (sf *Surface) Defaults()

func (*Surface) Destroy

func (sf *Surface) Destroy()

func (*Surface) FreeSwapchain

func (sf *Surface) FreeSwapchain()

FreeSwapchain frees any existing swawpchain (for ReInit or Destroy)

func (*Surface) Init

func (sf *Surface) Init(gp *GPU, vs vk.Surface) error

Init initializes the device and all other resources for the surface based on the vulkan surface handle which must be obtained from the OS-specific window, created first (e.g., via glfw)

func (*Surface) PresentImage

func (sf *Surface) PresentImage(frameIndex uint32) error

PresentImage waits on the RenderDone semaphore to present the rendered image to the surface, for the given frame index, as returned by AcquireNextImage.

func (*Surface) ReConfigFrames

func (sf *Surface) ReConfigFrames()

ReConfigFrames re-configures the Famebuffers using exiting settings. Assumes ConfigSwapchain has been called.

func (*Surface) ReConfigSwapchain

func (sf *Surface) ReConfigSwapchain() bool

ReConfigSwapchain does a re-initialize of swapchain, freeing existing. This must be called when the window is resized. It returns false if the swapchain size is zero.

func (*Surface) SetRender

func (sf *Surface) SetRender(rp *Render)

SetRender sets the Render and updates frames accordingly

func (*Surface) SubmitRender

func (sf *Surface) SubmitRender(cmd vk.CommandBuffer)

SubmitRender submits a rendering command that must have been added to the given command buffer, calling CmdEnd on the buffer first. This buffer triggers the associated Fence logic to control the sequencing of render commands over time. The ImageAcquired semaphore before the command is run.

type System

type System struct {

	// optional name of this System
	Name string

	// gpu device
	GPU *GPU

	// logical device for this System, which is a non-owned copy of either Surface or RenderFrame device
	Device Device

	// cmd pool specific to this system
	CmdPool CmdPool

	// if true, this is a compute system -- otherwise is graphics
	Compute bool

	// if true, variables are statically bound to specific offsets in memory buffers, vs. dynamically bound offsets.  Typically a compute shader operating on fixed data variables can use static binding, while graphics (e.g., vphong) requires dynamic binding to efficiently use the same shader code for multiple different values of the same variable type
	StaticVars bool

	// all pipelines
	Pipelines []*Pipeline

	// map of all pipelines -- names must be unique
	PipelineMap map[string]*Pipeline

	// map of events for synchronizing processing within a single command stream -- this is the best method for compute shaders to coordinate within a given sequence of shader runs in a single command stream
	Events map[string]vk.Event

	// map of semaphores for GPU-side sync between different submitted commands -- names must be unique -- note: better to use Events within one command if possible.
	Semaphores map[string]vk.Semaphore

	// map of fences for CPU-GPU sync -- names must be unique.  WaitIdle implictly uses a fence so it is not essential to use this for simple wait case
	Fences map[string]vk.Fence

	// map of command buffers, for persistent recorded commands -- names must be unique
	CmdBuffs map[string]vk.CommandBuffer

	// manages all the memory for all the Values
	Mem Memory

	// renderpass with depth buffer for this system
	Render Render
	// contains filtered or unexported fields
}

System manages a system of Pipelines that all share a common collection of Vars, Values, and a Memory manager. For example, this could be a collection of different pipelines for different material types, or different compute operations performed on a common set of data. It maintains its own logical device and associated queue.

func (*System) AddPipeline

func (sy *System) AddPipeline(pl *Pipeline)

AddPipeline adds given pipeline

func (*System) BeginRenderPass

func (sy *System) BeginRenderPass(cmd vk.CommandBuffer, fr *Framebuffer, descIndex int)

BeginRenderPass adds commands to the given command buffer to start the render pass on given framebuffer. Clears the frame first, according to the ClearValues. Also Binds descriptor sets to command buffer for given collection of descriptors descIndex (see Vars NDescs for info).

func (*System) BeginRenderPassNoClear

func (sy *System) BeginRenderPassNoClear(cmd vk.CommandBuffer, fr *Framebuffer, descIndex int)

BeginRenderPassNoClear adds commands to the given command buffer to start the render pass on given framebuffer. does NOT clear the frame first -- loads prior state. Also Binds descriptor sets to command buffer for given collection of descriptors descIndex (see Vars NDescs for info).

func (*System) CmdBindTextureVarIndex added in v0.0.10

func (sy *System) CmdBindTextureVarIndex(cmd vk.CommandBuffer, setIndex int, varNm string, valIndex int) (txIndex, descIndex int, switched bool, err error)

CmdBindTextureVarIndex returns the txIndex needed to select the given Texture value at valIndex in given variable in given set index, for use in a shader (i.e., pass txIndex as a push constant to the shader to select this texture). If there are more than MaxTexturesPerSet textures, then it may need to select a different descIndex where that val has been allocated -- the descIndex is returned, and switched is true if it had to issue a CmdBindVars to given command buffer to bind to that desc set, updating BindDescIndex. Typically other vars are bound to the same vals across sets, so this should not affect them, but that is not necessarily the case, so other steps might need to be taken. If the texture is not valid, a -1 is returned for txIndex, and an error is logged.

func (*System) CmdBindVars

func (sy *System) CmdBindVars(cmd vk.CommandBuffer, descIndex int)

CmdBindVars adds command to the given command buffer to bind the Vars descriptors, for given collection of descriptors descIndex (see Vars NDescs for info).

func (*System) CmdBuffByNameTry

func (sy *System) CmdBuffByNameTry(name string) (vk.CommandBuffer, error)

CmdBuffByNameTry returns fence by name with error for not found

func (*System) CmdResetBindVars

func (sy *System) CmdResetBindVars(cmd vk.CommandBuffer, descIndex int)

CmdResetBindVars adds command to the given command buffer to bind the Vars descriptors, for given collection of descriptors descIndex (see Vars NDescs for info).

func (*System) CmdSubmitWait

func (sy *System) CmdSubmitWait()

CmdSubmitWait does SubmitWait on CmdPool

func (*System) ComputeCmdBuff

func (sy *System) ComputeCmdBuff() vk.CommandBuffer

ComputeCmdBuff returns the default compute command buffer: CmdPool.Buff which can be used for executing arbitrary compute commands.

func (*System) ComputeCmdEnd

func (sy *System) ComputeCmdEnd(cmd vk.CommandBuffer)

ComputeCmdEnd adds an end to given command buffer

func (*System) ComputeCopyFromGPU added in v0.0.10

func (sy *System) ComputeCopyFromGPU(cmd vk.CommandBuffer, regs ...MemReg)

ComputeCopyFromGPU records command to copy given regions in the Storage buffer memory from GPU to CPU, in one call. Use SyncRegValueIndexFromCPU to get the regions.

func (*System) ComputeCopyToGPU

func (sy *System) ComputeCopyToGPU(cmd vk.CommandBuffer, regs ...MemReg)

ComputeCopyToGPU records command to copy given regions in the Storage buffer memory from CPU to GPU, in one call. Use SyncRegValueIndexFromCPU to get the regions.

func (*System) ComputeResetBegin

func (sy *System) ComputeResetBegin(cmd vk.CommandBuffer)

ComputeResetBegin resets and begins the recording of commands the given command buffer -- use prior to ComputeCommand if not needing to call ComputeBindVars

func (*System) ComputeResetBindVars

func (sy *System) ComputeResetBindVars(cmd vk.CommandBuffer, descIndex int)

ComputeResetBindVars adds command to the given command buffer, to bind the Vars descriptors, for given collection of descriptors descIndex (see Vars NDescs for info). Required whenever variables have changed their mappings, before running a command.

func (*System) ComputeSetEvent

func (sy *System) ComputeSetEvent(cmd vk.CommandBuffer, event string) error

ComputeSetEvent sets an event to be signalled when everything up to this point in the named command buffer has completed. This is the best way to coordinate processing within a sequence of compute shader calls within a single command buffer. Returns an error if the named event was not found.

func (*System) ComputeSubmitSignal

func (sy *System) ComputeSubmitSignal(cmd vk.CommandBuffer, signal, fence string) error

ComputeSubmitSignal submits command in buffer to system device queue with given signal semaphore (by name) when done, and with given fence (use empty string for none). The optional fence is used typically at the end of a block of such commands, whenever the CPU needs to be sure the submitted GPU commands have completed. Must use "ComputeWait" if using std ComputeWait function.

func (*System) ComputeSubmitWait

func (sy *System) ComputeSubmitWait(cmd vk.CommandBuffer)

ComputeSubmitWait submits the current set of commands in the default system CmdPool, typically from ComputeDispatch. Then waits for the commands to finish before returning control to the CPU. Results will be available immediately thereafter for retrieving back from the GPU.

func (*System) ComputeSubmitWaitSignal

func (sy *System) ComputeSubmitWaitSignal(cmd vk.CommandBuffer, wait, signal, fence string) error

ComputeSubmitWaitSignal submits command in given buffer to system device queue with given wait semaphore and given signal semaphore (by name) when done, and with given fence (use empty string for none). This will cause the GPU to wait until the wait semphaphore is signaled by a previous command with that semaphore as its signal. The optional fence is used typically at the end of a block of such commands, whenever the CPU needs to be sure the submitted GPU commands have completed. Must use "ComputeWait" if using std ComputeWait function.

func (*System) ComputeWait

func (sy *System) ComputeWait() error

ComputeWait waits for the standard ComputeWait fence

func (*System) ComputeWaitEvents

func (sy *System) ComputeWaitEvents(cmd vk.CommandBuffer, event ...string) error

ComputeWaitEvents waits until previous ComputeSetEvent event(s) have signalled. This is the best way to coordinate processing within a sequence of compute shader calls within named command buffer. However, use ComputeWaitMem* calls (e.g., WriteRead) to ensure memory writes have completed, instead of creating an Event. Returns an error if the named event was not found.

func (*System) ComputeWaitFence

func (sy *System) ComputeWaitFence(fence string) error

ComputeWaitFence waits for given fence (by name), and resets the fence

func (*System) ComputeWaitMemHostToShader

func (sy *System) ComputeWaitMemHostToShader(cmd vk.CommandBuffer)

ComputeWaitMemHostToShader records pipeline barrier ensuring global memory writes from the host to shader have completed. Use this if the first commands are to copy memory from host, instead of creating a separate Event.

func (*System) ComputeWaitMemShaderToHost

func (sy *System) ComputeWaitMemShaderToHost(cmd vk.CommandBuffer)

ComputeWaitMemShaderToHost records pipeline barrier ensuring global memory writes have completed from the compute shader, and are ready for the host to read. This is not necessary if a standard QueueWaitIdle is done at the end of a command (basically not really needed, but included for completeness).

func (*System) ComputeWaitMemWriteRead

func (sy *System) ComputeWaitMemWriteRead(cmd vk.CommandBuffer)

ComputeWaitMemWriteRead records pipeline barrier ensuring global memory writes from the shader have completed and are ready to read in the next step of a command queue. Use this instead of Events to synchronize steps of a computation.

func (*System) ComputeWaitMemoryBuff

func (sy *System) ComputeWaitMemoryBuff(cmd vk.CommandBuffer, buff *MemBuff)

ComputeWaitMemoryBuff records pipeline barrier ensuring given buffer's memory writes have completed for given buffer from the compute shader, and are ready for the host to read. Vulkan docs suggest that global memory buffer barrier is generally better to use (ComputeWaitMem*)

func (*System) Config

func (sy *System) Config()

Config configures the entire system, after everything has been setup (Pipelines, Vars, etc). Memory / Values do not yet need to be initialized but are allocated from the Vars on this call, so the total number of Values per Var, and number of VarSets, all must be configured.

func (*System) ConfigRender

func (sy *System) ConfigRender(imgFmt *ImageFormat, depthFmt Types)

ConfigRender configures the renderpass, including the image format that we're rendering to, for a surface render target, and the depth buffer format (pass UndefinedType for no depth buffer).

func (*System) ConfigRenderNonSurface

func (sy *System) ConfigRenderNonSurface(imgFmt *ImageFormat, depthFmt Types)

ConfigRenderNonSurface configures the renderpass, including the image format that we're rendering to, for a RenderFrame non-surface target, and the depth buffer format (pass UndefinedType for no depth buffer).

func (*System) Destroy

func (sy *System) Destroy()

func (*System) EndRenderPass

func (sy *System) EndRenderPass(cmd vk.CommandBuffer)

EndRenderPass adds commands to the given command buffer to end the render pass. It does not call EndCommandBuffer, in case any further commands are to be added.

func (*System) EventByNameTry

func (sy *System) EventByNameTry(name string) (vk.Event, error)

EventByNameTry returns event by name with error for not found

func (*System) FenceByNameTry

func (sy *System) FenceByNameTry(name string) (vk.Fence, error)

FenceByNameTry returns fence by name with error for not found

func (*System) InitCmd

func (sy *System) InitCmd()

InitCmd initializes the command pool and buffer

func (*System) InitCompute

func (sy *System) InitCompute(gp *GPU, name string) error

InitCompute initializes the System for compute functionality, which creates its own Compute device.

func (*System) InitGraphics

func (sy *System) InitGraphics(gp *GPU, name string, dev *Device) error

InitGraphics initializes the System for graphics use, using the graphics device from the Surface associated with this system or another device can be initialized by calling sy.Device.Init(gp, vk.QueueGraphicsBit)

func (*System) MemCmdEndSubmitWaitFree

func (sy *System) MemCmdEndSubmitWaitFree()

MemCmdEndSubmitWaitFree submits current one-time memory command using the Memory CmdPool and Device associated with this System Use this for other random memory transfer commands.

func (*System) MemCmdStart

func (sy *System) MemCmdStart() vk.CommandBuffer

MemCmdStart starts a one-time memory command using the Memory CmdPool and Device associated with this System Use this for other random memory transfer commands.

func (*System) NewCmdBuff

func (sy *System) NewCmdBuff(name string) vk.CommandBuffer

NewCmdBuff returns a new fence using system device

func (*System) NewComputePipelineEmbed

func (sy *System) NewComputePipelineEmbed(name string, efs embed.FS, fname string) *Pipeline

NewComputePipelineEmbed returns a new pipeline added to this System, using given file name from given embed.FS filesystem as a ComputeShader.

func (*System) NewEvent

func (sy *System) NewEvent(name string) vk.Event

NewEvent returns a new event using system device

func (*System) NewFence

func (sy *System) NewFence(name string) vk.Fence

NewFence returns a new fence using system device

func (*System) NewPipeline

func (sy *System) NewPipeline(name string) *Pipeline

NewPipeline returns a new pipeline added to this System, initialized for use in this system.

func (*System) NewSemaphore

func (sy *System) NewSemaphore(name string) vk.Semaphore

NewSemaphore returns a new semaphore using system device

func (*System) PipelineByNameTry

func (sy *System) PipelineByNameTry(name string) (*Pipeline, error)

PipelineByNameTry returns pipeline by name with error for not found

func (*System) ResetBeginRenderPass

func (sy *System) ResetBeginRenderPass(cmd vk.CommandBuffer, fr *Framebuffer, descIndex int)

ResetBeginRenderPass adds commands to the given command buffer to reset command buffer and call begin on it, then starts the render pass on given framebuffer (BeginRenderPass) Clears the frame first, according to the ClearValues. Also Binds descriptor sets to command buffer for given collection of descriptors descIndex (see Vars NDescs for info).

func (*System) ResetBeginRenderPassNoClear

func (sy *System) ResetBeginRenderPassNoClear(cmd vk.CommandBuffer, fr *Framebuffer, descIndex int)

ResetBeginRenderPassNoClear adds commands to the given command buffer to reset command buffer and call begin on it, then starts the render pass on given framebuffer (BeginRenderPass) does NOT clear the frame first -- loads prior state. Also Binds descriptor sets to command buffer for given collection of descriptors descIndex (see Vars NDescs for info).

func (*System) SemaphoreByNameTry

func (sy *System) SemaphoreByNameTry(name string) (vk.Semaphore, error)

SemaphoreByNameTry returns semaphore by name with error for not found

func (*System) SetClearColor

func (sy *System) SetClearColor(r, g, b, a float32)

SetClearColor sets the RGBA colors to set when starting new render For all pipelines, to keep graphics settings consistent.

func (*System) SetClearDepthStencil

func (sy *System) SetClearDepthStencil(depth float32, stencil uint32)

SetClearDepthStencil sets the depth and stencil values when starting new render For all pipelines, to keep graphics settings consistent.

func (*System) SetColorBlend

func (sy *System) SetColorBlend(alphaBlend bool)

SetColorBlend determines the color blending function: either 1-source alpha (alphaBlend) or no blending: new color overwrites old. Default is alphaBlend = true For all pipelines, to keep graphics settings consistent.

func (*System) SetCullFace

func (sy *System) SetCullFace(back bool)

SetCullFace sets the face culling mode: true = back, false = front use CullBack, CullFront constants

func (*System) SetFrontFace

func (sy *System) SetFrontFace(ccw bool)

SetFrontFace sets the winding order for what counts as a front face true = CCW, false = CW

func (*System) SetGraphicsDefaults

func (sy *System) SetGraphicsDefaults()

SetGraphicsDefaults configures all the default settings for all graphics rendering pipelines (not for a compute pipeline)

func (*System) SetLineWidth

func (sy *System) SetLineWidth(lineWidth float32)

SetLineWidth sets the rendering line width -- 1 is default.

func (*System) SetRasterization

func (sy *System) SetRasterization(polygonMode vk.PolygonMode, cullMode vk.CullModeFlagBits, frontFace vk.FrontFace, lineWidth float32)

SetRasterization sets various options for how to rasterize shapes: Defaults are: vk.PolygonModeFill, vk.CullModeBackBit, vk.FrontFaceCounterClockwise, 1.0 For all pipelines, to keep graphics settings consistent.

func (*System) SetTopology

func (sy *System) SetTopology(topo Topologies, restartEnable bool)

SetTopology sets the topology of vertex position data. TriangleList is the default. Also for Strip modes, restartEnable allows restarting a new strip by inserting a ?? For all pipelines, to keep graphics settings consistent.

func (*System) Vars

func (sy *System) Vars() *Vars

Vars returns a pointer to the vars for this pipeline, which has vals within it

type Texture

type Texture struct {
	Image

	// sampler for image
	Sampler
}

Texture supplies an Image and a Sampler

func (*Texture) AllocTexture

func (tx *Texture) AllocTexture()

AllocTexture allocates texture device image, stdview, and sampler

func (*Texture) Defaults

func (tx *Texture) Defaults()

func (*Texture) Destroy

func (tx *Texture) Destroy()

type Topologies

type Topologies int32

Topologies are the different vertex topology

type Types

type Types int32 //enums:enum

Types is a list of supported GPU data types, which can be stored properly aligned in device memory, and used by the shader code. Note that a Vector3 or arrays of single scalar values such as Float32 are not well supported outside of Vertex due to the std410 convention: http://www.opengl.org/registry/doc/glspec45.core.pdf#page=159 The Struct type is particularly challenging as each member must be aligned in general on a 16 byte boundary (i.e., vector4) (unless all elements are exactly 4 bytes, which might work?). Go automatically aligns members to 8 bytes on 64 bit machines, but that doesn't quite cut it.

const (
	UndefinedType Types = iota
	Bool32

	Int16
	Uint16

	Int32
	Int32Vector2
	Int32Vector4

	Uint32
	Uint32Vector2
	Uint32Vector4

	Float32
	Float32Vector2
	Float32Vector3 // note: only use for vertex data -- not properly aligned for uniforms
	Float32Vector4

	Float64
	Float64Vector2
	Float64Vector3
	Float64Vector4

	Float32Matrix4 // std transform matrix: math32.Matrix4 works directly
	Float32Matrix3 // std transform matrix: math32.Matrix3 works directly

	ImageRGBA32 // 32 bits with 8 bits per component of R,G,B,A -- std image format

	Depth32         // standard float32 depth buffer
	Depth24Stencil8 // standard 24 bit float with 8 bit stencil

	Struct
)
const TypesN Types = 24

TypesN is the highest valid value for type Types, plus one.

func TypesValues

func TypesValues() []Types

TypesValues returns all possible values for the type Types.

func (Types) Bytes

func (tp Types) Bytes() int

Bytes returns number of bytes for this type

func (Types) Desc

func (i Types) Desc() string

Desc returns the description of the Types value.

func (Types) Int64

func (i Types) Int64() int64

Int64 returns the Types value as an int64.

func (Types) MarshalText

func (i Types) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*Types) SetInt64

func (i *Types) SetInt64(in int64)

SetInt64 sets the Types value from an int64.

func (*Types) SetString

func (i *Types) SetString(s string) error

SetString sets the Types value from its string representation, and returns an error if the string is invalid.

func (Types) String

func (i Types) String() string

String returns the string representation of this Types value.

func (*Types) UnmarshalText

func (i *Types) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (Types) Values

func (i Types) Values() []enums.Enum

Values returns all possible values for the type Types.

func (Types) VkFormat

func (tp Types) VkFormat() vk.Format

VkFormat returns the Vulkan VkFormat for given type

func (Types) VkIndexType

func (tp Types) VkIndexType() vk.IndexType

VkIndexType returns the Vulkan vk.IndexType for var must be either Uint16 or Uint32

type Value added in v0.0.10

type Value struct {

	// name of this value, named by default as the variable name_idx
	Name string

	// index of this value within the Var list of values
	Index int

	// actual number of elements in an array -- 1 means scalar / singular value.  If 0, this is a dynamically sized item and the size must be set.
	N int

	// offset in bytes from start of memory buffer
	Offset int

	// val state flags
	Flags ValueFlags

	// if N > 1 (array) then this is the effective size of each element, which must be aligned to 16 byte modulo for Uniform types.  non naturally aligned types require slower element-by-element syncing operations, instead of memcopy.
	ElSize int

	// total memory size of this value in bytes, as allocated, including array alignment but not any additional buffer-required alignment padding
	AllocSize int

	// for Texture Var roles, this is the Texture
	Texture *Texture

	// pointer to the start of the staging memory for this value
	MemPtr unsafe.Pointer `display:"-"`
}

Value represents a specific value of a Var variable.

func (*Value) AllocHost added in v0.0.10

func (vl *Value) AllocHost(vr *Var, buff *MemBuff, buffPtr unsafe.Pointer, offset int) int

AllocHost allocates this value at given offset in owning Memory buffer. Computes the MemPtr for this item, and returns AllocSize() of this value, so memory can increment to next item. offsets are guaranteed to be properly aligned per minUniformBufferOffsetAlignment.

func (*Value) Bytes added in v0.0.10

func (vl *Value) Bytes() []byte

Bytes returns byte array of the Value data, including any additional alignment -- can be written to directly. Be mindful of potential padding and alignment issues relative to go-based storage. Set Mod flag when changes have been made.

func (*Value) ClearMod added in v0.0.10

func (vl *Value) ClearMod()

ClearMod clears modified flag

func (*Value) CopyFromBytes added in v0.0.10

func (vl *Value) CopyFromBytes(srcPtr unsafe.Pointer)

CopyFromBytes copies bytes from given source pointer into memory, and sets Mod flag. Use this for struct data types.

func (*Value) CopyToBytes added in v0.0.10

func (vl *Value) CopyToBytes(srcPtr unsafe.Pointer)

CopyToBytes copies bytes from val to given source pointer into memory. Use this for struct data types to retrieve computed results.

func (*Value) Floats32 added in v0.0.10

func (vl *Value) Floats32() math32.ArrayF32

Floats32 returns math32.ArrayF32 of the Value data -- can be written to directly. Only recommended for Vertex data. Otherwise, be mindful of potential padding and alignment issues relative to go-based storage. Set Mod flag when changes have been made.

func (*Value) Free added in v0.0.10

func (vl *Value) Free()

Free resets the MemPtr for this value

func (*Value) HasFlag added in v0.0.10

func (vl *Value) HasFlag(flag ValueFlags) bool

HasFlag checks if flag is set using atomic, safe for concurrent access

func (*Value) Init added in v0.0.10

func (vl *Value) Init(gp *GPU, vr *Var, idx int)

Init initializes value based on variable and index within list of vals for this var

func (*Value) IsMod added in v0.0.10

func (vl *Value) IsMod() bool

IsMod returns true if the value has been modified since last memory sync

func (*Value) MemReg added in v0.0.10

func (vl *Value) MemReg(vr *Var) MemReg

MemReg returns the memory region for this value

func (*Value) MemSize added in v0.0.10

func (vl *Value) MemSize(vr *Var) int

MemSize returns the memory allocation size for this value, in bytes

func (*Value) PaddedArrayCheck added in v0.0.10

func (vl *Value) PaddedArrayCheck() error

PaddedArrayCheck checks if this is an array with padding on the elements due to alignment issues. If this is the case, then direct copying is not possible.

func (*Value) SetFlag added in v0.0.10

func (vl *Value) SetFlag(on bool, flag ...enums.BitFlag)

SetFlag sets flag(s) using atomic, safe for concurrent access

func (*Value) SetGoImage added in v0.0.10

func (vl *Value) SetGoImage(img image.Image, layer int, flipY bool) error

SetGoImage sets Texture image data from an *image.RGBA standard Go image, at given layer, and sets the Mod flag, so it will be sync'd by Memory or if TextureOwns is set for the var, it allocates Host memory. This is most efficiently done using an image.RGBA, but other formats will be converted as necessary. If flipY is true then the Image Y axis is flipped when copying into the image data (requires row-by-row copy) -- can avoid this by configuring texture coordinates to compensate.

func (*Value) SetMod added in v0.0.10

func (vl *Value) SetMod()

SetMod sets modified flag

func (*Value) UInts32 added in v0.0.10

func (vl *Value) UInts32() math32.ArrayU32

UInts32 returns math32.ArrayU32 of the Value data -- can be written to directly. Only recommended for Vertex data. Otherwise, be mindful of potential padding and alignment issues relative to go-based storage. Set Mod flag when changes have been made.

type ValueFlags added in v0.0.10

type ValueFlags int64 //enums:bitflag -trim-prefix Value

ValueFlags are bitflags for Value state

const (
	// ValueMod the value has been modified
	ValueMod ValueFlags = iota

	// ValuePaddedArray array had to be padded -- cannot access elements continuously
	ValuePaddedArray

	// ValueTextureOwns val owns and manages the host staging memory for texture.
	// based on Var TextureOwns -- for dynamically changing images.
	ValueTextureOwns
)
const ValueFlagsN ValueFlags = 3

ValueFlagsN is the highest valid value for type ValueFlags, plus one.

func ValueFlagsValues added in v0.0.10

func ValueFlagsValues() []ValueFlags

ValueFlagsValues returns all possible values for the type ValueFlags.

func (ValueFlags) BitIndexString added in v0.0.10

func (i ValueFlags) BitIndexString() string

BitIndexString returns the string representation of this ValueFlags value if it is a bit index value (typically an enum constant), and not an actual bit flag value.

func (ValueFlags) Desc added in v0.0.10

func (i ValueFlags) Desc() string

Desc returns the description of the ValueFlags value.

func (ValueFlags) HasFlag added in v0.0.10

func (i ValueFlags) HasFlag(f enums.BitFlag) bool

HasFlag returns whether these bit flags have the given bit flag set.

func (ValueFlags) Int64 added in v0.0.10

func (i ValueFlags) Int64() int64

Int64 returns the ValueFlags value as an int64.

func (ValueFlags) MarshalText added in v0.0.10

func (i ValueFlags) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*ValueFlags) SetFlag added in v0.0.10

func (i *ValueFlags) SetFlag(on bool, f ...enums.BitFlag)

SetFlag sets the value of the given flags in these flags to the given value.

func (*ValueFlags) SetInt64 added in v0.0.10

func (i *ValueFlags) SetInt64(in int64)

SetInt64 sets the ValueFlags value from an int64.

func (*ValueFlags) SetString added in v0.0.10

func (i *ValueFlags) SetString(s string) error

SetString sets the ValueFlags value from its string representation, and returns an error if the string is invalid.

func (*ValueFlags) SetStringOr added in v0.0.10

func (i *ValueFlags) SetStringOr(s string) error

SetStringOr sets the ValueFlags value from its string representation while preserving any bit flags already set, and returns an error if the string is invalid.

func (ValueFlags) String added in v0.0.10

func (i ValueFlags) String() string

String returns the string representation of this ValueFlags value.

func (*ValueFlags) UnmarshalText added in v0.0.10

func (i *ValueFlags) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (ValueFlags) Values added in v0.0.10

func (i ValueFlags) Values() []enums.Enum

Values returns all possible values for the type ValueFlags.

type Values added in v0.0.10

type Values struct {

	// values in indexed order
	Values []*Value

	// map of vals by name -- only for specifically named vals vs. generically allocated ones -- names must be unique
	NameMap map[string]*Value

	// for texture values, this allocates textures to texture arrays by size -- used if On flag is set -- must call AllocTexBySize to allocate after ConfigGoImage is called on all vals.  Then call SetGoImage method on Values to set the Go Image for each val -- this automatically redirects to the group allocated images.
	TexSzAlloc szalloc.SzAlloc

	// for texture values, if AllocTexBySize is called, these are the actual allocated image arrays that hold the grouped images (size = TexSzAlloc.GpAllocs.
	GpTexValues []*Value
}

Values is a list container of Value values, accessed by index or name

func (*Values) ActiveValues added in v0.0.10

func (vs *Values) ActiveValues() []*Value

ActiveValues returns the Values to actually use for memory allocation etc this is Values list except for textures with TexSzAlloc.On active

func (*Values) AllocHost added in v0.0.10

func (vs *Values) AllocHost(vr *Var, buff *MemBuff, offset int) int

AllocHost allocates values at given offset in given Memory buffer. Computes the MemPtr for each item, and returns TotSize across all vals. The effective offset increment (based on size) is aligned at the given align byte level, which should be MinUniformBufferOffsetAlignment from gpu.

func (*Values) AllocTexBySize added in v0.0.10

func (vs *Values) AllocTexBySize(gp *GPU, vr *Var)

AllocTexBySize allocates textures by size so they fit within the MaxTexturesPerGroup. Must call ConfigGoImage on the original values to set the sizes prior to calling this, and cannot have the TextureOwns flag set. Also does not support arrays in source vals. Apps can always use szalloc.SzAlloc upstream of this to allocate. This method creates actual image vals in GpTexValues, which are allocated. Must call SetGoImage on Values here, which redirects to the proper allocated GpTexValues image and layer.

func (*Values) AllocTextures added in v0.0.10

func (vs *Values) AllocTextures(mm *Memory)

AllocTextures allocates images on device memory only called on Role = TextureRole

func (*Values) ConfigValues added in v0.0.10

func (vs *Values) ConfigValues(gp *GPU, dev vk.Device, vr *Var, nvals int) bool

ConfigValues configures given number of values in the list for given variable. If the same number of vals is given, nothing is done, so it is safe to call repeatedly. Otherwise, any existing vals will be deleted -- the Memory system must free all associated memory prior! Returns true if new config made, else false if same size.

func (*Values) Destroy added in v0.0.10

func (vs *Values) Destroy()

Destroy frees all existing values and resets the list of Values so subsequent Config will start fresh (e.g., if Var type changes).

func (*Values) Free added in v0.0.10

func (vs *Values) Free()

Free resets the MemPtr for values, resets any self-owned resources (Textures)

func (*Values) MemSize added in v0.0.10

func (vs *Values) MemSize(vr *Var, alignBytes int) int

MemSize returns size across all Values in list

func (*Values) ModRegs added in v0.0.10

func (vs *Values) ModRegs(vr *Var) []MemReg

ModRegs returns the regions of Values that have been modified

func (*Values) SetGoImage added in v0.0.10

func (vs *Values) SetGoImage(idx int, img image.Image, flipy bool)

SetGoImage calls SetGoImage on the proper Texture value for given index. if TexSzAlloc.On via AllocTexBySize then this is routed to the actual allocated image array, otherwise it goes directly to the standard Value.

SetGoImage sets staging image data from a standard Go image at given layer. This is most efficiently done using an image.RGBA, but other formats will be converted as necessary. If flipY is true then the Image Y axis is flipped when copying into the image data, so that images will appear upright in the standard OpenGL Y-is-up coordinate system. If using the Y-is-down Vulkan coordinate system, don't flip. Only works if IsHostActive and Image Format is default vk.FormatR8g8b8a8Srgb, Must still call AllocImage to have image allocated on the device, and copy from this host staging data to the device.

func (*Values) SetName added in v0.0.10

func (vs *Values) SetName(idx int, name string) (*Value, error)

SetName sets name of given Value, by index, adds name to map, checking that it is not already there yet. Returns val.

func (*Values) ValueByIndexTry added in v0.0.10

func (vs *Values) ValueByIndexTry(idx int) (*Value, error)

ValueByIndexTry returns Value at given index with range checking error message.

func (*Values) ValueByNameTry added in v0.0.10

func (vs *Values) ValueByNameTry(name string) (*Value, error)

ValueByNameTry returns value by name, returning error if not found

type Var

type Var struct {

	// variable name
	Name string

	// type of data in variable.  Note that there are strict contraints on the alignment of fields within structs -- if you can keep all fields at 4 byte increments, that works, but otherwise larger fields trigger a 16 byte alignment constraint.  Texture Images do not have such alignment constraints, and can be allocated in a big host buffer or in separate buffers depending on how frequently they are updated with different sizes.
	Type Types

	// number of elements if this is a fixed array -- use 1 if singular element, and 0 if a variable-sized array, where each Value can have its own specific size. This also works for arrays of Textures -- up to 128 max.
	ArrayN int

	// role of variable: Vertex is configured in the pipeline VkConfig structure, and everything else is configured in a DescriptorSet.  For TextureRole items, the last such Var in a set will automatically be flagged as variable sized, so the shader can specify: #extension GL_EXT_nonuniform_qualifier : require and the list of textures can be specified as a array.
	Role VarRoles

	// bit flags for set of shaders that this variable is used in
	Shaders vk.ShaderStageFlagBits

	// DescriptorSet associated with the timing of binding for this variable -- all vars updated at the same time should be in the same set
	Set int

	// binding or location number for variable -- Vertexs are assigned as one group sequentially in order listed in Vars, and rest are assigned uniform binding numbers via descriptor pools
	BindLoc int

	// size in bytes of one element (not array size).  Note that arrays in Uniform require 16 byte alignment for each element, so if using arrays, it is best to work within that constraint.  In Storage, with HLSL compute shaders, 4 byte (e.g., float32 or int32) works fine as an array type.  For Push role, SizeOf must be set exactly -- no vals are created.
	SizeOf int

	// texture manages its own memory allocation -- set this for texture objects that change size dynamically -- otherwise image host staging memory is allocated in a common buffer
	TextureOwns bool `edit:"-"`

	// index into the dynamic offset list, where dynamic offsets of vals need to be set -- for Uniform and Storage roles -- set during Set:DescLayout
	DynOffIndex int `edit:"-"`

	// the array of values allocated for this variable.  The size of this array is determined by the Set membership of this Var, and the current index is updated at the set level.  For Texture Roles, there is a separate descriptor for each value (image) -- otherwise dynamic offset binding is used.
	Values Values

	// for dynamically bound vars (Vertex, Uniform, Storage), this is the index of the currently bound value in Values list -- index in this array is the descIndex out of Vars NDescs (see for docs) to allow for parallel update pathways -- only valid until set again -- only actually used for Vertex binding, as unforms etc have the WriteDescriptor mechanism.
	BindValueIndex []int `edit:"-"`

	// index of the storage buffer in Memory that holds this Var -- for Storage buffer types.  Due to support for dynamic binding, all Values of a given Var must be stored in the same buffer, and the allocation mechanism ensures this.  This constrains large vars approaching the MaxStorageBufferRange capacity to only have 1 val, which is typically reasonable given that compute shaders use large data and tend to use static binding anyway, and graphics uses tend to be smaller.
	StorageBuff int `edit:"-"`

	// offset -- only for push constants
	Offset int `edit:"-"`
}

Var specifies a variable used in a pipeline, accessed in shader programs. A Var represents a type of input or output into the GPU program, including things like Vertex arrays, transformation matricies (Uniforms), Images (Textures), and arbitrary Structs for Compute shaders. Each Var belongs to a Set, and its binding location is allocated within that. Each set is updated at the same time scale, and all vars in the set have the same number of allocated Value instances representing a specific value of the variable. There must be a unique Value instance for each value of the variable used in a single render -- a previously used Value's contents cannot be updated within the render pass, but new information can be written to an as-yet unused Value prior to using in a render (although this comes at a performance cost).

func (*Var) AllocHost

func (vr *Var) AllocHost(buff *MemBuff, offset int) int

AllocHost allocates values at given offset in given Memory buffer. Computes the MemPtr for each item, and returns TotSize across all vals. The effective offset increment (based on size) is aligned at the given align byte level, which should be MinUniformBufferOffsetAlignment from gpu.

func (*Var) AllocTextures

func (vr *Var) AllocTextures(mm *Memory)

AllocTextures allocates images on device memory only called on Role = TextureRole

func (*Var) BindValue added in v0.0.10

func (vr *Var) BindValue(descIndex int) (*Value, error)

BindValue returns the currently bound value at given descriptor collection index as set by BindDyn* methods. Returns nil, error if not valid.

func (*Var) BuffType

func (vr *Var) BuffType() BuffTypes

BuffType returns the memory buffer type for this variable, based on Var.Role

func (*Var) Free

func (vr *Var) Free()

Free resets the MemPtr for values, resets any self-owned resources (Textures)

func (*Var) Init

func (vr *Var) Init(name string, typ Types, arrayN int, role VarRoles, set int, shaders ...ShaderTypes)

Init initializes the main values

func (*Var) MemSize

func (vr *Var) MemSize() int

MemSize returns the memory allocation size for this value, in bytes

func (*Var) MemSizeStorage

func (vr *Var) MemSizeStorage(mm *Memory, alignBytes int)

MemSizeStorage adds a Storage memory allocation record to Memory for all values for this Var

func (*Var) ModRegs

func (vr *Var) ModRegs() []MemReg

ModRegs returns the regions of Values that have been modified

func (*Var) SetTextureDev

func (vr *Var) SetTextureDev(dev vk.Device)

SetTextureDev sets Device for textures only called on Role = TextureRole

func (*Var) String

func (vr *Var) String() string

func (*Var) TextureValidIndex added in v0.0.10

func (vr *Var) TextureValidIndex(stIndex, idx int) int

TextureValidIndex returns the index of the given texture value at our index in list of vals, starting at given index, skipping over any inactive textures which do not show up when accessed in the shader. You must use this value when passing a texture index to the shader! returns -1 if idx is not valid

func (*Var) ValuesMemSize added in v0.0.10

func (vr *Var) ValuesMemSize(alignBytes int) int

ValuesMemSize returns the memory allocation size for all values for this Var, in bytes

type VarList

type VarList struct {

	// variables in order
	Vars []*Var

	// map of vars by name -- names must be unique
	VarMap map[string]*Var
}

VarList is a list of variables

func (*VarList) ValueByIndexTry added in v0.0.10

func (vs *VarList) ValueByIndexTry(varName string, valIndex int) (*Var, *Value, error)

ValueByIndexTry returns value by first looking up variable name, then value index, returning error if not found

func (*VarList) ValueByNameTry added in v0.0.10

func (vs *VarList) ValueByNameTry(varName, valName string) (*Var, *Value, error)

ValueByNameTry returns value by first looking up variable name, then value name, returning error if not found

func (*VarList) VarByNameTry

func (vs *VarList) VarByNameTry(name string) (*Var, error)

VarByNameTry returns Var by name, returning error if not found

type VarMem

type VarMem struct {

	// variable -- all Values of given Var are stored in the same Buffer
	Var *Var

	// index into storage buffer array holding this value
	Buff int

	// total size needed for this value, excluding alignment padding
	Size int

	// allocated offset within storage buffer for start of Var memory
	Offset int
}

VarMem is memory allocation info per Var, for Storage types. Used in initial allocation algorithm.

type VarRoles

type VarRoles int32 //enums:enum

VarRoles are the functional roles of variables, corresponding to Vertex input vectors and all the different "uniform" types as enumerated in vk.DescriptorType. This does NOT map directly to DescriptorType because we combine vertex and uniform data and require a different ordering.

const (
	UndefVarRole VarRoles = iota
	Vertex                // vertex shader input data: mesh geometry points, normals, etc.  These are automatically located in a separate Set, VertexSet (-2), and managed separately.
	Index                 // for indexed access to Vertex data, also located in VertexSet (-2) -- only one such Var per VarSet should be present -- will automatically be used if a dynamically bound val is set
	Push                  // for push constants, which have a minimum of 128 bytes and are stored directly in the command buffer -- they do not require any host-device synchronization or buffering, and are fully dynamic.  They are ideal for transformation matricies or indexes for accessing data.  They are stored in a special PushSet (-1) and managed separately.
	Uniform               // read-only general purpose data, uses UniformBufferDynamic with offset specified at binding time, not during initial configuration -- compared to Storage, Uniform items can be put in local cache for each shader and thus can be much faster to access -- use for a smaller number of parameters such as transformation matricies
	Storage               // read-write general purpose data, in StorageBufferDynamic (offset set at binding) -- this is a larger but slower pool of memory, with more flexible alignment constraints, used primarily for compute data
	UniformTexel          // read-only image-formatted data, which cannot be accessed via ImageView or Sampler -- only for rare cases where optimized image format (e.g., rgb values of specific bit count) is useful.  No Dynamic mode is available, so this can only be used for a fixed Value.
	StorageTexel          // read-write image-formatted data, which cannot be accessed via ImageView or Sampler -- only for rare cases where optimized image format (e.g., rgb values of specific bit count) is useful. No Dynamic mode is available, so this can only be used for a fixed Value.
	StorageImage          // read-write access through an ImageView (but not a Sampler) of an Image
	TextureRole           // a Texture is a CombinedImageSampler in Vulkan terminology -- a combination of a Sampler and a specific Image, which appears as a single entity in the shader.
)
const VarRolesN VarRoles = 10

VarRolesN is the highest valid value for type VarRoles, plus one.

func VarRolesValues

func VarRolesValues() []VarRoles

VarRolesValues returns all possible values for the type VarRoles.

func (VarRoles) BuffType

func (vr VarRoles) BuffType() BuffTypes

BuffType returns type of memory buffer for this role

func (VarRoles) Desc

func (i VarRoles) Desc() string

Desc returns the description of the VarRoles value.

func (VarRoles) Int64

func (i VarRoles) Int64() int64

Int64 returns the VarRoles value as an int64.

func (VarRoles) IsDynamic

func (vr VarRoles) IsDynamic() bool

IsDynamic returns true if role has dynamic offset binding

func (VarRoles) MarshalText

func (i VarRoles) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*VarRoles) SetInt64

func (i *VarRoles) SetInt64(in int64)

SetInt64 sets the VarRoles value from an int64.

func (*VarRoles) SetString

func (i *VarRoles) SetString(s string) error

SetString sets the VarRoles value from its string representation, and returns an error if the string is invalid.

func (VarRoles) String

func (i VarRoles) String() string

String returns the string representation of this VarRoles value.

func (*VarRoles) UnmarshalText

func (i *VarRoles) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (VarRoles) Values

func (i VarRoles) Values() []enums.Enum

Values returns all possible values for the type VarRoles.

func (VarRoles) VkDescriptor

func (vr VarRoles) VkDescriptor() vk.DescriptorType

VkDescriptor returns the vk.DescriptorType

func (VarRoles) VkDescriptorStatic

func (vr VarRoles) VkDescriptorStatic() vk.DescriptorType

VkDescriptorStatic returns the vk.DescriptorType for static variable binding type

type VarSet

type VarSet struct {
	VarList

	// set number
	Set int

	// number of value instances to allocate per variable in this set: each value must be allocated in advance for each unique instance of a variable required across a complete scene rendering -- e.g., if this is an object position matrix, then one per object is required.  If a dynamic number are required, allocate the max possible.  For Texture vars, each of the NDesc sets can have a maximum of MaxTexturesPerSet (16) -- if NValuesPer > MaxTexturesPerSet, then vals are wrapped across sets, and accessing them requires using the appropriate DescIndex, as in System.CmdBindTextureVarIndex.
	NValuesPer int

	// number of textures, at point of creating the DescLayout
	NTextures int

	// for texture vars, this is the number of descriptor sets required to represent all of the different Texture image Values that have been allocated.  Use Vars.BindAllTextureValues to bind all such vals, and System.CmdBindTextureVarIndex to automatically bind the correct set.
	NTextureDescs int

	// map of vars by different roles, within this set -- updated in Config(), after all vars added
	RoleMap map[VarRoles][]*Var

	// the parent vars we belong to
	ParentVars *Vars

	// set layout info -- static description of each var type, role, binding, stages
	VkLayout vk.DescriptorSetLayout

	// allocated descriptor set -- one of these per Vars.NDescs -- can have multiple sets that can be independently updated, e.g., for parallel rendering passes.  If only rendering one at a time, only need one.
	VkDescSets []vk.DescriptorSet
}

VarSet contains a set of Var variables that are all updated at the same time and have the same number of distinct Values values per Var per render pass. The first set at index -1 contains Vertex and Index data, handed separately.

func (*VarSet) Add

func (st *VarSet) Add(name string, typ Types, arrayN int, role VarRoles, shaders ...ShaderTypes) *Var

Add adds a new variable of given type, role, arrayN, and shaders where used

func (*VarSet) AddStruct

func (st *VarSet) AddStruct(name string, size int, arrayN int, role VarRoles, shaders ...ShaderTypes) *Var

AddStruct adds a new struct variable of given total number of bytes in size, type, role, set, and shaders where used

func (*VarSet) AddVar

func (st *VarSet) AddVar(vr *Var)

AddVar adds given variable

func (*VarSet) BindDynValue added in v0.0.10

func (st *VarSet) BindDynValue(vs *Vars, vr *Var, vl *Value) error

BindDynValue dynamically binds given uniform or storage value for given variable in given set.

This only dynamically updates the offset to point to the specified val. MUST call System.BindVars prior to any subsequent draw calls for this new offset to be bound at the proper point in the command buffer prior (call after all such dynamic bindings are updated.)

Do NOT call BindValuesStart / End around this.

returns error if not found.

func (*VarSet) BindDynValueIndex added in v0.0.10

func (st *VarSet) BindDynValueIndex(vs *Vars, varNm string, valIndex int) error

BindDynValueIndex dynamically binds given uniform or storage value by index for given variable name, in given set.

This only dynamically updates the offset to point to the specified val. MUST call System.BindVars prior to any subsequent draw calls for this new offset to be bound at the proper point in the command buffer prior (call after all such dynamic bindings are updated.)

Do NOT call BindValuesStart / End around this.

returns error if not found.

func (*VarSet) BindDynValueName added in v0.0.10

func (st *VarSet) BindDynValueName(vs *Vars, varNm, valNm string) error

BindDynValueName dynamically binds given uniform or storage value by name for given variable name, in given set.

This only dynamically updates the offset to point to the specified val. MUST call System.BindVars prior to any subsequent draw calls for this new offset to be bound at the proper point in the command buffer prior (call after all such dynamic bindings are updated.)

Do NOT call BindValuesStart / End around this.

returns error if not found.

func (*VarSet) BindDynValuesAllIndex added in v0.0.10

func (st *VarSet) BindDynValuesAllIndex(vs *Vars, idx int)

BindDynValuesAllIndex dynamically binds all uniform, storage values in given set, for all variables, for given value index.

This only dynamically updates the offset to point to the specified val. MUST call System.BindVars prior to any subsequent draw calls for this new offset to be bound at the proper point in the command buffer prior (call after all such dynamic bindings are updated.)

Do NOT call BindValuesStart / End around this.

func (*VarSet) BindDynVar

func (st *VarSet) BindDynVar(vs *Vars, vr *Var) error

BindDynVar binds dynamic variable for given var for Uniform, Storage variables.

All vals must be uploaded to Device memory prior to this, and it is not possible to update actual values during a render pass. The memory buffer is essentially what is bound here.

Must have called BindVarsStart prior to this.

func (*VarSet) BindDynVarName

func (st *VarSet) BindDynVarName(vs *Vars, varNm string) error

BindDynVarName binds dynamic variable for given var looked up by name, for Uniform, Storage variables.

All vals must be uploaded to Device memory prior to this, and it is not possible to update actual values during a render pass. The memory buffer is essentially what is bound here.

Must have called BindVarsStart prior to this.

func (*VarSet) BindDynVars

func (st *VarSet) BindDynVars(vs *Vars)

BindDynVars binds all dynamic vars in set, to be able to use dynamic vars, in subsequent BindDynValue* calls during the render pass, which update the offsets. For Uniform & Storage variables, which use dynamic binding.

All vals must be uploaded to Device memory prior to this, and it is not possible to update actual values during a render pass. The memory buffer is essentially what is bound here.

Must have called BindVarsStart prior to this.

func (*VarSet) BindStatVar

func (st *VarSet) BindStatVar(vs *Vars, vr *Var)

BindStatVar does static variable binding for given var, Each Value for a given Var is given a descriptor binding and the shader sees an array of values of corresponding length. All vals must be uploaded to Device memory prior to this, and it is not possible to update anything during a render pass.

func (*VarSet) BindStatVarName

func (st *VarSet) BindStatVarName(vs *Vars, varNm string) error

BindStatVarName does static variable binding for given var looked up by name, For non-Uniform, Storage, variables (e.g., Textures). Each Value for a given Var is given a descriptor binding and the shader sees an array of values of corresponding length. All vals must be uploaded to Device memory prior to this, and it is not possible to update anything during a render pass.

func (*VarSet) BindStatVars

func (st *VarSet) BindStatVars(vs *Vars)

BindStatVars binds all static vars to their current values, for non-Uniform, Storage, variables (e.g., Textures). Each Value for a given Var is given a descriptor binding and the shader sees an array of values of corresponding length. All vals must be uploaded to Device memory prior to this, and it is not possible to update anything during a render pass.

func (*VarSet) BindStatVarsAll

func (st *VarSet) BindStatVarsAll(vs *Vars)

BindStatVarsAll dynamically binds all uniform, storage values in given set, for all variables, for all values.

Must call BindVarStart / End around this.

func (*VarSet) Config

func (st *VarSet) Config(dev vk.Device) error

Config must be called after all variables have been added. configures binding / location for all vars based on sequential order. also does validation and returns error message.

func (*VarSet) ConfigValues added in v0.0.10

func (st *VarSet) ConfigValues(nvals int)

ConfigValues configures the Values for the vars in this set, allocating nvals per variable. There must be a unique value available for each distinct value to be rendered within a single pass. All Vars in the same set have the same number of vals. Any existing vals will be deleted -- must free all associated memory prior!

func (*VarSet) DescLayout

func (st *VarSet) DescLayout(dev vk.Device, vs *Vars)

DescLayout creates the DescriptorSetLayout in DescLayout for given set. Only for non-VertexSet sets. Must have set NValuesPer for any TextureRole vars, which require separate descriptors per.

func (*VarSet) Destroy

func (st *VarSet) Destroy(dev vk.Device)

Destroy destroys infrastructure for Set, Vars and Values -- assumes Free has already been called to free host and device memory.

func (*VarSet) DestroyLayout

func (st *VarSet) DestroyLayout(dev vk.Device)

DestroyLayout destroys layout

func (*VarSet) TextureGroupSizeIndexes added in v0.0.10

func (st *VarSet) TextureGroupSizeIndexes(vs *Vars, varNm string, valIndex int) *szalloc.Indexes

TextureGroupSizeIndexes for texture at given index, allocated in groups by size using Values.AllocTexBySize, returns the indexes for the texture and layer to actually select the texture in the shader, and proportion of the Gp allocated texture size occupied by the texture.

func (*VarSet) VkPushConfig

func (vs *VarSet) VkPushConfig() []vk.PushConstantRange

VkPushConfig returns vulkan push constant ranges

func (*VarSet) VkVertexConfig

func (st *VarSet) VkVertexConfig() *vk.PipelineVertexInputStateCreateInfo

VkVertexConfig fills in the relevant info into given vulkan config struct. for VertexSet only! Note: there is no support for interleaved arrays so each binding and location is assigned the same sequential number, recorded in var BindLoc

type Vars

type Vars struct {

	// map of sets, by set number -- VertexSet is -2, PushSet is -1, rest are added incrementally
	SetMap map[int]*VarSet

	// map of vars by different roles across all sets -- updated in Config(), after all vars added.  This is needed for VkDescPool allocation.
	RoleMap map[VarRoles][]*Var

	// true if a VertexSet has been added
	HasVertex bool `edit:"-"`

	// true if PushSet has been added
	HasPush bool `edit:"-"`

	// number of complete descriptor sets to construct -- each descriptor set can be bound to a specific pipeline at the start of rendering, and updated with specific Value instances to provide values for each Var used during rendering.  If multiple rendering passes are performed in parallel, then each requires a separate descriptor set (e.g., typically associated with a different Frame in the swapchain), so this number should be increased.
	NDescs int

	// our parent memory manager
	Mem *Memory `display:"-"`

	// if true, variables are statically bound to specific offsets in memory buffers, vs. dynamically bound offsets.  Typically a compute shader operating on fixed data variables can use static binding, while graphics (e.g., vphong) requires dynamic binding to efficiently use the same shader code for multiple different values of the same variable type
	StaticVars bool `edit:"-"`

	// vulkan descriptor layout based on vars
	VkDescLayout vk.PipelineLayout `display:"-"`

	// vulkan descriptor pool, allocated for NDescs and the different descriptor pools
	VkDescPool vk.DescriptorPool `display:"-"`

	// allocated descriptor sets -- outer index is Vars.NDescs for different groups of descriptor sets, one of which can be bound to a pipeline at any given time.  The inner dimension is per VarSet to cover the different sets of variable updated at different times or with different numbers of items.  This variable is used for whole-pipline binding at start of rendering.
	VkDescSets [][]vk.DescriptorSet

	// currently accumulating set of vals to write to update bindings -- initiated by BindValuesStart, executed by BindValuesEnd
	VkWriteValues []vk.WriteDescriptorSet `display:"-"`

	// current descriptor collection index, set in BindValuesStart
	BindDescIndex int `edit:"-"`

	// dynamic offsets for Uniform and Storage variables, -- outer index is Vars.NDescs for different groups of descriptor sets, one of which can be bound to a pipeline at any given time, inner index is DynOffIndex on Var -- offsets are set when Value is bound via BindDynValue*.
	DynOffs [][]uint32

	// number of textures, at point of creating the DescLayout
	NTextures int
}

Vars are all the variables that are used by a pipeline, organized into Sets (optionally including the special VertexSet or PushSet). Vars are allocated to bindings / locations sequentially in the order added!

func (*Vars) AddDynOff

func (vs *Vars) AddDynOff()

AddDynOff adds one more dynamic offset across all NDescs

func (*Vars) AddPushSet

func (vs *Vars) AddPushSet() *VarSet

AddPushSet adds a new push constant Set -- this is a special Set holding values sent directly in the command buffer.

func (*Vars) AddSet

func (vs *Vars) AddSet() *VarSet

AddSet adds a new non-Vertex Set for holding Uniforms, Storage, etc Sets are automatically numbered sequentially

func (*Vars) AddVertexSet

func (vs *Vars) AddVertexSet() *VarSet

AddVertexSet adds a new Vertex Set -- this is a special Set holding Vertex, Index vars

func (*Vars) AllocHost

func (vs *Vars) AllocHost(buff *MemBuff, offset int) int

func (*Vars) AllocTextures

func (vs *Vars) AllocTextures(mm *Memory)

AllocTextures allocates images on device memory

func (*Vars) BindAllTextureVars

func (vs *Vars) BindAllTextureVars(set int) error

BindAllTextureVars binds all Texture vars in given set to their current values, iterating over NTextureDescs in case there are multiple Desc sets required to represent more than MaxTexturesPerSet. Each Value for a given Var is given a descriptor binding and the shader sees an array of values of corresponding length. All vals must be uploaded to Device memory prior to this, and it is not possible to update anything during a render pass. This calls BindStart / Bind

func (*Vars) BindDynValuesAllIndex added in v0.0.10

func (vs *Vars) BindDynValuesAllIndex(idx int)

BindDynValuesAllIndex dynamically binds all uniform, storage values by index for all variables in all sets.

This only dynamically updates the offset to point to the specified val. MUST call System.BindVars prior to any subsequent draw calls for this new offset to be bound at the proper point in the command buffer prior (call after all such dynamic bindings are updated.)

Do NOT call BindValuesStart / End around this.

func (*Vars) BindDynVarName

func (vs *Vars) BindDynVarName(set int, varNm string) error

BindDynVarName binds dynamic variable for given var looked up by name, for Uniform, Storage variables.

All vals must be uploaded to Device memory prior to this, and it is not possible to update actual values during a render pass. The memory buffer is essentially what is bound here.

Must have called BindVarsStart prior to this.

func (*Vars) BindDynVars

func (vs *Vars) BindDynVars(set int) error

BindDynVars binds all dynamic vars in given set, to be able to use dynamic vars, in subsequent BindDynValue* calls during the render pass, which update the offsets. For Uniform & Storage variables, which use dynamic binding.

This is automatically called during Config on the System, and usually does not need to be called again.

All vals must be uploaded to Device memory prior to this, and it is not possible to update actual values during a render pass. The memory buffer is essentially what is bound here.

Must have called BindVarsStart prior to this.

func (*Vars) BindDynVarsAll

func (vs *Vars) BindDynVarsAll()

BindDynVarsAll binds all dynamic vars across all sets. Called during system config.

func (*Vars) BindDynamicValue added in v0.0.10

func (vs *Vars) BindDynamicValue(set int, vr *Var, vl *Value) error

BindDynamicValue dynamically binds given uniform or storage value for given variable in given set.

This only dynamically updates the offset to point to the specified val. MUST call System.BindVars prior to any subsequent draw calls for this new offset to be bound at the proper point in the command buffer prior (call after all such dynamic bindings are updated.)

Do NOT call BindValuesStart / End around this.

returns error if not found.

func (*Vars) BindDynamicValueIndex added in v0.0.10

func (vs *Vars) BindDynamicValueIndex(set int, varNm string, valIndex int) error

BindDynamicValueIndex dynamically binds given uniform or storage value by index for given variable name, in given set.

This only dynamically updates the offset to point to the specified val. MUST call System.BindVars prior to any subsequent draw calls for this new offset to be bound at the proper point in the command buffer prior (call after all such dynamic bindings are updated.)

Do NOT call BindValuesStart / End around this.

returns error if not found.

func (*Vars) BindDynamicValueName added in v0.0.10

func (vs *Vars) BindDynamicValueName(set int, varNm, valNm string) error

BindDynamicValueName dynamically binds given uniform or storage value by name for given variable name, in given set.

This only dynamically updates the offset to point to the specified val. MUST call System.BindVars prior to any subsequent draw calls for this new offset to be bound at the proper point in the command buffer prior (call after all such dynamic bindings are updated.)

Do NOT call BindValuesStart / End around this.

returns error if not found.

func (*Vars) BindStatVarName

func (vs *Vars) BindStatVarName(set int, varNm string) error

BindStatVarName does static variable binding for given var looked up by name, for non-Uniform, Storage, variables (e.g., Textures). Each Value for a given Var is given a descriptor binding and the shader sees an array of values of corresponding length.

All vals must be uploaded to Device memory prior to this, and it is not possible to update anything during a render pass.

Must have called BindVarsStart prior to this.

func (*Vars) BindStatVars

func (vs *Vars) BindStatVars(set int) error

BindStatVars binds all static vars to their current values, for given set, for non-Uniform, Storage, variables (e.g., Textures). Each Value for a given Var is given a descriptor binding and the shader sees an array of values of corresponding length.

All vals must be uploaded to Device memory prior to this, and it is not possible to update anything during a render pass.

Must have called BindVarsStart prior to this.

func (*Vars) BindStatVarsAll

func (vs *Vars) BindStatVarsAll()

BindStatVarsAll binds all static vars to their current values, for all Uniform and Storage variables, when using Static value binding.

All vals must be uploaded to Device memory prior to this.

func (*Vars) BindVarsEnd

func (vs *Vars) BindVarsEnd()

BindVarsEnd finishes a new step of binding started by BindVarsStart. Actually executes the binding updates, based on prior BindVar* calls.

func (*Vars) BindVarsStart

func (vs *Vars) BindVarsStart(descIndex int)

BindVarsStart starts a new step of binding vars to descriptor sets, using given descIndex description set index (among the NDescs allocated). Bound vars determine what the shader programs see, in subsequent calls to Pipeline commands.

This must be called *prior* to a render pass, never within it. Only BindDyn* and BindVertex* calls can be called within render.

Do NOT use this around BindDynValue or BindVertexValue calls only for BindVar* methods.

Subsequent calls of BindVar* methods will add to a list, which will be executed when BindValuesEnd is called.

This creates a set of entries in a list of WriteDescriptorSet's

func (*Vars) BindVertexValueIndex added in v0.0.10

func (vs *Vars) BindVertexValueIndex(varNm string, valIndex int) error

BindVertexValueIndex dynamically binds given VertexSet value by index for given variable name. using given descIndex description set index (among the NDescs allocated).

Value must have already been updated into device memory prior to this, ideally through a batch update prior to starting rendering, so that all the values are ready to be used during the render pass. This only dynamically updates the offset to point to the specified val.

Do NOT call BindValuesStart / End around this.

returns error if not found.

func (*Vars) BindVertexValueName added in v0.0.10

func (vs *Vars) BindVertexValueName(varNm, valNm string) error

BindVertexValueName dynamically binds given VertexSet value by name for given variable name. using given descIndex description set index (among the NDescs allocated).

Value must have already been updated into device memory prior to this, ideally through a batch update prior to starting rendering, so that all the values are ready to be used during the render pass. This dynamically updates the offset to point to the specified val.

Do NOT call BindValuesStart / End around this.

returns error if not found.

func (*Vars) Config

func (vs *Vars) Config() error

Config must be called after all variables have been added. Configures all Sets and also does validation, returning error does DescLayout too, so all ready for Pipeline config.

func (*Vars) DescLayout

func (vs *Vars) DescLayout(dev vk.Device)

DescLayout configures the PipelineLayout of DescriptorSetLayout info for all of the non-Vertex vars

func (*Vars) Destroy

func (vs *Vars) Destroy(dev vk.Device)

func (*Vars) Free

func (vs *Vars) Free(buff *MemBuff)

Free resets the MemPtr for values, resets any self-owned resources (Textures)

func (*Vars) MemSize

func (vs *Vars) MemSize(buff *MemBuff) int

func (*Vars) MemSizeStorage

func (vs *Vars) MemSizeStorage(mm *Memory, alignBytes int)

func (*Vars) ModRegs

func (vs *Vars) ModRegs(bt BuffTypes) []MemReg

ModRegs returns the regions of Values that have been modified

func (*Vars) ModRegsStorage

func (vs *Vars) ModRegsStorage(bufIndex int, buff *MemBuff) []MemReg

ModRegStorage returns the regions of Storage Values that have been modified

func (*Vars) NSets

func (vs *Vars) NSets() int

NSets returns the number of regular non-VertexSet sets

func (*Vars) PushSet

func (vs *Vars) PushSet() *VarSet

PushSet returns the Push Set -- a special Set holding push constants

func (*Vars) SetTry

func (vs *Vars) SetTry(set int) (*VarSet, error)

SetTry returns set by index, returning nil and error if not found

func (*Vars) StartSet

func (vs *Vars) StartSet() int

StartSet returns the starting set to use for iterating sets

func (*Vars) StringDoc

func (vs *Vars) StringDoc() string

StringDoc returns info on variables

func (*Vars) TextureGroupSizeIndexes added in v0.0.10

func (vs *Vars) TextureGroupSizeIndexes(set int, varNm string, valIndex int) *szalloc.Indexes

TextureGroupSizeIndexes for texture at given index, allocated in groups by size using Values.AllocTexBySize, returns the indexes for the texture and layer to actually select the texture in the shader, and proportion of the Gp allocated texture size occupied by the texture.

func (*Vars) ValueByIndexTry added in v0.0.10

func (vs *Vars) ValueByIndexTry(set int, varName string, valIndex int) (*Var, *Value, error)

ValueByIndexTry returns value by first looking up variable name, then value index, returning error if not found

func (*Vars) ValueByNameTry added in v0.0.10

func (vs *Vars) ValueByNameTry(set int, varName, valName string) (*Var, *Value, error)

ValueByNameTry returns value by first looking up variable name, then value name, within given set number, returning error if not found

func (*Vars) VarByNameTry

func (vs *Vars) VarByNameTry(set int, name string) (*Var, error)

VarByNameTry returns Var by name in given set number, returning error if not found

func (*Vars) VertexSet

func (vs *Vars) VertexSet() *VarSet

VertexSet returns the Vertex Set -- a special Set holding Vertex, Index vars

func (*Vars) VkPushConfig

func (vs *Vars) VkPushConfig() []vk.PushConstantRange

VkPushConfig returns vulkan push constant ranges, only if PushSet used.

func (*Vars) VkVertexConfig

func (vs *Vars) VkVertexConfig() *vk.PipelineVertexInputStateCreateInfo

VkVertexConfig returns vulkan vertex config struct, for VertexSet only! Note: there is no support for interleaved arrays so each binding and location is assigned the same sequential number, recorded in var BindLoc

Directories

Path Synopsis
examples
gosl translates Go source code into HLSL compatible shader code.
gosl translates Go source code into HLSL compatible shader code.
alignsl
package alignsl performs 16-byte alignment checking of struct fields and total size modulus checking of struct types to ensure HLSL (and GSL) compatibility.
package alignsl performs 16-byte alignment checking of struct fields and total size modulus checking of struct types to ensure HLSL (and GSL) compatibility.
examples/basic
This example just does some basic calculations on data structures and reports the time difference between the CPU and GPU.
This example just does some basic calculations on data structures and reports the time difference between the CPU and GPU.
slbool
package slbool defines a HLSL friendly int32 Bool type.
package slbool defines a HLSL friendly int32 Bool type.
slprint
Package printer implements printing of AST nodes.
Package printer implements printing of AST nodes.
package vkinit handles loading and initialization of Vulkan without any dependency upon glfw
package vkinit handles loading and initialization of Vulkan without any dependency upon glfw
vshape provides a library of 3D shapes, built from indexed triangle meshes, which can be added together in `ShapeGroup` lists.
vshape provides a library of 3D shapes, built from indexed triangle meshes, which can be added together in `ShapeGroup` lists.

Jump to

Keyboard shortcuts

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