It may be useful to use what web developers are pretty used to for colours. Parsing to rid of the # character for parsing not included.
This function takes a value like 0xffffff then returns an SDL_Color type. This is designed for use with SDL and OpenGL, so if you call SDL_GL_SwapBuffers() in your graphics loop function, then this function is likely for you. In SDL, OpenGL space is represented in BGR rather than RGB. And you should already know about the flip you have to do or else everything is upside down.
Part of my graphics loop function:
GLvoid graphics_draw(struct rs_graphics *graphics) {
/* Clear the screen and the depth buffer */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glScalef(1, -1, 1); /* Flip framebuffer because of SDL's upside down issue */
// Do some cool stuff
SDL_GL_SwapBuffers(); /* The black magic function */
}
Here is the SDL_Color SDL_Color_from_hex() function.
extern SDL_Color SDL_Color_from_hex(unsigned int hex);
SDL_Color SDL_Color_from_hex(unsigned int hex) {
SDL_Color color;
/* Make the color value safe; be sure to pass colour values correctly or used #define'd colors */
hex &= 0xffffff;
if (hex == 0) { /* Black */
color.b = color.g = color.r = 0;
return color;
}
else if (hex >= 0xffffff) { /* White or value too high */
color.b = color.g = color.r = 255;
return color;
}
/* RGB is actually BGR because we are using a BGR space in GL */
color.b = hex >> 0x10;
color.g = (hex >> 0x8) & 0xff;
color.r = hex & 0xff;
return color;
}
If you don't use OpenGL, you must switch around the B and R colours or else things will look strange.
The function is a few bitwise shifts, keeping this fast, and if you were to put this into a library for others to use, it verifies that values returned are safe. It is useless if the return value is ignored of course, so you may want to check for that. GCC provides an extension: __attribute__((warn_unused_result)).
The function can then be declared as:
extern SDL_Color SDL_Color_from_hex(unsigned int hex) __attribute__((warn_unused_result));
Now a call such as SDL_Color_from_hex(0xdeedee) will return a warning from GCC, but even an if check will not.
This only works with GCC so you may not want to make sure you are in that environment with something like this:
#define WARN_UNUSED __attribute__((warn_unused_result)) #ifndef __GNUC__ #define WARN_UNUSED #endif /* __GNUC__ */
Of course you can adjust this function return anything else you need, but I find it incredibly useful to be able to use familiar colour codes.
Comments
Post new comment