无法获取索引缓冲区以在 OpenGL 中绘制正方形

Cannot get index buffers to draw a square in OpenGL

我绝对是在做一些非常菜鸟的事情,但我就是不能用索引缓冲区画一个正方形。我正在按照 video 中的说明进行操作。但我只是没有得到预期的输出。

如果我注释掉数组中的一个顶点,它会绘制第二个三角形。此外,drawElement() 调用似乎按预期工作,因为我的代码中 ELEMENT_ARRAY 和 ARRAY_BUFFER 之间肯定存在链接,但我无法得到我一生的正方形。我检查并重新检查了我的代码很多次。有谁知道我可能会错过什么?这是我的代码:

#include <GL\glew.h>
#include <GLFW/glfw3.h>
#include <iostream>

#define print(x) std::cout << x << std::endl

static unsigned int CompileShader(unsigned int type, const std::string& source) {

    // returns an empty shader object of type specified
    unsigned int shader = glCreateShader(type);

    // because one of the arguments requires a double pointer
    const char* src = source.c_str();

    // Replaces(in this case writes) the source code of a shader object
    glShaderSource(shader, 1, &src, nullptr);

    // Compiles the shader
    glCompileShader(shader);

    // Finds compile status of shader
    int result;
    glGetShaderiv(shader, GL_COMPILE_STATUS, &result);

    if (result == GL_FALSE) {
        int length;
        glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);
        char* message = new char[length];

        glGetShaderInfoLog(shader, length, &length, message);
        print("Failed to compile shader");
        std::cout << (type == GL_VERTEX_SHADER ? "vertex" : "fragment") <<   std::endl;

        glDeleteShader(shader);
        return 0;
    }

    return shader;

}

static unsigned int CreateShader(const std::string& vertexShader, const  std::string& fragmentShader) {

// All shaders must be attached to a program object before executed. This     returns an empyty program object
    unsigned int program = glCreateProgram();

    // get shaders
    unsigned vs = CompileShader(GL_VERTEX_SHADER, vertexShader);
    unsigned fs = CompileShader(GL_FRAGMENT_SHADER, fragmentShader);

    // Attaches the shader to the program
    glAttachShader(program, vs);
    glAttachShader(program, fs);

    // creates shader executables
    glLinkProgram(program);

// validates success/failure/performance of program. stores in program's log
    glValidateProgram(program);

    return program;
}

int main(void)
{
    GLFWwindow* window;

    /* Initialize the library */
    if (!glfwInit())
        return -1;

    /* Create a windowed mode window and its OpenGL context */
    window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }


    /* Make the window's context current */
    glfwMakeContextCurrent(window);

    if (glewInit() != GLEW_OK) {
        print("Error");
    }

    float positions[8] = {
        -0.5f, -0.5f, // 0
         0.5f, -0.5f, // 1
        -0.5f,  0.5f, // 2
         0.5f,  0.5f  // 3
    };

    unsigned int indices[6] = {
        0, 1, 2,
        1, 2, 3
    };

    // Assigns a memory to GL_ARRAY_BUFFER
    unsigned int triangleBuffer;
    glGenBuffers(1, &triangleBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, triangleBuffer);

    // Fills in data to GL_ARRAY_BUFFER memory
    glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), positions, GL_STATIC_DRAW);

    // Defines where positions are located in GL_ARRAY_BUFFER and how to draw them configurations
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0);

    // Enables this vertex to be drawn using glDrawArrays().
    glEnableVertexAttribArray(0);


    // Shader programs in GLSL
    std::string vertexShader =
        // opengl version 3.3
        "#version 330 core\n"
        "\n"
        // select vertex attribute 0. vec4 because gl_Position requires vec4 argument. vertex shaders are 'in'
        "layout(location = 0) in vec4 position;\n"
        "\n"
        "void main()\n"
        "{\n"
        "   gl_Position = position;\n"
        "}\n";

    std::string fragmentShader =
        // opengl version 3.3
        "#version 330 core\n"
        "\n"
        // select vertex attribute 0. vec4 because color requires vec4 argument. fragment shader have 'out'
        "layout(location = 0) out vec4 color;\n"
        "\n"
        "void main()\n"
        "{\n"
        // colors in graphics are usually in 0-1 range. RGBA
        "   color = vec4(0.2, 0.3, 0.8, 1.0);\n"
        "}\n";

    // generate index buffers
    unsigned int ibo;
    glGenBuffers(1, &ibo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(unsigned int), &indices, GL_STATIC_DRAW);


    // Use Shaders
    unsigned int shaderProgram = CreateShader(vertexShader, fragmentShader);
    glUseProgram(shaderProgram);

    /* Loop until the user closes the window */
    while (!glfwWindowShouldClose(window))
    {
        /* Render here */
        glClear(GL_COLOR_BUFFER_BIT);

        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);

        /* Swap front and back buffers */
        glfwSwapBuffers(window);

        /* Poll for and process events */
        glfwPollEvents();
    }

    glfwTerminate();
    return 0;
}

总的来说,您的代码没有问题,但是顶点数组缓冲区大小的规范有误。 4顶点坐标

float positions[8] = { -0.5f, -0.5f, 0.5f, -0.5f, -0.5f,  0.5f, 0.5f,  0.5f };

由 8 个浮点数组成,而不是 6 个。

这意味着你的顶点数组是8*sizeof(float)。像这样更改您的代码:

glBufferData(
    GL_ARRAY_BUFFER,
    8 * sizeof(float), // <----- 8 instead of 6
    positions,
    GL_STATIC_DRAW );

注意,可以使用sizeof运算符来确定数组的字节大小:

glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW);

在 C++ 中,我更喜欢这样的东西:

const std::vector<float> positions{ -0.5f, -0.5f, 0.5f, -0.5f, -0.5f,  0.5f, 0.5f,  0.5f };
glBufferData(GL_ARRAY_BUFFER, positions.size()*sizeof(positions[0]), positions.data(), GL_STATIC_DRAW);