Marcus
Marcus

Reputation: 162

OpenGL generate triangle mesh

I am a beginner at OpenGl and I am trying to draw a triangle mesh in OpenGL like this and my problem is that it is not drawing and I cannot see why. Also if I print the array of vertices the x- and y-coordinate remain the same for all vertices. Both the x- and z-coordinates should lie between +1 and -1. The coordinates seem to be correct when m_meshResolution = 1 but not otherwise. I assume that there is a much easier way to try to do this so all advice is welcome.

int size = m_meshResolution * m_meshResolution * 2 * 3 * 3;
float* positions = new float[size]();

double triangleWidth = 2 / m_meshResolution;
float startX = -1.0f;
float startZ = 1.0f;
float x1 = 0;
float x2 = 0;
float z1 = 0;
float z2 = 0;
int index = 0;
//For each row
for (int r = 0; r < m_meshResolution; r++) {
    //For each column
    for (int c = 0; c < m_meshResolution; c++) {
        x1 = startX + c*divider;
        x2 = startX + (c+1)*divider;
        z1 = startZ - r*divider;
        z2 = startZ -(r+1)*divider;
        //Generate one triangle
        positions[index++] = x1;
        positions[index++] = 0;
        positions[index++] = z1;
        positions[index++] = x2;
        positions[index++] = 0;
        positions[index++] = z2;
        positions[index++] = x2;
        positions[index++] = 0;
        positions[index++] = z1;
        //Generate other triangle
        positions[index++] = x1;
        positions[index++] = 0;
        positions[index++] = z1;
        positions[index++] = x1;
        positions[index++] = 0;
        positions[index++] = z2;
        positions[index++] = x2;
        positions[index++] = 0;
        positions[index++] = z2;
    }

//Set buffers
glGenBuffers(1, &m_positionBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_positionBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW);

glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
glBindBuffer(GL_ARRAY_BUFFER, m_positionBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, false/*normalized*/, 0/*stride*/, 0/*offset*/);
glEnableVertexAttribArray(0);

//Draw
glBindVertexArray(m_vao);
glDrawArrays(GL_TRIANGLES, 0, m_meshResolution*m_meshResolution*2*3);

Upvotes: 0

Views: 2858

Answers (1)

rafix07
rafix07

Reputation: 20938

positions is a pointer, and sizeof(positions) returns 4 or 8 bytes, it depends on architecture, but the second parameter of glBufferData tells us

size Specifies the size in bytes of the buffer object's new data store.

you should use sizeof(float) * size as second parameter.

Upvotes: 4

Related Questions