Search code examples
javaopengllwjgl

Why doesn't lwjgl draw a Rectangle?


I want to draw a rectangle in lwjgl. The code should draw a rectangle, but it doesn't. I am using OpenGL 4.4 (LWJGL doesn't support beyond that).
I am mostly a beginner in 3d Graphics and such so any help would be greatly appreciated.

    float[] vertices= {
            0.5f, 0.5f, 0.0f,
            0.5f, -0.5f, 0.0f,
            -0.5f, -0.5f, 0.0f,
            -0.5f, 0.5f, 0.0f
    };
    float[] indices= {
            0,1,2,
            2,3,0
    };

    Shader vsh=new Shader("vertexShader.vsh",GL_VERTEX_SHADER);
    Shader fsh=new Shader("fragmentShader.fsh",GL_FRAGMENT_SHADER);
    sp=Shader.createProgram(vsh.shader,fsh.shader);

    int VBO,EBO;
    VAO=glGenVertexArrays();
    VBO=glGenBuffers();
    EBO=glGenBuffers();

    glBindVertexArray(VAO);
        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);

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

        glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);
        glEnableVertexAttribArray(0);
    glBindVertexArray(0);

    glClearColor(1.0f,1.0f,1.0f,1.0f);
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
void loop(){
    while(!glfwWindowShouldClose(w.window)) {       
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glUseProgram(sp);
        glBindVertexArray(VAO);
        glDrawElements(GL_TRIANGLES, 6,GL_UNSIGNED_INT,0);
        glBindVertexArray(0);

        glfwSwapBuffers(w.window);

        glfwPollEvents();
    }
}
void run() {
    init();
    loop();
}
public static void main(String[] args) {
    new Core().run();
}

It works when I remove the indices and use glDrawArrays instead of glDrawElements.


Solution

  • The type of the array of indices has to be int rather than float:

    float[] indices =
    int [] indices =

    The type of the data in the element array buffer has to match the which is specified when glDrawElements is called.

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT,0);
    

    The specified type must be one of GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, or GL_UNSIGNED_INT. The corresponding data types in java are byte, short respectively int.