Search code examples
javaopengllwjgl

How to bind a buffer in lwjgl


I'm trying to draw a triangle in the middle of the screen using lwjgl and OpenGL. My current code looks like this:

int vertexBuffer = glCreateBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, g_vertex_buffer_data, GL_STATIC_DRAW);
                              //and initalised FloatBuffer

And the main loop:

while (glfwWindowShouldClose(windowID) == GL_FALSE) {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
        glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, vertexBuffer);
        glEnableVertexAttribArray(0);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        glDisableVertexAttribArray(0);
        glfwSwapBuffers(windowID);
        glfwPollEvents();
    }

Could you help me?


Solution

  • You misunderstood the glCreateBuffers() function. Instead of binding the buffer itself to OpenGL, you generate an ID:

    IntBuffer buffer = BufferUtils.createIntBuffer(1);
    glCreateBuffers(buffer);
    int id = buffer.get(0);
    

    You could also just call glCreateBuffers() without arguments and use the return value as ID:

    int id = glCreateBuffers();
    

    To write data to this buffer you first have to bind it, this just tells OpenGL that you want to write to the bound offer.

    glBindBuffer(GL_ARRAY_BUFFER, id);
    

    As you can see you pass in the generated ID, to bind the corresponding buffer.

    Next you can write to the OpenGL buffer, like this:

    glBufferData(GL_ARRAY_BUFFER, g_vertex_buffer_data, GL_STATIC_DRAW);
    

    This sends the contents of g_vertex_buffer_data to the OpenGL context on the GPU. g_vertex_buffer_data contains your vertex data (model data) and you do not want to create a buffer OF this java.nio.Buffer, but let OpenGL generate an ID for a GPU-buffer and then send the contents of your java.nio.Buffer to the GPU-buffer.

    For information look at the LWJGL Wikipage about Vertex Buffer.