正如我們知道如果我們想要在世界空間中繪製某些東西,我們需要通過視圖矩陣和投影矩陣來乘以我們的數據。現在我需要爲我的任務在着色器之外進行頂點轉換並直接發送轉換頂點。就像這樣:爲什麼GPU外部的頂點轉換與GPU內部的頂點轉換不同?
初始化矩陣
glm::mat4 view, projection;
view = glm::lookAt(this->cameraPos, this->cameraPivot, this->Up);
projection = glm::perspective(glm::radians(60.0f), (float)screenWidth/(float)screenHeight, 0.1f, 100.0f);
代碼
vector<glm::vec3> data;
glm::mat4 projection, view;
...
data.push_back(glm::vec3(projection * view * glm::vec4(0.0, 0.0, 0.5, 0.0)));
data.push_back(glm::vec3(projection * view * glm::vec4(0.0, 0.5, 0.5, 0.0)));
data.push_back(glm::vec3(projection * view * glm::vec4(0.5, 0.5, 0.5, 0.0)));
data.push_back(glm::vec3(projection * view * glm::vec4(0.5, 0.0, 0.5, 0.0)));
...
shader.set();
GLuint VAO,VBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &wVBO);
glBindVertexArray(wVAO);
glBindBuffer(GL_ARRAY_BUFFER, wVBO);
glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(vector<glm::vec3>), &data.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
...
glBindVertexArray(wVAO);
glDrawArrays(GL_LINE_LOOP, 0, data.size());
glBindVertexArray(0);
着色
#version 330 core
layout (location = 0) in vec3 position;
void main()
{
gl_Position = vec4(position, 1.0f);
}
,但我得到錯誤的視圖轉換 - 它看起來像我的數據沒有考慮投影矩陣,只考慮視圖矩陣。但是,如果我改變它像往常一樣:
代碼
...
data.push_back(glm::vec3(glm::vec4(0.0, 0.0, 0.5, 0.0)));
...
shader.set();
glUniformMatrix4fv(glGetUniformLocation(shader.Program, "matrices"), 1,
GL_FALSE, glm::value_ptr(projection * view));
着色
#version 330 core
layout (location = 0) in vec3 position;
uniform mat4 matrices;
void main()
{
gl_Position = matrices * vec4(position, 1.0f);
}
它按預期工作。我的錯誤是什麼?在我的任務中,需要知道在世界空間中所有頂點的位置,然後纔會在着色器中發送。我怎樣才能做到這一點?
有點難以比較,當我們不知道你的頂點着色器。 – Vallentin
好的,一分鐘! – OpenGLNoob
也請顯示代碼,你初始化視圖和投影矩陣 – DanielCollier