sgl

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2022 License: Unlicense Imports: 14 Imported by: 0

README

sgl

simple wrapper on glfw/opengl for use in personal projects. can use go port of imgui for gui.

Todo

  • some useful 'premade' shader programs
    • 2d image "splat" (png, jpg, image.Image,...)
    • 3d shapes with vertex colors, normals, textures, point/directional lights
    • skybox
  • More opengl features.
  • Improve text/font rendering in font.go.
    • should be able to queue all strings into a single vbo with vertex coords and texture coords, then draw all in a single draw call.
  • rename some types and functions.
  • add utilites (from my gaia stars program)
  • make Texture2D more flexible
  • program->vao mapper?
    • to do foreach program { enable program; foreach vao { draw vao } }
  • change all "load" funcs that take a string path to also accept a fs.FS as the root
    • this will allow me to use pkg embed or os.DirFS, etc

Changelog

  • 0.6.0 todo
    • mouse and camera structs (when finalized).
    • keyboard/mouse somehow integrated into Window or other "input" manager?
    • map of pressed keys/mouse buttons so don't pass *Window to ChordSet.
  • 0.5.0
    • ChordSet functionality changed so chords are executed until all matching chords are executed or a chord with "Stop" set to true is executed.
    • icon loading window option.
    • convienience function to get font names from FontMap for use in Selecter.
    • real fix for imgui renderer to display images in color (from v0.3.0)
    • function to check opengl errors, and error type.
  • 0.4.0
    • skybox
    • resizable window option at creation
    • small api changes to Texture2D
    • Selecter uitility, basically for easier imgui combo and list boxes
    • changes to Chord/ChordSet that simplfy api and fix a subtle timing bug.
    • addition to Window of "Timer" named Clock
    • additions to Window for use in rendering loop control
    • addition of "IsNthFrame()" to Timer
    • simplify Vao to make mostly-unused params to Set*() and Draw() use defaults.
  • 0.3.0
    • changed/"fixed" imgui renderer to display images in color
    • modified window creation api to allow for fonts with imgui
    • package level function to set "default" (for me) opengl settings
    • a few useful utility types (Timer, Cycler, AnimationMap...)
  • 0.2.0
    • screen capture to image.Image
    • added simple framebuffer object.
    • renamed main data structure.
    • different api for window/platform creation.

Documentation

Index

Constants

View Source
const (
	SizeOfByte  = 1
	SizeOfFloat = 4 * SizeOfByte
	SizeOfInt   = 4 * SizeOfByte
	SizeOfV3    = 3 * SizeOfFloat
	SizeOfV4    = 4 * SizeOfFloat
	SizeOfM4    = 4 * SizeOfV4
)

Size of common types in bytes.

View Source
const (
	Float32 = gl.FLOAT
	Int32   = gl.INT
	Uint32  = gl.UNSIGNED_INT
	Int8    = gl.BYTE
	Uint8   = gl.UNSIGNED_BYTE
)

Common vertex attribute types.

View Source
const (
	VertexShader   = gl.VERTEX_SHADER
	FragmentShader = gl.FRAGMENT_SHADER
	GeometryShader = gl.GEOMETRY_SHADER
	ComputeShader  = gl.COMPUTE_SHADER
)

Aliases for common shader types to avoid slow autocomplete of gl pkg.

View Source
const (
	Triangles     = gl.TRIANGLES
	Points        = gl.POINTS
	Lines         = gl.LINES
	TriangleStrip = gl.TRIANGLE_STRIP
	TriangleFan   = gl.TRIANGLE_FAN
)

Easier access to gl "draw mode" types.

Variables

This section is empty.

Functions

func CheckError

func CheckError() error

func Destroy

func Destroy()

Destroy calls glfw.Terminate().

func ExecuteSets

func ExecuteSets(sets []ChordSet, win *glfw.Window)

ExecuteSets calls Execute() on each ChordSet.

func Init

func Init() error

Init should be called once to initalize GLFW along with a deferred call to Destroy.

func OpenImages

func OpenImages(filenames ...string) ([]*image.RGBA, error)

OpenImages opens the images specified by filename and converts them to RGBA format.

func SetGLDefaults

func SetGLDefaults()

SetGLDefaults sets a few opengl options that I commonly use.

func UseDefaultFramebuffer

func UseDefaultFramebuffer()

UseDefaultFramebuffer unbinds other FBOs and binds the default framebuffer.

Types

type Animation

type Animation func(float32) bool

Animation is a function that takes a time delta and returns whether or not the animation has completed.

type AnimationMap

type AnimationMap map[string]Animation

AnimationMap holds animations keyed by some name.

func (AnimationMap) Float32

func (am AnimationMap) Float32(name string, value *float32, durationSec, from, to float32)

Float32 inserts a new animation with "name" which animates the value from "from" to "to" over "durationSec" seconds.

func (AnimationMap) Has

func (am AnimationMap) Has(name string) bool

Has checks the animation map for an animation of the given name.

func (AnimationMap) Update

func (am AnimationMap) Update(dt float32)

Update every animation in the map, deleting those that are completed.

func (AnimationMap) Vec3f

func (am AnimationMap) Vec3f(name string, value *mgl32.Vec3, durationSec float32, from, to mgl32.Vec3)

Vec3f inserts a new animation with "name" which animates the value from "from" to "to" over "durationSec" seconds.

type Attribute

type Attribute struct {
	ID     uint32 // index or location of attribute
	Name   string // name of attribute in the shader GLSL
	Size   int32  // 'numbers' in a single attribute
	Type   uint32 // gl.FLOAT, etc
	Stride int32  // bytes
	Offset int    // bytes

}

func (*Attribute) Enable

func (a *Attribute) Enable()

Enable (associate) attribute with "current" VAO/VBO.

type Character

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

type CharacterDict

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

func NewCharacterDict

func NewCharacterDict(font *basicfont.Face) *CharacterDict

func (CharacterDict) Delete

func (cd CharacterDict) Delete()

func (CharacterDict) DrawString

func (cd CharacterDict) DrawString(text string, x, y, scale float32, color mgl32.Vec3, width, height float32)

(0, 0) are in the top left of the screen (inverted Y compared to standard opengl)

type Chord

type Chord struct {
	Keys    []glfw.Key         // List of keys to be down to execute this chord
	Mouse   []glfw.MouseButton // List of mouse buttons to be down to execute this chord
	Execute func()             // The function to execute
	Wait    float64            // Wait time (seconds) between sucessive allowable executions
	Stop    bool               // When set, no further chords will be executed after this one has been
	// contains filtered or unexported fields
}

Chord is an input "gesture", which may be one or more keys (eg CTRL+ALT+T) or mouse buttons (A + left-click).

func (*Chord) Match

func (c *Chord) Match(win *glfw.Window, now time.Time) bool

Match determines whether or not the keys for this chord are pressed and if the chord's Wait time has elapsed.

type ChordSet

type ChordSet []Chord

ChordSet is a logic grouping of (related) Chords.

func CombineSets

func CombineSets(sets ...ChordSet) []ChordSet

CombineSets makes a slice of ChordSets for convenience, sorting each one.

func (ChordSet) Execute

func (cs ChordSet) Execute(win *glfw.Window)

Execute runs the function for each Chord that matches the current key state. Execution of chords will stop when the first chord is encountered with its "Stop" member set to true.

func (ChordSet) Len

func (cs ChordSet) Len() int

Len is the number of elements in the collection.

func (ChordSet) Less

func (cs ChordSet) Less(i int, j int) bool

Less reports whether the element with index i should sort before the element with index j.

func (ChordSet) Match

func (cs ChordSet) Match(win *glfw.Window) *Chord

Match returns first Chord in the set that matches the current key state.

func (ChordSet) Sort

func (cs ChordSet) Sort() ChordSet

Sort called sort.Sort() on the ChordSet, returning the same ChordSet for convenience.

func (ChordSet) Swap

func (cs ChordSet) Swap(i int, j int)

Swap swaps the elements with indexes i and j.

type Cycler

type Cycler struct {
	Title   string
	Current int
	Things  []interface{}
}

Cycler lets one easily cycle through a list of "whatever". It's a simpler version of Selecter that doesn't name items and allows only relative (Next() and Previous()) selection changes.

func NewCycler

func NewCycler(items ...interface{}) *Cycler

NewCycler creates a Cycler from items.

func (*Cycler) Get

func (c *Cycler) Get() interface{}

Get the current item.

func (*Cycler) Next

func (c *Cycler) Next()

Next moves to the next item, or wraps around if at the end.

func (*Cycler) Previous

func (c *Cycler) Previous()

Previous moves to the previous item, or wraps around if at the begining.

type Fbo

type Fbo struct {
	ID            uint32
	Width, Height int32

	ColorBuffer *Texture2D
	// contains filtered or unexported fields
}

Fbo is a very simple Frame Buffer Object with a texture bound as a color attachment and renderbuffer for depth and stencil attachments.

func NewFbo

func NewFbo(width, height int) (*Fbo, error)

NewFbo creates a FBO of the given dimensions.

func (*Fbo) Delete

func (fbo *Fbo) Delete()

Delete resources associated with the FBO.

func (*Fbo) Use

func (fbo *Fbo) Use()

Use binds the FBO for use.

type FontMap

type FontMap map[string]struct {
	Filename string
	Size     float32
	Font     imgui.Font
}

FontMap associates a friendly name (key) with info about a font loaded for use with imgui. The Filename and Size fields are used during initializtion of imgui.

func (FontMap) Names

func (fm FontMap) Names() []interface{}

Names gets the friendly names (keys) from a FontMap. interface{} is used instead of string for easy use in a Selecter.

type GlError

type GlError map[uint32]string

func (GlError) Error

func (e GlError) Error() string

type NamedItems

type NamedItems []selecteritem

NamedItems is a slice of structs that pairs a Name string with any Item.

func MakeItems

func MakeItems(items ...interface{}) NamedItems

MakeItems creates a NamedItems from the provided "items". Items implementing fmt.Stringer use that for Name. Most other types use their (possibly truncated) go representation, which will be annotated with its type for types such as slices, structs, etc.

func (NamedItems) Sort

func (items NamedItems) Sort() NamedItems

Sort the NamedItems by Name, descending (alphabetical). Returns the NamedItems for "inline" use.

type Program

type Program struct {
	ID      uint32
	Shaders map[uint32]*Shader // map[type]shader
}

func NewProgram

func NewProgram() *Program

func (*Program) AddShader

func (prog *Program) AddShader(shaderType uint32, source string, uniformNames []string, attribs ...Attribute)

AddShader creates and associates a shader with this program.

func (*Program) Build

func (prog *Program) Build() error

Build will compile and link a program.

func (*Program) Compile

func (prog *Program) Compile() error

func (*Program) Compute

func (prog *Program) Compute() *Shader

func (*Program) Delete

func (prog *Program) Delete()

func (*Program) Fragment

func (prog *Program) Fragment() *Shader

func (*Program) Geometry

func (prog *Program) Geometry() *Shader
func (prog *Program) Link() error

func (*Program) Use

func (prog *Program) Use()

func (*Program) Vertex

func (prog *Program) Vertex() *Shader

type Selecter

type Selecter struct {
	Title   string
	Current int
	Things  []interface{}
	Names   []string
}

Selecter lets someone create an indexed list of "whatever" with an associated name. The current selection can be changed absolutely (with Set()) or relatively (with Next() and Previous()). Only 1 item can be selected. This is helpful for use with imgui's combo box or list box.

func NewSelecter

func NewSelecter(items NamedItems) *Selecter

NewSelecter creates a Selecter using the items to populate its Things and Names slices.

func (*Selecter) Get

func (s *Selecter) Get() selecteritem

Get the current item. example:

 fmt.Println(selecter.Get().Name)
	thing := selecter.Get().Item.(mytype)

func (*Selecter) Next

func (s *Selecter) Next()

Next changes the selection to the next item, or wraps around if at the end.

func (*Selecter) Previous

func (s *Selecter) Previous()

Previous changes the selection to the previous item, or wraps around if at the end.

func (*Selecter) Selected

func (s *Selecter) Selected(index int) bool

Selected returns true if index is the current selection.

func (*Selecter) SelectedName

func (s *Selecter) SelectedName(name string) bool

SelectedName performs a linear search on the Names slice for name and, if a match is found, returns true if it is the current selection.

func (*Selecter) Set

func (s *Selecter) Set(index int)

Set the current selection. index is clamped to the bounds of the Things slice.

func (*Selecter) SetName

func (s *Selecter) SetName(name string)

SetName performs a linear search on the Names slice for name and, if a match is found, sets it to the current selection. No change is performed if a match is not found.

type Shader

type Shader struct {
	ID       uint32
	Type     uint32 // gl.VERTEX_SHADER, gl.FRAGMENT_SHADER, etc
	Source   string
	Attribs  map[string]*Attribute
	Uniforms map[string]int32
}

func (*Shader) Attributes

func (s *Shader) Attributes() (copy []Attribute)

Attributes gets a slice of copies of the shader's attributes.

func (*Shader) SetFloat

func (s *Shader) SetFloat(uniformName string, count int32, val *float32)

func (*Shader) SetInt

func (s *Shader) SetInt(uniformName string, count int32, val *int32)

func (*Shader) SetMat4

func (s *Shader) SetMat4(uniformName string, count int32, val *mgl32.Mat4)

func (*Shader) SetVec2

func (s *Shader) SetVec2(uniformName string, count int32, val *mgl32.Vec2)

func (*Shader) SetVec3

func (s *Shader) SetVec3(uniformName string, count int32, val *mgl32.Vec3)

func (*Shader) SetVec4

func (s *Shader) SetVec4(uniformName string, count int32, val *mgl32.Vec4)

type Skybox

type Skybox struct {
	TextureID uint32
	Vao       *Vao
}

Skybox is a complete cubemap skybox.

func NewSkybox

func NewSkybox(faces []*image.RGBA) (*Skybox, error)

NewSkybox creates a skybox. It expects faces in this order:

+X (right)
-X (left)
+Y (top)
-Y (bottom)
+Z (front)
-Z (back)

func (*Skybox) Delete

func (sky *Skybox) Delete()

Delete resources.

func (*Skybox) Draw

func (sky *Skybox) Draw(view, projection mgl32.Mat4)

Draw should be called after other objects.

type Texture2D

type Texture2D struct {
	ID            uint32
	Width, Height int32
}

func NewTexture2D

func NewTexture2D(rgba *image.RGBA) (*Texture2D, error)

func (*Texture2D) Delete

func (tex *Texture2D) Delete()

func (*Texture2D) ReadImage

func (tex *Texture2D) ReadImage() *image.RGBA

ReadImage gets a Go image from the texture.

func (*Texture2D) Reload

func (tex *Texture2D) Reload(img *image.RGBA)

type Timer

type Timer struct {
	TotalFrames uint64
	TotalTime   float64
	DeltaT      float64 // Seconds
	Start       time.Time
	Now         time.Time
}

Timer keeps time and other similar info useful for an opengl render loop.

func (*Timer) AvgFps

func (t *Timer) AvgFps() float64

AvgFps gets the average framerate over the total program runtime (or since Reset() was called).

func (*Timer) Fps

func (t *Timer) Fps() float64

Fps gets the instantaneous framerate of this render loop.

func (*Timer) IsNthFrame

func (t *Timer) IsNthFrame(n uint64) bool

IsNthFrame returns true if the current frame number is on the "nth" since the timer was last reset. Just frame count mod n == 0. Example:

if timer.IsNthFrame(2) {
	// do something every other frame
}

func (*Timer) Reset

func (t *Timer) Reset()

Reset the timer to an initial state. Should call once before the render loop.

func (*Timer) Update

func (t *Timer) Update()

Update the timer with the current time. Call once each render loop.

type Vao

type Vao struct {
	VaoID    uint32       // id for vao
	Vbo      uint32       // id for vertex buffer object associated with this vao
	Ebo      uint32       // id for element (vertex index) buffer associated with this vao
	DrawMode uint32       // "mode" for drawing, such as TRIANGLES or LINES
	Tex      []*Texture2D // ids for all textures to be used with this vao (on draw)
	Prog     *Program     // program to load when drawing
	// contains filtered or unexported fields
}

func NewVao

func NewVao(drawMode uint32, program *Program) *Vao

func (*Vao) CountVerts

func (v *Vao) CountVerts() int32

func (*Vao) Delete

func (v *Vao) Delete()

func (*Vao) Draw

func (v *Vao) Draw()

Draw call Vao.Prog.Use() first!

func (*Vao) DrawOptions

func (v *Vao) DrawOptions(mode uint32, first, count int32)

DrawOptions call Vao.Prog.Use() before drawing.

func (*Vao) SetEbo

func (v *Vao) SetEbo(data []uint32)

func (*Vao) SetEboOptions

func (v *Vao) SetEboOptions(sizeInBytes int, data []uint32, usage uint32)

func (*Vao) SetTexture

func (v *Vao) SetTexture(uniformName string, texture *Texture2D)

SetTexture associates named uniform (in frag shader) with this texture, and also associates the texture with the texture "number" of the texture's index in the Tex slice. eg. TEXTURE0 is at Tex[0], TEXTURE1 at Tex[1], etc.

func (*Vao) SetVbo

func (v *Vao) SetVbo(data []float32)

func (*Vao) SetVboOptions

func (v *Vao) SetVboOptions(sizeInBytes int, data []float32, usage uint32)

type Window

type Window struct {
	// Allows direct access to some of the imgui data.
	Gui *imguiData

	// Allows direct access to the glfw window.
	GlfwWindow *glfw.Window

	// OpenGL version and driver info.
	GlVersion string

	// Basically 'read only' info about the dimensions of the window.
	Dimensions WindowMetric

	// Updated each frame.
	Clock Timer
	// contains filtered or unexported fields
}

Window implements a window, opengl contenxt based on github.com/go-gl/glfw (v3.3), and (optionally) imgui context. It also has additional helpful features.

func NewWindow

func NewWindow(title string, size WindowMetric, options ...WindowOption) (*Window, error)

NewWindow attempts to initialize a GLFW context/window/imgui etc.

func (*Window) AddCharCallback

func (platform *Window) AddCharCallback(callback glfw.CharCallback)

func (*Window) AddKeyCallback

func (platform *Window) AddKeyCallback(callback glfw.KeyCallback)

func (*Window) AddMouseButtonCallback

func (platform *Window) AddMouseButtonCallback(callback glfw.MouseButtonCallback)

func (*Window) AddScrollCallback

func (platform *Window) AddScrollCallback(callback glfw.ScrollCallback)

func (*Window) Aspect

func (platform *Window) Aspect() float32

Aspect returns aspect ratio.

func (*Window) BeginFrame

func (platform *Window) BeginFrame() (continueRendering bool)

BeginFrame updates certain state for the new frame, and returns true if the render loop should continue running.

func (*Window) CanUseGui

func (platform *Window) CanUseGui() bool

CanUseGui tests if imgui is configured ("Gui" is non-nil).

func (*Window) CapturesKeyboard

func (platform *Window) CapturesKeyboard() bool

CapturesKeyboard returns true if Imgui is capturing keyboard input.

func (*Window) CapturesMouse

func (platform *Window) CapturesMouse() bool

CapturesMouse returns true if Imgui is capturing mouse input.

func (*Window) ClearBuffers

func (platform *Window) ClearBuffers()

ClearBuffers clears color buffer and depth buffer.

func (*Window) ClipboardText

func (platform *Window) ClipboardText() string

ClipboardText returns the current clipboard text, if available.

func (*Window) DisplaySize

func (platform *Window) DisplaySize() [2]float32

DisplaySize returns the dimension of the display.

func (*Window) Dispose

func (platform *Window) Dispose()

Dispose cleans up the resources.

func (*Window) FramebufferSize

func (platform *Window) FramebufferSize() [2]float32

FramebufferSize returns the dimension of the framebuffer.

func (*Window) Fullscreen

func (platform *Window) Fullscreen(full bool, width, height int) (setWidth, setHeight int)

Fullscreen toggles windowed and fullscreen modes. Parameters width and height will set screen resolution only for fullscreen mode, and values of 0 will use the current resolution.

func (*Window) InitLoop

func (platform *Window) InitLoop()

InitLoop should be called once at the beginning of the render loop.

func (*Window) MakeContextCurrent

func (platform *Window) MakeContextCurrent()

MakeContextCurrent calls Window's MakeContextCurrent() to activate the opengl context for use.

func (*Window) PollEvents

func (platform *Window) PollEvents()

PollEvents handles all pending window events.

func (*Window) RenderImgui

func (platform *Window) RenderImgui(gui func())

RenderImgui will perform the beginning and ending steps of rendering the imgui constructed by calls to the imgui pkg in the 'gui' function.

func (*Window) ScreenCapture

func (platform *Window) ScreenCapture() image.Image

ScreenCapture saves a copy of the opengl front buffer and saves it into an image.Image.

func (*Window) SetClipboardText

func (platform *Window) SetClipboardText(text string)

SetClipboardText sets the text as the current clipboard text.

func (*Window) ShouldClose

func (platform *Window) ShouldClose() bool

ShouldClose returns true if the window is to be closed.

func (*Window) SwapBuffers

func (platform *Window) SwapBuffers()

SwapBuffers performs a buffer swap.

type WindowMetric

type WindowMetric struct {
	X, Y       int
	W, H       int
	Fullscreen bool
	Resizable  bool
}

WindowMetric contains info on the window position (X, Y), size (W, H), and windowed/fullscreen status. The window position and size are only valid while the window is in windowed mode (ie W and H are not the resolution when fullscreen).

type WindowOption

type WindowOption func(*Window) error

WindowOption sets a option during window creation.

func SetIcons

func SetIcons(paths ...string) WindowOption

SetIcons offers icon candidates to the window. PNG or JPEG in 16x16, 32x32, and 48x48 are good.

func UseImgui

func UseImgui(fonts FontMap) WindowOption

UseImgui is an option to setup additional bits so the window can be used with Imgui to create a user interface. Provide a key (for later reference) and the `Filename` and `Size` fields to load fonts for use with imgui. Pass nil to just use the default font. Imgui ini file disabled by default.

Jump to

Keyboard shortcuts

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