I have this code sample from threejs example [http://threejs.org/examples/#webgl_animation_cloth] where a float value is converted to vec4. I have seen this logic on few other forums but no explanation.
- Could someone explain what this logic is doing and the use of 256 ?.I understand the bitwise masking and shifting .
I have seen this link too Packing float into vec4 - how does this code work?
It says the vec4 will be stored in a 32 bit RGBA8 buffer finally.
Since we are passing the depth value into a color buffer , how will opengl know what to do with this ?Also since vec4 has 4 components , each of 4 bytes making it 16 bytes which makes it 16 * 8 bits , how does this fit into 32 bit RGBA8 ?
vec4 pack_depth( const in float depth ) { const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0,256.0,1.0); const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0); vec4 res = fract( depth * bit_shift ); res -= res.xxyz * bit_mask; return res; } void main() { vec4 pixel = texture2D( texture, vUV ); if ( pixel.a < 0.5 ) discard; gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z ); }