0

The language is cg.

I have an 8-bit float that must be between 0 and 1 (it's the 'a' component of a float4 rgba color value). I want to store a 6-bit unsigned integer and a 2-bit unsigned integer in that. How can I safely store these two values in those 8 bits?

I couldn't find any documentation on the format of an 8-bit float, especially one limited between 0 and 1. I'm assuming it's more complicated than just data / 255 ?

Charles
  • 50,943
  • 13
  • 104
  • 142
lifeformed
  • 525
  • 4
  • 16

1 Answers1

3

The OpenGL standard guarantees that at least 256 distinct values are preserved when writing to an 8-bit framebuffer. I’m pretty sure Cg does the same.

So you should be able to write your two values in this way:

output.a = (4.0 * clamp(val1, 0.0, 63.0)
                + clamp(val2, 0.0, 3.0)) / 255.0;

And retrieve them like this:

float val1 = floor(input.a * 255.0 / 4.0);
float val2 = fmod(input.a * 255.0, 4.0);

This is equivalent to bitwise operations on integers.

sam hocevar
  • 11,853
  • 5
  • 49
  • 68
  • Do you mean I just set the float as my integer? When I tried it, it just clamped my value between 0 and 1, so I'm unable to retrieve it. Or am I missing something here? – lifeformed Feb 04 '13 at 02:10
  • I am not sure I follow here. I thought you had 8 bits of information to pass from the CPU to the GPU and the data channel is the 4th component of a `float4`. If so, I say encode these 8 bits to a 0—255 integer, pass it to the GPU where it’ll be normalised by DirectX or OpenGL (you need to ask for that) to 0—1, and finally multiply by 255.0 in the shader. Otherwise, could you maybe explain what data formats you are using on the GPU and on the CPU? – sam hocevar Feb 04 '13 at 02:14
  • All of my calculations are within a cg shader - I am encoding values between lighting passes. In my base pass, I need to write to each pixel a 32-bit RGBA value. I want to store custom data about each pixel in the A component. In a different lighting pass, I want to retrieve that data, given the RGBA value. – lifeformed Feb 04 '13 at 03:36
  • Okay, I think I understand better. I modified my answer accordingly. – sam hocevar Feb 04 '13 at 12:05