OpenGL生成三角网格



我是OpenGL的初学者,我试图在OpenGl中绘制一个三角网格,而我的问题是它不是绘制的,我看不出原因。另外,如果我打印顶点的数组,则x-和y坐标对于所有顶点保持不变。X-和Z坐标都应在 1和-1之间。当m_meshResolution = 1时,坐标似乎是正确的,但没有其他情况。我认为有一种尝试这样做的方法要简单得多,因此欢迎所有建议。

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);

positions是一个指针,sizeof(positions)返回4或8个字节,它取决于架构,但是glBufferData的第二个参数告诉我们

大小 指定Buffer对象的新数据存储的字节中的大小。

您应该将sizeof(float) * size用作第二个参数。

相关内容

  • 没有找到相关文章

最新更新