Home  >  Article  >  Backend Development  >  Why Can\'t I Display a Triangle Using go-gl/glfw and github.com/banthar/gl Despite Successful Window and Background Setup?

Why Can\'t I Display a Triangle Using go-gl/glfw and github.com/banthar/gl Despite Successful Window and Background Setup?

DDD
DDDOriginal
2024-11-01 18:13:02322browse

Why Can't I Display a Triangle Using go-gl/glfw and github.com/banthar/gl Despite Successful Window and Background Setup?

Vertex Buffers and Displaying Triangles in Go

Question:

Using the Go github.com/banthar/gl package, the tutorial code from http://www.opengl-tutorial.org/beginners-tutorials/tutorial-2-the-first-triangle/ successfully creates a window and sets the background color, but fails to display a triangle. The equivalent C code does display the triangle. Why?

Answer:

The errors may be attributed to incorrect arguments passed to the AttribPointer function. The following adjustments have been identified to resolve the issue:

  • AttribPointer Arguments: Pass nil for the array buffer offset instead of (void*)0. This tells the OpenGL library to use the current buffer binding as the starting point for the vertex attribute.
  • BufferData Size: Specify the size of the vertex buffer in bytes instead of the number of elements. For example, if the vertex buffer contains n 32-bit floating-point values, pass 4 * n to BufferData.

Corrected Go Code:

package main

import (
    "github.com/banthar/gl"
    "github.com/go-gl/glfw/v3.2/glfw"
    "log"
)

func main() {
    // ... ( GLFW window setup, GL initialization code) ...

    // Create vertex buffer
    gVertexBufferData := []float32{-1.0, -1.0, 0.0, 1.0, -1.0, 0.0, 0.0, 1.0, 0.0}
    vertexBuffer := gl.GenBuffer()
    vertexBuffer.Bind(gl.ARRAY_BUFFER)
    gl.BufferData(gl.ARRAY_BUFFER, len(gVertexBufferData)*4, gVertexBufferData, gl.STATIC_DRAW)

    for {
        // ... (Clear screen, enable/disable vertex attrib, draw triangle) ...
        vertexAttrib.AttribPointer(
            3,     // Size
            gl.FLOAT, // Type
            false, // Normalized?
            0,     // Stride
            nil)   // Array buffer offset

        // ... (Continue drawing loop) ...
    }
}

The above is the detailed content of Why Can\'t I Display a Triangle Using go-gl/glfw and github.com/banthar/gl Despite Successful Window and Background Setup?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn