如何将触摸坐标从Java传递到片段着色器?

时间:2019-05-04 13:22:43

标签: android opengl-es glsl

我是Opengl的新手,我目前正在使用片段着色器通过触摸效果更改图像的某些像素颜色,但是我不知道如何将触摸坐标从Java传递到片段着色器。

1 个答案:

答案 0 :(得分:0)

解决方案是使用统一变量。这些是变量,其值在Java中设置。但是,可以在GLSL着色器程序中访问它们。

着色器类的示例:

private int programId;
private int vertexShaderId;
private int fragmentShaderId;

private int uniformLocation_touchCoordinates;

public MyShader(String vertexShader, String fragmentShader) {
    vertexShaderId = //load vertex shader;
    fragmentShaderId = //load fragment shader;

    programId = glCreateProgram();
    glAttachShader(programId, vertexShaderId);
    glAttachShader(programId, fragmentShaderId);

    //bind in variables of the vertex shader here

    glLinkProgram(programId);
    glValidateProgram(programId);

    //init uniform variables
    uniformLocation_touchCoordinates = glGetUniformLocation(programId, "touchCoordinates");
}
public void bind() {
    glUseProgram(programId);
}
public void unbind() {
    glUseProgram(0);
}

public void loadTouchCoordinates(float x, float y) {
    glUniform2f(uniformLocation_touchCoordinates, x, y);
}

fragmentShader:

//version tag, input and output variables

uniform vec2 touchCoordinates;

void main(void) {
    //...
}

用法:

public class Renderer {
    MyShader shader = new MyShader(..., ...); //pass shader code

    public void render() {
        shader.bind();

        //update uniform variable with your data
        shader.loadTouchCoordinates(..., ...); //pass coordinates

        //do your render logic here

        shader.unbind();
    }
}