Home / Posts tagged "Photoshop"

Photoshop curve and gradient map in shader and texture

Recently I’ve been working on a project which I need to recreate some photoshop effects in code. Most of them are quite easy to do or to find sample shader codes, such as hue/saturation/brightness and contrast. However there are still 2 effects need a bit more work : Curve and Gradient map.

Screen Shot 2014-08-15 at 11.25.02  Screen Shot 2014-08-15 at 11.31.43

The way curve and gradient map works is to map your current color value to another one, so the question for us is how to save this mapping information and then pass it into our code. It seems quite complicated at first glance, we need to save a lot data such as all 3 RGB channels plus an overall one for curve. However there is an easy way to do it : using texture. What we need is to create a base gradient texture from black to white like this :

baseTextureand apply your curve or gradient map on this texture to get the mapping texture you need.

export02

The next step is to do the mapping in the fragment shader, for the curve :

uniform sampler2D   texture;
uniform sampler2D   textureCurve;

void main(void) {
    
    vec2 texCoord   = gl_TexCoord[0].st;
    vec4 color      = texture2D(texture, texCoord);
    
    color.r         = texture2D(textureCurve, vec2(gl_FragColor.r, 0)).r;
    color.g         = texture2D(textureCurve, vec2(gl_FragColor.g, 0)).g;
    color.b         = texture2D(textureCurve, vec2(gl_FragColor.b, 0)).b;
    
    gl_FragColor    = color;
}

and for the gradient map :

uniform sampler2D   texture;
uniform sampler2D   textureMap;

#define sq3         1.73205080757

void main(void) {
    
    vec2 texCoord   = gl_TexCoord[0].st;
    vec4 color      = texture2D(texture, texCoord);
    float lenColor  = length(color.rgb) / sq3;
    color.rgb       = texture2D(textureMap, vec2(lenColor, 0)).rgb;
    
    gl_FragColor    = color;
}

This is really nice and easy, we don’t need to find a way to save mapping data with lots of numbers, a simple texture will do the job , and it’s much easier to export the texture too.