【问题标题】:OpenGL won't draw within class [duplicate]OpenGL不会在类内绘制[重复]
【发布时间】:2021-01-19 08:52:47
【问题描述】:

我对 OpenGL 有点陌生,我目前正在尝试创建一个可以处理将顶点绘制到屏幕上的类,但它似乎不起作用,它不绘制任何东西。我知道这个问题与着色器无关 cz 当我在没有类的情况下(直接在 main.cpp 文件中)这样做时它可以工作。

模型.h

#include <glad/glad.h>
class Model
{
private:
    GLuint VAO, VBO, EBO;

public:
    Model(float vertices[], unsigned int indices[]);
    void Draw();
};

模型.cpp

#include "Model.h"
Model::Model(float vertices[], unsigned int indices[])
{
    glGenVertexArrays(1, &this->VAO);
    glGenBuffers(1, &this->VBO);
    glGenBuffers(1, &this->EBO);

    glBindVertexArray(this->VAO);

    glBindBuffer(GL_ARRAY_BUFFER, this->VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);
}

void Model::Draw()
{
    glBindVertexArray(VAO);
    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
}

Main.cpp

#include <iostream>
#include "Model.h"
#include "Shader.h"
#include "Window.h"

int main()
{
std::cout << "Start" << std::endl;

float vertices[] = {
     0.5f,  0.5f, 0.0f,
     0.5f, -0.5f, 0.0f,
    -0.5f, -0.5f, 0.0f,
    -0.5f,  0.5f, 0.0f
};
unsigned int indices[] = {
    0, 1, 3,
    1, 2, 3
};

Window window("MyWindow", 800, 600);
window.Show();

Model square(vertices, indices);

Shader testShader("testVertexShader.glsl", "testFragmentShader.glsl");

glViewport(0, 0, 800, 600);

while (!window.ShouldClose())
{
    /*glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);*/     

    testShader.Use();
    square.Draw();

    window.Update();
}

testShader.Delete();
window.Close();

std::cout << "End" << std::endl;

return 0;

}

【问题讨论】:

  • sizeof(vertices) 是错误的。它会给你一个固定的数字,4 或 8(指针的大小)。

标签: c++


【解决方案1】:

与类或 OpenGL 无关,但与数组和指针有关的常见错误。

错误在这里

sizeof(vertices)

在这个构造函数中的顶点是一个指针。因此sizeof(vertices) 给你的是指针的大小,而不是原始数组的大小。

sizeof(indices) 出现同样的错误。

将您需要的大小作为单独的参数传递,或者做 C++ 程序员应该做的事情并使用向量而不是数组。

Model::Model(const std::vector<float>& vertices, const std::vector<unsigned int>& indices)
{
    ...
    glBufferData(GL_ARRAY_BUFFER, vertices.size()*sizeof(vertices[0]), vertices.data(), GL_STATIC_DRAW);
    ...
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size()*sizeof(indices[0]), indices.data(), GL_STATIC_DRAW);
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多