How to use element array buffer?

Hello,

I’m trying to draw things using by element array buffer in the 3D space.
However I can’t draw anything with element array buffer but with vertex array buffer.

Can you please advice me how to fix the issue?

Below is my codes

[Vertex Shader]

#version 450 core
layout (location = 0) in vec3 aPos;

out vec4 aColor;

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;
uniform vec4 color;
uniform float size;

void main() {
    aColor = color;
    gl_Position = projection * view * model * vec4(aPos, 1.0);
    gl_PointSize = size;
}

[Fragment Shader]

#version 450 core
in vec4 aColor;

out vec4 FragColor;

void main() {
    FragColor = aColor;
}

[Vertices and Indices]

float vertice[] = {
    -0.2, 0.2, -0.2,
    -0.2, 0.2, 0.2,
    0.2, 0.2, -0.2,
    0.2, 0.2, 0.2,
    0.2, -0.2, -0.2,
    0.2, -0.2, 0.2,
    -0.2, -0.2, -0.2,
    -0.2, -0.2, 0.2
};

float surfaceIncides[] = {
    0, 3, 2,
    3, 0, 1,
    4, 7, 6,
    7, 4, 5,
    1, 5, 3,
    5, 1, 7,
    2, 6, 0,
    6, 2, 4,
    3, 4, 2,
    4, 3, 5,
    0, 7, 1,
    7, 0, 6
};

unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);

glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertice), vertice, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(0);

GLuint surfaceEAB;
glGenBuffers(1, &surfaceEAB);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, surfaceEAB);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(surfaceIncides), surfaceIncides, GL_STATIC_DRAW);

[Drawing codes]

// Draw Cube
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, surfaceEAB);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);

// Draw points
glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
modeling.setFloat("size", 10.0);
glBindVertexArray(VAO);
glDrawArrays(GL_POINTS, 0, 8);
glBindVertexArray(0);

[Result]

float surfaceIncides[] ....

glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);

float is not a valid data type to use here; indices should be unsigned short or unsigned int, and the type parameter to glDrawElements should match. (OpenGL also supports unsigned byte indices but you really shouldn’t use that.)

okay, thanks!!

but, I’ve tried it with

unsigned int surfaceIncides[] ....
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);

but still, nothing is drawn on the screen…

Oh now I found the reason why…

I have to remove this otherwise drawings gets deleted

glBindVertexArray(0);

so now I can draw things on screen!!

Thanks!!!

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.