奇怪的 SDL_Surface->format->BytesPerPixel 值

Weird SDL_Surface->format->BytesPerPixel value

所以我正在使用 SDL_image 在我的 OpenGL 应用程序中加载高度图和创建地形。

我就是这样初始化的SDL_image:

int flags = IMG_INIT_PNG;
int initted = IMG_Init(flags);
if((initted & flags) != flags) {
    printf("IMG_Init: Failed to init required jpg and png support!\n");
    printf("IMG_Init: %s\n", IMG_GetError());
    return;
}

Load(filename);

...这是我的加载函数:

void Load(string filename) {
    img = IMG_Load(filename.c_str());
    if(!img) {
        printf("IMG_Load: %s\n", IMG_GetError());
        return;
    }
    printf("IMG_Load: %s\n", IMG_GetError());
    xsize = img->w;
    ysize = img->h;

    SDL_LockSurface(img);
    imgData = (Uint32*)img->pixels;
    SDL_UnlockSurface(img);
}

然后,在我准备顶点缓冲区的 Terrain class 中,我使用以下方法读取像素值:

Uint32 getPixel(int x, int y) {
    SDL_LockSurface(img);

    int bpp = img->format->BytesPerPixel;
    //cout << "bpp " << bpp << "\n";
    /* Here p is the address to the pixel we want to retrieve */
    Uint8 *p = (Uint8 *)img->pixels + y * img->pitch + x * bpp;

    SDL_UnlockSurface(img);

    switch(bpp) {
    case 1:
        return *p;
        break;

    case 2:
        return *(Uint16 *)p;
        break;

    case 3:
        if(SDL_BYTEORDER == SDL_BIG_ENDIAN)
            return p[0] << 16 | p[1] << 8 | p[2];
        else
            return p[0] | p[1] << 8 | p[2] << 16;
        break;

    case 4:
        return *(Uint32 *)p;
        break;

    default:
        return 0;       /* shouldn't happen, but avoids warnings */
    }
}

...事实证明,每次我 运行 程序 img->format->BytesPerPixel return 都是一个随机值...到底是什么?有人有什么主意吗?这应该只有 return 1、2、3 或 4。

好吧,我只是愚蠢...但是如果有人遇到像我这样的问题:我包含了错误版本的 SDL_image...#include <SDL/SDL_image.h> 而不是 #include <SDL2/SDL_image.h>.现在一切都按预期工作:)