我正在尝试将纹理应用于opengl中的基本三角形。问题是我的纹理不起作用,它只会在三角形上应用一种奇怪的颜色......
我已经看过文档和一些 youtube 教程,但我真的无法让它工作。
以下是一些代码示例:
纹理构造函数 -
Textures::Textures(const std::string& fileName)
{
int width, height, numComponents;
unsigned char * data = stbi_load(
fileName.c_str()
, &width
, &height
, &numComponents
, 0
);
if (data == NULL)
std::cerr << "Texture loading error: " << fileName << std::endl;
glGenTextures(1, &m_texture);
glBindTexture(GL_TEXTURE_2D, m_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
if (numComponents == 3)
glTexImage2D(
GL_TEXTURE_2D
, 0
, GL_RGB
, width
, height
, 0
, GL_RGB
, GL_UNSIGNED_BYTE
, data
);
else if(numComponents == 4)
glTexImage2D(
GL_TEXTURE_2D
, 0
, GL_RGBA
, width
, height
, 0
, GL_RGBA
, GL_UNSIGNED_BYTE
, data
);
glBindTexture(GL_TEXTURE_2D, 0);
stbi_image_free(data);
}
网格构造函数 -
Meshes::Meshes(Vertex* vertices, unsigned int numVertices)
{
m_drawCount = numVertices;
glGenVertexArrays(1, &m_vertexArrayObject);
glBindVertexArray(m_vertexArrayObject);
std::vector<glm::vec3> positions;
std::vector<glm::vec2> texCoord;
positions.reserve(numVertices);
texCoord.reserve(numVertices);
for (unsigned int i = 0; i < numVertices; ++i) {
positions.push_back( *vertices[i].getPos() );
texCoord.push_back( *vertices[i].getTexture() );
}
glGenBuffers(NUM_BUFFERS, m_vertexArrayBuffers);
glBindBuffer(GL_ARRAY_BUFFER, m_vertexArrayBuffers[POSITION_VB]);
glBufferData(
GL_ARRAY_BUFFER
, positions.size() * sizeof(positions[0])
, &positions[0]
, GL_STATIC_DRAW
);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, m_vertexArrayBuffers[TEXTURE_COORD_VB]);
glBufferData(
GL_ARRAY_BUFFER
, texCoord.size() * sizeof(texCoord[0])
, &texCoord[0]
, GL_STATIC_DRAW
);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);
glBindVertexArray(0);
}
着色器片段 -
#version 120
varying out vec4 diffuseColor;
varying vec2 texCoord0;
uniform sampler2D diffuse;
void main()
{
diffuseColor = texture2D(diffuse, texCoord0 );
}
着色器顶点 -
#version 120
attribute vec3 position;
attribute vec2 texCoord;
varying vec2 texCoord0;
void main()
{
gl_Position.xyz = position;
gl_Position.w = 1;
texCoord0 = texCoord;
}
这是github上的代码,您可以自己查看:https ://github.com/Kosta-Git/Pong/tree/master/Pong
另外我还有另一个问题是我什至无法加载 texture.jpg 文件(bricks.jpg 有效),但我想这是因为它不是 512x512。