gfx

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2014 License: BSD-3-Clause Imports: 8 Imported by: 0

README

Azul3D - gfx

This package provides generic interfaces to GPU-based rendering techniques.

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

Version 1.0.1

  • Documentation
  • azul3d.org/gfx.v1
  • import "azul3d.org/gfx.v1"
  • Changes
  • Fixed a bug causing Transforms to be constantly recalculated (see #16).

Version 1

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 where the origin (0, 0) is the bottom-left, instead the origin (0, 0) is the top-left because:

  1. Go's image package uses top-left as the origin.

  2. If we followed OpenGL convention we would have to flip the image or texture coordinates on the CPU before upload to the GPU or in each shader.

Index

Constants

This section is empty.

Variables

View Source
var ColorModel color.Model = 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 DefaultState = State{
	AlphaMode:    NoAlpha,
	Blend:        DefaultBlendState,
	WriteRed:     true,
	WriteGreen:   true,
	WriteBlue:    true,
	WriteAlpha:   true,
	Dithering:    true,
	DepthTest:    true,
	DepthWrite:   true,
	DepthCmp:     Less,
	StencilTest:  false,
	FaceCulling:  BackFaceCulling,
	StencilFront: DefaultStencilState,
	StencilBack:  DefaultStencilState,
}

The default state that should be used for graphics objects.

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

func InsertionSort

func InsertionSort(data sort.Interface)

InsertionSort performs a simple insertion sort on the sort interface. In the case of ByDist it performs generally as fast as sort.Sort() except that it can exploit temporal coherence improving performance dramatically when the objects have not moved much.

Types

type AlphaMode

type AlphaMode uint8

AlphaMode describes a single alpha transparency mode that can be used for rendering 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:
	//     Render 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:
	//     Render 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:
	//     Render 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 render ordering issues, although it does cause
	//     jagged-looking edges).
	AlphaToCoverage
)

func (AlphaMode) String

func (m AlphaMode) String() string

String returns a string representation of this alpha transparency mode. e.g. NoAlpha -> "NoAlpha"

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 BlendOp = iota
	BOne
	BSrcColor
	BOneMinusSrcColor
	BDstColor
	BOneMinusDstColor
	BSrcAlpha
	BOneMinusSrcAlpha
	BDstAlpha
	BOneMinusDstAlpha
	BConstantColor
	BOneMinusConstantColor
	BConstantAlpha
	BOneMinusConstantAlpha

	// Not applicable for use in BlendState.SrcRGB.
	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 rendering an object whose AlphaMode == BlendedAlpha.

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 ByDist

type ByDist struct {
	// The list of objects to sort.
	Objects []*Object

	// The target position to compare against. The list is sorted based off
	// each object's distance away from this position (typically this is the
	// camera's position).
	Target lmath.Vec3
}

ByDist sorts a list of graphics objects based on their distance away from a target position (typically the camera). As such if the sorted objects are drawn in order then they are drawn back-to-front (which is useful for rendering alpha-blended objects such that transparency appears correct).

Using sort.Reverse this doubles as front-to-back sorting (which is useful for drawing opaque objects efficiently due to depth testing).

The Less() method properly read-locks the objects when required.

func (ByDist) Len

func (b ByDist) Len() int

Implements sort.Interface.

func (ByDist) Less

func (b ByDist) Less(ii, jj int) bool

Implements sort.Interface.

func (ByDist) Swap

func (b ByDist) Swap(i, j int)

Implements sort.Interface.

type ByState

type ByState []*Object

ByState sorts a list of graphics objects based on the change of their graphics state in order to reduce graphics state changes and increase the overall throughput when rendering several objects whose graphics state differ.

The Less() method properly read-locks the objects when required.

func (ByState) Len

func (b ByState) Len() int

Implements sort.Interface.

func (ByState) Less

func (b ByState) Less(i, j int) bool

Implements sort.Interface.

func (ByState) Swap

func (b ByState) Swap(i, j int)

Implements sort.Interface.

type Camera

type Camera struct {
	*Object

	// The projection matrix of the camera, which is responsible for projecting
	// world coordinates into device coordinates.
	Projection Mat4
}

Camera represents a camera object, it may be moved in 3D space using the objects transform and the viewing frustum controls how the camera views things. Since a camera is in itself also an object it may also have visible meshes attatched to it, etc.

func NewCamera

func NewCamera() *Camera

NewCamera returns a new *Camera with the default values.

func (*Camera) Copy

func (c *Camera) Copy() *Camera

Copy returns a new copy of this Camera.

The camera's read lock must be held for this method to operate safely.

func (*Camera) Destroy

func (c *Camera) Destroy()

Destroy destroys this camera for use by other callees to NewCamera. You must not use it after calling this method. This makes an implicit call to c.Object.Destroy.

The camera's write lock must be held for this method to operate safely.

func (*Camera) Project

func (c *Camera) Project(p3 lmath.Vec3) (p2 lmath.Vec2, ok bool)

Project returns a 2D point in normalized device space coordinates given a 3D point in the world.

If ok=false is returned then the point is outside of the camera's view and the returned point may not be meaningful.

The camera's read lock must be held for this method to operate safely.

func (*Camera) Reset

func (c *Camera) Reset()

Reset resets this camera to it's default (NewCamera) state.

The camera's write lock must be held for this method to operate safely.

func (*Camera) SetOrtho

func (c *Camera) SetOrtho(view image.Rectangle, near, far float64)

SetOrtho sets this camera's Projection matrix to an orthographic one.

The view parameter is the viewing rectangle for the orthographic projection in window coordinates.

The near and far parameters describe the minimum closest and maximum furthest clipping points of the view frustum.

Clients who need advanced control over how the orthographic viewing frustum is set up may use this method's source as a reference (e.g. to change the center point, which this method sets at the bottom-left).

The camera's write lock must be held for this method to operate safely.

func (*Camera) SetPersp

func (c *Camera) SetPersp(view image.Rectangle, fov, near, far float64)

SetPersp sets this camera's Projection matrix to an perspective one.

The view parameter is the viewing rectangle for the orthographic projection in window coordinates.

The fov parameter is the Y axis field of view (e.g. some games use 75) to use.

The near and far parameters describe the minimum closest and maximum furthest clipping points of the view frustum.

Clients who need advanced control over how the perspective viewing frustum is set up may use this method's source as a reference (e.g. to change the center point, which this method sets at the center).

The camera's write lock must be held for this method to operate safely.

type Canvas

type Canvas interface {
	Downloadable

	// SetMSAA should request that this canvas use multi-sample anti-aliasing
	// during rendering. 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 graphics hardware or
	// rendering API does not support it.
	SetMSAA(enabled bool)

	// MSAA returns the last value passed into SetMSAA on this renderer.
	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 returned by this method may change at any given time (e.g.
	// when a user resizes the window).
	Bounds() image.Rectangle

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

	// ClearDepth submits a depth-clear operation to the renderer. 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 the entire canvas is cleared.
	ClearDepth(r image.Rectangle, depth float64)

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

	// Draw submits a draw operation to the renderer. It will draw the given
	// graphics object onto the specified rectangle of the canvas.
	//
	// The canvas will lock the object and camera object and they may stay
	// locked until some point in the future when the draw operation completes.
	//
	// If not nil, then the object is drawn according to how it is seen by the
	// given camera object (taking into account the camera object's
	// transformation and projection 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.Shader == nil
	//  len(o.Shader.Error) > 0
	//  len(o.Meshes) == 0
	//  !o.Meshes[N].Loaded && len(o.Meshes[N].Vertices) == 0
	//
	// If the rectangle is empty the entire canvas is drawn to.
	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 rendering, 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
	// GPUInfo.OcclusionQuery) 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).

All methods must be safe to call from multiple goroutines.

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)

Implements image/color.Color interface.

type CoordConv

type CoordConv uint8

CoordSpace 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 (
	// Zero-value depth/stencil format. Used to represent nil/none/zero.
	ZeroDSFormat DSFormat = iota

	// The 16-bit depth buffer format.
	Depth16

	// The 24-bit depth buffer format.
	Depth24

	// The 32-bit depth buffer format.
	Depth32

	// The 24-bit depth buffer, combined with 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 (t DSFormat) String() string

String returns a string name for this depth/stencil buffer format. For example:

Depth24AndStencil8 -> "Depth24AndStencil8"

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. requires
	// reloading the entire object).
	//
	// This method is safe to invoke 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 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 renderers support
	// downloading RGB/A textures and sometimes 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 (
	// Culls only back faces (i.e. only the front side is rendered).
	BackFaceCulling FaceCullMode = iota

	// Culls only front faces (i.e. only the back side is rendered).
	FrontFaceCulling

	// Does not cull any faces (i.e. both sides are rendered).
	NoFaceCulling
)

func (FaceCullMode) String

func (f FaceCullMode) String() string

String returns a string representation of this FaceCullMode. e.g. BackFaceCulling -> "BackFaceCulling"

type GPUInfo

type GPUInfo struct {
	// MaxTextureSize is the maximum size of either X or Y dimension of texture
	// images for use with the renderer, 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 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.
	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 renderer to the
	// nearest power-of-two.
	NPOT bool

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

	// Major and minor versions of the OpenGL version in use, or -1 if not
	// available. For example:
	//  3, 0 (for OpenGL 3.0)
	GLMajor, GLMinor int

	// A read-only slice of OpenGL extension strings, empty if not available.
	GLExtensions []string

	// Major and minor versions of the OpenGL Shading Language version in use,
	// or -1 if not available. For example:
	//  1, 30 (for GLSL 1.30)
	GLSLMajor, GLSLMinor int

	// The maximum number of floating-point variables available for varying
	// variables inside GLSL programs, or -1 if not available. Generally at
	// least 32.
	GLSLMaxVaryingFloats int

	// The maximum number of shader inputs (i.e. floating-point values, where a
	// 4x4 matrix is 16 floating-point values) that can be used inside a GLSL
	// vertex shader, or -1 if not available. Generally at least 512.
	GLSLMaxVertexInputs int

	// The maximum number of shader inputs (i.e. floating-point values, where a
	// 4x4 matrix is 16 floating-point values) that can be used inside a GLSL
	// fragment shader, or -1 if not available. Generally at least 64.
	GLSLMaxFragmentInputs int
}

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

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 {
	sync.RWMutex

	// The native object of this mesh. Once loaded the renderer using this mesh
	// must assign a value to this field. Typically clients should not assign
	// values to this field at all.
	NativeMesh

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

	// 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

	// Weather or not the mesh will be dynamically updated. Only used as a hint
	// to increase performence of dynamically updated meshes, does not actually
	// control whether or not a mesh may be dynamically updated.
	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 renderer 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 renderer 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 renderer should take note
	// and re-upload the data slice to the graphics hardware.
	ColorsChanged 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 renderer 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 renderer 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.

Clients are responsible for utilizing the RWMutex of the mesh when using it or invoking methods.

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) Bounds

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

Bounds implements the Boundable interface. It is thread-safe and performs locking automatically. 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.

The mesh's write lock must be held for this method to operate safely.

func (*Mesh) ClearData

func (m *Mesh) ClearData()

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

The mesh's write lock must be held for this method to operate safely.

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).

The mesh's read lock must be held for this method to operate safely.

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.

The mesh's write lock must be held for this method to operate safely.

func (*Mesh) GenerateBary

func (m *Mesh) GenerateBary()

GenerateBary generates the barycentric coordinates for this mesh.

The mesh's write lock must be held for this method to operate safely.

func (*Mesh) HasChanged

func (m *Mesh) HasChanged() bool

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

The mesh's read lock must be held for this method to operate safely.

func (*Mesh) Reset

func (m *Mesh) Reset()

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

The mesh's write lock must be held for this method to operate safely.

type NativeMesh

type NativeMesh Destroyable

NativeMesh represents the native object of a mesh, typically only renderers create these.

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.
	//
	// This method is safe to invoke from multiple goroutines concurrently.
	SampleCount() int
}

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

type NativeShader

type NativeShader Destroyable

NativeShader represents the native object of a shader. Typically only renderers will create these.

type NativeTexture

type NativeTexture interface {
	Destroyable
	Downloadable

	// ChosenFormat tells the texture format chosen by the renderer 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 renderer is responsible for creating these and fulfilling the interface.

type Object

type Object struct {
	sync.RWMutex

	// The native object of this graphics object. The renderer using this
	// graphics object must assign a value to this field after a call to
	// Draw() has finished before unlocking the object.
	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 rendering 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 renderer implementations to
	// optimize the number of draw calls that must occur to render
	// consecutively listed meshes here (this allows for 'hardware' instancing
	// support).
	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.Lock()
	//  o.CachedBounds = nil
	//  o.Unlock()
	//
	// And then simply invoke o.Bounds() again to calculate the bounds again.
	CachedBounds *lmath.Rect3
}

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

Clients are responsible for utilizing the RWMutex of the object when using it or invoking methods.

func NewObject

func NewObject() *Object

NewObject creates and returns a new object with:

o.State == DefaultState
o.Transform == DefaultTransform

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.Lock()
o.CachedBounds = nil
o.Unlock()

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).

This method properly write-locks the object.

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.

The object's read lock must be held for this method to operate safely.

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 shader is only copied by pointer.

The object's read lock must be held for this method to operate safely.

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.

The object's write lock must be held for this method to operate safely.

func (*Object) Reset

func (o *Object) Reset()

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

The object's write lock must be held for this method to operate safely.

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 RTTConfig

type RTTConfig struct {
	// Bounds is the target resolution of the canvas to render at. If it is an
	// empty rectangle, the renderer's bounds is used instead.
	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
	// could 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. All three textures are nil.
  2. Any non-nil texture is not accompanies by a format.
  3. 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 Renderer

type Renderer interface {
	Canvas

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

	// GPUInfo should return information about the graphics hardware.
	GPUInfo() GPUInfo

	// LoadMesh should begin loading the specified mesh asynchronously.
	//
	// Additionally, the renderer will set m.Loaded to true, and then invoke
	// m.ClearData(), thus allowing the data slices to be garbage collected).
	//
	// The renderer will lock the mesh and it may stay locked until sometime in
	// the future when the load operation completes. The mesh will be sent over
	// the done channel once the load operation has completed if the channel is
	// not nil and sending would not block.
	LoadMesh(m *Mesh, done chan *Mesh)

	// LoadTexture should begin loading the specified texture asynchronously.
	//
	// Additionally, the renderer will set t.Loaded to true, and then invoke
	// t.ClearData(), thus allowing the source image to be garbage collected.
	//
	// The renderer will lock the texture and it may stay locked until sometime
	// in the future when the load operation completes. The texture will be
	// sent over the done channel once the load operation has completed if the
	// channel is not nil and sending would not block.
	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 renderer will set s.Loaded to true, and then invoke
	// s.ClearData(), thus allowing the source data slices to be garbage
	// collected.
	//
	// The renderer will lock the shader and it may stay locked until sometime
	// in the future when the load operation completes. The shader will be sent
	// over the done channel once the load operation has completed if the
	// channel is not nil and sending would not block.
	LoadShader(s *Shader, done chan *Shader)

	// RenderToTexture creates and returns a canvas that when rendered 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
}

Renderer is capable of loading meshes, textures, and shaders. A renderer can be drawn to as it implements the Canvas interface, and can also be used to All methods must be safe to call from multiple goroutines.

func Nil

func Nil() Renderer

Nil returns a renderer that does not actually render anything.

type Shader

type Shader struct {
	sync.RWMutex

	// The native object of this shader. Once loaded (if no compiler error
	// occured) then the renderer using this shader must assign a value to this
	// field. Typically clients should not assign values to this field at all.
	NativeShader

	// 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

	// The GLSL vertex shader source.
	GLSLVert []byte

	// The GLSL fragment shader.
	GLSLFrag []byte

	// 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
	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.

Clients are responsible for utilizing the RWMutex of the shader when using it or invoking methods.

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.

The shader's write lock must be held for this method to operate safely.

func (*Shader) Reset

func (s *Shader) Reset()

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

The shader's write lock must be held for this method to operate safely.

type State

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

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

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

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

	// Whether or not depth testing and depth writing should be enabled when
	// rendering 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 rendering the
	// object.
	StencilTest bool

	// Whether or not (and how) face culling should occur when rendering
	// 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 rendering a graphics object. Changes to such properties across multiple draw calls (called 'graphics state changes' or '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 (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.

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 rendering 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 rendering. 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 renderer 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 rendering.

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

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

	// Samples point from the closest mipmap. May not be used as a magnification
	// filter.
	NearestMipmapNearest

	// Bilinear filter the pixel from the closest mipmap. May not be used as a
	// magnification filter.
	LinearMipmapNearest

	// Samples the pixel from two closest mipmaps, and linearly blends. May not
	// be used as a magnification filter.
	NearestMipmapLinear

	// (Trilinear filtering) Bilinearly filters the pixel from two mipmaps, and
	// linearly blends the result. 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 (t TexFilter) String() string

String returns a string representation of this TexFilter. e.g. Nearest -> "Nearest"

type TexFormat

type TexFormat uint8

TexFormat specifies a single texture storage format.

const (
	// Zero-value texture format. Used to represent nil/none/zero.
	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 (t TexFormat) String() string

String returns a string name for this texture format. For example:

RGBA -> "RGBA"

type TexWrap

type TexWrap uint8

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

const (
	// The extra area of the texture is repeated into infinity.
	Repeat TexWrap = iota

	// The extra area of the texture is represented by stretching the edge
	// pixels out into infinity.
	Clamp

	// The extra area of the texture is represented by the border color
	// specified on the texture object.
	BorderColor

	// The extra area of the texture is represented by itself mirrored into
	// infinity.
	Mirror
)

func (TexWrap) String

func (t TexWrap) String() string

String returns a string representation of this TexWrapMode. e.g. Repeat -> "Repeat"

type Texture

type Texture struct {
	sync.RWMutex

	// The native object of this texture. Once loaded the renderer using this
	// texture must assign a value to this field. Typically clients should not
	// assign values to this field at all.
	NativeTexture

	// Weather or not this texture is currently loaded or not.
	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

	// 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 renderer may use an image format
	// that is similar and is supported (and the format chosen by the renderer
	// 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.

Clients are responsible for utilizing the RWMutex of the texture when using it or invoking methods.

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.

The texture's write lock must be held for this method to operate safely.

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.

The texture's read lock must be held for this method to operate safely.

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.

The texture's write lock must be held for this method to operate safely.

func (*Texture) Reset

func (t *Texture) Reset()

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

The textures's write lock must be held for this method to operate safely.

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

Implements 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.Mat4
	//  [][]gfx.Mat4
	//  []gfx.Vec4
	//  [][]gfx.Vec4
	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 renderer
	// should take note and re-upload the data slice to the graphics hardware.
	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.

Jump to

Keyboard shortcuts

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