2016-12-23 146 views
0

我想用OpenGL畫一個四邊形,但是它不起作用,因爲我引入了索引。如果沒有索引我的代碼工作正常,我可以用glDrawArrays用OpenGL渲染四邊形的問題

#define GLEW_STATIC 
#include <GL\glew.h> 
#include <GLFW\glfw3.h> 
#include <GL\glew.h> 
#include <glm.hpp> 
#include <iostream> 
#include <fstream> 
#include <string> 
#include <vector> 

#define WIDTH 800 
#define HEIGHT 600 
#define TITLE "Dynamic" 

GLFWwindow* window; 
int vaoID; 


std::vector<float> vertices = {-0.5f, 0.5f, 0,  -0.5f, -0.5f, 0,  0.5f, -0.5f, 0, 0,  0.5f, 0.5f, 0}; 
std::vector<int> indices = { 0, 1, 3, 3, 1, 2 }; 
void loadToVAO(std::vector<float> vertices, std::vector<int> indices); 

void update() { 
    loadToVAO(vertices, indices); 
    while (!glfwWindowShouldClose(window)) { 
     glfwPollEvents(); 
     glClear(GL_COLOR_BUFFER_BIT); 
     glClearColor(1, 0, 0, 1); 
     //glDrawArrays(GL_TRIANGLES, 0, 6); 
     glDrawElements(GL_TRIANGLES, 6, GL_INT, 0); 
     glfwSwapBuffers(window); 
    } 
} 

int main() { 
    if (!glfwInit()) 
     std::cout << "Couldn't initialize GLFW!" << std::endl; 

    window = glfwCreateWindow(WIDTH, HEIGHT, TITLE, NULL, NULL); 
    glfwMakeContextCurrent(window); 
    glfwSwapInterval(1); 

    if (GLEW_OK != glewInit()) 
     std::cout << "GLEW is not working!" << std::endl; 

    std::cout << "Your GL version: " << glGetString(GL_VERSION) << std::endl; 
    //glEnable(GL_CULL_FACE); 
    //glCullFace(GL_BACK); 
    update(); 
} 

void loadToVAO(std::vector<float> vertices, std::vector<int> indices) { 
    GLuint vertexVBO; 
    GLuint indicesVBO; 
    GLuint vaoID; 
    glGenBuffers(1, &vertexVBO); 
    glGenVertexArrays(1, &vaoID); 
    glBindVertexArray(vaoID); 
    glGenBuffers(1, &indicesVBO); 
    glBindBuffer(GL_ARRAY_BUFFER, vertexVBO); 
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesVBO); 
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices) * sizeof(int), &indices[0], GL_STATIC_DRAW); 
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) * sizeof(float), &vertices[0], GL_STATIC_DRAW); 
    glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); 
    glEnableVertexAttribArray(0); 
} 

回答

1

再次,sizeof運營商的問題,因爲它返回的基本類型的大小,而不是一些數據大小的指針指向。在線路

glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices) * sizeof(int), &indices[0], GL_STATIC_DRAW); 

sizeof(indices) == sizeof(std::vector<int>)它是矢量對象的大小和包含於載體中的數據的大小。這裏的正確的代碼是使用indices.size()返回矢量中元素的個數:

glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(int), &indices[0], GL_STATIC_DRAW); 

同樣爲頂點的上傳。

編輯:你不應該通過價值傳遞載體,除非它是絕對必要的。當您將它們傳遞給loadToVAO時,Atm將複製這兩個向量的內容。如果將函數簽名更改爲

void loadToVAO(std::vector<float>& vertices, std::vector<int>& indices) 

向量通過引用傳遞並且數據不會被複制。