Converting 32 float to 4 byte equivalents... or something like that

I want to calculate the distance from the viewpoint/eyepoint to each vertex in my scene then store that value in the r,g,b and a components of a RGBA8 texture… I have gone round in circles trying to figure out how to go from a single 32 bit number to 4 - 8bit numbers. Is the following reasonable? That is… should it work? If not, does anyone know what would?

Fragment Shader:

// Calculate Distance To Each Vertex from vertex position
// in eyespace passed as varying from vertex shader
float distance = length(eyepoint);

// convert distance from floating point to fixed point
// with 8 fractional bits
float fixedPointDistance = distance * pow(2, 8);

// get upper 16 bits
int upper16Bits = int(fixedPointDistance/65536);

// get lower 16 bits
int lower16Bits = int(fixedPointDistance);

// get byte1 (or bits 23-31)
int byte1 = int(upper16Bits/256);

// get byte2 (or bits 16-23)
int byte2 = int(upper16Bits*256)/256);

// get byte3 (or bits 8-15)
int byte3 = int(lower16Bits/256);

// get byte1 (or bits 0-7)
int byte4 = int(lower16Bits*256)/256);

float red   = float(byte1/256);
float green = float(byte2/256);
float blue  = float(byte3/256);
float alpha = float(byte4/256);

gl_FragColor = vec4(red, green, blue, alpha);

CD

Seems right, you shlould be also able to use bite-shift operators “>>” and “<<”.

I wish, but bit shifts are not supported in GLSL.

CD

Originally posted by glAren:
… you shlould be also able to use bite-shift operators “>>” and “<<”.

There’s an example on codesampler.com using such a procedure to pack a 24-bit value into RGB channels. Look for the “shadow map with FBO” example.

I seem to recall this demo doing that in the fragment shader for lighting depth buffers:

http://www.delphi3d.net/download/portalengine.zip

Originally posted by CelticDaddio:
[b] I wish, but bit shifts are not supported in GLSL.

CD
[/b]
You are right, its reserved for the future use in spec.

Why not pre computed these datas stores to a texture ? it’s too expensive for shaders.

look at the glslspec,in next generation it will add more operator, more and more like c++,even TEMPLATE

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.