Search code examples
opengld

Can't render a triangle with EBO


I wanna render a rectangle with GL_ELEMENT_ARRAY_BUFFER but I get only one line render. With GL_ARRAY_BUFFER it works. For example, I've tried to render only one triangle but it also doesn't work.

Screenshot

Init:

Vertex[] vertices = [
    Vertex(-0.5, -0.5, 0), Vertex(0.5, -0.5, 0), Vertex(0, 0.5, 0)
];
GLuint[] indices = [0, 1, 2];
GLuint VAO, VBO, EBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, vertices.length * Vertex.sizeof, vertices.ptr, GL_STATIC_DRAW);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBindBuffer(GL_TRIANGLES, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.sizeof, &indices, GL_STATIC_DRAW);
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, null);
glCompileShader(vertexShader);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, null);
glCompileShader(fragmentShader);
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);

Rendering:

glClearColor(0.2, 0.2, 0.2, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glVertexAttribPointer(0,3,GL_FLOAT, GL_FALSE, float.sizeof * 3, cast(void*) 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glUseProgram(shaderProgram);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, &indices);

Full code.

What is wrong?


Solution

  • I've got a solution. There was an issue with:

    glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, &indices);

    &indices is a ptr to an entire array. But seems OpenGL requires ptr to each array element with indices.ptr.