奇怪的OpenGL纹理问题?

3

这是我尝试加载的纹理:

enter image description here

这是我运行代码时看到的:

enter image description here

这是我使用的代码:

#include "sdl.h"
#include "sdl_opengl.h"
#include <stdio.h>
#include <gl/GL.h>
#include <gl/GLU.h>

Uint32 loadTexture(char* fileName)
{
    Uint32 id;
    SDL_Surface *img = NULL;

    //load into memory using SDL
    img = SDL_LoadBMP(fileName);
    //generate an id for this texture
    glGenTextures(1, &id);
    //use this texture
    glBindTexture(GL_TEXTURE_2D, id);
    //load the texture into video memory via OpenGL
    glTexImage2D(
        GL_TEXTURE_2D,
        0,
        GL_RGB,
        img->w,
        img->h,
        0,
        GL_RGB,
        GL_UNSIGNED_SHORT_5_6_5,
        img->pixels
        );

    //set mip map settings
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    SDL_FreeSurface(img);

    return id;
}

Uint32 tex;

void init()
{
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0, 1.0, 1.0, 0.0, -1.0, 1.0);
    glMatrixMode(GL_MODELVIEW);
    glEnable(GL_TEXTURE_2D);

    tex = loadTexture("fireball.bmp");
}
void display()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();

    glBindTexture(GL_TEXTURE_2D, tex);

    glBegin(GL_QUADS);
    glTexCoord2f(0.0, 0.0);
    glVertex3f(0.25, 0.25, 0.0);


    glTexCoord2f(1.0, 0.0);
    glVertex3f(0.5, 0.25, 0.0);


    glTexCoord2f(1.0, 1.0);
    glVertex3f(0.5, 0.5, 0.0);


    glTexCoord2f(0.0, 1.0);
    glVertex3f(0.25, 0.5, 0.0);
    glEnd();
}

int main()
{
    INT32 isRunning = 1;
    SDL_Surface *screen = NULL;
    SDL_Event event;
    INT32 start;
    INT32 FPS = 30;

    SDL_Init(SDL_INIT_EVERYTHING);

    screen = SDL_SetVideoMode(640, 480, 32, SDL_OPENGL);

    init();

    while(isRunning)
    {
        start = SDL_GetTicks();

        while(SDL_PollEvent(&event))
        {
            switch(event.type)
            {
                case SDL_QUIT: isRunning = 0; break;
            }
        }

        display();

        SDL_GL_SwapBuffers();

        if(1000 / FPS > SDL_GetTicks() - start)
        {
            SDL_Delay(1000 / FPS - (SDL_GetTicks() - start));
        }
    }

    SDL_Quit();

    return(0);
}
1个回答

5
glTexImage2D(
    GL_TEXTURE_2D,
    0,
    GL_RGB,
    img->w,
    img->h,
    0,
    GL_RGB,
    GL_UNSIGNED_SHORT_5_6_5,
    img->pixels
    );

这实际上是它的格式吗?每2个字节是一个5/6/5 RGB像素。我不知道Windows BMP文件是否可以存储5/6/5图像数据,但我从未费心编写图像加载代码,所以我不确定。我认为BMP数据只能是8/8/8 BGR格式。

即使可以是5/6/5,您确定这张图片是在这种格式下的吗?

此外,行对齐是什么?我没有看到您使用glPixelStorei设置GL_UNPACK_ALIGNMENT,因此您必须希望每一行都对齐到4个字节大小。这是正确的吗?


我其实不确定GL_UNPACK_ALIGNMENT和glPixelStorei是什么意思。我现在会去看OpenGL文档,但是要知道我是在看视频教程。这个人在Linux而不是Windows上使用。我还会尝试更改格式,因为你说可能是错误的。 - LunchMarble
1
经过调整数值,以下是可行的代码:glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, img->w, img->h, 0, GL_BGR, GL_UNSIGNED_BYTE, img->pixels ); - LunchMarble

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接