gfx

package
v0.0.0-...-793ea6c Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2021 License: BSD-3-Clause Imports: 9 Imported by: 41

Documentation

Overview

Package gfx provides generic interfaces to GPU-based rendering techniques.

This package is not useful by itself but instead part of a larger picture as this package provides generic interfaces and data types to modern graphics rendering API's such as OpenGL, OpenGL ES, WebGL, Direct3D, etc.

The coordinate system used by this package is the right-handed Z up coordinate system unless explicitly specified otherwise.

Texture coordinates do not follow OpenGL convention but rather Go convention where the origin (0, 0) is the top-left corner of the texture.

Examples

The examples repository contains several examples which utilize the gfx core packages. Please see:

https://azul3d.org/examples

Index

Constants

This section is empty.

Variables

View Source
var ColorModel = color.ModelFunc(colorModel)

ColorModel represents the graphics color model (i.e. normalized 32-bit floating point values RGBA color).

View Source
var DefaultBlendState = BlendState{
	Color:    Color{0, 0, 0, 0},
	SrcRGB:   BOne,
	SrcAlpha: BOne,
	DstRGB:   BOneMinusSrcAlpha,
	DstAlpha: BOneMinusSrcAlpha,
	RGBEq:    BAdd,
	AlphaEq:  BAdd,
}

The default blend state to use for graphics objects (by default it works well for premultiplied alpha blending).

View Source
var DefaultStencilState = StencilState{
	WriteMask: 0xFFFF,
	Fail:      SKeep,
	DepthFail: SKeep,
	DepthPass: SKeep,
	Cmp:       Always,
}

The default stencil state that should be used for graphics objects.

Functions

This section is empty.

Types

type AlphaMode

type AlphaMode uint8

AlphaMode describes a single alpha transparency mode that can be used for drawing transparent parts of objects.

const (
	// NoAlpha means the object should be drawn without transparency. Parts
	// of the object that would normally be drawn as transparent will be drawn
	// as an opaque black color instead.
	NoAlpha AlphaMode = iota

	// AlphaBlend means the object should be drawn with alpha-blended
	// transparency. This type of transparency works well for most (but not
	// all) cases.
	//
	// Pros:
	//     Pixels can be semi-transparent.
	//
	// Cons:
	//     Draw order dependant. Opaque objects mut be drawn before
	//     transparent ones due to the way alpha blending works.
	//
	//     Does not work well with self-occluding transparent objects (e.g. a
	//     cube where all faces are semi-transparent) because individual faces
	//     would have to be sorted for correct order -- which is not feasible
	//     in realtime applications.
	//
	AlphaBlend

	// BinaryAlpha means the object should be drawn with binary transparency,
	// this causes transparency to be thought of as a 'binary' decision, where
	// each pixel is either fully transparent or opaque.
	//
	// Pixels with an alpha value of less than 0.5 are considered fully
	// transparent (invisible), and likewise pixels with an alpha value of
	// greater than or equal to 0.5 are considered fully opaque (solid,
	// non-transparent).
	//
	// Pros:
	//     Draw order independent. Regardless of the order objects are drawn
	//     the result will look the same (unlike AlphaBlend).
	//
	// Cons:
	//     Jagged-looking edges because pixels may not be semi-transparent.
	//
	BinaryAlpha

	// AlphaToCoverage means the object should be drawn using alpha-to-coverage
	// with special multisample bits.
	//
	// Pros:
	//     Draw order independent. Regardless of the order objects are drawn
	//     the result will look the same (unlike AlphaBlend).
	//
	//     No jagged-looking edges, pixels may be semi-transparent (unlike
	//     BinaryAlpha).
	//
	// Cons:
	//     Only some newer hardware supports it (in the event that hardware
	//     does not support it the fallback used is BinaryAlpha because it also
	//     does not suffer from draw ordering issues, although it does cause
	//     jagged-looking edges).
	AlphaToCoverage
)

func (AlphaMode) String

func (i AlphaMode) String() string

type BlendEq

type BlendEq uint8

BlendEq represents a single blend equation to use when blending RGB or Alpha components in the color buffer, it must be one of BlendAdd, BlendSubtract, BlendReverseSubtract.

const (
	// BAdd represents a blending equation where the src and dst colors are
	// added to eachother to produce the result.
	BAdd BlendEq = iota

	// BSub represents a blending equation where the src and dst colors are
	// subtracted from eachother to produce the result.
	BSub

	// BReverseSub represents a blending equation where the src and dst colors
	// are reverse-subtracted from eachother to produce the result.
	BReverseSub
)

type BlendOp

type BlendOp uint8

BlendOp represents a single blend operand, e.g. BOne, BOneMinusSrcAlpha.

const (
	// BZero is the zero-value blend operand (e.g. zero color).
	BZero BlendOp = iota

	// BOne is the one-value blend operand (e.g. full color).
	BOne

	// BSrcColor is the blend operand for source color.
	BSrcColor

	// BOneMinusSrcColor is the blend operand for 1 - src.
	BOneMinusSrcColor

	// BDstColor is the blend operand for destination color.
	BDstColor

	// BOneMinusDstColor is the blend operand for 1 - dst.
	BOneMinusDstColor

	// BSrcAlpha is the blend operand for source alpha.
	BSrcAlpha

	// BOneMinusSrcAlpha is the blend operand for 1 - src.alpha.
	BOneMinusSrcAlpha

	// BDstAlpha is the blend operand for dst.alpha.
	BDstAlpha

	// BOneMinusDstAlpha is the blend operand for 1 - dst.alpha.
	BOneMinusDstAlpha

	// BConstantColor is the blend operand for a constant color (as set in the
	// BlendState.Color field).
	BConstantColor

	// BOneMinusConstantColor is the blend operand for 1 - a constant color (as
	// set in the BlendState.Color field).
	BOneMinusConstantColor

	// BConstantAlpha is the blend operand for a constant alpha (as set in the
	// BlendState.Color field).
	BConstantAlpha

	// BOneMinusConstantAlpha is the blend operand for 1 - a constant alpha (as
	// set in the BlendState.Color field).
	BOneMinusConstantAlpha

	// BSrcAlphaSaturate is the blend operand for source alpha saturation. It
	// is not applicable for use in the BlendState.SrcRGB field.
	BSrcAlphaSaturate
)

type BlendState

type BlendState struct {
	// The constant blend color to be used (e.g. with BConstantColor).
	Color Color

	// Specifies the blend operand to use for the source RGB components.
	// All predefined BlendOp constants may be used.
	SrcRGB BlendOp

	// Specifies the blend operand to use for the destination RGB components.
	// All predefined BlendOp constants may be used except BSrcAlphaSaturate.
	DstRGB BlendOp

	// Specifies the blending operation to use between source and destination
	// alpha components.
	SrcAlpha, DstAlpha BlendOp

	// Specifies the blending equation to use for RGB and Alpha components,
	// respectively.
	RGBEq, AlphaEq BlendEq
}

BlendState represents the blend state to use when drawing an object whose AlphaMode == AlphaBlend.

func (BlendState) Compare

func (b BlendState) Compare(other BlendState) bool

Compare compares this state against the other one using DefaultBlendState as a reference when inequality occurs and returns whether or not this state should sort before the other one for purposes of state sorting.

type Boundable

type Boundable interface {
	// Bounds returns the axis-aligned bounding box of this boundable object.
	Bounds() lmath.Rect3
}

Boundable represents any object that can return it's axis-aligned bounding box.

type Bounds

type Bounds lmath.Rect3

Bounds is a simple datatype which implements the Boundable interface.

func (Bounds) Bounds

func (b Bounds) Bounds() lmath.Rect3

Bounds implements the Boundable interface.

type Camera

type Camera interface {
	Transformable

	// Update should be called before using the camera (e.g. at the start of
	// the frame). It is used to make the camera aware of the rectangle it is
	// drawing to on the screen.
	Update(b image.Rectangle)

	// Projection should return the camera's projection matrix. The matrix is
	// responsible for projecting world coordinates into normalized device
	// coordinates (-1, -1) to (+1, +1).
	Projection() Mat4
}

Camera represents a single camera object. See the camera subpackage for a basic camera implementation.

type Canvas

type Canvas interface {
	Downloadable

	// SetMSAA should request that this canvas use multi-sample anti-aliasing
	// during drawing. By default MSAA is enabled.
	//
	// Even if MSAA is requested to be enabled, there is no guarantee that it
	// will actually be used. For instance if the device does not support it.
	SetMSAA(enabled bool)

	// MSAA returns the last value passed into SetMSAA on this canvas.
	MSAA() bool

	// Precision should return the precision of the canvas's color, depth, and
	// stencil buffers.
	Precision() Precision

	// Bounds should return the bounding rectangle of this canvas, any and all
	// methods of this canvas that take rectangles as parameters will be
	// clamped to these bounds.
	//
	// The bounds that this method returns may change over time (e.g. when a
	// user resizes the window).
	Bounds() image.Rectangle

	// Clear submits a clear operation to the canvas. It will clear the given
	// rectangle of the canvas's color buffer to the specified background
	// color.
	//
	// If the rectangle is empty this function is no-op.
	Clear(r image.Rectangle, bg Color)

	// ClearDepth submits a depth-clear operation to the canvas. It will clear
	// the given rectangle of the canvas's depth buffer to the specified depth
	// value (in the range of 0.0 to 1.0, where 1.0 is furthest away).
	//
	// If the rectangle is empty this function is no-op.
	ClearDepth(r image.Rectangle, depth float64)

	// ClearStencil submits a stencil-clear operation to the canvas. It will
	// clear the given rectangle of the canvas's stencil buffer to the
	// specified stencil value.
	//
	// If the rectangle is empty this function is no-op.
	ClearStencil(r image.Rectangle, stencil int)

	// Draw submits a draw operation to the canvas. It will draw the given
	// graphics object onto the specified rectangle of the canvas.
	//
	// Upon calling this method, ownership of the graphics object is given to
	// the canvas itself and you may no longer access it safely until the
	// canvas gives ownership of the object back to you.
	//
	// The canvas returns owernship of the object via the channel, if done !=
	// nil, or more effectively after Render has returned.
	//
	// If not nil, then the object is drawn according to how it is seen by the
	// given projector (e.g. camera), taking into account the projector's
	// projection and transformation matrices.
	//
	// If the GPU supports occlusion queries (see GPUInfo.OcclusionQuery) and
	// o.OcclusionTest is set to true then at some point in the future (or when
	// QueryWait() is called) the native object will record the number of
	// samples that passed depth and stencil testing phases such that when
	// SampleCount() is called it will return the number of samples last drawn
	// by the object.
	//
	// The canvas must invoke o.Bounds() some time before clearing data slices
	// of loaded meshes, such that the object has a chance to determine it's
	// bounding box.
	//
	// The object will not be drawn if any of the following cases are true:
	//
	//  o.State == nil
	//  o.Shader == nil
	//  len(o.Shader.Error) > 0
	//  len(o.Meshes) == 0
	//  !o.Meshes[N].Loaded && len(o.Meshes[N].Vertices) == 0
	//  !o.Textures[n].Loaded && o.Textures[N].Source == nil
	//
	// If the rectangle is empty this function is no-op.
	Draw(r image.Rectangle, o *Object, c Camera)

	// QueryWait blocks until all pending draw object's occlusion queries
	// completely finish. Most clients should avoid this call as it can easilly
	// cause graphics pipeline stalls if not handled with care.
	//
	// Instead of calling QueryWait immediately for conditional drawing, it is
	// common practice to instead make use of the previous frame's occlusion
	// query results as this allows the CPU and GPU to work in parralel instead
	// of being directly synchronized with one another.
	//
	// If the GPU does not support occlusion queries (see DeviceInfo's
	// OcclusionQuery field) then this function is no-op.
	QueryWait()

	// Render should finalize all pending clear and draw operations as if they
	// where all submitted over a single channel like so:
	//
	//  pending := len(ops)
	//  for i := 0; i < pending; i++ {
	//      op := <-ops
	//      finalize(op)
	//  }
	//
	// and once complete the final frame should be sent to the graphics
	// hardware for rasterization.
	//
	// Additionally, a call to Render() means an implicit call to QueryWait().
	Render()
}

Canvas defines a canvas that can be drawn to (i.e. a window that the user will visibly see, or a texture that will store the results for later use).

A canvases method's are safe to call from multiple goroutines concurrently.

type Cmp

type Cmp uint8

Cmp represents a single comparison operator, like Less, Never, etc.

const (
	// Always is like Go's 'true', for example:
	//  if true {
	//      ...
	//  }
	Always Cmp = iota

	// Never is like Go's 'false', for example:
	//  if false {
	//      ...
	//  }
	Never

	// Less is like Go's '<', for example:
	//  if a < b {
	//      ...
	//  }
	Less

	// LessOrEqual is like Go's '<=', for example:
	//  if a <= b {
	//      ...
	//  }
	LessOrEqual

	// Greater is like Go's '>', for example:
	//  if a > b {
	//      ...
	//  }
	Greater

	// GreaterOrEqual is like Go's '>=', for example:
	//  if a >= b {
	//      ...
	//  }
	GreaterOrEqual

	// Equal is like Go's '==', for example:
	//  if a == b {
	//      ...
	//  }
	Equal

	// NotEqual is like Go's '!=', for example:
	//  if a != b {
	//      ...
	//  }
	NotEqual
)

type Color

type Color struct {
	R, G, B, A float32
}

Color represents a normalized (values are in the range of 0.0 to 1.0) 32-bit floating point RGBA color data type.

func (Color) RGBA

func (c Color) RGBA() (r, g, b, a uint32)

RGBA implements the color.Color interface.

type CoordConv

type CoordConv uint8

CoordConv represents a single coordinate space conversion.

World space is the top-most 'world' or 'global' space. A transform whose parent is nil explicitly means the parent is the 'world'.

Local space is the local space that this transform defines. Conceptually you may think of a transform as positioning, scaling, shearing, etc it's (local) space relative to it's parent.

Parent space is the local space of any given transform's parent. If the transform does not have a parent then parent space is identical to world space.

const (
	// LocalToWorld converts from local space to world space.
	LocalToWorld CoordConv = iota

	// WorldToLocal converts from world space to local space.
	WorldToLocal

	// ParentToWorld converts from parent space to world space.
	ParentToWorld

	// WorldToParent converts from world space to parent space.
	WorldToParent
)

type DSFormat

type DSFormat uint8

DSFormat specifies a single depth or stencil buffer storage format.

const (
	// ZeroDSFormat is a zero-value depth/stencil format.
	ZeroDSFormat DSFormat = iota

	// Depth16 is the 16-bit depth-buffer-only format.
	Depth16

	// Depth24 is the 24-bit depth-buffer-only format.
	Depth24

	// Depth32 is the 32-bit depth-buffer-only format.
	Depth32

	// Depth24AndStencil8 is the combined 24-bit depth-buffer and 8-bit
	// stencil-buffer format.
	Depth24AndStencil8
)

func (DSFormat) DepthBits

func (f DSFormat) DepthBits() uint8

DepthBits returns the number of depth bits in this format. For example:

Depth16 == 16
Depth24AndStencil8 == 24

func (DSFormat) IsCombined

func (f DSFormat) IsCombined() bool

IsCombined tells if f is a combined depth and stencil buffer format. It must be one of the following:

Depth24AndStencil8

func (DSFormat) IsDepth

func (f DSFormat) IsDepth() bool

IsDepth tells if f is a valid depth buffer format. It must be one of the following:

Depth16
Depth24
Depth32
Depth24AndStencil8

func (DSFormat) IsStencil

func (f DSFormat) IsStencil() bool

IsStencil tells if f is a valid stencil buffer format. It must be one of the following:

Depth24AndStencil8

func (DSFormat) StencilBits

func (f DSFormat) StencilBits() uint8

StencilBits returns the number of stencil bits in this format. For example:

Depth24AndStencil8 == 8
Depth16 == 0

func (DSFormat) String

func (i DSFormat) String() string

type Destroyable

type Destroyable interface {
	// Destroy destroys this object. Once destroyed the object can still be
	// used but doing so is not advised for performance reasons (e.g. it
	// requires reloading the entire object).
	//
	// Destroy can be called any number of times and safely from multiple
	// goroutines concurrently.
	Destroy()
}

Destroyable defines a destroyable object. Once an object is destroyed it may still be used, but typically doing so is not good and would e.g. involve reloading the entire object and cause performance issues.

Clients should invoke the Destroy() method when they are done utilizing the object or else doing so will be left up to a runtime Finalizer.

type Device

type Device interface {
	// The base canvas of the device (typically the window on the screen). The
	// canvas, like all other canvases, must not be accessed from multiple
	// goroutines concurrently.
	Canvas

	// Clock should return the graphics clock object which monitors the time
	// between frames, etc. The device is responsible for ticking it every
	// time a frame is rendered.
	Clock() *clock.Clock

	// Info should return information about the graphics hardware.
	Info() DeviceInfo

	// LoadMesh should begin loading the specified mesh asynchronously.
	//
	// Additionally, the device will set m.Loaded to true, and then invoke
	// m.ClearData(), thus allowing the data slices to be garbage collected).
	//
	// When the mesh is fully loaded, it is sent to the done channel if != nil,
	// and as long as sending would not block (i.e. ensure a buffer size of at
	// least one).
	//
	// Upon calling this method, ownership of the mesh is transferred to the
	// device itself and you may no longer access it safely until the device
	// passes ownership back to you over the done channel.
	LoadMesh(m *Mesh, done chan *Mesh)

	// LoadTexture should begin loading the specified texture asynchronously.
	//
	// Additionally, the device will set t.Loaded to true, and then invoke
	// t.ClearData(), thus allowing the source image to be garbage collected.
	//
	// When the texture is fully loaded, it is sent to the done channel
	// if != nil, and as long as sending would not block (i.e. ensure a buffer
	// size of at least one).
	//
	// Upon calling this method, ownership of the mesh is transferred to the
	// device itself and you may no longer access it safely until the device
	// passes ownership back to you over the done channel.
	LoadTexture(t *Texture, done chan *Texture)

	// LoadShader should begin loading the specified shader asynchronously.
	//
	// Additionally, if the shader was successfully loaded (no error log was
	// written) then the device will set s.Loaded to true, and then invoke
	// s.ClearData(), thus allowing the source data slices to be garbage
	// collected.
	//
	// When the shader is fully loaded (or has an error), it is sent to the
	// done channel if != nil, and as long as sending would not block (i.e.
	// ensure a buffer size of at least one).
	//
	// Upon calling this method, ownership of the shader is transferred to the
	// device itself and you may no longer access it safely until the device
	// passes ownership back to you over the done channel.
	LoadShader(s *Shader, done chan *Shader)

	// RenderToTexture creates and returns a canvas that when drawn to, stores
	// the results into one or multiple of the three textures (Color, Depth,
	// Stencil) of the given configuration.
	//
	// If the any of the configuration's formats are not supported by the
	// graphics hardware (i.e. not in GPUInfo.RTTFormats), then nil is
	// returned.
	//
	// If the given configuration is not valid (see the cfg.Valid method) then
	// a panic will occur.
	//
	// Any non-nil texture in the configuration will be set to loaded, will
	// have ClearData() called on it, and will have it's bounds set to
	// cfg.Bounds.
	RenderToTexture(cfg RTTConfig) Canvas
}

Device represents a graphics device and is capable of loading meshes, textures, and shaders. A device itself has a base canvas which can be drawn to (typically a window on the screen, for instance).

A devices method's are safe to call from multiple goroutines concurrently.

func Nil

func Nil() Device

Nil returns a device that does not actually draw anything.

type DeviceInfo

type DeviceInfo struct {
	// GL is a pointer to information about the OpenGL implementation, if the
	// device is a OpenGL device. Otherwise it is nil.
	GL *GLInfo

	// GLSL is a pointer to information about the GLSL implementation, if the
	// device is a OpenGL device. Otherwise it is nil.
	GLSL *GLSLInfo

	// MaxTextureSize is the maximum size of either X or Y dimension of texture
	// images for use with the device, or -1 if not available.
	MaxTextureSize int

	// Whether or not the AlphaToCoverage alpha mode is supported (if false
	// then BinaryAlpha will automatically be used as a fallback).
	AlphaToCoverage bool

	// Whether or not rendering objects with the DepthClamp state enabled is
	// supported.
	DepthClamp bool

	// Whether or not occlusion queries are supported or not.
	OcclusionQuery bool

	// The number of bits reserved for the sample count when performing
	// occlusion queries, if the number goes above what this many bits could
	// store then it is generally (but not always) clamped to that value.
	//
	// Some devices (e.g. OpenGL ES ones without certain extensions) only
	// support boolean occlusion queries (i.e. you can only tell if some
	// samples passed, but not how many specifically).
	OcclusionQueryBits int

	// The name of the graphics hardware, or an empty string if not available.
	// For example it may look something like:
	//
	//  Mesa DRI Intel(R) Sandybridge Mobile
	//
	Name string

	// The vendor name of the graphics hardware, or an empty string if not
	// available. For example:
	//
	//  Intel Open Source Technology Center
	//
	Vendor string

	// Whether or not the graphics hardware supports Non Power Of Two texture
	// sizes.
	//
	// If true, then textures may be any arbitrary size (while keeping in mind
	// this often incurs a performance cost, and does not work well with
	// compression or mipmapping).
	//
	// If false, then texture dimensions must be a power of two (e.g. 32x64,
	// 512x512, etc) or else the texture will be resized by the device to the
	// nearest power-of-two.
	NPOT bool

	// The formats available for render-to-texture (RTT).
	RTTFormats

	// Whether or not the graphics hardware supports the use of the BorderColor
	// TexWrap mode. If the hardware doesn't support it the device falls back
	// to the Clamp TexWrap mode in it's place.
	//
	// (Mobile) OpenGL ES 2 never supports BorderColor.
	//
	// (Desktop) OpenGL 2 always supports BorderColor.
	TexWrapBorderColor bool
}

DeviceInfo describes general information and limitations of the graphics device, such as the maximum texture size and other features which may or may not be supported by the graphics device.

type Downloadable

type Downloadable interface {
	// Download should download the given intersecting rectangle of this
	// downloadable image from the graphics hardware into system memory and
	// send it to the complete channel when done.
	//
	// If downloading this texture is impossible (i.e. hardware does not
	// support this) then nil will be sent over the channel and all future
	// attempts to download this texture will fail as well.
	//
	// It should be noted that the downloaded image may not be pixel-identical
	// to the previously uploaded source image of a texture, for instance if
	// texture compression was used it may suffer from compression artifacts,
	// etc.
	//
	// Only a texture created from render-to-texture is guaranteed to succeed,
	// others may not (esp. compressed textures). Most devices support
	// downloading RGB/A textures and some support depth/alpha ones.
	Download(r image.Rectangle, complete chan image.Image)
}

Downloadable represents a image that can be downloaded from the graphics hardware into system memory (e.g. for taking a screen-shot).

type FaceCullMode

type FaceCullMode uint8

FaceCullMode represents a single face culling mode. BackFaceCulling is the default (zero value).

const (
	// BackFaceCulling is a face culling mode for culling back faces only (i.e.
	// only the front side will be drawn).
	BackFaceCulling FaceCullMode = iota

	// FrontFaceCulling is a face culling mode for culling front faces only
	// (i.e. only the back side is drawn).
	FrontFaceCulling

	// NoFaceCulling is a face culling mode for culling no faces at all (i.e.
	// both sides will be drawn).
	NoFaceCulling
)

func (FaceCullMode) String

func (i FaceCullMode) String() string

type GLInfo

type GLInfo struct {
	// Major, minor, and release versions of the OpenGL version in use. For
	// example:
	//
	//  // OpenGL v2.1.3
	//  MajorVersion: 2
	//  MinorVersion: 1
	//  ReleaseVersion: 3
	//
	MajorVersion, MinorVersion, ReleaseVersion int

	// VendorVersion is a vendor/manufacturer specific version string. It can
	// be anything at all (and sometimes nothing), but is typically the driver
	// version in use. For example:
	//
	//  "Mesa 10.5.0-devel (git-b3721cd 2014-11-26 trusty-oibaf-ppa)"
	//  ""
	//
	VendorVersion string

	// A read-only slice of OpenGL extension strings.
	Extensions []string
}

GLInfo holds information about the OpenGL implementation.

func (*GLInfo) String

func (g *GLInfo) String() string

String returns a OpenGL version string like so:

"OpenGL v2.1 - Mesa 10.5.0-devel (git-b3721cd 2014-11-26 trusty-oibaf-ppa)"

func (*GLInfo) Version

func (g *GLInfo) Version() string

Version returns a version string like so:

"v1"
"v2.1"
"v2.1.1"

type GLSLInfo

type GLSLInfo struct {
	// Major, minor, and release versions of the OpenGL Shading Language
	// version present. For example:
	//
	//  // GLSL v1.30.2
	//  MajorVersion: 1
	//  MinorVersion: 30
	//  ReleaseVersion: 2
	//
	MajorVersion, MinorVersion, ReleaseVersion int

	// MaxVaryingFloats is the number of floating-point varying variables
	// available inside GLSL programs.
	//
	// Generally at least 32.
	MaxVaryingFloats int

	// MaxVertexInputs is the maximum number of vertex shader inputs (i.e.
	// floating-point values, where a 4x4 matrix is 16 floating-point values).
	//
	// Generally at least 512.
	MaxVertexInputs int

	// MaxFragmentInputs is the maximum number of fragment shader inputs (i.e.
	// floating-point values, where a 4x4 matrix is 16 floating-point values).
	//
	// Generally at least 64.
	MaxFragmentInputs int
}

GLSLInfo holds information about the GLSL implementation.

func (*GLSLInfo) String

func (g *GLSLInfo) String() string

String returns a GLSL version string like so:

"GLSL v1"

func (*GLSLInfo) Version

func (g *GLSLInfo) Version() string

Version returns a version string like so:

"v1"
"v2.1"
"v2.1.1"

type GLSLSources

type GLSLSources struct {
	// The GLSL vertex shader source code.
	Vertex []byte

	// The GLSL fragment shader source code.
	Fragment []byte
}

GLSLSources represents the sources to a GLSL shader program.

func (*GLSLSources) Copy

func (s *GLSLSources) Copy() *GLSLSources

Copy returns a deep copy of this shader and it's source byte slices.

type Mat4

type Mat4 [4][4]float32

Mat4 represents a 32-bit floating point 4x4 matrix for compatability with graphics hardware. lmath.Mat4 should be used anywhere that an explicit 32-bit type is not needed.

func ConvertMat4

func ConvertMat4(m lmath.Mat4) Mat4

ConvertMat4 converts the 64-bit lmath.Mat4 to a 32-bit Mat4 matrix.

func (Mat4) Mat4

func (m Mat4) Mat4() lmath.Mat4

Mat4 converts this 32-bit Mat4 to a 64-bit lmath.Mat4 matrix.

type Mesh

type Mesh struct {
	// The native object of this mesh. Once the mesh is loaded by a device this
	// field will be initialized by the device. Only device implementations
	// should assign values to this field.
	NativeMesh Destroyable

	// Weather or not this mesh is currently loaded or not.
	Loaded bool

	// The primitive type of this mesh. The zero-value (i.e. default value) is
	// Triangles.
	Primitive

	// If true then when this mesh is loaded the sources of it will be kept
	// instead of being set to nil (which allows them to be garbage collected).
	KeepDataOnLoad bool

	// Dynamic is a hint (it does not restrict how the mesh may be used) to the
	// graphics device on how this mesh might be used. If you intend to update
	// mesh data often (i.e. it's not static) then set this to true.
	Dynamic bool

	// AABB is the axis aligned bounding box of this mesh. There may not be one
	// if AABB.Empty() == true, but one can be calculate using the
	// CalculateBounds() method.
	AABB lmath.Rect3

	// A slice of indices, if non-nil then this slice contains indices into
	// each other slice (such as Vertices) and this is a indexed mesh.
	//
	// The indices are uint32 (instead of int) for compatability with graphics
	// hardware.
	Indices []uint32

	// Weather or not the indices have changed since the last time the mesh
	// was loaded. If set to true the device should take note and re-upload the
	// data slice to the graphics hardware.
	IndicesChanged bool

	// The slice of vertices for the mesh.
	Vertices []Vec3

	// Weather or not the vertices have changed since the last time the
	// mesh was loaded. If set to true the device should take note and
	// re-upload the data slice to the graphics hardware.
	VerticesChanged bool

	// The slice of vertex colors for the mesh.
	Colors []Color

	// Weather or not the vertex colors have changed since the last time
	// the mesh was loaded. If set to true the device should take note
	// and re-upload the data slice to the graphics hardware.
	ColorsChanged bool

	// The slice of normals for the mesh.
	Normals []Vec3

	// Weather or not the normals have changed since the last time the
	// mesh was loaded. If set to true the device should take note and
	// re-upload the data slice to the graphics hardware.
	NormalsChanged bool

	// A slice of barycentric coordinates for the mesh.
	Bary []Vec3

	// Whether or not the barycentric coordinates have changed since the last
	// time the mesh was loaded. If set to true the device should take note
	// and re-upload the data slice to the graphics hardware.
	BaryChanged bool

	// A slice of texture coordinate sets for the mesh, there may be
	// multiple sets which directly relate to multiple textures on a
	// object.
	TexCoords []TexCoordSet

	// A map of custom per-vertex attributes for the mesh. It is analogous to
	// the Colors, Bary, and TexCoords fields. It allows you to submit a set of
	// named custom per-vertex data to shaders.
	//
	// For instance you could submit a set of per-vertex vec3's with:
	//  myData := make([]gfx.Vec3, len(mesh.Vertices))
	//  mesh.Attribs["MyName"] = gfx.VertexAttrib{
	//      Data: myData,
	//  }
	//
	// If changes to the data are made, the data set will have to be uploaded
	// to the graphics hardware again, so you must inform the device when you
	// change the data:
	//  ... modify myData ...
	//  mesh.Attribs["MyName"].Changed = true
	//
	// In GLSL you could access that per-vertex data by writing:
	//  attribute vec3 MyName;
	//
	// Arrays of data are available in GLSL by slice indice suffixes:
	//  // Data declared in Go:
	//  myData := make([][]gfx.Mat4, 2)
	//
	//  // And in GLSL:
	//  attribute mat4 MyName0; // Per-vertex data from myData[0].
	//  attribute mat4 MyName1; // Per-vertex data from myData[1].
	//
	// See the documentation on the VertexAttrib type for more information
	// regarding what data types may be used.
	Attribs map[string]VertexAttrib
}

Mesh represents a single mesh made up of several components. A mesh may or may not be made up of indexed vertices, etc, depending on whether or not len(m.Indices) == 0 holds true.

In the event that a mesh is indexed, m.Indices holds the indices and it can be expected that each other slice (Vertices for instance) will hold at least enough elements (or be nil) such that the each index will not be out of bounds.

A mesh and it's methods are not safe for access from multiple goroutines concurrently.

func NewMesh

func NewMesh() *Mesh

NewMesh returns a new *Mesh, for effeciency it may be a re-used one (see the Destroy method) whose slices have zero-lengths.

func (*Mesh) Append

func (m *Mesh) Append(other *Mesh)

Append appends the other mesh's data slices to this one.

This function can properly maintain the existing index type of a mesh, so that in any of the following cases:

mesh.Append(mesh)
indexedMesh.Append(indexedMesh)
indexedMesh.Append(mesh)
mesh.Append(indexedMesh)

The original mesh's indexing is kept: anything appended to an indexed mesh always ends up as an indexed mesh, and vice versa.

Only data slices that both meshes have in common are kept: e.g. if only one mesh has vertex colors, the mesh (m) will have it's vertex colors set to nil. You can check which data slices are in common by comparing the states of both meshes (see the MeshState documentation).

func (*Mesh) Bounds

func (m *Mesh) Bounds() lmath.Rect3

Bounds implements the Boundable interface. If the AABB of this mesh is empty then the bounds are calculated.

func (*Mesh) CalculateBounds

func (m *Mesh) CalculateBounds()

CalculateBounds calculates a new axis aligned bounding box for this mesh.

func (*Mesh) ClearData

func (m *Mesh) ClearData()

ClearData sets the data slices of this mesh to nil if m.KeepDataOnLoad is set to false.

func (*Mesh) Copy

func (m *Mesh) Copy() *Mesh

Copy returns a new copy of this Mesh. Depending on how large the mesh is this may be an expensive operation. Explicitly not copied over is the native mesh, the OnLoad slice, and the loaded and changed statuses (Loaded, IndicesChanged, VerticesChanged, etc).

func (*Mesh) Destroy

func (m *Mesh) Destroy()

Destroy destroys this mesh for use by other callees to NewMesh. You must not use it after calling this method. This makes an implicit call to m.NativeMesh.Destroy.

func (*Mesh) GenerateBary

func (m *Mesh) GenerateBary()

GenerateBary generates the barycentric coordinates for this mesh.

func (*Mesh) HasChanged

func (m *Mesh) HasChanged() bool

HasChanged tells if any of the data slices of the mesh are marked as having changed.

func (*Mesh) Reset

func (m *Mesh) Reset()

Reset resets this mesh to it's default (NewMesh) state.

func (*Mesh) State

func (m *Mesh) State(s *MeshState)

State fills the given MeshState structure with information regarding the current state of this mesh. For example:

var state = &MeshState{}
mesh.State(&state) // Fill the state structure with the mesh's state.

type MeshState

type MeshState struct {
	// Whether or not indices, vertices, etc are present in the mesh.
	Indices, Vertices, Colors, Normals, Bary bool

	// How many texture coordinate sets are present in the mesh. The boolean
	// value signifies whether the len(texCoord.Slice) > 0 or not.
	TexCoords []bool

	// A map of attribute names to boolean values signifying whether the
	// len(attrib.Data) > 0 or not.
	Attribs map[string]bool
}

MeshState represents the state that a mesh is in: specifically what data slices it has present (i.e. does it have vertex colors, normals, etc).

A mesh state can be used to determine what the difference is between two meshes:

var stateA, stateB gfx.MeshState
meshA.State(&stateA) // Query mesh A's state.
meshB.State(&stateB) // Query mesh B's state.

// Calculate the difference between the two states.
anyDiff := stateA.Diff(stateB)
if anyDiff {
    // The two mesh states have a difference of some sort (i.e. one has
    // vertex colors and the other does not). Appending them together would
    // result in some sort of data loss (describes by the stateA receiver
    // struct)

    // We can check directly by looking at the results of the diff:
    if stateA.Normals {
        // Now we're certain that one mesh has normals and the other does
        // not. Appending the two meshes together would result in the loss
        // of the normals.
    }
}

It can also be used to directly tell if two meshes could be appended together without losing any data from either mesh:

var stateA, stateB gfx.MeshState
meshA.State(&stateA) // Query mesh A's state.
meshB.State(&stateB) // Query mesh B's state.

// Check the two states for equality.
if stateA.Equals(stateB) {
    // The meshes can be appended together with no loss of information.
}

If your only intent is to query if a mesh has a given data slice, you can check it yourself directly yourself:

hasNormals := len(mesh.Normals) > 0

func (*MeshState) Diff

func (s *MeshState) Diff(a, b *MeshState) bool

Diff calculates the difference between the mesh states a and b, the result is stored inside of s.

If there is any difference between the two, true is returned.

func (*MeshState) Equals

func (s *MeshState) Equals(other *MeshState) bool

Equals tells if this mesh state is equal to the other one.

type NativeObject

type NativeObject interface {
	Destroyable

	// If the GPU supports occlusion queries (see GPUInfo.OcclusionQuery) and
	// OcclusionTest is set to true on the graphics object, then this method
	// will return the number of samples that passed the depth and stencil
	// testing phases the last time the object was drawn. If occlusion queries
	// are not supported then -1 will be returned.
	SampleCount() int
}

NativeObject represents a native graphics object, they are normally only created by devices.

type NativeTexture

type NativeTexture interface {
	Destroyable
	Downloadable

	// ChosenFormat tells the texture format chosen by the device for storing
	// this texture on the graphics device. It may differ from the Texture's
	// Format field only if the graphics device does not support that format.
	ChosenFormat() TexFormat
}

NativeTexture represents the native object of a *Texture, the device is responsible for creating these and fulfilling the interface.

type Object

type Object struct {
	// The native object of this graphics object. The device using this
	// graphics object will assign a value to this field once ownership of the
	// object has been passed back to the caller of Draw.
	NativeObject

	// Whether or not this object should be occlusion tested. See also the
	// SampleCount() method of NativeObject.
	OcclusionTest bool

	// The render state of this object.
	*State

	// The transformation of the object.
	*Transform

	// The shader program to be used during drawing the object.
	*Shader

	// A slice of meshes which make up the object. The order in which the
	// meshes appear in this slice also affects the order in which they are
	// sent to the graphics card.
	//
	// This is a slice specifically to allow device implementations to optimize
	// the number of draw calls that must occur to draw consecutively listed
	// meshes.
	Meshes []*Mesh

	// A slice of textures which are used to texture the meshes of this object.
	// The order in which the textures appear in this slice is also the order
	// in which they are sent to the graphics card.
	Textures []*Texture

	// CachedBounds represents the pre-calculated cached bounding box of this
	// object. Note that the bounds are only calculated once Object.Bounds() is
	// invoked.
	//
	// If you make changes to the vertices of any mesh associated with this
	// object, or if you add / remove meshes from this object, the bounds will
	// not reflect this automatically. Instead, you must clear the cached
	// bounds explicitly:
	//
	//  o.CachedBounds = nil
	//
	// And then simply invoke o.Bounds() again to calculate the bounds again.
	CachedBounds *lmath.Rect3
}

Object represents a single graphics object for drawing, it has a transformation matrix which is applied to each vertex of each mesh, it has a shader program, meshes, and textures used for drawing the object.

A graphics object and it's methods are not safe for access from multiple goroutines concurrently.

func NewObject

func NewObject() *Object

NewObject creates and returns a new object with:

o.Transform == NewTransform()

func (*Object) Bounds

func (o *Object) Bounds() lmath.Rect3

Bounds implements the Boundable interface. The returned bounding box takes into account all of the mesh's bounding boxes, transformed into world space.

The bounding box is cached (see o.CachedBounds) so that multiple calls to this method are fast. If you make changes to the vertices, or add/remove meshes from this object you need to explicitly clear the cached bounds so that the next call to Bounds() will calculate the bounding box again:

o.CachedBounds = nil

You do not need to clear the cached bounds if the transform of the object has changed (as it is applied after calculation of the bounding box).

func (*Object) Compare

func (o *Object) Compare(other *Object) bool

Compare compares this object's state (including shader and textures) against the other one and determines if it should sort before the other one for state sorting purposes.

func (*Object) Copy

func (o *Object) Copy() *Object

Copy returns a new copy of this Object. Explicitily not copied is the native object. The transform is copied via it's Copy() method.

The state, shader, meshes, and textures are all shallow copies only (i.e. only the pointer values are copied).

func (*Object) Destroy

func (o *Object) Destroy()

Destroy destroys this object for use by other callees to NewObject. You must not use it after calling this method. This makes an implicit call to o.NativeObject.Destroy.

func (*Object) Reset

func (o *Object) Reset()

Reset resets this object to it's default (NewObject) state.

type Precision

type Precision struct {
	// The precision in bits of each pixel in the color buffer, per color (e.g.
	// 8/8/8/8 would be 32bpp RGBA color, 8/8/8/0 would be 24bpp RGB color, and
	// so on).
	RedBits, GreenBits, BlueBits, AlphaBits uint8

	// The precision in bits of each pixel in the depth buffer (e.g. 8, 16, 24,
	// etc).
	DepthBits uint8

	// The precision in bits of each pixel in the stencil buffer (e.g. 8, 16,
	// 24, etc).
	StencilBits uint8

	// The number of samples available per pixel (e.g. the number of MSAA
	// samples).
	Samples int
}

Precision represents the precision in bits of the color, depth, and stencil buffers as well as the number of samples per pixel.

type Primitive

type Primitive uint8

Primitive represents a single primitive type.

const (
	// Triangles is a primitive type where each three mesh vertices forms a
	// single triangle.
	Triangles Primitive = iota

	// Lines is a primitive type where each two mesh vertices form a single
	// 1px wide line.
	//
	// Lines are restricted to 1px wide by the physical graphics hardware, if
	// you need wider lines you should form them from triangles.
	Lines

	// Points is a primitive type where each mesh vertex forms a single point
	// whose size is determined by the shader.
	Points
)

func (Primitive) String

func (i Primitive) String() string

type RTTConfig

type RTTConfig struct {
	// Bounds is the target resolution of the canvas to render at.
	Bounds image.Rectangle

	// The number of samples to use for multisampling. It should be one of the
	// numbers listed in the GPUInfo.RTTFormats structure.
	Samples int

	// Color, Depth, and Stencil textures, each of these texture's Format
	// fields are explicitly ignored (see the format fields below). If any of
	// these textures are non-nil, the results of that buffer (e.g. the color
	// buffer) are stored into that texture.
	//
	// Specify nil for any you do not intend to use as a texture (e.g. if you
	// want a 16-bit depth buffer but do not intend to use it as a texture, you
	// should set Depth == nil and DepthFormat == Depth16).
	Color, Depth, Stencil *Texture

	// Color format to use for the color buffer, it should be one listed in the
	// GPUInfo.RTTFormats structure.
	ColorFormat TexFormat

	// Depth and Stencil formats to use for the depth and stencil buffers,
	// respectively. They should be ones listed in the GPUInfo.RTTFormats
	// structure.
	//
	// Combined depth and stencil formats can be used (e.g. by setting
	// both DepthFormat and StencilFormat to Depth24AndStencil8), they are
	// often faster and use less memory, but with the caveat that they cannot
	// be used as textures.
	DepthFormat, StencilFormat DSFormat
}

RTTConfig represents a configuration used for creating a render-to-texture (RTT) canvas. At least one of Color, Depth, or Stencil textures must be non nil.

func (RTTConfig) Valid

func (c RTTConfig) Valid() bool

Valid tells if this render-to-texture (RTT) configuration is valid or not, a configuration is considered invalid if:

  1. It's bounding rectangle is empty.
  2. All three textures are nil.
  3. Any non-nil texture is not accompanies by a format.
  4. Either DepthFormat.IsCombined() or StencilFormat.IsCombined() and the other is not.

type RTTFormats

type RTTFormats struct {
	// Slice of sample counts available for multisampling.
	Samples []int

	// Slice of color buffer formats.
	ColorFormats []TexFormat

	// Slices of depth and stencil buffer formats.
	DepthFormats, StencilFormats []DSFormat
}

RTTFormats represents color, depth, and stencil buffer formats applicable to render-to-texture (RTT).

func (RTTFormats) Choose

func (f RTTFormats) Choose(p Precision, compression bool) (color TexFormat, depth, stencil DSFormat)

Choose returns a color, depth, and stencil format from the formats, f. It tries to choose the most applicable one to the requested precision. If compression is true, it tries to choose the most compressed format.

func (RTTFormats) ChooseConfig

func (f RTTFormats) ChooseConfig(p Precision, compression bool) RTTConfig

ChooseConfig is short-hand for:

colorFormat, depthFormat, stencilFormat := f.Choose(p, compression)
cfg := RTTConfig{
    ColorFormat: colorFormat,
    DepthFormat: depthFormat,
    StencilFormat: stencilFormat,
}

type Shader

type Shader struct {
	// The native object of this shader. Once the shader is loaded (if no
	// compiler error occured) then this field will be initialized by the
	// device. Only device implementations should assign values to this field.
	NativeShader Destroyable

	// Weather or not this shader is currently loaded or not.
	Loaded bool

	// If true then when this shader is loaded the data sources of it will be
	// kept instead of being set to nil (which allows them to be garbage
	// collected).
	KeepDataOnLoad bool

	// The name of the shader, optional (used in the shader compilation error
	// log).
	Name string

	// GLSL represents the sources to the GLSL shader. Only OpenGL devices
	// support GLSL, so you can check for this:
	//
	//  if device.Info().GLSL != nil {
	//      // Device supports GLSL shaders.
	//  }
	//
	GLSL *GLSLSources

	// A map of names and values to use as inputs for the shader program while
	// rendering. Values must be of the following data types or else they will
	// be ignored:
	//
	//  bool
	//  float32
	//  []float32
	//  gfx.Vec3
	//  []gfx.Vec3
	//  gfx.Vec4
	//  []gfx.Vec4
	//  gfx.Mat4
	//  []gfx.Mat4
	//  gfx.Color
	//  []gfx.Color
	//  gfx.TexCoord
	//  []gfx.TexCoord
	//
	Inputs map[string]interface{}

	// The error log from compiling the shader program, if any. Only set once
	// the shader is loaded.
	Error []byte
}

Shader represents a single shader program.

A shader and it's methods are not safe for access from multiple goroutines concurrently.

func NewShader

func NewShader(name string) *Shader

NewShader returns a new, initialized *Shader object with the given name.

func (*Shader) ClearData

func (s *Shader) ClearData()

ClearData sets the data slices (s.GLSLVert, s.Error, etc) of this shader to nil if s.KeepDataOnLoad is set to false.

func (*Shader) Copy

func (s *Shader) Copy() *Shader

Copy returns a new copy of this Shader. Explicitly not copied over is the native shader, the OnLoad slice, the Loaded status, and error log slice.

func (*Shader) Destroy

func (s *Shader) Destroy()

Destroy destroys this shader for use by other callees to NewShader. You must not use it after calling this method. This makes an implicit call to s.NativeShader.Destroy.

func (*Shader) Reset

func (s *Shader) Reset()

Reset resets this shader to it's default (NewShader) state.

type State

type State struct {
	// A single alpha transparency mode describing how transparent parts of
	// of the object are to be drawn.
	//
	// Must be one of: NoAlpha, AlphaBlend, BinaryAlpha, AlphaToCoverage
	AlphaMode AlphaMode

	// Blend represents how blending between existing (source) and new
	// (destination) pixels in the color buffer occurs when AlphaMode ==
	// AlphaBlend.
	Blend BlendState

	// Whether or not red/green/blue/alpha should be written to the color
	// buffer or not when drawing the object.
	WriteRed, WriteGreen, WriteBlue, WriteAlpha bool

	// Whether or not dithering should be used when drawing the object.
	Dithering bool

	// DepthClamp when enabled effectively disables the near and far clipping
	// planes when drawing the object.
	DepthClamp bool

	// Whether or not depth testing and depth writing should be enabled when
	// drawing the object.
	DepthTest, DepthWrite bool

	// The comparison operator to use for depth testing against existing pixels
	// in the depth buffer.
	DepthCmp Cmp

	// Whether or not stencil testing should be enabled when drawing the
	// object.
	StencilTest bool

	// Whether or not (and how) face culling should occur when drawing the
	// object.
	//
	// Must be one of: BackFaceCulling, FrontFaceCulling, NoFaceCulling
	FaceCulling FaceCullMode

	// The stencil state for front and back facing pixels, respectively.
	StencilFront, StencilBack StencilState
}

State represents a generic set of graphics state properties to be used when drawing a graphics object. Changes to such properties across multiple draw calls (called 'graphics state changes' or sometimes 'render state changes') have a performance cost.

The performance penalty mentioned depends on several factors (graphics hardware, drivers, the specific property being changed, etc). The important factor to recognize is that multiple draw calls are faster when the objects being draw would cause less changes to the graphics state than the previously drawn object.

func NewState

func NewState() *State

NewState returns a new initialized state with the default properties.

func (*State) Compare

func (s *State) Compare(other *State) bool

Compare compares this state against the other one using DefaultState as a reference when inequality occurs and returns whether or not this state should sort before the other one for purposes of state sorting.

func (*State) Copy

func (s *State) Copy() *State

Copy returns a copy of this state, it is short-handed for:

cpy := *s
return &cpy

func (*State) Destroy

func (s *State) Destroy()

Destroy destroys this state for use by other callees to NewState. You must not use it after calling this method.

func (*State) Reset

func (s *State) Reset()

Reset resets the state to it's default state.

type StencilOp

type StencilOp uint8

StencilOp represents a single stencil operation to occur when the stencil function passes, like SKeep, SReplace, etc.

const (
	// SKeep keeps the existing stencil data.
	SKeep StencilOp = iota

	// SZero sets the stencil data to zero.
	SZero

	// SReplace replaces the existing stencil data with the stencil reference
	// value.
	SReplace

	// SIncr increments the stencil value by one and clamps the result.
	SIncr

	// SIncrWrap increments the stencil value by 1 and wraps the result if
	// necessary.
	SIncrWrap

	// SDecr decrements the stencil value by one and clamps the result.
	SDecr

	// SDecrWrap decrements the stencil value by 1 and wraps the result if
	// necessary.
	SDecrWrap

	// SInvert inverts the stencil data.
	SInvert
)

type StencilState

type StencilState struct {
	// A mask that will be AND'd with each pixel to be written to the stencil
	// buffer, e.g. 0xFFFF would allow writing to the full range of every pixel
	// in the stencil buffer when drawing the object.
	WriteMask uint

	// A mask that will be AND'd with each pixel to be read/compared to the
	// existing value in the stencil buffer, e.g. 0xFFFF would disable the use
	// of the mask altogether.
	ReadMask uint

	// The reference value that will be used to compare existing values in the
	// stencil buffer against, e.g. if s.Reference == 2 and if s.Func ==
	// GreaterOrEqual, then any value below 2 would not be affected.
	Reference uint

	// Fail specifies what stencil operation should occur when the stencil test
	// fails.
	//
	// Any predefined StencilOp constant is accepted.
	Fail StencilOp

	// DepthFail specifies what stencil operation should occur when the stencil
	// test passes but the depth test fails.
	//
	// Any predefined StencilOp constant is accepted.
	DepthFail StencilOp

	// DepthPass specifies what stencil operation should occur when the stencil
	// test passes and the depth test passes.
	//
	// Any predefined StencilOp constant is accepted.
	DepthPass StencilOp

	// Cmp specifies the comparison operator to use when comparing stencil data
	// with existing data in the stencil buffer.
	//
	// Any predefined Cmp constant is accepted.
	Cmp Cmp
}

StencilState represents the state to use when the stencil test occurs for a front or back facing pixel of an object during drawing. If written in Go it would look something like:

if (s.Reference & s.ReadMask) s.Cmp (stencilValue & s.ReadMask) {
    if depthTestFailed {
        stencilValue = s.DepthFail() & s.WriteMask
    } else {
        stencilValue = s.DepthPass() & s.WriteMask
    }
} else {
    stencilValue = s.Fail() & s.WriteMask
}

func (StencilState) Compare

func (s StencilState) Compare(other StencilState) bool

Compare compares this state against the other one using DefaultStencilState as a reference when inequality occurs and returns whether or not this state should sort before the other one for purposes of state sorting.

type TexCoord

type TexCoord struct {
	U, V float32
}

TexCoord represents a 2D texture coordinate with U and V components.

type TexCoordSet

type TexCoordSet struct {
	// The slice of texture coordinates for the set.
	Slice []TexCoord

	// Weather or not the texture coordinates of this set have changed since
	// the last time the mesh was loaded. If set to true the device should
	// take note and re-upload the data slice to the graphics hardware.
	Changed bool
}

TexCoordSet represents a single texture coordinate set for a mesh.

type TexFilter

type TexFilter uint8

TexFilter represents a single texture filter to be used for minification or magnification of a texture during drawing.

const (
	// Nearest samples the nearest pixel.
	Nearest TexFilter = iota

	// Linear samples the four closest pixels and linearly interpolates them.
	Linear

	// NearestMipmapNearest samples the pixel from the nearest mipmap, it may
	// not be used as a magnification filter.
	NearestMipmapNearest

	// LinearMipmapNearest (AKA Bilinear filtering) samples the pixel from the
	// nearest mipmap.
	//
	// It may not be used as a magnification filter.
	LinearMipmapNearest

	// NearestMipmapLinear samples the pixel from the two closest mipmaps, and
	// linearly blends the result.
	//
	// It may not be used as a magnification filter.
	NearestMipmapLinear

	// LinearMipmapLinear (AKA Trilinear filtering) bilinearly filters the
	// pixel from the two mipmaps, and linear blends the result.
	//
	// It may not be used as a magnification filter.
	LinearMipmapLinear
)

func (TexFilter) Mipmapped

func (t TexFilter) Mipmapped() bool

Mipmapped tells if the texture filter is a mipmapped one, that is one of:

NearestMipmapNearest
LinearMipmapNearest
NearestMipmapLinear
LinearMipmapLinear

func (TexFilter) String

func (i TexFilter) String() string

type TexFormat

type TexFormat uint8

TexFormat specifies a single texture storage format.

const (
	// ZeroTexFormat is the zero-value texture format, it is not a valid format
	// and is mainly used to catch zero-value errors.
	ZeroTexFormat TexFormat = iota

	// RGBA is a standard 32-bit premultiplied alpha image format.
	RGBA

	// RGB is a standard 24-bit RGB image format with no alpha component.
	RGB

	// DXT1 is a DXT1 texture compression format in RGB form (i.e. fully
	// opaque) each 4x4 block of pixels take up 64-bits of data, as such when
	// compared to a standard 24-bit RGB format it provides a 6:1 compression
	// ratio.
	DXT1

	// DXT1RGBA is a DXT1 texture compression format in RGBA form with 1 bit
	// reserved for alpha (i.e. fully transparent or fully opaque per-pixel
	// transparency).
	DXT1RGBA

	// DXT3 is a RGBA texture compression format with four bits per pixel
	// reserved for alpha. Each 4x4 block of pixels take up 128-bits of data,
	// as such when compared to a standard 32-bit RGBA format it provides a 4:1
	// compression ratio. Color information stored in DXT3 is mostly the same
	// as DXT1.
	DXT3

	// DXT5 is a RGBA format similar to DXT3 except it compresses the alpha
	// chunk in a similar manner to DXT1's color storage. It provides the same
	// 4:1 compression ratio as DXT3.
	DXT5
)

func (TexFormat) Bits

func (t TexFormat) Bits() (r, g, b, a uint8)

Bits returns the number of bits per color component in this texture format. For example:

r, g, b, a := RGB.Bits()
r == 8 && g == 8 && b == 8 && a == 0

A panic will occur if the format is not one of the predefined ones in this package.

ZeroTexFormat, DXT1, DXT3, and DXT5 formats will return only zero.

func (TexFormat) String

func (i TexFormat) String() string

type TexWrap

type TexWrap uint8

TexWrap represents a single way that the extra area of a texture wraps around a mesh.

const (
	// Repeat repeats the extra area of the texture into infinity.
	Repeat TexWrap = iota

	// Clamp clamps the extra area of the texture by stretching the edge pixels
	// out into infinity.
	Clamp

	// BorderColor represents the extra area of the texture by the border color
	// specified on the Texture object.
	//
	// Not all devices support BorderColor (See DeviceInfo.TexWrapBorderColor
	// for more information). To check for support:
	//
	//  if devInfo.TexWrapBorderColor {
	//      // Have BorderColor support.
	//  }
	//
	// Devices fall back to the Clamp TexWrap mode in the event that you
	// attempt to use it and the device does not support it.
	BorderColor

	// Mirror represents the extra area of the texture by mirroring itself into
	// infinity.
	Mirror
)

func (TexWrap) String

func (i TexWrap) String() string

type Texture

type Texture struct {
	// The native object of this texture. Once the texture is loaded by a
	// device this field will be initialized by the device. Only device
	// implementations should assign values to this field.
	NativeTexture

	// Weather or not this texture is currently loaded or not. If Loaded is set
	// false on a already-loaded texture, it will cause the device to reload
	// the texture.
	Loaded bool

	// If true then when this texture is loaded the data image source of it
	// will be kept instead of being set to nil (which allows it to be garbage
	// collected).
	KeepDataOnLoad bool

	// Dynamic is a hint (it does not restrict how the texture may be used) to
	// the graphics device on how this texture might be used. If you intend to
	// update texture data often (i.e. it's not static) then set this to true.
	Dynamic bool

	// The bounds of the texture, in the case of a texture loaded from a image
	// this should be set to the image's bounds. In the case of rendering to a
	// texture this should be set to the desired canvas resolution.
	Bounds image.Rectangle

	// The source image of the texture, may be nil (i.e. in the case of render
	// to texture, unless downloaded).
	Source image.Image

	// The texture format to use for storing this texture on the GPU, which may
	// result in lossy conversions (e.g. RGB would lose the alpha channel, etc).
	//
	// If the format is not supported then the device may use an image format
	// that is similar and is supported (and the format chosen by the device
	// can be determined via NativeTexture's ChosenFormat method).
	Format TexFormat

	// The U and V wrap modes of this texture.
	WrapU, WrapV TexWrap

	// The color of the border when a wrap mode is set to BorderColor.
	BorderColor Color

	// The texture filtering used for minification and magnification of the
	// texture.
	MinFilter, MagFilter TexFilter
}

Texture represents a single 2D texture that may be applied to a mesh for drawing.

A texture and it's methods are not safe for access from multiple goroutines concurrently.

func NewTexture

func NewTexture() *Texture

NewTexture returns a new, initialized *Texture object.

func (*Texture) ClearData

func (t *Texture) ClearData()

ClearData sets the data source image, t.Source, of this texture to nil if t.KeepDataOnLoad is set to false.

func (*Texture) Copy

func (t *Texture) Copy() *Texture

Copy returns a new copy of this Texture. Explicitly not copied over is the native texture, the OnLoad slice, the Loaded status, and the source image (because the image type is not strictly known). Because the texture's source image is not copied over, you may want to copy it directly over yourself.

func (*Texture) Destroy

func (t *Texture) Destroy()

Destroy destroys this texture for use by other callees to NewTexture. You must not use it after calling this method. This makes an implicit call to t.NativeTexture.Destroy.

func (*Texture) Reset

func (t *Texture) Reset()

Reset resets this texture to it's default (NewTexture) state.

type Transform

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

Transform represents a 3D transformation to a coordinate space. A transform effectively defines the position, scale, shear, etc of the local space, therefore it is sometimes said that a Transform is a coordinate space.

It can be safely used from multiple goroutines concurrently. It is built from various components such as position, scale, and shear values and may use euler or quaternion rotation. It supports a hierarchial tree system of transforms to create complex transformations.

When in doubt about coordinate spaces it can be helpful to think about the fact that each vertex of an object is considered to be in it's local space and is then converted to world space for display.

Since world space serves as the common factor among all transforms (i.e. any value in any transform's local space can be converted to world space and back) converting between world and local/parent space can be extremely useful for e.g. relative movement/rotation to another object's transform.

func NewTransform

func NewTransform() *Transform

NewTransform returns a new *Transform with the default values (a uniform scale of one).

func (*Transform) Convert

func (t *Transform) Convert(c CoordConv) lmath.Mat4

Convert returns a matrix which performs the given coordinate space conversion.

func (*Transform) ConvertPos

func (t *Transform) ConvertPos(p lmath.Vec3, c CoordConv) lmath.Vec3

ConvertPos converts the given point, p, using the given coordinate space conversion. For instance to convert a point in local space into world space:

t.ConvertPos(p, LocalToWorld)

func (*Transform) ConvertRot

func (t *Transform) ConvertRot(r lmath.Vec3, c CoordConv) lmath.Vec3

ConvertRot converts the given rotation, r, using the given coordinate space conversion. For instance to convert a rotation in local space into world space:

t.ConvertRot(p, LocalToWorld)

func (*Transform) Copy

func (t *Transform) Copy() *Transform

Copy returns a new transform with all of it's values set equal to t (i.e. a copy of this transform).

func (*Transform) Destroy

func (t *Transform) Destroy()

Destroy destroys this transform for use by other callees to NewTransform. You must not use it after calling this method.

func (*Transform) Equals

func (t *Transform) Equals(other *Transform) bool

Equals tells if the two transforms are equal.

func (*Transform) IsQuat

func (t *Transform) IsQuat() bool

IsQuat tells if this transform is currently utilizing quaternion or euler rotation.

The last call to either SetQuat or SetRot is what effictively determines whether quaternion or euler rotation will be used by this transform.

func (*Transform) LocalMat4

func (t *Transform) LocalMat4() lmath.Mat4

LocalMat4 returns a matrix describing the space that this transform defines. It is the matrix that is built out of the components of this transform, it does not include any parent transformation, etc.

func (*Transform) Mat4

func (t *Transform) Mat4() lmath.Mat4

Mat4 is short-hand for:

return t.Convert(LocalToWorld)

func (*Transform) New

func (t *Transform) New() *Transform

New returns a new transform whose child is this one. It is short-handed for:

ret := NewTransform()
ret.SetParent(t)

func (*Transform) Parent

func (t *Transform) Parent() Transformable

Parent returns the parent of this transform, as previously set.

func (*Transform) Pos

func (t *Transform) Pos() lmath.Vec3

Pos returns the local position of this transform.

func (*Transform) Quat

func (t *Transform) Quat() lmath.Quat

Quat returns the quaternion rotation of this transform. If this transform is instead using euler rotation (see IsQuat) then a quaternion is created from the euler rotation of this transform and returned.

The last call to either SetQuat or SetRot is what effictively determines whether quaternion or euler rotation will be used by this transform.

func (*Transform) Reset

func (t *Transform) Reset()

Reset sets all of the values of this transform to the default ones.

func (*Transform) Rot

func (t *Transform) Rot() lmath.Vec3

Rot returns the euler rotation of this transform. If this transform is instead using quaternion (see IsQuat) rotation then it is converted to euler rotation and returned.

The last call to either SetQuat or SetRot is what effictively determines whether quaternion or euler rotation will be used by this transform.

func (*Transform) Scale

func (t *Transform) Scale() lmath.Vec3

Scale returns the local scacle of this transform.

func (*Transform) SetParent

func (t *Transform) SetParent(p Transformable)

SetParent sets a parent transform for this transform to effectively inherit from. This allows creating complex hierarchies of transformations.

e.g. setting the parent of a camera's transform to the player's transform makes it such that the camera follows the player.

func (*Transform) SetPos

func (t *Transform) SetPos(p lmath.Vec3)

SetPos sets the local position of this transform.

func (*Transform) SetQuat

func (t *Transform) SetQuat(q lmath.Quat)

SetQuat sets the quaternion rotation of this transform.

The last call to either SetQuat or SetRot is what effictively determines whether quaternion or euler rotation will be used by this transform.

func (*Transform) SetRot

func (t *Transform) SetRot(r lmath.Vec3)

SetRot sets the euler rotation of this transform in degrees about their respective axis (e.g. if r.X == 45 then it is 45 degrees around the X axis).

The last call to either SetQuat or SetRot is what effictively determines whether quaternion or euler rotation will be used by this transform.

func (*Transform) SetScale

func (t *Transform) SetScale(s lmath.Vec3)

SetScale sets the local scale of this transform (e.g. a scale of lmath.Vec3{2, 1.5, 1} would make an object appear twice as large on the local X axis, one and a half times larger on the local Y axis, and would not scale on the local Z axis at all).

func (*Transform) SetShear

func (t *Transform) SetShear(s lmath.Vec3)

SetShear sets the local shear of this transform.

func (*Transform) Shear

func (t *Transform) Shear() lmath.Vec3

Shear returns the local shear of this transform.

func (*Transform) Transform

func (t *Transform) Transform() *Transform

Transform implements the Transformable interface by simply returning t.

type Transformable

type Transformable interface {
	Transform() *Transform
}

Transformable represents a generic interface to any object that can return it's transformation.

type Vec3

type Vec3 struct {
	X, Y, Z float32
}

Vec3 represents a 32-bit floating point three-component vector for compatability with graphics hardware. lmath.Vec3 should be used anywhere that an explicit 32-bit type is not needed.

func ConvertVec3

func ConvertVec3(v lmath.Vec3) Vec3

ConvertVec3 converts the 64-bit lmath.Vec3 to a 32-bit Vec3 vector.

func (Vec3) Vec3

func (v Vec3) Vec3() lmath.Vec3

Vec3 converts this 32-bit Vec3 to a 64-bit lmath.Vec3 vector.

type Vec4

type Vec4 struct {
	X, Y, Z, W float32
}

Vec4 represents a 32-bit floating point four-component vector for compatability with graphics hardware. lmath.Vec4 should be used anywhere that an explicit 32-bit type is not needed.

func ConvertVec4

func ConvertVec4(v lmath.Vec4) Vec4

ConvertVec4 converts the 64-bit lmath.Vec4 to a 32-bit Vec4 vector.

func (Vec4) Vec4

func (v Vec4) Vec4() lmath.Vec4

Vec4 converts this 32-bit Vec4 to a 64-bit lmath.Vec4 vector.

type VertexAttrib

type VertexAttrib struct {
	// The literal per-vertex data slice. It must be a slice whose length is
	// exactly the same as the mesh's Vertices slice (because it is literally
	// per-vertex data). The underlying type must be one of the following or
	// else the attribute may be ignored completely:
	//  []float32
	//  [][]float32
	//  []gfx.Vec3
	//  [][]gfx.Vec3
	//  []gfx.Vec4
	//  [][]gfx.Vec4
	//  []gfx.Mat4
	//  [][]gfx.Mat4
	//  []gfx.Color
	//  [][]gfx.Color
	//  []gfx.TexCoord
	//  [][]gfx.TexCoord
	Data interface{}

	// Weather or not the per-vertex data (see the Data field) has changed
	// since the last time the mesh was loaded. If set to true the device
	// should take note and re-upload the data slice to the device's memory.
	Changed bool
}

VertexAttrib represents a per-vertex attribute.

func (VertexAttrib) Copy

func (a VertexAttrib) Copy() VertexAttrib

Copy returns a new copy of this vertex attribute data set. It makes a deep copy of the underlying Data slice. Explicitly not copied is the Changed boolean.

Directories

Path Synopsis
Package camera provides a basic 2D and 3D camera implementation.
Package camera provides a basic 2D and 3D camera implementation.
Package clock measures frame-based application performance.
Package clock measures frame-based application performance.
Package gfxutil implements basic gfx utilities.
Package gfxutil implements basic gfx utilities.
Package gl2 provides a OpenGL 2 based graphics device.
Package gl2 provides a OpenGL 2 based graphics device.
gl/2.0/gl
Package gl implements Go bindings to OpenGL.
Package gl implements Go bindings to OpenGL.
glc
gles2/2.0/gles2
Package gles2 implements Go bindings to OpenGL.
Package gles2 implements Go bindings to OpenGL.
tag
Package tag simply exposes a few build tags as constants.
Package tag simply exposes a few build tags as constants.
Package webgl provides a WebGL graphics device.
Package webgl provides a WebGL graphics device.
Package window is the easiest way to open a window and draw graphics.
Package window is the easiest way to open a window and draw graphics.

Jump to

Keyboard shortcuts

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