Advertisement Jump to content
Sign in to follow this  

packing a float into a A8R8G8B8 texture (shader)

This topic is 4300 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Looks like this is already a solved problem, but here's another thread on it:

Codesampler thread;

That one shows how you can do a limited amount of additive blends as well. I'm still stuck on filtering though.

Share this post

Link to post
Share on other sites
for your information, I am using the code given in that CodeSampler thread:

encode (fDist is the normalized distance):

const float4 bitSh = float4( 256*256*256, 256*256, 256, 1);
const float4 bitMsk = float4( 0, 1.0/256.0, 1.0/256.0, 1.0/256.0);

float4 comp;
comp = fDist * bitSh;
comp = frac(comp);
comp -= comp.xxyz * bitMsk;
return comp;

decode (vec is the rgba encoded value):

const float4 bitShifts = float4(1.0/(256.0*256.0*256.0), 1.0/(256.0*256.0), 1.0/256.0, 1);
return dot(vec.xyzw , bitShifts);

The code given by Ysaneya introduces some artefacts, certainly cause by the missing "comp -= comp.xxyz * bitMsk;" (which is actually the difference between Ysaneya's code and the one given in the CodeSampler thread).

Right now the result is very good, it allows me to store the scene camera depth texture using a ARGB8 rendertarget, which allows using the same Z-buffer as the main surface (and thus writing the Z buffer during my camera-depth texture generation, allowing early Z-cull during the main scene rendering pass)!

Well done guys, thanks a lot !

Share this post

Link to post
Share on other sites
Your code does not work with one value - 1. You always get 0 after decoding because frac(1) = 0.

Share this post

Link to post
Share on other sites
thanks for the feedback.

It is not a problem in my case, just have to divide my distance by (zfar + 1).

I guess in most of the cases a similar solution exists.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!