Created
January 9, 2012 23:26
-
-
Save Flexi23/1585608 to your computer and use it in GitHub Desktop.
mapping vec4 rgba to higher precision vec2 in glsl (texture as vector field)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// GLSL fragment shader code to store and restore signed 15bit fixed point 2D vector in a normalized color value | |
// red and green are mapped to horizontal, blue and alpha to vertical | |
// the most significant bit is used as signum | |
// maximum velocity is 128 (7bit), overall accuracy is 1/256 (8bit) | |
// by Felix Woitzel (@Flexi23) Jan. 2012 | |
// velocity vector to color value | |
vec4 encode(vec2 v){ | |
vec4 rgba; | |
v += 128.; | |
int ix = int( v.x * 256. ); // convert to int to split accurately | |
int v1x = ix / 256; // hi | |
int v1y = ix - v1x * 256; // lo | |
rgba.r = float( v1x + 1 ) / 255.; // normalize | |
rgba.g = float( v1y + 1 ) / 255.; | |
int iy = int( v.y * 256.); | |
int v2x = iy / 256; // hi | |
int v2y = iy - v2x * 256; // lo | |
rgba.b = float( v2x + 1 ) / 255.; | |
rgba.a = float( v2y + 1 ) / 255.; | |
return rgba - 1./256.; | |
} | |
// color to velocity vector | |
vec2 decode(vec4 c){ | |
vec2 v = vec2(0.); | |
int ir = int(c.r*255.); | |
int ig = int(c.g*255.); | |
int irg = ir*256 + ig; | |
v.x = float(irg) / 256.; | |
int ib = int(c.b*255.); | |
int ia = int(c.a*255.); | |
int iba = ib*256 + ia; | |
v.y = float(iba) / 256.; | |
v -= 128.; | |
return v; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment