Search code examples
javaopenglsegmentation-faultlwjglglfw

Java GLFW segfault when using GL_ELEMENT_ARRAY_BUFFER


Whenever I use GL_ELEMENT_ARRAY_BUFFER to draw my objects, GLFW throws me a segfault on glfwSwapBuffers();

Here's the problematic code:

public Mesh( float[] verts, int[] indices ) {
    indicesCount = indices.length;

    vertexBuffer = glGenBuffers();
    elementBuffer = glGenBuffers();
    vertexArray = glGenVertexArrays();

    glBindVertexArray( vertexArray );
    glBindBuffer( GL_ARRAY_BUFFER, vertexBuffer );
    glBufferData( GL_ARRAY_BUFFER, verts, GL_STATIC_DRAW );

    glVertexAttribPointer( 0, 3, GL_FLOAT, false, 6 * 4, 0 * 4 );
    glEnableVertexAttribArray( 0 );

    glVertexAttribPointer( 1, 3, GL_FLOAT, false, 6 * 4, 3 * 4 );
    glEnableVertexAttribArray( 1 );

    // Uncommenting this code causes segfault
    //glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, elementBuffer );
    //glBufferData( elementBuffer, indices, GL_STATIC_DRAW );

    glBindVertexArray( 0 );
    glBindBuffer( GL_ARRAY_BUFFER, 0 );
    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
}

public void draw() {
    glBindVertexArray( vertexArray );

    //glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, elementBuffer );
    //glDrawElements( GL_TRIANGLES, indicesCount, GL_UNSIGNED_INT, 0 );
    glDrawArrays( GL_TRIANGLES, 0, 3 );
    glBindVertexArray( 0 );
}

Segfault is caused by this code:

System.out.println( "Hello" );  // <- Would get printed 
glfwSwapBuffers( windowID );    // <- SIGSEGV
System.out.println( "Hello2" ); // <- Would not get printed

I am using latest LWJGL version 3.2.0, although I also tried 3.1.6, to no avail. I am completely lost, and if nothing works I guess I'll just have to stick to using C++, cause the same code works perfectly there.


Solution

  • The 1st parameter of glBufferData has to be the target (GL_ELEMENT_ARRAY_BUFFER) to which the buffer object is bound and not the named buffer object. glBufferData affects the named buffer which is bound to the target.

    Use the following code to solve your issue:

    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, elementBuffer );
    glBufferData( GL_ELEMENT_ARRAY_BUFFER, indices, GL_STATIC_DRAW );