forked from go-gl-legacy/glh
/
context.go
105 lines (87 loc) · 2.35 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Copyright 2012 The go-gl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package glh
import (
"github.com/go-gl/gl"
)
// Types implementing Context can be used with `With`
type Context interface {
Enter()
Exit()
}
// 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
func With(c Context, action func()) {
defer OpenGLSentinel()()
c.Enter()
defer c.Exit()
action()
}
// Combine multiple contexts into one
func Compound(contexts ...Context) CompoundContextImpl {
return CompoundContextImpl{contexts}
}
type CompoundContextImpl struct{ contexts []Context }
func (c CompoundContextImpl) Enter() {
for i := range c.contexts {
c.contexts[i].Enter()
}
}
func (c CompoundContextImpl) Exit() {
for i := range c.contexts {
c.contexts[len(c.contexts)-i-1].Exit()
}
}
// A context which preserves the matrix mode, drawing, etc.
type Matrix struct{ Type gl.GLenum }
func (m Matrix) Enter() {
gl.PushAttrib(gl.TRANSFORM_BIT)
gl.MatrixMode(m.Type)
gl.PushMatrix()
}
func (m Matrix) Exit() {
gl.PopMatrix()
gl.PopAttrib()
}
// A context which preserves Attrib bits
type Attrib struct{ Bits gl.GLbitfield }
func (a Attrib) Enter() {
gl.PushAttrib(a.Bits)
}
func (a Attrib) Exit() {
gl.PopAttrib()
}
// Context which does `gl.Begin` and `gl.End`
// Example:
// With(Primitive{gl.LINES}, func() { gl.Vertex2f(0, 0); gl.Vertex2f(1,1) })
type Primitive struct{ Type gl.GLenum }
func (p Primitive) Enter() { gl.Begin(p.Type) }
func (p Primitive) Exit() { gl.End() }
// Set the GL_PROJECTION matrix to use window co-ordinates and load the identity
// matrix into the GL_MODELVIEW matrix
type WindowCoords struct {
NoReset bool
Invert bool
}
func (wc WindowCoords) Enter() {
w, h := GetViewportWH()
Matrix{gl.PROJECTION}.Enter()
if !wc.NoReset {
gl.LoadIdentity()
}
if wc.Invert {
gl.Ortho(0, float64(w), float64(h), 0, -1, 1)
} else {
gl.Ortho(0, float64(w), 0, float64(h), -1, 1)
}
Matrix{gl.MODELVIEW}.Enter()
gl.LoadIdentity()
}
func (wc WindowCoords) Exit() {
Matrix{gl.MODELVIEW}.Exit()
Matrix{gl.PROJECTION}.Exit()
}