Search code examples
c++openglglfwglm-mathvbo

Trouble Rendering a Grid of Triangles in OpenGL


I'm trying to render a square grid made up of triangles in OpenGL and C++ using the standard VBO/VAO/EBO techniques but for some reason this stuff wont render right.

I start by generating the vertices and indices for my grid based on a gridSideLength

int gridSideLength= 16; // any power of 2
unsigned int gridVBO, gridVAO, gridEBO;

const uint32_t verticesCount = (gridSideLength + 1) * (gridSideLength + 1);
const uint32_t indicesCount = gridSideLength * gridSideLength* 2;

std::vector<glm::vec3> vertices(verticesCount);
std::vector<glm::vec3> indices(indicesCount);

// populate vertices
uint32_t idx = 0;
for (float i = -(gridSideLength / 2); i <= (gridSideLength / 2); ++i) {
    for (float j = -(gridSideLength / 2); j <= (gridSideLength / 2); ++j) {
        vertices[idx] = glm::vec3((float)j, 0.0f, (float)i);
        idx++;

    }
}

// populate indices with clockwise winding
idx = 0;
for (int i = 0; i < gridSideLength; ++i) {
    int row1 = i * (gridSideLength + 1);
    int row2 = (i + 1) * (gridSideLength + 1);

    for (int j = 0; j < gridSideLength; ++j) {
        indices[idx++] = glm::uvec3(row1 + j, row1 + j + 1, row2 + j + 1);
        indices[idx++] = glm::uvec3(row1 + j, row2 + j + 1, row2 + j);

    }
}

As far as I can tell by printing the values out, this generates the correct vertices and indices.

Next, set up the VBO, VAO, and EBO objects

// bind grid VBO, VAO, and EBO
glGenBuffers(1, &gridVBO);
glBindBuffer(GL_ARRAY_BUFFER, gridVBO);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vertices[0]), &vertices[0], GL_STATIC_DRAW);

glGenVertexArrays(1, &gridVAO);
glBindVertexArray(gridVAO);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

glGenBuffers(1, &gridEBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, gridEBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(indices[0]), &indices[0], GL_STATIC_DRAW);

Again this looks alright to me and I can render some things fine with it but idk.

Lastly, my render loop:

while (glfwWindowShouldClose(window) == false) 
{
    glm::mat4 model = glm::mat4(1.0f);
    glm::mat4 view = camera.CalculateViewMatrix();
    glm::mat4 projection = glm::perspective(glm::radians(camera.getZoom()), (float)SCREEN_WIDTH / (float)SCREEN_HEIGHT, 0.1f, 100.0f);

    // ...
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glClearColor(0.05f, 0.05f, 0.05f, 1.0f);
        
    glBindVertexArray(m_GridVAO);
    glDrawElements(GL_TRIANGLES, indices.size() * 3, GL_UNSIGNED_INT, 0);
}

Unfortunately, all I get is a single line and I'm not sure where to go from here besides banging my head against a wall. Does Does anything stick out as wrong? Thanks for any help!


Solution

  • Vertex indices must be integer values:

    std::vector<glm::vec3> indices(indicesCount);

    std::vector<glm::uvec3> indices(indicesCount);