当为opengl纹理加载图像时,stb_image不会垂直翻转

时间:2018-12-26 13:42:17

标签: c++ opengl visual-studio-2017 stb-image

渲染时,我尝试加载的图像已旋转90度。我正在使用“ stbi垂直加载时翻转图像”,但是渲染纹理时,图像会旋转90度。

我试图更改索引和tex坐标,但是没有用。

//Mesh struct
Mesh mesh = {
// Position         // Color                // Tex coords
0.5f, 0.5f, 0.0f,   1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.0f,  0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.0f,  0.0f, 0.0f, 0.5f, 1.0f, 0.0f, 1.0f,
// Index
0,1,2,2,3,0
};

//The other code
/*Texture*/
int width, height, bpp;
unsigned char* image;
string path = "res/textures/Brick.png";
unsigned int texture;

stbi_set_flip_vertically_on_load(1);
image = stbi_load(path.c_str(), &width, &height, &bpp, 4);

glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, 
GL_UNSIGNED_BYTE, image);

if (image)
    stbi_image_free(image);

glActiveTexture(GL_TEXTURE0);
glUniform1i(glGetUniformLocation(shader, "Texture"), 0);

/*Position*/
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), 
(void*)0);
glEnableVertexAttribArray(0);
/*Color*/
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 9 * sizeof(float), 
(void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
/*Texture*/
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 9 * sizeof(float), 
(void*)(7 * sizeof(float)));
glEnableVertexAttribArray(2);

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

纹理应作为图像出现,并且不应旋转90度。 图片:https://opengameart.org/sites/default/files/oga-textures/brick_base.png

1 个答案:

答案 0 :(得分:1)

您说过我试图更改索引和纹理坐标,但是没有用。但是我认为您的问题恰恰在于2D到3D坐标映射。

您共享的当前映射坐标预计

旋转90度。我的意思是:

mode

如果您不希望旋转90度,则应为:

0.5f, 0.5f, 0.0f -> 0.0f, 0.0f
0.5f, -0.5f, 0.0f -> 1.0f, 0.0f
-0.5f, -0.5f, 0.0f -> 1.0f, 1.0f
-0.5f, 0.5f, 0.0f -> 0.0f, 1.0f

因此您的0.5f, 0.5f, 0.0f -> 0.0f, 0.0f 0.5f, -0.5f, 0.0f -> 1.0f, 0.0f -0.5f, -0.5f, 0.0f -> 0.0f, 1.0f -0.5f, 0.5f, 0.0f -> 1.0f, 1.0f 应该是这样的(不会交换颜色,请根据需要更改颜色):

mesh

已编辑