Skip to content

Instantly share code, notes, and snippets.

@cabbibo
Created May 26, 2021 17:54
Show Gist options
  • Save cabbibo/c0c33188c786db3869eb886cebec0758 to your computer and use it in GitHub Desktop.
Save cabbibo/c0c33188c786db3869eb886cebec0758 to your computer and use it in GitHub Desktop.
// Setting bounds because your packed flaot will go from 0->1
const float BOUNDS = 1000.0;
float unnormalizeCoordinate(float x) {
return (x * 2.0 - 1.0) * BOUNDS;
}
float normalizeCoordinate(float x) {
return (x / BOUNDS) * 0.5 + 0.5;
}
const vec4 bitEnc = vec4(1.,255.,65025.,16581375.);
const vec4 bitDec = 1./bitEnc;
vec4 packRGBA (float v) {
vec4 enc = bitEnc * v;
enc = fract(enc);
enc -= enc.yzww * vec2(1./255., 0.).xxxy;
return enc;
}
float unpackRGBA (vec4 v) {
v = floor(v * 255.0 + 0.5) / 255.0;
return dot(v, bitDec);
}
// to get your position
// if you are using multiple render textures
float x = unnormalizeCoordinate( unpackRGBA(texture2d( posXDataTexture , uvlocation));
float y = unnormalizeCoordinate( unpackRGBA(texture2d( posYDataTexture , uvlocation));
float z = unnormalizeCoordinate( unpackRGBA(texture2d( posZDataTexture , uvlocation));
// to get your position
// if you are using one data texture ( uvLocation will change based on which pixel you want to look up )
float x = unnormalizeCoordinate( unpackRGBA(texture2d( posDataTexture , uvlocationX));
float y = unnormalizeCoordinate( unpackRGBA(texture2d( posDataTexture , uvlocationY));
float z = unnormalizeCoordinate( unpackRGBA(texture2d( posDataTexture , uvlocationZ));
float3 pos = float3(x,y,z)
// if using multiple data textures, pack casually
gl_FragColor = packRGBA(normalizeCoordinate(pos.x));
if just 1 data texture, you will need to know which type of pixel you need to pack
if( id == 0 ){
gl_FragColor = packRGBA(normalizeCoordinate(pos.x));
}else if( id == 1 ){
gl_FragColor = packRGBA(normalizeCoordinate(pos.y));
}else{
gl_FragColor = packRGBA(normalizeCoordinate(pos.z));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment