I’m learning the SDL library and one of the functions to create a surface is SDL_CreateRGBSurface. The four parameters I’m wondering about are R, G, B, and A masks. What exactly is a mask in this context?
I’m also following a book about SDL and the author passed in 5 bits of red, 5 bits of blue, and 6 bits of green for the mask values. What does that mean though? What do the mask values do?
I filled in a rectangle onto the screen using a random number (Uint32 color) and got green. When I changed the mask values I noticed that the color changed even with the same color value.
Basically what’s happening is that when the SDL determines how much of each color to display, it looks at which bits are set in the mask to determine which bits to pay attention to in the color. It’s not quite as simple as a bitwise
ANDbecause the values are shifted over. For example,and you’ve set your masks to be
then the color will be green {R=0, G=128, B=0}. The bits of
colorspecified byRmaskare 0, the bits specified byGmaskare0x80 == 128, and the bits specified byBmaskare 0. If you were to reverse the masks for the same color:now the color will be blue {R=0, G=0, B=128}. It appears that the example you’re looking at uses 16 bit color without an alpha channel. Since 16 bits do not divide evenly by 3 color channels, green gets an extra bit (as the human eye is believed to be more sensitive to green).
Example:
The color will be {R=2, G=17/2=8.5, B=20}. (the extra bit for green means the value needs to be halved to normalize it).
I’m not sure of how exactly SDL does it, or what types of crazy masks you can use with SDL, but I would imagine the actual algorithm is along the lines of a bitwise
AND, then right-shift as many bits as are cleared in the least significant portion of the mask? Or else working from most significant to least significant bit, for each bit that’s set in the mask, shift the total left and add 1 if the corresponding bit of the color is set.