// Creating a RenderObject with a given shaderProgram, texture, and set of // vertices. func CreateRenderObject(shaderProgram ShaderProgram, texture Texture, vertices []float32) *RenderObject { renderObject := new(RenderObject) // Creating the basic information. renderObject.shaderProgram = uint32(shaderProgram) renderObject.texture = uint32(texture) gl.GenVertexArrays(1, &renderObject.vao) gl.GenBuffers(1, &renderObject.vbo) gl.GenBuffers(1, &renderObject.ebo) // Filling the RenderObject with information. gl.BindVertexArray(renderObject.vao) gl.BindBuffer(gl.ARRAY_BUFFER, renderObject.vbo) gl.BufferData(gl.ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW) gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, renderObject.ebo) vertOrder := []uint32{ 0, 1, 2, 2, 3, 0, } gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(vertOrder)*4, gl.Ptr(vertOrder), gl.STATIC_DRAW) // Loading up vertex attributes. vertAttrib := uint32(gl.GetAttribLocation(renderObject.shaderProgram, gl.Str("vert\x00"))) gl.EnableVertexAttribArray(vertAttrib) gl.VertexAttribPointer(vertAttrib, 2, gl.FLOAT, false, 4*4, gl.PtrOffset(0)) // Loading up texture attributes. texAttrib := uint32(gl.GetAttribLocation(renderObject.shaderProgram, gl.Str("vertTexCoord\x00"))) gl.EnableVertexAttribArray(texAttrib) gl.VertexAttribPointer(texAttrib, 2, gl.FLOAT, false, 4*4, gl.PtrOffset(2*4)) return renderObject }
func NewEffectsRenderer(w, h int) (r *EffectsRenderer, err error) { r = &EffectsRenderer{ width: w, height: h, Color: mgl32.Vec3{0.0, 0.0, 0.0}, } _, _, r.oldwidth, r.oldheight = twodee.GetInteger4(gl.VIEWPORT) if r.shader, err = twodee.BuildProgram(EFFECTS_VERTEX, EFFECTS_FRAGMENT); err != nil { return } r.positionLoc = uint32(gl.GetAttribLocation(r.shader, gl.Str("a_Position\x00"))) r.textureLoc = uint32(gl.GetAttribLocation(r.shader, gl.Str("a_TextureCoordinates\x00"))) r.textureUnitLoc = gl.GetUniformLocation(r.shader, gl.Str("u_TextureUnit\x00")) r.colorLoc = gl.GetUniformLocation(r.shader, gl.Str("v_Color\x00")) gl.BindFragDataLocation(r.shader, 0, gl.Str("v_FragData\x00")) var size float32 = 1.0 var rect = []float32{ -size, -size, 0.0, 0, 0, -size, size, 0.0, 0, 1, size, -size, 0.0, 1, 0, size, size, 0.0, 1, 1, } if r.coords, err = twodee.CreateVBO(len(rect)*4, rect, gl.STATIC_DRAW); err != nil { return } if r.framebuffer, r.texture, err = r.initFramebuffer(w, h); err != nil { return } return }
func NewLinesRenderer(camera *Camera) (lr *LinesRenderer, err error) { var ( program uint32 vbos = make([]uint32, 2) point TexturedPoint ) if program, err = BuildProgram(LINES_VERTEX, LINES_FRAGMENT); err != nil { return } gl.GenBuffers(2, &vbos[0]) lr = &LinesRenderer{ Renderer: NewRenderer(camera), program: program, buffer: vbos[0], indexBuffer: vbos[1], bufferBytes: 0, positionLoc: uint32(gl.GetAttribLocation(program, gl.Str("v_Position\x00"))), normalLoc: uint32(gl.GetAttribLocation(program, gl.Str("v_Normal\x00"))), miterLoc: uint32(gl.GetAttribLocation(program, gl.Str("f_Miter\x00"))), modelviewLoc: gl.GetUniformLocation(program, gl.Str("m_ModelView\x00")), projectionLoc: gl.GetUniformLocation(program, gl.Str("m_Projection\x00")), thicknessLoc: gl.GetUniformLocation(program, gl.Str("f_Thickness\x00")), colorLoc: gl.GetUniformLocation(program, gl.Str("v_Color\x00")), innerLoc: gl.GetUniformLocation(program, gl.Str("f_Inner\x00")), offPosition: gl.PtrOffset(int(unsafe.Offsetof(point.X))), offNormal: gl.PtrOffset(int(unsafe.Offsetof(point.TextureX))), offMiter: gl.PtrOffset(int(unsafe.Offsetof(point.Z))), stride: int32(unsafe.Sizeof(point)), } if e := gl.GetError(); e != 0 { err = fmt.Errorf("ERROR: OpenGL error %X", e) } return }
func GetAttribLocation(shaderName, attribName string) (int32, error) { prog, ok := shader_progs[shaderName] if !ok { return -1, fmt.Errorf("No shader named '%s'", shaderName) } return gl.GetAttribLocation(prog, gl.Str(fmt.Sprintf("%s\x00", attribName))), nil }
// Rendering this LineRender. func (lr *LineRender) Render() { // Binding the appropriate information. gl.BindVertexArray(lr.vao) gl.BindBuffer(gl.ARRAY_BUFFER, lr.vbo) gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, lr.ebo) gl.UseProgram(lr.shaderProgram) // Loading up vertex attributes. vertAttrib := uint32(gl.GetAttribLocation(lr.shaderProgram, gl.Str("vert\x00"))) gl.EnableVertexAttribArray(vertAttrib) gl.VertexAttribPointer(vertAttrib, 2, gl.FLOAT, false, 2*4, gl.PtrOffset(0)) // Line thickness information. gl.Uniform1f( gl.GetUniformLocation(lr.shaderProgram, gl.Str("in_thickness\x00")), lr.weight) // Fragment shader color information. gl.Uniform4f( gl.GetUniformLocation(lr.shaderProgram, gl.Str("in_color\x00")), lr.color.Red, lr.color.Green, lr.color.Blue, lr.color.Alpha) gl.BindFragDataLocation(lr.shaderProgram, 0, gl.Str("out_color\x00")) // Performing the render. gl.DrawElements(gl.LINE_STRIP, lr.points, gl.UNSIGNED_INT, nil) }
func (p *Program) Attrib(name string, stride uintptr) *VertexAttribute { var nameStr = gl.Str(fmt.Sprintf("%v\x00", name)) return &VertexAttribute{ location: uint32(gl.GetAttribLocation(p.program, nameStr)), stride: stride, } }
func getAttribLocation(program uint32, name string) (uint32, error) { a := gl.GetAttribLocation(program, gl.Str(name+"\x00")) if a == -1 { return 0, fmt.Errorf("couldn't get attrib location: %q", name) } // Cast to uint32 for EnableVertexAttribArray and VertexAttribPointer better. return uint32(a), nil }
func NewGlowRenderer(w, h int, blur int, strength float32, scale float32) (r *GlowRenderer, err error) { r = &GlowRenderer{ width: w, height: h, blur: blur, strength: strength, scale: scale, } _, _, r.oldwidth, r.oldheight = GetInteger4(gl.VIEWPORT) if r.shader, err = BuildProgram(GLOW_VERTEX, GLOW_FRAGMENT); err != nil { return } r.orientationLoc = gl.GetUniformLocation(r.shader, gl.Str("Orientation\x00")) r.blurAmountLoc = gl.GetUniformLocation(r.shader, gl.Str("BlurAmount\x00")) r.blurScaleLoc = gl.GetUniformLocation(r.shader, gl.Str("BlurScale\x00")) r.blurStrengthLoc = gl.GetUniformLocation(r.shader, gl.Str("BlurStrength\x00")) r.bufferDimensionsLoc = gl.GetUniformLocation(r.shader, gl.Str("BufferDimensions\x00")) r.positionLoc = uint32(gl.GetAttribLocation(r.shader, gl.Str("a_Position\x00"))) r.textureLoc = uint32(gl.GetAttribLocation(r.shader, gl.Str("a_TextureCoordinates\x00"))) r.textureUnitLoc = gl.GetUniformLocation(r.shader, gl.Str("u_TextureUnit\x00")) gl.BindFragDataLocation(r.shader, 0, gl.Str("v_FragData\x00")) var size float32 = 1.0 var rect = []float32{ -size, -size, 0.0, 0, 0, -size, size, 0.0, 0, 1, size, -size, 0.0, 1, 0, size, size, 0.0, 1, 1, } if r.coords, err = CreateVBO(len(rect)*4, rect, gl.STATIC_DRAW); err != nil { return } if r.GlowFb, r.GlowTex, err = r.initFramebuffer(w, h); err != nil { return } if r.BlurFb, r.BlurTex, err = r.initFramebuffer(w, h); err != nil { return } return }
func NewBatchRenderer(camera *Camera) (tr *BatchRenderer, err error) { var ( program uint32 ) if program, err = BuildProgram(BATCH_VERTEX, BATCH_FRAGMENT); err != nil { return } tr = &BatchRenderer{ Renderer: NewRenderer(camera), Program: program, PositionLoc: uint32(gl.GetAttribLocation(program, gl.Str("a_Position\x00"))), TextureLoc: uint32(gl.GetAttribLocation(program, gl.Str("a_TextureCoordinates\x00"))), TextureUnitLoc: gl.GetUniformLocation(program, gl.Str("u_TextureUnit\x00")), ModelViewLoc: gl.GetUniformLocation(program, gl.Str("m_ModelViewMatrix\x00")), ProjectionLoc: gl.GetUniformLocation(program, gl.Str("m_ProjectionMatrix\x00")), TexOffsetLoc: gl.GetUniformLocation(program, gl.Str("u_TextureOffset\x00")), } if e := gl.GetError(); e != 0 { err = fmt.Errorf("ERROR: OpenGL error %X", e) } return }
func getAttribLocation(prog uint32, name string) int32 { // attempt to get it from the cache first al, found := attrCache[name] if found { return al } // pull the location from the shader and cache it attrGLName := name + "\x00" al = gl.GetAttribLocation(prog, gl.Str(attrGLName)) // cache even if it returns -1 so that it doesn't repeatedly check attrCache[name] = al return al }
func NewTextRenderer(camera *Camera) (tr *TextRenderer, err error) { var ( rect []float32 program uint32 vbo uint32 ) rect = []float32{ 0, 0, 0.0, 0.0, 0.0, 0, 1, 0.0, 0.0, 1.0, 1, 0, 0.0, 1.0, 0.0, 1, 1, 0.0, 1.0, 1.0, } if program, err = BuildProgram(TEXT_VERTEX, TEXT_FRAGMENT); err != nil { return } if vbo, err = CreateVBO(len(rect)*4, rect, gl.STATIC_DRAW); err != nil { return } tr = &TextRenderer{ Renderer: NewRenderer(camera), VBO: vbo, Program: program, PositionLoc: uint32(gl.GetAttribLocation(program, gl.Str("a_Position\x00"))), TextureLoc: uint32(gl.GetAttribLocation(program, gl.Str("a_TextureCoordinates\x00"))), TextureUnitLoc: gl.GetUniformLocation(program, gl.Str("u_TextureUnit\x00")), TransLoc: gl.GetUniformLocation(program, gl.Str("v_Trans\x00")), ScaleLoc: gl.GetUniformLocation(program, gl.Str("v_Scale\x00")), ProjectionLoc: gl.GetUniformLocation(program, gl.Str("m_ProjectionMatrix\x00")), Width: camera.ScreenBounds.Max.X() - camera.ScreenBounds.Min.X(), Height: camera.ScreenBounds.Max.Y() - camera.ScreenBounds.Min.Y(), } if e := gl.GetError(); e != 0 { err = fmt.Errorf("ERROR: OpenGL error %X", e) } return }
func BindBuffers() { //vertexData *OpenGLVertexInfo) { vertexData := &vertexDataTest // check to see if there are any vertices at all to bind if len(vertexData.vertexData) == 0 { return } gl.BindBuffer(gl.ARRAY_BUFFER, vbo) gl.BufferData(gl.ARRAY_BUFFER, len(vertexData.vertexData)*4, gl.Ptr(vertexData.vertexData), gl.DYNAMIC_DRAW) positionAttrib := uint32(gl.GetAttribLocation(program, gl.Str("vertexPosition_modelspace\x00"))) gl.EnableVertexAttribArray(positionAttrib) gl.VertexAttribPointer(positionAttrib, 3, gl.FLOAT, false, 4*NUM_ATTRIBUTES, gl.PtrOffset(0)) colorAttrib := uint32(gl.GetAttribLocation(program, gl.Str("diffuse\x00"))) gl.EnableVertexAttribArray(colorAttrib) gl.VertexAttribPointer(colorAttrib, 4, gl.FLOAT, false, 4*NUM_ATTRIBUTES, gl.PtrOffset(3*4)) uvAttrib := uint32(gl.GetAttribLocation(program, gl.Str("vertexUV\x00"))) gl.EnableVertexAttribArray(uvAttrib) gl.VertexAttribPointer(uvAttrib, 2, gl.FLOAT, false, 4*NUM_ATTRIBUTES, gl.PtrOffset(7*4)) mNormAttrib := uint32(gl.GetAttribLocation(program, gl.Str("mNorm\x00"))) gl.EnableVertexAttribArray(mNormAttrib) gl.VertexAttribPointer(mNormAttrib, 3, gl.FLOAT, false, 4*NUM_ATTRIBUTES, gl.PtrOffset(9*4)) wNormAttrib := uint32(gl.GetAttribLocation(program, gl.Str("wNorm\x00"))) gl.EnableVertexAttribArray(wNormAttrib) gl.VertexAttribPointer(wNormAttrib, 3, gl.FLOAT, false, 4*NUM_ATTRIBUTES, gl.PtrOffset(12*4)) shaderMode := uint32(gl.GetAttribLocation(program, gl.Str("mode\x00"))) gl.EnableVertexAttribArray(shaderMode) gl.VertexAttribPointer(shaderMode, 1, gl.FLOAT, false, 4*NUM_ATTRIBUTES, gl.PtrOffset(15*4)) samplerIdx := uint32(gl.GetAttribLocation(program, gl.Str("samplerIdx\x00"))) gl.EnableVertexAttribArray(samplerIdx) gl.VertexAttribPointer(samplerIdx, 1, gl.FLOAT, false, 4*NUM_ATTRIBUTES, gl.PtrOffset(16*4)) // gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, elementvbo) // gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(vertexData.Elements)*4, gl.Ptr(vertexData.Elements), gl.STATIC_DRAW) // gl.ActiveTexture(gl.TEXTURE0) // gl.BindTexture(gl.TEXTURE_2D, 1) }
func NewFramerateRenderer() (r *Framerate, err error) { r = &Framerate{ shader: core.NewProgram(), data: newFramerateData(120), } if err = r.shader.Load(FRAMERATE_VERTEX, FRAMERATE_FRAGMENT); err != nil { return } r.shader.Bind() gl.GenBuffers(1, &r.vbo) gl.BindBuffer(gl.ARRAY_BUFFER, r.vbo) var ( point framerateDataPoint locPosition = uint32(gl.GetAttribLocation(r.shader.ID(), gl.Str("v_Position\x00"))) offPosition = gl.PtrOffset(int(unsafe.Offsetof(point.pos))) ) r.stride = int32(unsafe.Sizeof(point)) r.locColor = gl.GetUniformLocation(r.shader.ID(), gl.Str("v_Color\x00")) r.locModelView = gl.GetUniformLocation(r.shader.ID(), gl.Str("m_ModelView\x00")) r.locProjection = gl.GetUniformLocation(r.shader.ID(), gl.Str("m_Projection\x00")) gl.EnableVertexAttribArray(locPosition) gl.VertexAttribPointer(locPosition, 2, gl.FLOAT, false, r.stride, offPosition) return }
func NewSpriteRenderer(camera *Camera) (tr *SpriteRenderer, err error) { var ( program uint32 vbos = make([]uint32, 1) sprite SpriteConfig frameOffset = int(unsafe.Offsetof(sprite.Frame)) viewOffset = int(unsafe.Offsetof(sprite.View)) ) if program, err = BuildProgram(SPRITE_VERTEX, SPRITE_FRAGMENT); err != nil { return } gl.GenBuffers(1, &vbos[0]) tr = &SpriteRenderer{ Renderer: NewRenderer(camera), program: program, instanceVBO: vbos[0], instanceBytes: 0, translationLoc: uint32(gl.GetAttribLocation(program, gl.Str("v_Translation\x00"))), rotationLoc: uint32(gl.GetAttribLocation(program, gl.Str("v_Rotation\x00"))), scaleLoc: uint32(gl.GetAttribLocation(program, gl.Str("v_Scale\x00"))), pointAdjLoc: uint32(gl.GetAttribLocation(program, gl.Str("m_PointAdjustment\x00"))), textureAdjLoc: uint32(gl.GetAttribLocation(program, gl.Str("m_TextureAdjustment\x00"))), colorLoc: uint32(gl.GetAttribLocation(program, gl.Str("v_Color\x00"))), textureUnitLoc: gl.GetUniformLocation(program, gl.Str("TextureUnit\x00")), projectionLoc: gl.GetUniformLocation(program, gl.Str("m_ProjectionMatrix\x00")), offAttrX: gl.PtrOffset(viewOffset + int(unsafe.Offsetof(sprite.View.X))), offAttrRotationX: gl.PtrOffset(viewOffset + int(unsafe.Offsetof(sprite.View.RotationX))), offAttrColor: gl.PtrOffset(int(unsafe.Offsetof(sprite.Color))), offAttrScaleX: gl.PtrOffset(viewOffset + int(unsafe.Offsetof(sprite.View.ScaleX))), offAttrPointAdj: frameOffset + int(unsafe.Offsetof(sprite.Frame.PointAdjustment)), offAttrTextureAdj: frameOffset + int(unsafe.Offsetof(sprite.Frame.TextureAdjustment)), } if e := gl.GetError(); e != 0 { err = fmt.Errorf("ERROR: OpenGL error %X", e) } return }
func loadFont(img *image.RGBA, config *FontConfig) (f *Font, err error) { f = new(Font) f.config = config // Resize image to next power-of-two. img = Pow2Image(img).(*image.RGBA) ib := img.Bounds() f.textureWidth = float32(ib.Dx()) f.textureHeight = float32(ib.Dy()) for _, glyph := range config.Glyphs { if glyph.Width > f.maxGlyphWidth { f.maxGlyphWidth = glyph.Width } if glyph.Height > f.maxGlyphHeight { f.maxGlyphHeight = glyph.Height } } // save to disk for testing if f.IsDebug { file, err := os.Create("out.png") if err != nil { panic(err) } defer file.Close() b := bufio.NewWriter(file) err = png.Encode(b, img) if err != nil { panic(err) } err = b.Flush() if err != nil { panic(err) } } // generate texture gl.GenTextures(1, &f.textureID) gl.BindTexture(gl.TEXTURE_2D, f.textureID) gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR) gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR) gl.TexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, int32(ib.Dx()), int32(ib.Dy()), 0, gl.RGBA, gl.UNSIGNED_BYTE, gl.Ptr(img.Pix), ) gl.BindTexture(gl.TEXTURE_2D, 0) // create shader program and define attributes and uniforms f.program, err = NewProgram(fontVertexShaderSource, fontFragmentShaderSource) if err != nil { return f, err } // attributes f.centeredPosition = uint32(gl.GetAttribLocation(f.program, gl.Str("centered_position\x00"))) f.uv = uint32(gl.GetAttribLocation(f.program, gl.Str("uv\x00"))) // uniforms f.finalPositionUniform = gl.GetUniformLocation(f.program, gl.Str("final_position\x00")) f.orthographicMatrixUniform = gl.GetUniformLocation(f.program, gl.Str("orthographic_matrix\x00")) f.scaleMatrixUniform = gl.GetUniformLocation(f.program, gl.Str("scale_matrix\x00")) f.fragmentTextureUniform = gl.GetUniformLocation(f.program, gl.Str("fragment_texture\x00")) f.colorUniform = gl.GetUniformLocation(f.program, gl.Str("fragment_color_adjustment\x00")) return f, nil }
//SetPos sets de Position attribute in the shader argument func (vertexArray *VertexArray) SetPos(shader blankShader.BlankShader) { vertAttrib := uint32(gl.GetAttribLocation(shader.Handle, gl.Str("pos\x00"))) gl.EnableVertexAttribArray(vertAttrib) gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, 5*4, gl.PtrOffset(0)) vertexArray.handlePos = vertAttrib }
func CreateContext(width, height int) Context { vertexShader := ` #version 330 uniform mat4 projection; uniform mat4 camera; uniform mat4 model; in vec3 vert; void main() { gl_Position = projection * camera * model * vec4(vert, 1); } ` + "\x00" fragmentShader := ` #version 330 uniform vec4 color; out vec4 outputColor; void main() { outputColor = color; } ` + "\x00" vertices := []float32{ 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, } if err := glfw.Init(); err != nil { log.Fatalln("failed to initialize glfw:", err) } // defer glfw.Terminate() glfw.WindowHint(glfw.Resizable, glfw.False) glfw.WindowHint(glfw.ContextVersionMajor, 3) glfw.WindowHint(glfw.ContextVersionMinor, 3) glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile) glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True) window, err := glfw.CreateWindow(width, height, "OpenGL", nil, nil) if err != nil { panic(err) } window.MakeContextCurrent() if err := gl.Init(); err != nil { panic(err) } program, err := newProgram(vertexShader, fragmentShader) if err != nil { panic(err) } gl.UseProgram(program) projection := mgl32.Ortho2D(0, 800, 0, 600) projectionUniform := gl.GetUniformLocation(program, gl.Str("projection\x00")) gl.UniformMatrix4fv(projectionUniform, 1, false, &projection[0]) camera := mgl32.LookAtV(mgl32.Vec3{0, 0, 0.5}, mgl32.Vec3{0, 0, 0}, mgl32.Vec3{0, 1, 0}) cameraUniform := gl.GetUniformLocation(program, gl.Str("camera\x00")) gl.UniformMatrix4fv(cameraUniform, 1, false, &camera[0]) model := mgl32.Ident4() modelUniform := gl.GetUniformLocation(program, gl.Str("model\x00")) gl.UniformMatrix4fv(modelUniform, 1, false, &model[0]) var vao uint32 gl.GenVertexArrays(1, &vao) gl.BindVertexArray(vao) var vbo uint32 gl.GenBuffers(1, &vbo) gl.BindBuffer(gl.ARRAY_BUFFER, vbo) gl.BufferData(gl.ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW) vertAttrib := uint32(gl.GetAttribLocation(program, gl.Str("vert\x00"))) gl.EnableVertexAttribArray(vertAttrib) gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, 3*4, gl.PtrOffset(0)) gl.Enable(gl.DEPTH_TEST) gl.DepthFunc(gl.LESS) return Context{Window: window, program: program} }
func main() { vertices, normals := obj.Parse(os.Args[1]) // initialize GLFW if err := glfw.Init(); err != nil { panic(err) } defer glfw.Terminate() // set opengl core profile 3.3 glfw.WindowHint(glfw.ContextVersionMajor, 3) glfw.WindowHint(glfw.ContextVersionMinor, 3) glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile) glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True) window, err := glfw.CreateWindow(640, 480, "GOpenGL", nil, nil) if err != nil { panic(err) } window.MakeContextCurrent() // initialise OpenGL library if err := gl.Init(); err != nil { panic(err) } // link program from shaders program, err := newProgram("vertex.glsl", "fragment.glsl") if err != nil { panic(err) } gl.UseProgram(program) // vertex attribute object holds links between attributes and vbo var vao uint32 gl.GenVertexArrays(1, &vao) gl.BindVertexArray(vao) // vertex buffer with per-vertex data var vbo [2]uint32 gl.GenBuffers(2, &vbo[0]) // position data gl.BindBuffer(gl.ARRAY_BUFFER, vbo[0]) gl.BufferData(gl.ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW) // set up position attribute with layout of vertices posAttrib := uint32(gl.GetAttribLocation(program, gl.Str("position\x00"))) gl.VertexAttribPointer(posAttrib, 3, gl.FLOAT, false, 3*4, gl.PtrOffset(0)) gl.EnableVertexAttribArray(posAttrib) // normal data gl.BindBuffer(gl.ARRAY_BUFFER, vbo[1]) gl.BufferData(gl.ARRAY_BUFFER, len(normals)*4, gl.Ptr(normals), gl.STATIC_DRAW) normAttrib := uint32(gl.GetAttribLocation(program, gl.Str("normal\x00"))) gl.VertexAttribPointer(normAttrib, 3, gl.FLOAT, false, 3*4, gl.PtrOffset(0)) gl.EnableVertexAttribArray(normAttrib) uniModel := gl.GetUniformLocation(program, gl.Str("model\x00")) uniView := gl.GetUniformLocation(program, gl.Str("view\x00")) uniProj := gl.GetUniformLocation(program, gl.Str("proj\x00")) matView := mgl32.LookAt(2.0, 2.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0) gl.UniformMatrix4fv(uniView, 1, false, &matView[0]) matProj := mgl32.Perspective(mgl32.DegToRad(45.0), 640.0/480.0, 1.0, 10.0) gl.UniformMatrix4fv(uniProj, 1, false, &matProj[0]) uniLightDir := gl.GetUniformLocation(program, gl.Str("lightDir\x00")) uniLightCol := gl.GetUniformLocation(program, gl.Str("lightCol\x00")) gl.Uniform3f(uniLightDir, -0.5, 0.0, -1.0) gl.Uniform3f(uniLightCol, 0.0, 0.5, 0.5) startTime := glfw.GetTime() gl.Enable(gl.DEPTH_TEST) gl.ClearColor(1.0, 1.0, 1.0, 1.0) for !window.ShouldClose() { // clear buffer gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) matRot := mgl32.HomogRotate3DZ(float32(glfw.GetTime() - startTime)) gl.UniformMatrix4fv(uniModel, 1, false, &matRot[0]) gl.DrawArrays(gl.TRIANGLES, 0, int32(len(vertices))) window.SwapBuffers() glfw.PollEvents() } }
func main() { // init glfw if err := glfw.Init(); err != nil { panic(err) } defer glfw.Terminate() glfw.WindowHint(glfw.Resizable, glfw.False) glfw.WindowHint(glfw.ContextVersionMajor, 4) glfw.WindowHint(glfw.ContextVersionMinor, 1) glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile) glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True) // make an application window window, err := glfw.CreateWindow(windowWidth, windowHeight, "Hello", nil, nil) if err != nil { panic(err) } window.MakeContextCurrent() // init gl if err := gl.Init(); err != nil { panic(err) } fmt.Println("OpenGL version", gl.GoStr(gl.GetString(gl.VERSION))) // create vertex & fragment shader program, err := newProgram(vertexShader, fragmentShader) if err != nil { panic(err) } gl.UseProgram(program) gl.BindFragDataLocation(program, 0, gl.Str("fc\x00")) points := []float32{ -0.5, -0.5, 0.5, 0.5, 0.5, -0.5, -0.5, 0.5, } vertices := []uint32{ 0, 2, 1, 3, } // configure the vertex data var vao uint32 gl.GenVertexArrays(1, &vao) gl.BindVertexArray(vao) defer gl.BindVertexArray(0) var vbo uint32 gl.GenBuffers(1, &vbo) gl.BindBuffer(gl.ARRAY_BUFFER, vbo) gl.BufferData(gl.ARRAY_BUFFER, len(points)*4, gl.Ptr(points), gl.STATIC_DRAW) var ibo uint32 gl.GenBuffers(1, &ibo) gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo) gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW) vertAttrib := uint32(gl.GetAttribLocation(program, gl.Str("pv\x00"))) gl.EnableVertexAttribArray(vertAttrib) gl.VertexAttribPointer(vertAttrib, 2, gl.FLOAT, false, 2*4, gl.PtrOffset(0)) // global settings gl.Enable(gl.DEPTH_TEST) gl.DepthFunc(gl.LESS) gl.ClearColor(1.0, 1.0, 1.0, 1.0) for !window.ShouldClose() { gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) gl.UseProgram(program) gl.BindVertexArray(vao) gl.DrawElements(gl.LINE_LOOP, 4, gl.UNSIGNED_INT, gl.PtrOffset(0)) window.SwapBuffers() glfw.PollEvents() } }
func main() { // init glfw if err := glfw.Init(); err != nil { panic(err) } defer glfw.Terminate() glfw.WindowHint(glfw.Resizable, glfw.False) glfw.WindowHint(glfw.ContextVersionMajor, 4) glfw.WindowHint(glfw.ContextVersionMinor, 1) glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile) glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True) // make an application window window, err := glfw.CreateWindow(windowWidth, windowHeight, "Transform", nil, nil) if err != nil { panic(err) } window.MakeContextCurrent() // init gl if err := gl.Init(); err != nil { panic(err) } fmt.Println("OpenGL version", gl.GoStr(gl.GetString(gl.VERSION))) // create vertex & fragment shader program, err := newProgram(vertexShader, fragmentShader) if err != nil { panic(err) } gl.UseProgram(program) projection := mgl32.Perspective(mgl32.DegToRad(45.0), float32(windowWidth)/windowHeight, 0.1, 10.0) projectionUniform := gl.GetUniformLocation(program, gl.Str("projection\x00")) gl.UniformMatrix4fv(projectionUniform, 1, false, &projection[0]) camera := mgl32.LookAtV( mgl32.Vec3{3, 3, 3}, mgl32.Vec3{0, 0, 0}, mgl32.Vec3{0, 1, 0}, ) cameraUniform := gl.GetUniformLocation(program, gl.Str("camera\x00")) gl.UniformMatrix4fv(cameraUniform, 1, false, &camera[0]) model := mgl32.Ident4() modelUniform := gl.GetUniformLocation(program, gl.Str("model\x00")) gl.UniformMatrix4fv(modelUniform, 1, false, &model[0]) gl.BindFragDataLocation(program, 0, gl.Str("vert\x00")) points := []float32{ -0.9, -0.9, -0.9, 0.9, -0.9, -0.9, 0.9, -0.9, 0.9, -0.9, -0.9, 0.9, -0.9, 0.9, -0.9, 0.9, 0.9, -0.9, 0.9, 0.9, 0.9, -0.9, 0.9, 0.9, } vertices := []uint32{ 0, 1, 1, 2, 2, 3, 3, 0, 0, 4, 1, 5, 2, 6, 3, 7, 4, 5, 5, 6, 6, 7, 7, 4, } // configure the vertex data var vao uint32 gl.GenVertexArrays(1, &vao) gl.BindVertexArray(vao) defer gl.BindVertexArray(0) var vbo uint32 gl.GenBuffers(1, &vbo) gl.BindBuffer(gl.ARRAY_BUFFER, vbo) gl.BufferData(gl.ARRAY_BUFFER, len(points)*4, gl.Ptr(points), gl.STATIC_DRAW) var ibo uint32 gl.GenBuffers(1, &ibo) gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo) gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(vertices)*4, gl.Ptr(vertices), gl.STATIC_DRAW) vertAttrib := uint32(gl.GetAttribLocation(program, gl.Str("vert\x00"))) gl.EnableVertexAttribArray(vertAttrib) gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, 3*4, gl.PtrOffset(0)) // global settings gl.Enable(gl.DEPTH_TEST) gl.DepthFunc(gl.LESS) gl.ClearColor(0.0, 0.0, 0.0, 1.0) angleX := 0.0 angleY := 0.0 angleZ := 0.0 previousTime := glfw.GetTime() for !window.ShouldClose() { gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT) time := glfw.GetTime() elapsed := time - previousTime previousTime = time angleX += math.Sin((elapsed / period) * math.Pi * 2.0) angleY += math.Sin((elapsed / period) / 6.0 * math.Pi * 2.0) angleZ += math.Sin((elapsed / period) / 3.0 * math.Pi * 2.0) model = mgl32.HomogRotate3DY(float32(angleY)).Mul4(mgl32.HomogRotate3DX(float32(angleX))).Mul4(mgl32.HomogRotate3DZ(float32(angleZ))) gl.UseProgram(program) gl.UniformMatrix4fv(modelUniform, 1, false, &model[0]) gl.BindVertexArray(vao) gl.DrawElements(gl.LINES, int32(len(vertices)), gl.UNSIGNED_INT, gl.PtrOffset(0)) window.SwapBuffers() glfw.PollEvents() } }
func loadBoundingBox(f *Font, X1 Point, X2 Point) (b *BoundingBox, err error) { b = new(BoundingBox) b.font = f // create shader program and define attributes and uniforms b.program, err = NewProgram(boxVertexShaderSource, boxFragmentShaderSource) if err != nil { return b, err } // ebo, vbo data b.vboIndexCount = 4 * 2 // 4 indexes per bounding box (containing 2 position) b.eboIndexCount = 6 // each rune requires 6 triangle indices for a quad b.vboData = make([]float32, b.vboIndexCount, b.vboIndexCount) b.eboData = make([]int32, b.eboIndexCount, b.eboIndexCount) b.makeBufferData(X1, X2) if f.IsDebug { fmt.Printf("bounding %v %v\n", X1, X2) fmt.Printf("bounding vbo data\n%v\n", b.vboData) fmt.Printf("bounding ebo data\n%v\n", b.eboData) } // attributes b.centeredPosition = uint32(gl.GetAttribLocation(b.program, gl.Str("centered_position\x00"))) // uniforms b.finalPositionUniform = gl.GetUniformLocation(b.program, gl.Str("final_position\x00")) b.orthographicMatrixUniform = gl.GetUniformLocation(b.program, gl.Str("orthographic_matrix\x00")) // size of glfloat glfloatSize := int32(4) gl.GenVertexArrays(1, &b.vao) gl.GenBuffers(1, &b.vbo) gl.GenBuffers(1, &b.ebo) // vao gl.BindVertexArray(b.vao) // vbo // specify the buffer for which the VertexAttribPointer calls apply gl.BindBuffer(gl.ARRAY_BUFFER, b.vbo) gl.EnableVertexAttribArray(b.centeredPosition) gl.VertexAttribPointer( b.centeredPosition, 2, gl.FLOAT, false, 0, gl.PtrOffset(0), ) gl.BufferData(gl.ARRAY_BUFFER, int(glfloatSize)*b.vboIndexCount, gl.Ptr(b.vboData), gl.DYNAMIC_DRAW) gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, b.ebo) gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, int(glfloatSize)*b.eboIndexCount, gl.Ptr(b.eboData), gl.DYNAMIC_DRAW) gl.BindVertexArray(0) // not necesssary, but i just want to better understand using vertex arrays gl.BindBuffer(gl.ARRAY_BUFFER, 0) gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, 0) return b, nil }