0
votes

I want to write an app for Android with OpenGL ES 2.0 that displays a colored rectangle, like that: colored rectangle

This are my 2 shaders:

// Vertex Shader
attribute vec4 vPosition;
void main() {
  gl_Position = vPosition;
}

// Fragment Shader
uniform vec4 u_colorRGBA;
void main() {
    gl_FragColor = u_colorRGBA;
}

I can draw rectangles with different colors, but i want to draw them so each corner has a diffrent color. Can i pass variables from the vertex shader to the fragment shader to define the color of each corner? If so how do i define the variables and pass them over? Or is there another way to do it?

2
You have to use attributes for this (similar to vPosition)BDL

2 Answers

0
votes

I figured out a way to do it:

I changed my shaders like this:

// Vertex Shader
attribute vec4 inColor;
varying vec4 vColor;
attribute vec4 vPosition;
void main() {
  gl_Position = vPosition;
  vColor = inColor;
}

// Fragment Shader
varying vec4 vColor;
void main() {
    gl_FragColor = vColor;
}

Then i draw the rectangle like that:

public static void Draw(float vertices[], int verticesCount, float color[]) {
    vertexBuffer.put(vertices);
    vertexBuffer.position(0);

    GLES20.glEnableVertexAttribArray(sPosition);
    GLES20.glVertexAttribPointer(sPosition, 3, GLES20.GL_FLOAT, false, 0, vertexBuffer);

    colorBuffer.put(color);
    colorBuffer.position(0);

    GLES20.glEnableVertexAttribArray(sColor);
    GLES20.glVertexAttribPointer(sColor, 4, GLES20.GL_FLOAT, false, 0, colorBuffer);

    GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, verticesCount);  // Draw

    GLES20.glDisableVertexAttribArray(sPosition);
    GLES20.glDisableVertexAttribArray(sColor);
}

Is this the correct way of doing it? Or are their better ways?

0
votes

Good job, that is only one way to pass color variables through two shaders.

However, a little more simply, you can do it without passing them through two shaders.

vec2 uv = gl_FragCoord.xy / resolution.xy; 
gl_FragColor = vec4(uv,0.0,1.0);

You still need to pass one uniform2f, resolution directly going to the fragment shader or you can define it as a constant like const vec2 resolution = vec2(320.,480.); in the fragment shader