From feff22144689df9da5ddb8e9693326b77feb7949 Mon Sep 17 00:00:00 2001 From: xengineering Date: Fri, 21 May 2021 14:02:40 +0200 Subject: Refactor OpenGL-related Code --- graphics.go | 55 ++++++++++++++++++++++++++++++++++++------------------- main.go | 8 +++----- 2 files changed, 39 insertions(+), 24 deletions(-) diff --git a/graphics.go b/graphics.go index 6cb3400..91edcce 100644 --- a/graphics.go +++ b/graphics.go @@ -39,37 +39,54 @@ const ( ` + "\x00" ) -// initOpenGL initializes OpenGL and returns an intiialized program -func initOpenGL() uint32 { - log.Println("OpenGL init") +type Graphics struct { + version string + vao uint32 + vertexShader uint32 + fragmentShader uint32 + program uint32 +} + +func newGraphics() Graphics { - if err := gl.Init(); err != nil { - panic(err) + var graphics Graphics = Graphics{} + + // init OpenGL and save/log version + log.Println("OpenGL init") + err := gl.Init() + if err != nil { + log.Fatal(err) } - version := gl.GoStr(gl.GetString(gl.VERSION)) - log.Println("OpenGL version", version) + graphics.version = gl.GoStr(gl.GetString(gl.VERSION)) + log.Println("OpenGL version", graphics.version) - vertexShader, err := compileShader(VERTEX_SHADER, gl.VERTEX_SHADER) + // compile shaders + graphics.vertexShader, err = compileShader(VERTEX_SHADER, gl.VERTEX_SHADER) if err != nil { - panic(err) + log.Fatal(err) } - fragmentShader, err := compileShader(FRAGMENT_SHADER, gl.FRAGMENT_SHADER) + graphics.fragmentShader, err = compileShader(FRAGMENT_SHADER, gl.FRAGMENT_SHADER) if err != nil { - panic(err) + log.Fatal(err) } - prog := gl.CreateProgram() - gl.AttachShader(prog, vertexShader) - gl.AttachShader(prog, fragmentShader) - gl.LinkProgram(prog) - return prog + // create GL program + graphics.program = gl.CreateProgram() + gl.AttachShader(graphics.program, graphics.vertexShader) + gl.AttachShader(graphics.program, graphics.fragmentShader) + gl.LinkProgram(graphics.program) + + // create VAO + graphics.vao = makeVao(triangle) + + return graphics } -func draw(vao uint32, program uint32) { +func (graphics Graphics) draw() { gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) - gl.UseProgram(program) + gl.UseProgram(graphics.program) - gl.BindVertexArray(vao) + gl.BindVertexArray(graphics.vao) gl.DrawArrays(gl.TRIANGLES, 0, int32(len(triangle)/3)) } diff --git a/main.go b/main.go index e2d6e43..8f2afcc 100644 --- a/main.go +++ b/main.go @@ -30,15 +30,13 @@ func main() { var app App = newApp() defer app.terminate() // GLFW needs to be terminated! - // init OpenGL - program := initOpenGL() - - vao := makeVao(triangle) + // initialize graphics + var graphics Graphics = newGraphics() // main loop for !app.window.ShouldClose() { + graphics.draw() app.handle() - draw(vao, program) } } -- cgit v1.2.3-70-g09d2