代码之家  ›  专栏  ›  技术社区  ›  Ameen Izhac

当抽象到类中时,我的OpenGL顶点数组不再工作

  •  0
  • Ameen Izhac  · 技术社区  · 7 年前

    我正在使用OpenGL渲染一些立方体,我已经成功地渲染了大约10个立方体,但是我现在想把代码抽象成类。我从顶点数组对象开始。

    我已经阅读了代码,并按照它的着色器,确保顶点数据得到它需要的地方。

    #include "cube_vertex_array.h"
    
    cube_vertex_array::cube_vertex_array(float* vertex_buffer, const std::string& texture_file)
    {
        GLCall(glGenVertexArrays(1, &va_ID));
        GLCall(glBindVertexArray(va_ID));
    
    GLCall(glGenBuffers(1, &vb_ID));
    GLCall(glBindBuffer(GL_ARRAY_BUFFER, vb_ID));
    GLCall(glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer), vertex_buffer, GL_STATIC_DRAW));
    GLCall(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(0 * sizeof(float))));
    GLCall(glEnableVertexAttribArray(0));
    GLCall(glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))));
    GLCall(glEnableVertexAttribArray(1));
    
    GLCall(glGenTextures(1, &texture));
    GLCall(glBindTexture(GL_TEXTURE_2D, texture));
    GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT));
    GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT));
    GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
    GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
    int width, height, nrChanells;
    stbi_set_flip_vertically_on_load(true);
    unsigned char* data = stbi_load(texture_file.c_str(), &width, &height, &nrChanells, 0);
    if (data)
    {
        GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data));
        GLCall(glGenerateMipmap(GL_TEXTURE_2D));
    }
    else { std::cout << "failed to load texture" << std::endl; }
    stbi_image_free(data);
    
    GLCall(glBindVertexArray(0));
    }
    
    void cube_vertex_array::bind()
    {
        GLCall(glBindVertexArray(va_ID));
    }
    

    main()
    {
    cube_vertex_array cube_1(vertices, "resources/test.png");
    cube_1.bind();
    while (!glfwWindowShouldClose(window))
        {
        cube_1.bind();
        GLCall(glDrawArrays(GL_TRIANGLES, 0, 36));
        }
        GLCall(glDeleteVertexArrays(1, &cube_1.va_ID));                                                                             
    GLCall(glDeleteBuffers(1, &cube_1.vb_ID));
    }   
    

    我希望看到多个立方体渲染,但这不会发生。如果我将顶点数组直接实现到主文件中,代码会渲染立方体,但是当抽象到类中时,它不会渲染任何内容。这里可能有什么问题?

    0 回复  |  直到 7 年前
        1
  •  1
  •   ZimmerA    7 年前

    问题是你“打电话” sizeof(vertex_buffer)

    GLCall(glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_buffer), vertex_buffer, GL_STATIC_DRAW));
    

    vertex_buffer 是指向数组的指针,因此如果您“调用” sizeof float* 而不是数组时间中的元素数 sizeof(float)

    解决这个问题的一种方法是将数组的大小作为参数传递。 您可以做的另一件事是发送数组中元素的数量,并将其乘以sizeof(float)。

    推荐文章