Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an OpenGL texture from sdl palette surface (SDL_PIXELFORMAT_INDEX8)

I created a bmp and I load it using SDL_LoadBMP when inspecting the generated SDL_Surface I can see it is of format SDL_PIXELFORMAT_INDEX8.

I want to use the SDL surface to generate a texture using glTexImage2D.

Normally I could just inspect the surface Something close to this:

SDL_Surface * surface = SDL_LoadBMP(filename.c_str()); 
GLenum mode = 0;
Uint8 bpp = surface->format->BytesPerPixel;
Uint32 rm = surface->format->Rmask;
if (bpp == 3 && rm == 0x000000ff) mode = GL_RGB;
if (bpp == 3 && rm == 0x00ff0000) mode = GL_BGR;
if (bpp == 4 && rm == 0x000000ff) mode = GL_RGBA;
if (bpp == 4 && rm == 0xff000000) mode = GL_BGRA;

GLsizei width = surface->w;
GLsizei height = surface->h;
GLenum format = mode;
GLvoid * pixels = surface->pixels;

/*insert gl texture magic*/

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, format, GL_UNSIGNED_BYTE, pixels);

However SDL_PIXELFORMAT_INDEX8 has a BytesPerPixel of 1 and all masks are 0. From the SDL Code Examples I read that: "A pixel format has either a palette or masks. If a palette is used Rmask, Gmask, Bmask, and Amask will be 0."

So I assume that my data has a palette instead of masks.

The glTexImage2D states that it would only accept GL_ALPHA, GL_RGB, GL_RGBA, GL_LUMINANCE, and GL_LUMINANCE_ALPHA.

Can I create a texture directly from any surface even if it is based on a palette? Is there a way to use SDL to transform any Image into GL_RGBA? Am I missing an even better way?

like image 210
Johannes Avatar asked Oct 03 '17 14:10

Johannes


1 Answers

I was able to convert into a known format so it is accepted by OpenGL.

GLenum mode = GL_RGBA;
SDL_PixelFormat * target = SDL_AllocFormat(SDL_PIXELFORMAT_RGBA32);
SDL_Surface * surface = SDL_ConvertSurface(tmp, target, 0);
SDL_FreeSurface(tmp);
SDL_FreeFormat(target);
like image 155
Johannes Avatar answered Sep 17 '22 03:09

Johannes