Skip to content

Instantly share code, notes, and snippets.

@gcatlin gcatlin/triangle.go
Created Jan 12, 2015

Embed
What would you like to do?
Go SDL2 OpenGL minimal example
package main
import (
"runtime"
"github.com/go-gl/gl"
"github.com/veandco/go-sdl2/sdl"
)
func main() {
winTitle := "OpenGL Demo"
winX, winY := sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED
winWidth, winHeight := 800, 600
runtime.LockOSThread()
sdl.Init(sdl.INIT_VIDEO)
defer sdl.Quit()
sdl.GL_SetAttribute(sdl.GL_CONTEXT_PROFILE_MASK, sdl.GL_CONTEXT_PROFILE_CORE)
sdl.GL_SetAttribute(sdl.GL_CONTEXT_MAJOR_VERSION, 3)
sdl.GL_SetAttribute(sdl.GL_CONTEXT_MINOR_VERSION, 2)
window, _ := sdl.CreateWindow(winTitle, winX, winY, winWidth, winHeight, sdl.WINDOW_OPENGL)
defer window.Destroy()
context := sdl.GL_CreateContext(window)
defer sdl.GL_DeleteContext(context)
gl.Init()
vertSource := `
#version 150 core
in vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}`
fragSource := `
#version 150 core
out vec4 outColor;
void main() {
outColor = vec4(1.0, 1.0, 1.0, 1.0);
}`
vao := gl.GenVertexArray()
vao.Bind()
defer vao.Delete()
vbo := gl.GenBuffer()
vbo.Bind(gl.ARRAY_BUFFER)
defer vbo.Delete()
verts := []float32{
0.0, 0.5,
0.5, -0.5,
-0.5, -0.5,
}
gl.BufferData(gl.ARRAY_BUFFER, len(verts)*4, verts, gl.STATIC_DRAW)
vertShader := gl.CreateShader(gl.VERTEX_SHADER)
vertShader.Source(vertSource)
vertShader.Compile()
defer vertShader.Delete()
fragShader := gl.CreateShader(gl.FRAGMENT_SHADER)
fragShader.Source(fragSource)
fragShader.Compile()
defer fragShader.Delete()
shaderProgram := gl.CreateProgram()
shaderProgram.AttachShader(vertShader)
shaderProgram.AttachShader(fragShader)
shaderProgram.BindFragDataLocation(0, "outColor")
shaderProgram.Link()
shaderProgram.Use()
defer shaderProgram.Delete()
posAttrib := shaderProgram.GetAttribLocation("position")
posAttrib.EnableArray()
posAttrib.AttribPointer(2, gl.FLOAT, false, 0, nil)
for running := true; running; {
for e := sdl.PollEvent(); e != nil; e = sdl.PollEvent() {
switch e.(type) {
case *sdl.QuitEvent:
running = false
}
}
gl.ClearColor(0, 0, 0, 1)
gl.Clear(gl.COLOR_BUFFER_BIT)
gl.DrawArrays(gl.TRIANGLES, 0, 3)
sdl.GL_SwapWindow(window)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.