如何在着色器中旋转纹理,Android

时间:2015-07-14 21:05:17

标签: android matrix opengl-es glsl

所以我有一个纹理,我希望在给定角度rotation的情况下旋转。这是我的UV坐标

float[] landscapeVerts = {
    // X, Y, Z, U, V
    -ratio, -1.0f, z_0, 1.0f, 0.0f,
    ratio, -1.0f, z_0, 0.0f, 0.0f,
    -ratio,  1.0f, z_0, 1.0f, 1.0f,
    ratio,  1.0f, z_0, 0.0f, 1.0f,
};

我想只旋转UV部分。所以我在着色器中构建了以下矩阵来实现这一点。

    Matrix.setIdentityM(mProjMatrix, 0); //start with identity matrix
    Matrix.translateM(mProjMatrix,0,-0.5f,-0.5f,0.0f); // move center to center [0 1] : [-.5 .5]
    Matrix.rotateM(mProjMatrix, 0, rotation, 0.0f,0.0f,-1.0f); // rotate about z axis
    Matrix.translateM(mProjMatrix,0,0.5f,0.5f,0.0f); // move back to [0 1] range

然后我将矩阵加载到着色器中uSTMatrix并将纹理坐标乘以它

"uniform mat4 uMVPMatrix;\n" +
"uniform mat4 uSTMatrix;\n" +
"attribute vec4 aPosition;\n" +
"attribute vec4 aTextureCoord;\n" +
"varying vec2 vTextureCoord;\n" +
"varying vec2 calcTexCoord;\n" +
"void main() {\n" +
"  gl_Position = uMVPMatrix * aPosition;\n" +
"  vTextureCoord = (uSTMatrix * aTextureCoord).xy;\n" +
"  calcTexCoord = aTextureCoord.xy;\n" +
"}\n";

但这不是我想做的事情。在着色器中应该很容易实现这一点,我缺少什么?或者如何轻松完成。

1 个答案:

答案 0 :(得分:0)

我明白了。只需要改变操作顺序。

float[] identityMatrix = new float[16];
Matrix.setIdentityM(identityMatrix, 0); //start with identity matrix
Matrix.translateM(mProjMatrix,0,identityMatrix, 0, 0.5f,0.5f,0.0f); // move back to [0 1] range
Matrix.rotateM(identityMatrix, 0, mProjMatrix, 0, rotation, 0.0f,0.0f,1.0f); // rotate about z axis
Matrix.translateM(mProjMatrix,0, identityMatrix, 0, -0.5f,-0.5f,0.0f); // move center to center [0 1] : [-.5 .5]

而不是移动到中心,旋转和向后移动;我们反向构建矩阵 - >向后移动,旋转,然后移动到中心。