I was looking for a way to pack more data in texture, in case I don't need the full 256 range of one color channel, (notably bitfield, to store a time of day shadow history, per pixel for opengl 2.0) I figure out this:
Packing more integer data in a single integer number:
nombre = data1 * base1 + ... + datan * basen
Decoding the data packed:
nombre = input
datan = nombre % base
reste = nombre / base
datan-1 = reste % base
reste = reste / base
...
data1 = reste % base
reste = reste/base
With base being the integer range of value packed per data. Base = 256, mean you will retrieve data that range from 0 to 255, base 2 will be 0 to 1.
It's simple, for example consider a simple exemple where you want to store 3 data in a single channel, you can divide by 10 and get the reminder for the data, since color are limited to 256 values, you will have 3 data, 2 inside the 10 range (0 to 9) per pixel, and one 1 with 3 values (0,1 and 2) due to cap of 256, that's the easy way. Basically the size of the base give you the size of the range of the data value. Base 256 being the original texture color "base format" in the form of rgba, which give you 4 data per pixel.
Now if you want equal division for all data, using:
- base 16 give you 2 data (4bits) -> 8 data of 16 possible values per pixel in a texture
- base 4 give you 4 data (2bits) -> 16 data of 4 possible values per pixel in a texture
- base 2 give you 8 data (bitfield) -> 32 data of 2 possible values per pixel in a texture
If you use these data as grayscale, you can use gradient to recompose the color as if it is indexed colors.
However It might only works with point filtering, not with bilinear/anisotropic filtering, and maybe mipmap will fail, unless you have to define your own mipmap values to keep compatibility. To test.Also there is some quirk to solve while converting the integer to shader, as shader mostly operate with float, and there is some ROUNDING ERROR issues to take care of. see here:
https://gamedev.stackexchange.com/questions/22864/enconding-decoding-bit-value-in-texture-alpha-channel