Apps OpenGL ES 2, how to send float attributes to fragment shader

McCloud

Lurker
Hi There.

I am studying OpenGL ES 2. The reason for this version is that there are still lots of devices that can't support v.3, and I want my game to be compatible with most devices, while being able to make use of some nice accelerated effects in it.

So, my question is: I have managed to send a float attribute to the vertex shader, by using an attribute location and a FloatBuffer only with attributes data.

Let's say that I want to send an alpha value to this attribute, and send it again from the vertex shader to the fragment shader, since I want to use this alpha value in each fragment.

Then in my animation thread, I update this alpha value, and when rendering, I update the FloatBuffer, bind the new value and so on...

The problem is... It seems the only way to send my alpha attribute to the fragment shader is through a varying float. But I don't want this value to be interpolated per vertex, what is, indeed, happening (and from my value to zero). If I try to declare and use a simple float variable in both shaders, or use in out float variables, the 1.2 shader version don't accept it. The 1.2 version also does not have a flat modifier.

I searched a lot already, but the only ways I found were by using some extension or v.3, and it does not solves the problem, once the said extension is never guaranteed to exist in many devices, and I don't want to use v.3, then...

How to make it work? Thank you very much.
 

McCloud

Lurker
Thread starter
Okay, folks, sorry for the trouble, but I just found the solution...

It may seem quite obvious, but, considering the research I did, many many people have the same doubt!

PLUS it is NOT OBVIOUS since I'll get an uniform into the vertex shader, but I'll declare a varying variable to send the value from the vertex shader to the fragment shader. Since it's source is a uniform, it's value will NOT be interpolated!

Well, Instead of passing an attribute, I passed an uniform, just like this:

[HIGH]
// Java:
private static final String U_ALPHA = "u_Alpha";
int uAlphaLocation = GLES20.glGetUniformLocation(textureProgram.getProgram(), U_ALPHA);
// While binding the value:
GLES20.glUniform1f(uAlphaLocation, alpha);

// Vertex Shader:
#version 120

uniform float u_Alpha; // input from Java - UNIFORM
varying float v_Alpha; // output to fragment shader

void main()
{
v_Alpha = u_Alpha; // sending the value to the fragment shader
// ...
}

// Fragment Shader:
#version 120

precision mediump float;

varying float v_Alpha;

void main()
{
// just use the v_Alpha value, it WON'T be interpolated
gl_FragColor = vec4(0.0, 1.0, 1.0, v_Alpha); // for example
}
[/HIGH]
 
Top