Packing a float value in RGBA

Here’s the way to pack a float value in a RGBA8 texture. You should try to use float textures instead but if that’s not possible then this might be a good work around.

// Packing a [0-1] float value into a 4D vector where each component will be a 8-bits integer
vec4 packFloatToVec4i(const float value)
{
   const vec4 bitSh = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);
   const vec4 bitMsk = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);
   vec4 res = fract(value * bitSh);
   res -= res.xxyz * bitMsk;
   return res;
}
 
// Unpacking a [0-1] float value from a 4D vector where each component was a 8-bits integer
float unpackFloatFromVec4i(const vec4 value)
{
   const vec4 bitSh = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);
   return(dot(value, bitSh));
}

The source was posted on the GameDev forum:
http://www.gamedev.net/community/forums/topic.asp?topic_id=463075&whichpage=1&#3054958

Be Sociable, Share!

4 thoughts on “Packing a float value in RGBA

  1. Pingback: Lost in the Triangles » Blog Archive » Encoding floats to RGBA – the final?

  2. Pingback: SSAO in stage 3D « flashing in public

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>