Android OpenGL-ES-2.0 圆形或圆盘

Android OpenGL-ES-2.0 Circle or disc

我正在尝试在 OpenGL-ES 2.0 中绘制光盘。根据 user2901066 对这个问题 How to draw basic circle in OpenGL ES 2.0 Android 的第二个回答,我正在做:

String VertexShaderCode ="uniform mat4 uMVPMatrix;\n" +
        "attribute vec4 vPosition;\n" +
        "void main() {\n" +
        "gl_Position = uMVPMatrix * vPosition;\n" +
        "}";
String FragmentShaderCode = "precision mediump float;\n" +
        "void main() {\n" +

        //The problem is here

        //"if ((textureCoord.x * textureCoord.x) + (textureCoord.y * textureCoord.y) <= 1.0)" +
        "if (true)\n" +

        "gl_FragColor = vec4(1.0f, 0.0f, 0.0f, 1.0f);\n" +
        "else\n" +
        "gl_FragColor = vec4(1.0f, 0.0f, 0.0f, 0.0f);\n" +
        "}";
int vertexShader = this.loadShader(GLES20.GL_VERTEX_SHADER, VertexShaderCode);
int fragmentShader = this.loadShader(GLES20.GL_FRAGMENT_SHADER, FragmentShaderCode);

mGlProgram = GLES20.glCreateProgram();
GLES20.glAttachShader(mGlProgram, vertexShader);
GLES20.glAttachShader(mGlProgram, fragmentShader);
GLES20.glLinkProgram(mGlProgram);

GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);

protected int PositionHandle;
protected int MVPMatrixHandle;
static final int COORDS_PER_VERTEX = 3;
private final int VertexStride = COORDS_PER_VERTEX * 4;

private float LineCoords[] = new float[4 * 3];
private FloatBuffer VertexBuffer;
private final int VertexCount = 4;

ByteBuffer bb = ByteBuffer.allocateDirect(LineCoords.length * 4);
bb.order(ByteOrder.nativeOrder());

VertexBuffer = bb.asFloatBuffer();
VertexBuffer.put(LineCoords);
VertexBuffer.position(0);

float[] mvpMatrix = {1.0f, 0.0f, 0.0f, 0.0f,
        0.0f, 1.0f, 0.0f, 0.0f,
        0.0f, 0.0f, 1.0f, 0.0f,
        0.0f, 0.0f, 0.0f, 1.0f};

LineCoords[0] = -1.0f;
LineCoords[1] = 1.0f;
LineCoords[3] = -1.0f;
LineCoords[4] = -1.0f;
LineCoords[6] = 1.0f;
LineCoords[7] = -1.0f;
LineCoords[9] = 1.0f;
LineCoords[10] = 1.0f;

VertexBuffer.put(LineCoords);
VertexBuffer.position(0);

GLES20.glUseProgram(mGlProgram);
PositionHandle = GLES20.glGetAttribLocation(mGlProgram, "vPosition");
GLES20.glEnableVertexAttribArray(PositionHandle);
GLES20.glVertexAttribPointer(PositionHandle, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, VertexStride, VertexBuffer);
MVPMatrixHandle = GLES20.glGetUniformLocation(mGlProgram, "uMVPMatrix");
GLES20.glUniformMatrix4fv(MVPMatrixHandle, 1, false, mvpMatrix, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, VertexCount);
GLES20.glDisableVertexAttribArray(PositionHandle);

我的问题是获取片段着色器中的位置以便应用正确的颜色。我该怎么做?

您需要在两个着色器上声明一个可变变量:

varying vec2 textureCoord;

然后在顶点着色器上,为其添加一些值,例如:

textureCoord = gl_Position.xy;

然后这个变量将被发送到为每个片段插值的片段着色器,以便您的片段着色器可以使用它:

if ((textureCoord.x * textureCoord.x) + (textureCoord.y * textureCoord.y) <= 1.0)
{
    gl_FragColor = vec4(1.0f, 0.0f, 0.0f, 1.0f);
} else {
    gl_FragColor = vec4(1.0f, 0.0f, 0.0f, 0.0f);
}