OpenGL轮换倾斜问题

时间:2012-06-28 22:07:38

标签: java opengl transformation

我对OpenGL中围绕x轴的任何旋转都有一些问题。我所拥有的是一个在着色器内部渲染的基本立方体,具有法线照明计算功能。立方体的变换是投影矩阵乘以模型矩阵。这个连接是在着色器内部完成的,而旋转和平移计算是在我编写的Matrix类中完成的。当围绕y轴进行任何旋转时,一切都按预期旋转,如下图所示:

Render Result Render Result

当围绕x轴发生任何旋转时问题开始,如下所示:

Render Result Render Result

显然,x轴旋转会使场景偏斜,导致所有内容都不显示。以下是每次渲染时计算矩阵和传递的代码到着色器:

glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);

viewMatrix.setIdentity();
viewMatrix.translate(new Vector4(translation));
viewMatrix.rotate(1, 0, 0, -rotateX);
viewMatrix.rotate(0, 1, 0, rotateY);
Matrix4 mvMatrix = new Matrix4(viewMatrix);

Matrix4 pMatrix = new Matrix4(projectionMatrix);

lightShader.useShader();        
lightShader.setUniformVector("vColor", new Vector4(.4f,0,0,1f));
lightShader.setUniformMatrix("mvMatrix", mvMatrix);
lightShader.setUniformMatrix("pMatrix", pMatrix);
triangleBatch.draw(lightShader.getAttributes());

Display.update();

着色器代码如下:

uniform mat4 mvMatrix;
uniform mat4 pMatrix;
uniform vec4 vColor;
varying vec4 outFragColor;
attribute vec4 inVertex;
attribute vec4 inNormal;
void main(void) { 
    vec3 newNorm = vec3(inNormal);
    mat3 mNormalMatrix;
    mNormalMatrix[0] = mvMatrix[0].xyz;
    mNormalMatrix[1] = mvMatrix[1].xyz;
    mNormalMatrix[2] = mvMatrix[2].xyz;
    vec3 vNorm = normalize(mNormalMatrix * newNorm);
    vec3 vLightDir = vec3(0.0, 0.0, 1.0); 
    float fDot = max(0.0, dot(vNorm, vLightDir)); 
    outFragColor.rgb = vColor.rgb * fDot;
    outFragColor.a = vColor.a;
    mat4 mvpMatrix;
    mvpMatrix = pMatrix * mvMatrix;
    gl_Position = mvpMatrix * inVertex; 
}

最后,旋转的矩阵数学代码如下:

public Matrix4 rotate(Vector4 a, float radians){
    Matrix4 temp = new Matrix4().setToRotate(a, radians);
    this.multiply(temp);
    return this;
}

public Matrix4 setToRotate(Vector4 a, float radians){
    a = new Vector4(a).normalise();
    float c = GameMath.cos(radians);
    float s = GameMath.sin(radians);
    float t = 1-c;
    float x = a.x;
    float y = a.y;
    float z = a.z;
    float x2 = a.x*a.x;
    float y2 = a.y*a.y;
    float z2 = a.z*a.z;
    this.setIdentity();
    this.matrix[0] = c + t*x2;
    this.matrix[1] = t*x*y + s*z;
    this.matrix[2] = t*x*z - s*y;
    this.matrix[4] = t*x*y - s*z;
    this.matrix[5] = c + t*y2;
    this.matrix[6] = t*y*z + s*x;
    this.matrix[8] = t*x*z + s*y;
    this.matrix[9] = t*y*z + s*x;
    this.matrix[10] = c + t*z2;
    return this;
}

矩阵存储在专业列中。

1 个答案:

答案 0 :(得分:0)

我发现了问题所在。显然,setToRotate()中的一个操作需要从加法更改为减法。它现在按预期工作。