glh

package module
v0.0.0-...-6300d2b Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2015 License: BSD-3-Clause Imports: 11 Imported by: 36

README

glh: golang OpenGL helpers

Build Status

This package contains a number of functions useful for applications using OpenGL.

Code Reference

Features

  • Textures and Texture Atlas.
  • Easy framebuffer rendering to texture
  • Contexts
  • Basic text manipulation
  • Easy shader loading
  • Easy efficient uploading of many colour/vertices
  • Mesh buffer

Documentation

Index

Constants

View Source
const (
	// Classic mode uses manual glBegin/glEnd calls to construct the
	// mesh. This is extremely slow, and mostly only useful for debugging
	// purposes. This implies OpenGL version 'Ye Olde'+.
	RenderClassic = iota

	// Arrays mode uses vertex arrays which involves gl*Pointer calls and
	// directly passing in the vertex data. This is slower than using VBO's,
	// because the data has to be uploaded to the GPU on every render pass.
	// It is useful for older systems where glBufferData is not available.
	// This implies OpenGL version 1.5+.
	RenderArrays

	// Buffered mode uses VBO's. This is the preferred mode for systems
	// where shader support is not present or deemed necessary. This implies
	// OpenGL version 2.1+.
	RenderBuffered
)

Known render modes.

Variables

This section is empty.

Functions

func CaptureRGBA

func CaptureRGBA(im *image.RGBA)

func CaptureToPng

func CaptureToPng(filename string)

Note: You may want to call ClearAlpha(1) first..

func CheckGLError

func CheckGLError() error

CheckGLError returns an opengl error if one exists.

func ClearAlpha

func ClearAlpha(alpha_value gl.GLclampf)

Clear the alpha channel in the color buffer

func ColorC

func ColorC(c color.Color)

func DebugLines

func DebugLines()

Draws a cross on the screen with known lengths, useful for understanding screen dimensions

func DrawAxes

func DrawAxes()

Draws lines of unit length along the X, Y, Z axis in R, G, B

func DrawQuadd

func DrawQuadd(x, y, w, h float64)

Same as DrawQuadi, double co-ordinates

func DrawQuadi

func DrawQuadi(x, y, w, h int)

Draw a Quad with integer co-ordinates (Using Squarei)

func GetViewportWH

func GetViewportWH() (int, int)

Returns w, h of viewport

func GetViewportWHD

func GetViewportWHD() (float64, float64)

func IsPow2

func IsPow2(x uint32) bool

IsPow2 returns true if the given value is a power-of-two.

func MakeShader

func MakeShader(shader_type gl.GLenum, source string) gl.Shader

func NewProgram

func NewProgram(shaders ...Shader) gl.Program

func OpenGLSentinel

func OpenGLSentinel() func()

Used as "defer OpenGLSentinel()()" checks the gl error code on call and exit

func Pow2

func Pow2(x uint32) uint32

Pow2 returns the first power-of-two value >= to n. This can be used to create suitable texture dimensions.

func Pow2Image

func Pow2Image(src image.Image) image.Image

Pow2Image returns the given image, scaled to the smallest power-of-two dimensions larger or equal to the input dimensions. It preserves the image format and contents.

This is useful if an image is to be used as an OpenGL texture. These often require image data to have power-of-two dimensions.

func ProjToWindow

func ProjToWindow(x, y float64) (float64, float64)

Returns x, y in window co-ordinates at 0 in the z direction

func Sizeof

func Sizeof(gtype gl.GLenum) uint

Sizeof yields the byte size for GL type specified by the given enum.

func Squared

func Squared(x, y, w, h float64)

Same as Squarei, double co-ordinates

func Squarei

func Squarei(x, y, w, h int)

Emit Vertices of a square with texture co-ordinates which wind anti-clockwise

func WindowToProj

func WindowToProj(x, y int) (float64, float64)

Returns x, y in window co-ordinates at 0 in the z direction

func With

func With(c Context, action func())

I like python. Therefore `func With`. Useful to ensure that changes to state don't leak further than you would like and to insert implicit error checking Example usage:

With(Matrix{gl.PROJECTION}, func() { .. operations which modify matrix .. })
// Changes to the matrix are undone here

Types

type AtlasRegion

type AtlasRegion struct {
	X int
	Y int
	W int
	H int
}

A region denotes an allocated chunk of space in an atlas.

type Attr

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

An Attr describes the type and size of a single vertex component. These tell the MeshBuffer how to interpret mesh data.

func NewAttr

func NewAttr(name string, size int, typ, usage gl.GLenum) *Attr

NewAttr creates a new mesh attribute for the given size, type, usage value and name.

In RenderShader mode, the name is the variable by which the component can be referenced from a shader program.

In other modes, the MeshBuffer uses this name to identify the attribute's purpose. In these cases, it is advised to use the NewIndexAttr, NewPositionAttr, etc. wrappers.

func NewColorAttr

func NewColorAttr(size int, typ, usage gl.GLenum) *Attr

NewColorAttr creates a new vertex color attribute.

func NewIndexAttr

func NewIndexAttr(size int, typ, usage gl.GLenum) *Attr

NewIndexAttr creates a new index attribute.

func NewNormalAttr

func NewNormalAttr(size int, typ, usage gl.GLenum) *Attr

NewNormalAttr creates a new surface normal attribute.

func NewPositionAttr

func NewPositionAttr(size int, typ, usage gl.GLenum) *Attr

NewPositionAttr creates a new vertex position attribute.

func NewTexCoordAttr

func NewTexCoordAttr(size int, typ, usage gl.GLenum) *Attr

NewTexCoordAttr creates a new vertex texture coordinate attribute.

func (*Attr) Clear

func (a *Attr) Clear()

Clear clears the attribute buffer.

func (*Attr) Data

func (a *Attr) Data() interface{}

Data returns the atribute data store.

This value should be asserted to a concrete type, which would be a slice of the attrbute's type. E.g.: []float32, []uint8, etc.

func (*Attr) Invalid

func (a *Attr) Invalid() bool

Invalid returns true if the data store needs to be re-committed.

func (*Attr) Invalidate

func (a *Attr) Invalidate()

Invalidate marks the data store as invalid. This should be done any time the data is modified externally. It will be re-committed on the next render pass.

func (*Attr) Len

func (a *Attr) Len() int

Len returns the number of elements in the data store.

func (*Attr) Name

func (a *Attr) Name() string

Name returns the attribute name.

func (*Attr) SetTarget

func (a *Attr) SetTarget(t gl.GLenum)

SetTarget sets the buffer target.

func (*Attr) Size

func (a *Attr) Size() int

Size returns the number of elements in a vertext component for this attribute.

func (*Attr) Stride

func (a *Attr) Stride() int

Stride returns the stride value for the data type this attribute holds.

func (*Attr) Target

func (a *Attr) Target() gl.GLenum

Target returns the buffer target.

func (*Attr) Type

func (a *Attr) Type() gl.GLenum

Type returns the data type of the attribute.

type Attrib

type Attrib struct{ Bits gl.GLbitfield }

A context which preserves Attrib bits

func (Attrib) Enter

func (a Attrib) Enter()

func (Attrib) Exit

func (a Attrib) Exit()

type CompoundContextImpl

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

func Compound

func Compound(contexts ...Context) CompoundContextImpl

Combine multiple contexts into one

func (CompoundContextImpl) Enter

func (c CompoundContextImpl) Enter()

func (CompoundContextImpl) Exit

func (c CompoundContextImpl) Exit()

type Context

type Context interface {
	Enter()
	Exit()
}

Types implementing Context can be used with `With`

func Disable

func Disable(enums ...gl.GLenum) Context

func Enable

func Enable(enums ...gl.GLenum) Context

type Framebuffer

type Framebuffer struct {
	*Texture

	Level int
	// contains filtered or unexported fields
}

During this context, OpenGL drawing operations will instead render to `*Texture`. Example usage:

With(Framebuffer{my_texture}, func() { .. operations to render to texture .. })

Internally this will permanently allocate a framebuffer with the appropriate dimensions. Beware that using a large number of textures with differing sizes will therefore cause some graphics cards to run out of memory.

func (*Framebuffer) BindFramebuffer

func (b *Framebuffer) BindFramebuffer(target gl.GLenum)

func (*Framebuffer) Enter

func (b *Framebuffer) Enter()

func (*Framebuffer) Exit

func (b *Framebuffer) Exit()

type Matrix

type Matrix struct{ Type gl.GLenum }

A context which preserves the matrix mode, drawing, etc.

func (Matrix) Enter

func (m Matrix) Enter()

func (Matrix) Exit

func (m Matrix) Exit()

type Mesh

type Mesh map[string][2]int

Mesh describes the data offsets for a single mesh inside a mesh buffer.

type MeshBuffer

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

MeshBuffer represents a mesh buffer. It caches and renders vertex data for an arbitrary amount of independent meshes.

func NewMeshBuffer

func NewMeshBuffer(mode RenderMode, attr ...*Attr) *MeshBuffer

NewMeshBuffer returns a new mesh buffer object.

The mode parameter defines the mode in which this buffer treats and renders vertex data. It should hold one of the predefined RenderMode constants.

The given attributes define the type and size of each vertex component. For example:

mb := NewMeshBuffer(
    // Render our data using VBO's.
    glh.RenderBuffered,

    // Indices: 1 unsigned short per index; static data.
    NewIndexAttr(1, gl.USIGNED_SHORT, gl.STATIC_DRAW),

    // Positions: 3 floats; static data.
    NewPositionAttr(3, gl.FLOAT, gl.STATIC_DRAW),

    // Colors: 4 floats; changing regularly.
    NewColorAttr(4, gl.FLOAT, gl.DYNAMIC_DRAW),
)

Any mesh data loaded into this buffer through MeshBuffer.Add(), must adhere to the format defined by these attributes. THis includes the order in which the data is supplied. It must match the order in which the attributes are defined here.

func (*MeshBuffer) Add

func (mb *MeshBuffer) Add(argv ...interface{}) int

Add appends new mesh data to the buffer.

The data specified in these lists should match the buffer attributes. We expect to receive lists like []float32, []byte in the same order as the attributes where supplied to NewMeshBuffer.

Returns an index into the MeshBuffer.Meshes() list.

func (*MeshBuffer) Attr

func (mb *MeshBuffer) Attr(name string) *Attr

Attr returns the attribute for the given name.

func (*MeshBuffer) Clear

func (mb *MeshBuffer) Clear()

Clear clears the mesh buffer.

func (*MeshBuffer) Colors

func (mb *MeshBuffer) Colors() *Attr

Colors returns the mesh attribute for color data. This is relevant only for render modes other than RenderShader.

func (*MeshBuffer) Indices

func (mb *MeshBuffer) Indices() *Attr

Indices returns the mesh attribute for index data. This is relevant only for render modes other than RenderShader.

func (*MeshBuffer) Meshes

func (mb *MeshBuffer) Meshes() []Mesh

Meshes returns a list of meshes in the buffer.

func (*MeshBuffer) Mode

func (mb *MeshBuffer) Mode() RenderMode

Mode returns the render mode for this buffer.

func (*MeshBuffer) Normals

func (mb *MeshBuffer) Normals() *Attr

Normals returns the mesh attribute for normal data. This is relevant only for render modes other than RenderShader.

func (*MeshBuffer) Positions

func (mb *MeshBuffer) Positions() *Attr

Positions returns the mesh attribute for position data. This is relevant only for render modes other than RenderShader.

func (*MeshBuffer) Release

func (mb *MeshBuffer) Release()

Release releases all resources for this buffer.

func (*MeshBuffer) Render

func (mb *MeshBuffer) Render(mode gl.GLenum)

Render renders the entire mesh buffer. The mode defines one of the symbolic constants like GL_TRIANGLES, GL_QUADS, GL_POLYGON, GL_TRIANGLE_STRIP, etc.

func (*MeshBuffer) RenderMesh

func (mb *MeshBuffer) RenderMesh(index int, mode gl.GLenum)

RenderMesh renders a single mesh, idenfified by its index. The mode defines one of the symbolic constants like GL_TRIANGLES, GL_QUADS, GL_POLYGON, GL_TRIANGLE_STRIP, etc.

func (*MeshBuffer) TexCoords

func (mb *MeshBuffer) TexCoords() *Attr

TexCoords returns the mesh attribute for texture coordinate data. This is relevant only for render modes other than RenderShader.

type Primitive

type Primitive struct{ Type gl.GLenum }

Context which does `gl.Begin` and `gl.End` Example:

With(Primitive{gl.LINES}, func() { gl.Vertex2f(0, 0); gl.Vertex2f(1,1) })

func (Primitive) Enter

func (p Primitive) Enter()

func (Primitive) Exit

func (p Primitive) Exit()

type RenderMode

type RenderMode uint8

A RenderMode determines how a MeshBuffer should buffer and render mesh data.

type Shader

type Shader struct {
	Type    gl.GLenum
	Program string
}

func (Shader) Compile

func (s Shader) Compile() gl.Shader

type Texture

type Texture struct {
	gl.Texture
	W, H int
}

A 2D Texture which implements Context, so can be used as:

`With(texture, func() { .. textured primitives .. })`

which sets gl.ENABLE_BIT

func NewTexture

func NewTexture(w, h int) *Texture

Create a new texture, initialize it to have a `gl.LINEAR` filter and use `gl.CLAMP_TO_EDGE`.

func (*Texture) AsImage

func (t *Texture) AsImage() *image.RGBA

Return the OpenGL texture as a golang `image.RGBA`

func (Texture) Enter

func (b Texture) Enter()

func (Texture) Exit

func (b Texture) Exit()

func (*Texture) FromImage

func (t *Texture) FromImage(im image.Image, level int)

Initialize this texture with image data from `im`. Note: copies the texture if it isn't in RGBA format. This can happen if you load from png files.

func (*Texture) FromImageRGBA

func (t *Texture) FromImageRGBA(rgba *image.RGBA, level int)

func (*Texture) FromPngReader

func (t *Texture) FromPngReader(in io.Reader, level int) error

func (*Texture) Init

func (t *Texture) Init()

Initialize texture storage. _REQUIRED_ before using it as a framebuffer target.

type TextureAtlas

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

A texture atlas is used to tightly pack arbitrarily many small images into a single texture.

The actual implementation is based on the article by Jukka Jylänki: "A Thousand Ways to Pack the Bin - A Practical Approach to Two-Dimensional Rectangle Bin Packing", February 27, 2010.

More precisely, this is an implementation of the 'Skyline Bottom-Left' algorithm.

func NewTextureAtlas

func NewTextureAtlas(width, height, depth int) *TextureAtlas

NewAtlas creates a new texture atlas.

The given width, height and depth determine the size and depth of the underlying texture.

depth should be 1, 3 or 4 and it will specify if the texture is created with Alpha, RGB or RGBA channels. The image data supplied through Atlas.Set() should be of the same format.

func (*TextureAtlas) Allocate

func (a *TextureAtlas) Allocate(width, height int) (AtlasRegion, bool)

Allocate allocates a new region of the given dimensions in the atlas. It returns false if the allocation failed. This can happen when the specified dimensions exceed atlas bounds, or the atlas is full.

func (*TextureAtlas) Bind

func (a *TextureAtlas) Bind(target gl.GLenum)

Bind binds the atlas texture, so it can be used for rendering.

func (*TextureAtlas) Clear

func (a *TextureAtlas) Clear()

Clear removes all allocated regions from the atlas. This invalidates any previously allocated regions.

func (*TextureAtlas) Commit

func (a *TextureAtlas) Commit(target gl.GLenum)

Commit creates the actual texture from the atlas image data. This should be called after all regions have been defined and set, and before you start using the texture for display.

func (*TextureAtlas) Depth

func (a *TextureAtlas) Depth() int

Depth returns the underlying texture color depth.

func (*TextureAtlas) Height

func (a *TextureAtlas) Height() int

Height returns the underlying texture height in pixels.

func (*TextureAtlas) Release

func (a *TextureAtlas) Release()

Release clears all atlas resources.

func (*TextureAtlas) Save

func (a *TextureAtlas) Save(file string) (err error)

Save saves the texture as a PNG image.

func (*TextureAtlas) Set

func (a *TextureAtlas) Set(region AtlasRegion, src []byte, stride int)

Set pastes the given data into the atlas buffer at the given coordinates. It assumes there is enough space available for the data to fit.

func (*TextureAtlas) Unbind

func (a *TextureAtlas) Unbind(target gl.GLenum)

Unbind unbinds the current texture. Note that this applies to any texture currently active. If this is not the atlas texture, it will still perform the action.

func (*TextureAtlas) Width

func (a *TextureAtlas) Width() int

Width returns the underlying texture width in pixels.

type WindowCoords

type WindowCoords struct {
	NoReset bool
	Invert  bool
}

Set the GL_PROJECTION matrix to use window co-ordinates and load the identity matrix into the GL_MODELVIEW matrix

func (WindowCoords) Enter

func (wc WindowCoords) Enter()

func (WindowCoords) Exit

func (wc WindowCoords) Exit()

Jump to

Keyboard shortcuts

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