我刚开始实现 librocket(一个从 HTML 生成网格的 UI 库),其中一个要求是RenderInterface
. 该库基本上发送您从生成的网格继承的类,RenderInterface
并希望您保存网格,然后它希望您渲染这个生成的网格。听起来不错,因为您有机会为 3rd 方库实现自己的渲染系统。但是我的问题可能与 lib 无关。
正如我告诉 lib 将网格发送到我的班级:
GLuint m_BufferID[2];
//...
glGenBuffers(2, m_BufferID);
//..
glBindBuffer(GL_ARRAY_BUFFER, m_BufferID[0]);
glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_BufferID[1]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
这基本上是在 Lib 向我发送网格时发生的。实际上它还加载了纹理等,但这目前并不重要。(注意:data 是一个指向 ROCKET_LIB::Vertex 数组的指针)
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(ROCKET_CORE::Vertex), (GLvoid*)offsetof(Rocket::Core::Vertex, position));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ROCKET_CORE::Vertex), (GLvoid*)offsetof(Rocket::Core::Vertex, colour));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(ROCKET_CORE::Vertex), (GLvoid*)offsetof(Rocket::Core::Vertex, tex_coord));
glUniformMatrix4fv(0, 1, GL_FALSE, &m_TransMatrix[0][0]);
glUniform2f(1, translation.x, translation.y);
glActiveTexture(GL_TEXTURE0);
glBindBuffer(GL_ARRAY_BUFFER, m_BufferID[0]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_BufferID[1]);
glDrawElements(GL_TRIANGLES, m_indices_count, GL_UNSIGNED_INT, NULL);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
网格上传到 GPU 后,我用上面的代码渲染它。为了完成这个问题,这里是我的着色器:
顶点着色器:
#version 330
layout(location = 0) in vec2 inPosition;
layout(location = 1) in vec4 inColor;
layout(location = 2) in vec2 inTexCoord;
out vec4 fragColor;
out vec2 fragTexCoord;
layout(location = 0) uniform mat4 m_Ortho;
layout(location = 1) uniform vec2 m_Translation;
void main()
{
// Setting out values
fragColor = inColor;
fragTexCoord = inTexCoord;
// Settings transformed position
gl_Position = vec4(inPosition + m_Translation, 1.0f, 1.0f) * m_Ortho;
}
片段着色器:
#version 330
in vec4 fragColor;
in vec2 fragTexCoord;
out vec4 outColor;
layout (location = 2) uniform sampler2D m_TextureSampler;
void main()
{
// Just for testing purpose show the text coord as color
outColor = vec4(fragTexCoord, 0.0f, 1.0f);
}
哦,我只是生成矩阵:
glm::ortho(0.0f, static_cast<float>(m_Width), static_cast<float>(m_Height), 0.0f, -1.0f, 1.0f);
从 DirectX 我了解到你必须转置矩阵,我也在 opengl 中尝试过,但最后两个结果都很奇怪。这是一个屏幕截图,它表明某些事情肯定是不对的。(线框已激活)