gpu

package
v1.2.17 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2022 License: BSD-3-Clause Imports: 8 Imported by: 0

Documentation

Overview

Package gpu provides an abstract interface to a graphical processing unit (GPU).

Currently it is only supporting OpenGL (version 3.3), but the design should be sufficiently general to accommodate Vulkan with not too many changes. Those are the primary cross-platform GPU systems.

The gpu interfaces provide a chain of construction, starting with the GPU which can create a Program or a Pipeline (collection of programs), which is the core of the system, defining different Shader programs that run on the GPU.

Each Program has Uniform variables (constants across all GPU cores) and Input Vectors which are the vectorized data that each GPU core computes in parallel. For graphics, the Vectors are verticies, normals, etc. The Output vectors transfer information from one shader program to another (e.g., the Vertex shader sends output to the Fragment shader). Programs should be written in 3.3 GLSL but DO NOT include the version info as it will be automatically added.

All Vectors processed by a Program must be contained in a SINGLE VectorsBuffer which can interleave or just append the data from multiple Vectors into a single continguous chunk of memory. Typically it is more efficient to use an indexed view onto the Vectors data, provided by the IndexesBuffer.

The BufferMgr manages a VectorsBuffer and IndexesBuffer, and corresponds to the Vertex Array Object in OpenGL.

For typical usage (e.g., in gi3d), there is a different Program for each different type of Material, and e.g., the Uniform's define the camera's view transform and any uniform colors, etc. Each Object or Shape (or Geometry) has a BufferMgr configured with the vertex, normal, etc data for its particular shape.

Index

Constants

This section is empty.

Variables

View Source
var BUniType = UniType{Type: Bool}

BUniType is a single bool

View Source
var FUniType = UniType{Type: Float32}

FUniType is a single float32

View Source
var IUniType = UniType{Type: Int}

IUniType is a single int32

View Source
var KiT_ShaderTypes = kit.Enums.AddEnum(ShaderTypesN, kit.NotBitFlag, nil)
View Source
var KiT_Types = kit.Enums.AddEnum(TypesN, kit.NotBitFlag, nil)
View Source
var KiT_VectorRoles = kit.Enums.AddEnum(VectorRolesN, kit.NotBitFlag, nil)
View Source
var KiT_VectorUsages = kit.Enums.AddEnum(VectorUsagesN, kit.NotBitFlag, nil)
View Source
var Mat3fUniType = UniType{Type: Float32, Mat: 3}

Mat3fUniType is a 3x3 matrix of float32

View Source
var Mat4fUniType = UniType{Type: Float32, Mat: 4}

Mat4fUniType is a 4x4 matrix of float32

View Source
var TypeNames = map[Types]string{
	UndefType: "none",
	Bool:      "bool",
	Int:       "int",
	UInt:      "uint",
	Float32:   "float",
	Float64:   "double",
}

GLSL type names

View Source
var Vec2fUniType = UniType{Type: Float32, Vec: 2}

Vec2fUniType is a 2-vector of float32

View Source
var Vec2fVecType = VectorType{Type: Float32, Vec: 2}

Vec2fVecType is a 2-vector of float32

View Source
var Vec3fUniType = UniType{Type: Float32, Vec: 3}

Vec3fUniType is a 3-vector of float32

View Source
var Vec3fVecType = VectorType{Type: Float32, Vec: 3}

Vec3fVecType is a 3-vector of float32

View Source
var Vec4fUniType = UniType{Type: Float32, Vec: 4}

Vec4fUniType is a 4-vector of float32

View Source
var Vec4fVecType = VectorType{Type: Float32, Vec: 4}

Vec4fVecType is a 4-vector of float32

Functions

func CString

func CString(s string) string

CString returns a null-terminated string if not already so

func CStrings

func CStrings(list []string) []string

CStrings returns null-terminated strings if not already so

func GoString

func GoString(s string) string

GoString returns a non-null-terminated string if not already so

func TypeBytes

func TypeBytes(tp Types) int

TypeBytes returns number of bytes for given type -- 4 except Float64 = 8

Types

type BufferMgr

type BufferMgr interface {
	// AddVectorsBuffer makes a new VectorsBuffer to contain Vectors.
	AddVectorsBuffer(usg VectorUsages) VectorsBuffer

	// VectorsBuffer returns the VectorsBuffer for this mgr
	VectorsBuffer() VectorsBuffer

	// AddIndexesBuffer makes a new IndexesBuffer to contain Indexes.
	AddIndexesBuffer(usg VectorUsages) IndexesBuffer

	// IndexesBuffer returns the IndexesBuffer for this mgr
	IndexesBuffer() IndexesBuffer

	// Activate binds buffers as active and configures as needed
	Activate()

	// Handle returns the unique handle for this buffer manager -- only valid after Activate()
	// this is the VAO
	Handle() uint32

	// Transfer transfers all buffer data to GPU (e.g., for initial upload).
	// Activate must have been called with no other such buffers activated in between.
	TransferAll()

	// TransferVectors transfers vectors buffer data to GPU -- if vector data has changed.
	// Activate must have been called with no other such buffers activated in between.
	TransferVectors()

	// TransferIndexes transfers indexes buffer data to GPU -- if indexes data has changed.
	// Activate must have been called with no other such buffers activated in between.
	TransferIndexes()

	// Delete deletes the GPU resources associated with this buffer
	// (requires Activate to re-establish a new one).
	// Should be called prior to Go object being deleted
	// (ref counting can be done externally).
	Delete()
}

BufferMgr maintains VectorsBuffer and IndexesBuffer and also the critical VAO (Vertex Array Object) for OpenGL which holds these active buffer pointers. A typical Shape / Object / Geom will just have this. IMPORTANT: BufferMgr cannot be shared across contexts (windows)! TheGPU.NewBufferMgr() returns a new buffer manager.

type Drawing

type Drawing interface {
	// Clear clears the given properties of the current render target
	Clear(color, depth bool)

	// ClearColor sets the color to draw when clear is called
	ClearColor(r, g, b float32)

	// DepthTest turns on / off depth testing (standard less-than-or-equal depth assumed).
	DepthTest(on bool)

	// StencilTest turns on / off stencil testing
	StencilTest(on bool)

	// CullFace sets face culling, for front and / or back faces (back typical).
	// If you don't do this, rendering of standard Phong model will not work.
	// if ccw = true then standard CCW face ordering is used, else CW (clockwise).
	CullFace(front, back, ccw bool)

	// Multisample turns on or off multisampling (antialiasing)
	Multisample(on bool)

	// Op sets the blend function based on go standard draw operation
	// Src disables blending, and Over uses alpha-blending
	Op(op draw.Op)

	// Wireframe sets the rendering to lines instead of fills if on = true
	Wireframe(on bool)

	// Viewport sets the rendering viewport to given rectangle.
	// It is important to update this for each render -- cannot assume it.
	Viewport(rect image.Rectangle)

	// Triangles uses all existing settings to draw Triangles
	// (non-indexed)
	Triangles(start, count int)

	// TriangleStrips uses all existing settings to draw Triangles Strips
	// (non-indexed)
	TriangleStrips(start, count int)

	// TrianglesIndexed uses all existing settings to draw Triangles Indexed.
	// You must have activated an IndexesBuffer that supplies
	// the indexes, and start + count determine range of such indexes
	// to use, and must be within bounds for that.
	TrianglesIndexed(start, count int)

	// TriangleStripsIndexed uses all existing settings to draw Triangle Strips Indexed.
	// You must have activated an IndexesBuffer that supplies
	// the indexes, and start + count determine range of such indexes
	// to use, and must be within bounds for that.
	TriangleStripsIndexed(start, count int)

	// Flush ensures that all rendering is pushed to current render target.
	// Especially useful for rendering to framebuffers (Window SwapBuffer
	// automatically does a flush)
	Flush()
}

Drawing provides commonly-used GPU drawing functions and state settings that affect drawing. All operate on the current context with current program, target, etc

var Draw Drawing

Draw is the current oswin gpu Drawing instance. Call methods as, e.g.: gpu.Draw.Triangles(..) etc..

type Framebuffer

type Framebuffer interface {
	// Name returns the name of the framebuffer
	Name() string

	// SetName sets the name of the framebuffer
	SetName(name string)

	// Size returns the size of the framebuffer
	Size() image.Point

	// SetSize sets the size of the framebuffer.
	// If framebuffer has been Activate'd, then this resizes the GPU side as well.
	SetSize(size image.Point)

	// Bounds returns the bounds of the framebuffer's image. It is equal to
	// image.Rectangle{Max: t.Size()}.
	Bounds() image.Rectangle

	// SetSamples sets the number of samples to use for multi-sample
	// anti-aliasing.  When using as a primary 3D render target,
	// the recommended number is 4 to produce much better-looking results.
	// If just using as an intermediate render buffer, then you may
	// want to turn off by setting to 0.
	// Setting to a number > 0 automatically disables use of external
	// Texture2D that might have previously been set by SetTexture --
	// must call Texture() to get downsampled texture instead.
	SetSamples(samples int)

	// Samples returns the number of multi-sample samples
	Samples() int

	// SetTexture sets an existing Texture2D to serve as the color buffer target
	// for this framebuffer.  This also implies SetSamples(0), and that
	// the Texture() method just directly returns the texture set here.
	// If we have a non-zero size, then the texture is automatically resized
	// to the size of the framebuffer, otherwise the fb inherits size of texture.
	SetTexture(tex Texture2D)

	// Texture returns the current contents of the framebuffer as a Texture2D.
	// For Samples() > 0 this reduces the optimized internal render buffer to a
	// standard 2D texture -- the return texture is owned and managed by the
	// framebuffer, and re-used every time Texture() is called.
	// If SetTexture was called, then it just returns that texture
	// which was directly rendered to.
	Texture() Texture2D

	// DepthAt returns the depth-buffer value at given x,y coordinate in
	// framebuffer coordinates (i.e., Y = 0 is at bottom).
	// Must be called with a valid gpu context and on proper thread for that context,
	// with framebuffer active.
	DepthAt(x, y int) float32

	// DepthAll returns the entire depth buffer as a slice of float32 values
	// of same size as framebuffer.  This slice is pointer to internal reused
	// value -- copy to retain values or modify.
	// Must be called with a valid gpu context and on proper thread for that context,
	// with framebuffer active.
	DepthAll() []float32

	// Activate establishes the GPU resources and handle for the
	// framebuffer and all other associated buffers etc (if not already done).
	// It then sets this as the current rendering target for subsequent
	// gpu drawing commands.
	Activate() error

	// Rendered should be called after rendering to the framebuffer,
	// to ensure the update of data transferred from the framebuffer
	// (texture, depth buffer)
	Rendered()

	// Handle returns the GPU handle for the framebuffer -- only
	// valid after Activate.
	Handle() uint32

	// Delete deletes the GPU resources associated with this framebuffer
	// (requires Activate to re-establish a new one).
	// Should be called prior to Go object being deleted
	// (ref counting can be done externally).
	// Does NOT delete any Texture set by SetTexture -- must be done externally.
	Delete()
}

Framebuffer is an offscreen render target. gi3d renders exclusively to a Framebuffer, which is then copied to the overall oswin.Window.WinTex texture that backs the window for final display to the user. Use gpu.TheGPU.NewFramebuffer for a new freestanding framebuffer, or gpu.Texture2D.ActivateFramebuffer to activate for rendering onto an existing texture.

type GPU

type GPU interface {
	// Init initializes the GPU framework etc
	// if debug is true, then it turns on debugging mode
	// and, if available, enables automatic error callback
	// unfortunately that is not avail for OpenGL on mac
	// and possibly other systems, so ErrCheck must be used
	// but it is a NOP if the callback method is avail.
	Init(debug bool) error

	// ActivateShared activates the invisible shared context
	// which is shared across all other window / offscreen
	// rendering contexts, and should be used as the context
	// for initializing shared resources.
	ActivateShared() error

	// IsDebug returns true if debug mode is on
	IsDebug() bool

	// ErrCheck checks if there have been any GPU-related errors
	// since the last call to ErrCheck -- if callback errors
	// are avail, then returns most recent such error, which are
	// also automatically logged when they occur.
	ErrCheck(ctxt string) error

	// RenderToWindow sets the current context's window as the
	// render target (i.e., the default framebuffer 0).
	// This can be used if a Framebuffer was previously active.
	// Automatically called during UseContext to make sure.
	RenderToWindow()

	// Type returns the GPU data type id for given type
	Type(typ Types) uint32

	// NewProgram returns a new Program with given name -- for standalone programs.
	// See also NewPipeline.
	NewProgram(name string) Program

	// NewPipeline returns a new Pipeline to manage multiple coordinated Programs.
	NewPipeline(name string) Pipeline

	// NewBufferMgr returns a new BufferMgr for managing Vectors and Indexes for rendering.
	NewBufferMgr() BufferMgr

	// NewInputVectors returns a new Vectors input variable that has a pre-specified
	// layout(location = X) in programs -- allows same inputs to be used across a set
	// of programs that all use the same locations.
	NewInputVectors(name string, loc int, typ VectorType, role VectorRoles) Vectors

	// NewTexture2D returns a new Texture2D with given name (optional).
	// These Texture2D's must be Activate()'d and Delete()'d and otherwise managed
	// (no further tracking is done by the gpu framework)
	NewTexture2D(name string) Texture2D

	// NewFramebuffer returns a new Framebuffer for rendering directly
	// onto a texture instead of onto the Window (i.e., for offscreen rendering).
	// samples is typically 4 for multisampling anti-aliasing (generally recommended).
	// See also Texture2D.ActivateFramebuffer to activate a framebuffer for rendering
	// to an existing texture.
	NewFramebuffer(name string, size image.Point, samples int) Framebuffer

	// NewUniforms makes a new named set of uniforms (i.e,. a Uniform Buffer Object)
	// These uniforms can be bound to programs -- first add all the uniform variables
	// and then AddUniforms to each program that uses it.
	// Uniforms will be bound etc when the program is compiled.
	NewUniforms(name string) Uniforms

	// 	NextUniformBindingPoint returns the next avail uniform binding point.
	// Counts up from 0 -- this call increments for next call.
	NextUniformBindingPoint() int
}

GPU provides the main interface to the GPU hardware. Currently based on OpenGL. All calls apply to the current context, which must be set with Activate() call on relevant oswin.Window. Framebuffer.Activate() will also set the rendering target to a framebuffer instead of the window. Furthermore, all GPU calls must be embedded in oswin.TheApp.RunOnMain function call to run on the main thread:

oswin.TheApp.RunOnMain(func() {
   win.Activate()
   // do GPU calls here
})
var TheGPU GPU

TheGPU is the current oswin GPU instance

type IndexesBuffer

type IndexesBuffer interface {
	// SetLen sets the number of indexes in buffer
	SetLen(ln int)

	// Len returns the number of indexes in bufer
	Len() int

	// Set sets the indexes by copying given data
	Set(idxs mat32.ArrayU32)

	// Returns the indexes (direct copy of internal buffer -- can be modified)
	Indexes() mat32.ArrayU32

	// Activate binds buffer as active one
	Activate()

	// Handle returns the unique handle for this buffer -- only valid after Activate()
	Handle() uint32

	// Transfer transfers data to GPU -- Activate must have been called with no other
	// such buffers activated in between.  Automatically uses re-specification
	// strategy per: https://www.khronos.org/opengl/wiki/Buffer_Object_Streaming
	// so it is safe if buffer was still being used from prior GL rendering call.
	Transfer()

	// Delete deletes the GPU resources associated with this buffer
	// (requires Activate to re-establish a new one).
	// Should be called prior to Go object being deleted
	// (ref counting can be done externally).
	Delete()
}

IndexesBuffer manages a buffer of indexes for index-based rendering (i.e., GL_ELEMENT_ARRAY_BUFFER for glDrawElements calls in OpenGL).

type Pipeline

type Pipeline interface {
	// Name returns name of this pipeline
	Name() string

	// SetName sets name of this pipeline
	SetName(name string)

	// AddProgram adds program with given name to the pipeline
	AddProgram(name string) Program

	// ProgramByName returns program by name.
	// Returns nil if not found (error auto logged).
	ProgramByName(name string) Program

	// Programs returns list (slice) of programs in pipeline, in order added
	Programs() []Program

	// Delete deletes the GPU resources associated with this pipeline
	// Should be called prior to Go object being deleted
	// (ref counting can be done externally).
	Delete()
}

Pipeline manages a sequence of Programs that can be activated in an appropriate order to achieve some overall step of rendering. A new Pipeline can be created in TheGPU.NewPipeline().

type Program

type Program interface {
	// Name returns name of program
	Name() string

	// SetName sets name of program
	SetName(name string)

	// AddShader adds shader of given type, unique name and source code.
	// Any array uniform's will add their #define NAME_LEN's to the top
	// of the source code automatically, so the source can assume those exist
	// when compiled (NAME is uppper-cased version of variable name).
	// Also the appropriate #version is added automatically.
	AddShader(typ ShaderTypes, name string, src string) (Shader, error)

	// ShaderByName returns shader by its unique name
	ShaderByName(name string) Shader

	// ShaderByType returns shader by its type
	ShaderByType(typ ShaderTypes) Shader

	// SetFragDataVar sets the variable name to use for the fragment shader's output
	SetFragDataVar(name string)

	// AddUniform adds an individual standalone uniform variable to the program of given type.
	// Must add all uniform variables before compiling, as they add to source.
	AddUniform(name string, typ UniType, ary bool, ln int) Uniform

	// NewUniforms makes a new named set of uniforms (i.e,. a Uniform Buffer Object)
	// These uniforms can be bound to programs -- first add all the uniform variables
	// and then AddUniforms to each program that uses it (already added to this one).
	// Uniforms will be bound etc when the program is compiled.
	NewUniforms(name string) Uniforms

	// AddUniforms adds an existing Uniforms collection of uniform variables to this
	// program.
	// Uniforms will be bound etc when the program is compiled.
	AddUniforms(unis Uniforms)

	// UniformByName returns a Uniform based on unique name -- this could be in a
	// collection of Uniforms (i.e., a Uniform Buffer Object in GL) or standalone
	// Returns nil if not found (error auto logged)
	UniformByName(name string) Uniform

	// UniformsByName returns Uniforms collection of given name
	// Returns nil if not found (error auto logged)
	UniformsByName(name string) Uniforms

	// AddInput adds a Vectors input variable to the program -- name must = 'in' var name.
	// This input will get bound to variable and handle updated when program is compiled.
	AddInput(name string, typ VectorType, role VectorRoles) Vectors

	// AddOutput adds a Vectors output variable to the program -- name must = 'out' var name.
	// This output will get bound to variable and handle updated when program is compiled.
	AddOutput(name string, typ VectorType, role VectorRoles) Vectors

	// Inputs returns a list (slice) of all the input ('in') vectors defined for this program.
	Inputs() []Vectors

	// Outputs returns a list (slice) of all the output ('out') vectors defined for this program.
	Outputs() []Vectors

	// InputByName returns given input vectors by name.
	// Returns nil if not found (error auto logged)
	InputByName(name string) Vectors

	// OutputByName returns given output vectors by name.
	// Returns nil if not found (error auto logged)
	OutputByName(name string) Vectors

	// InputByRole returns given input vectors by role.
	// Returns nil if not found (error auto logged)
	InputByRole(role VectorRoles) Vectors

	// OutputByRole returns given input vectors by role.
	// Returns nil if not found (error auto logged)
	OutputByRole(role VectorRoles) Vectors

	// Compile compiles all the shaders and links the program, binds the uniforms
	// and input / output vector variables, etc.
	// This must be called after setting the lengths of any array uniforms (e.g.,
	// the number of lights)
	// showSrc arg prints out the final compiled source, including automatic
	// defines etc at the top, even if there are no errors, which can be useful for debugging.
	Compile(showSrc bool) error

	// Handle returns the handle for the program -- only valid after a Compile call
	Handle() uint32

	// Activate activates this as the active program -- must have been Compiled first.
	Activate()

	// Delete deletes the GPU resources associated with this program
	// (requires Compile and Activate to re-establish a new one).
	// Should be called prior to Go object being deleted
	// (ref counting can be done externally).
	Delete()
}

Program manages a set of shaders and associated variables and uniforms. Multiple programs can be assembled into a Pipeline, which can create new Programs. GPU.NewProgram() can also create standalone Programs. All uniforms must be added before compiling program.

type Shader

type Shader interface {
	// Name returns the unique name of this shader
	Name() string

	// Type returns the type of the shader
	Type() ShaderTypes

	// Compile compiles given source code for the shader, of given type and unique name.
	// Currently, source must be GLSL version 410, which is the supported version of OpenGL.
	// The source does not need to be null terminated (with \x00 code) but that will be more
	// efficient, skipping the extra step of adding the null terminator.
	// Context must be set.
	Compile(src string) error

	// Handle returns the GPU handle for this shader
	Handle() uint32

	// Source returns the actual final source code for the shader
	// excluding the null terminator (for display purposes).
	// This includes extra auto-generated code from the Program.
	Source() string

	// OrigSource returns the original user-supplied source code
	// excluding the null terminator (for display purposes)
	OrigSource() string

	// Delete deletes the GPU resources for shader -- should be deleted after linked into a program.
	Delete()

	// GPUType returns the GPU type id for given shader type
	GPUType(typ ShaderTypes) uint32
}

Shader manages a single shader program. call Program.AddShader to add a new Shader.

type ShaderTypes

type ShaderTypes int32

ShaderTypes is a list of GPU shader types

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

func (*ShaderTypes) FromString

func (i *ShaderTypes) FromString(s string) error

func (ShaderTypes) String

func (i ShaderTypes) String() string

type Texture2D

type Texture2D interface {
	oswin.Texture

	// Framebuffer returns a framebuffer for rendering onto this
	// texture -- calls ActivateFramebuffer() if one is not
	// already activated.
	Framebuffer() Framebuffer
}

Texture2D manages a 2D texture, including loading from an image file and activating on GPU. Because a Texture2D is used for rendering to an oswin.Window, the oswin.Texture interface defines everything at that level, and gpu.Texture2D is just effectively an alias to that same interface.

For greater clarity, please use the gpu.Texture2D interface for all GPU-specific code, and oswin.Texture for oswin-specific code.

type Types

type Types int32

Types is a list of GPU data types

const (
	UndefType Types = iota
	Bool
	Int
	UInt
	Float32
	Float64
	TypesN
)

func (*Types) FromString

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

func (Types) String

func (i Types) String() string

type UniType

type UniType struct {
	Type Types `desc:"data type"`
	Vec  int   `desc:"if a vector, this is the length of the vector, 0 for scalar (valid values are 2,3,4)"`
	Mat  int   `desc:"square matrix dimensions, if a matrix (valid values are 3,4)"`
}

UniType represents a fully-specified GPU uniform type, including vectors and matricies

func (*UniType) Bytes

func (ty *UniType) Bytes() int

Bytes returns actual size of this element in bytes

func (*UniType) Name

func (ty *UniType) Name() string

Name returns the full GLSL type name for the type

func (*UniType) StdBytes

func (ty *UniType) StdBytes() int

StdBytes returns number of bytes taken up by this element, in std140 format (including padding) https://learnopengl.com/Advanced-OpenGL/Advanced-GLSL

type Uniform

type Uniform interface {
	// Name returns name of the uniform
	Name() string

	// Type returns type of the uniform
	Type() UniType

	// Array returns true if this is an array uniform.
	// If so, then it automatically generates a #define NAME_LEN <Len> definition prior
	// to the uniform definition, and if Len == 0 then it is *not* defined at all.
	// All code referencing this uniform should use #if NAME_LEN>0 wrapper.
	Array() bool

	// Len returns number of array elements, if an Array (can be 0)
	Len() int

	// SetLen sets the number of array elements -- if this is changed, then the associated
	// Shader program needs to be re-generated and recompiled.
	SetLen(ln int)

	// Offset returns byte-wise offset into the UBO where this uniform starts (only for UBO's)
	Offset() int

	// Size() returns actual byte-wise size of this uniform raw data (c.f., StdSize)
	Size() int

	// StdSize() returns byte-wise size of this uniform, *including padding* for representation
	// on the GPU -- e.g., as determined by the std140 standard opengl layout
	StdSize() int

	// Handle() returns the unique id for this uniform.
	// if in a UBO, then this is the index of the item within the list of UBO's
	Handle() int32

	// SetValue sets the value of the uniform to given value, which must be of the corresponding
	// elemental or mat32.Vector or mat32.Matrix type.  Proper context must be bound, etc.
	SetValue(val interface{}) error

	// LenDefine returns the #define NAME_LEN source code for this uniform, empty if not an array
	LenDefine() string
}

Uniform represents a single uniform variable, which can be contained within a Uniform Buffer Object or used as a separate independent uniform. This can be an array of values as well, in which case a NAME_LEN macro is always defined to reflect the length of the array. These uniforms are used directly to generate the shader code. See Program.AddUniform to create a new standalone one, and Program.NewUniforms to create a new set of them (i.e., Uniform Buffer Object)

type Uniforms

type Uniforms interface {
	// Name returns the name of this set of uniforms
	Name() string

	// SetName sets the name of this set of uniforms
	SetName(name string)

	// AddUniform adds a uniform variable to this collection of uniforms of given type
	AddUniform(name string, typ UniType, ary bool, ln int) Uniform

	// UniformByName returns a Uniform based on unique name.
	// returns nil and logs an error if not found
	UniformByName(name string) Uniform

	// LenDefines returns the #define NAME_LEN source code for all uniforms, empty if no arrays
	LenDefines() string

	// Activate generates the Uniform Buffer Object structure and reserves the binding point
	Activate() error

	// Resize resizes the buffer if needed -- call if any of the member uniforms
	// might have been resized.  Calls Activate if not already activated.
	Resize() error

	// Bind binds the Uniform Buffer Object structure to given program
	Bind(prog Program) error

	// Handle returns the handle for the program -- only valid after a Compile call
	Handle() uint32

	// BindingPoint returns the unique binding point for this set of Uniforms --
	// needed for connecting to programs
	BindingPoint() uint32
}

Uniforms is a set of Uniform objects that are all organized together (i.e., a UniformBufferObject in OpenGL)

type VectorRoles

type VectorRoles int32

VectorRoles are the functional roles of vectors

const (
	UndefRole VectorRoles = iota
	VertexPosition
	VertexNormal
	VertexTangent
	VertexColor
	VertexTexcoord
	VertexTexcoord2
	SkinWeight
	SkinIndex
	VectorRolesN
)

func (*VectorRoles) FromString

func (i *VectorRoles) FromString(s string) error

func (VectorRoles) String

func (i VectorRoles) String() string

type VectorType

type VectorType struct {
	Type Types `desc:"data type"`
	Vec  int   `desc:"length of vector (valid values are 2,3,4)"`
}

VectorType represents a fully-specified GPU vector type, e.g., for inputs / outputs to shader programs

func (*VectorType) Bytes

func (ty *VectorType) Bytes() int

Bytes returns number of bytes per Vector element (len * 4 basically)

type VectorUsages

type VectorUsages int32

VectorUsages are the usage hints for vector buffers

const (
	// The data store contents will be modified once and used at most a few times.
	// The data store contents are modified by the application, and used as the source for GL drawing and image specification commands.
	StreamDraw VectorUsages = iota

	// The data store contents will be modified once and used at most a few times.
	// The data store contents are modified by reading data from the GL, and used to return that data when queried by the application.
	StreamRead

	// The data store contents will be modified once and used at most a few times.
	// The data store contents are modified by reading data from the GL, and used as the source for GL drawing and image specification commands.
	StreamCopy

	// The data store contents will be modified once and used many times.
	// The data store contents are modified by the application, and used as the source for GL drawing and image specification commands.
	StaticDraw

	// The data store contents will be modified once and used many times.
	// The data store contents are modified by reading data from the GL, and used to return that data when queried by the application.
	StaticRead

	// The data store contents will be modified once and used many times.
	// The data store contents are modified by reading data from the GL, and used as the source for GL drawing and image specification commands.
	StaticCopy

	// The data store contents will be modified repeatedly and used many times.
	// The data store contents are modified by the application, and used as the source for GL drawing and image specification commands.
	DynamicDraw

	// The data store contents will be modified repeatedly and used many times.
	// The data store contents are modified by reading data from the GL, and used to return that data when queried by the application.
	DynamicRead

	// The data store contents will be modified repeatedly and used many times.
	// The data store contents are modified by reading data from the GL, and used as the source for GL drawing and image specification commands.
	DynamicCopy

	VectorUsagesN
)

func (*VectorUsages) FromString

func (i *VectorUsages) FromString(s string) error

func (VectorUsages) String

func (i VectorUsages) String() string

type Vectors

type Vectors interface {
	// Name returns the name of the vectors (i.e., as it is referred to in the shader program)
	Name() string

	// Type returns the vector data type
	Type() VectorType

	// Role returns the functional role of these vectors
	Role() VectorRoles

	// Handle returns the unique handle for these vectors within the program where it is used
	// Can also be specified using layout(location = X) specifier.
	Handle() uint32

	// Set sets all the parameters of the Vectors, and flags it as init -- when
	// created for predefined locations.
	Set(name string, handle uint32, typ VectorType, role VectorRoles)
}

Vectors manages arrays of vectors that are processed as inputs to a shader program and received as outputs from compute shaders. i.e., a Vertex Buffer Object in OpenGL. It is created by Program.AddInputs, .AddOutputs, and stores the Handle into that program's variable. This handle is then bound to a buffer in VectorsBuffer.

type VectorsBuffer

type VectorsBuffer interface {
	// Usage returns whether this is dynamic or static etc
	Usage() VectorUsages

	// SetUsage sets the usage of the buffer
	SetUsage(usg VectorUsages)

	// AddVectors adds a Vectors to this buffer, all interleaved vectors
	// must be added first, before any non-interleaved (error will be logged if not).
	// Vectors are created in a Program, and connected to this buffer here.
	// All Vectors in a given Program must be stored in a SINGLE buffer.
	// Add all Vectors before setting the length, which then computes offset and strides
	// for each vector.
	AddVectors(vec Vectors, interleave bool)

	// NumVectors returns number of vectors in the buffer
	NumVectors() int

	// Vectors returns a list (slice) of all the vectors in the buffer, in order.
	Vectors() []Vectors

	// VectorsByName returns given vectors by name.
	// Returns nil if not found (error auto logged)
	VectorsByName(name string) Vectors

	// VectorsByRole returns given vectors by role.
	// Returns nil if not found (error auto logged)
	VectorsByRole(role VectorRoles) Vectors

	// SetLen sets the number of elements in the buffer -- must be same number for each
	// Vectors type in buffer.  Also triggers computation of offsets and strides for each
	// vector -- call after having added all vectors.
	SetLen(ln int)

	// Len returns the number of elements in the buffer.
	Len() int

	// ByteOffset returns the starting offset of given Vectors in buffer.
	// Only valid after SetLen has been called.
	ByteOffset(vec Vectors) int

	// Offset returns the float element wise starting offset of given Vectors (ByteOffset / 4).
	// Only valid after SetLen has been called.
	Offset(vec Vectors) int

	// Stride returns the float element stride of given Vectors in buffer
	Stride(vec Vectors) int

	// ByteStride returns the byte stride of given Vectors in buffer (Stride * 4)
	ByteStride(vec Vectors) int

	// SetAllData sets all of the data in the buffer copying from given source
	SetAllData(data mat32.ArrayF32)

	// AllData returns the raw buffer data. This is the pointer to the internal
	// data -- if you modify it, you modify the internal data!  copy first if needed.
	AllData() mat32.ArrayF32

	// SetVecData sets data for given Vectors -- handles interleaving etc
	SetVecData(vec Vectors, data mat32.ArrayF32)

	// VecData returns data for given Vectors -- this is a copy for interleaved data
	// and a direct sub-slice for non-interleaved.
	VecData(vec Vectors) mat32.ArrayF32

	// Vec3Func iterates over all values of given vec3 Vectors
	// and calls the specified callback function with a pointer to each item as a Vec3.
	// Modifications to vec will be applied to the buffer at each iteration.
	// The callback function returns false to break or true to continue.
	Vec3Func(vec Vectors, fun func(vec *mat32.Vec3) bool)

	// Activate binds buffer as active one, and configures it per all existing settings
	Activate()

	// IsActive returns true if buffer has already been Activate'd
	// and thus exists on the GPU
	IsActive() bool

	// Handle returns the unique handle for this buffer -- only valid after Activate()
	Handle() uint32

	// Transfer transfers data to GPU -- Activate must have been called with no other
	// such buffers activated in between.  Automatically uses re-specification
	// strategy per: https://www.khronos.org/opengl/wiki/Buffer_Object_Streaming
	// so it is safe if buffer was still being used from prior GL rendering call.
	Transfer()

	// TransferVec transfers only data for given vector to GPU -- only valid
	// if Activate() and Transfer() have been called already, and only for
	// non-interleaved vectors.
	TransferVec(vec Vectors)

	// Delete deletes the GPU resources associated with this buffer
	// (requires Activate to re-establish a new one).
	// Should be called prior to Go object being deleted
	// (ref counting can be done externally).
	Delete()

	// DeleteAllVectors deletes all Vectors defined for this buffer (calls Delete first)
	DeleteAllVectors()

	// DeleteVectorsByName deletes Vectors of given name (calls Delete first)
	DeleteVectorsByName(name string)

	// DeleteVectorsByRole deletes Vectors of given role (calls Delete first)
	DeleteVectorsByRole(role VectorRoles)

	// GPUUsage returns the GPU vector usage id for given usage
	GPUUsage(usg VectorUsages) uint32
}

VectorsBuffer represents a buffer with multiple Vectors elements, which can be either interleaved (contiguous from the start only) or appended seqeuentially. All elements must be Float32, not Float64! Need a different buffer type that handles 64bit. It is created in BufferMgr.AddVectorsBuffer -- the Mgr is essential for managing buffers. The buffer maintains its own internal memory storage (mat32.ArrayF32) which can be operated upon or set from external sources.

Jump to

Keyboard shortcuts

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