View Full Version : Shader question in ES 2 iPad app

02-26-2014, 12:09 PM
I'm working on an iPad drawing app and I have a question regarding how to implement a specific fragment shader for a brush in the app. I'm not very familiar with GLSL because the app was previously using ES 1.1 which did not have shaders. I'm looking for guidance, I need this out pretty quickly.

From a high level:

How do I get a fragment shader to only build up to a certain alpha value at one location? The brush drawing on top of itself eventually changes to an alpha of 1.0 at the location where it is continuously drawn, but let's say I want the cap to be 0.75 for example. Is there a way to set a cap value for the gl_FragColor in a fragment shader? How should I go about doing this?

This is what my fragment shader looks like so far:

uniform sampler2D brushTexture;

varying lowp vec4 v_color;
varying lowp vec2 v_texCoords;

void main()
gl_FragColor = v_color * texture2D(brushTexture, v_texCoords);

And my vertex shader if that is helpful:

attribute vec4 position;
attribute vec2 texCoord;

uniform mat4 MVP;

attribute vec4 a_color;

varying vec4 v_color;
varying vec2 v_texCoords;

void main()
v_color = a_color;
v_texCoords = texCoord;
gl_Position = MVP * position;

Thanks for any help.

03-07-2014, 03:24 PM
At a high level, you can't do this with simple rendering & blending in OpenGL. You could build a more complex system with "opacity groups" by rendering a collection of brush strokes into an FBO, allowing the alpha to saturate to 1.0, and then compositing the result with the alpha scaled back down to your desired max.

However, if you are only concerned with iOS, and you can figure out how to express your "saturate to 0.75" per-pixel algorithm in C, then you can use EXT_shader_framebuffer_fetch (http://www.khronos.org/registry/gles/extensions/EXT/EXT_shader_framebuffer_fetch.txt) to implement the same custom blending in the fragment shader. Be warned that it won't easily port to other platforms. (http://www.opengl.org/discussion_boards/showthread.php/183629-Equivalent-for-gl_LastFragData-0-on-OpenGL?p=1257765&viewfull=1#post1257765)