Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color interpolation in GLSL fragment shader?

I need to map a scalar value to color that ranges 0 to 1. It will go from GREEN to RED (from 0 to 1) Linear Interpolation using the texture co-ordinates (also ranges from 0 to 1)

I have figured out that I need to write color value in gl_FragColor which is a vector of dimension 4. I'm not sure how I can calculate the R, G and B channels for gl_FragColor just by one scalar value that ranges for 0 to 1.0 (It will from GREEN to RED and at 0.5 it will be WHITE)

like image 795
ammar26 Avatar asked Oct 30 '25 13:10

ammar26


1 Answers

#version 120

...

float remap( float minval, float maxval, float curval )
{
    return ( curval - minval ) / ( maxval - minval );
} 

...

const vec4 GREEN = vec4( 0.0, 1.0, 0.0, 1.0 );
const vec4 WHITE = vec4( 1.0, 1.0, 1.0, 1.0 );
const vec4 RED   = vec4( 1.0, 0.0, 0.0, 1.0 );

float u = <whatever, grabbed from a uniform?>;
u = clamp( u, 0.0, 1.0 );
if( u < 0.5 )
    gl_FragColor = mix( GREEN, WHITE, remap( 0.0, 0.5, u ) );
else
    gl_FragColor = mix( WHITE, RED, remap( 0.5, 1.0, u ) );

Or you could sample a 3-pixel 1D texture.

like image 177
genpfault Avatar answered Nov 03 '25 14:11

genpfault



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!