matrix - 对象旋转时法线旋转错误

标签 matrix 3d webgl quaternions gl-matrix

我正在 WebGL 中渲染一个简单的圆环。旋转顶点工作正常,但法线有问题。当围绕单个轴旋转时,它们保持正确的方向,但是当围绕第二个轴的旋转增加时,法线开始以错误的方式向上旋转,直到其中一个旋转为 180°,然后法线的旋转方向与完全相反他们应该。
我认为问题出在用于旋转的四元数上,但我无法确定出了什么问题。

这是我项目的一个(稍作修改,但仍显示问题)jsfiddle:https://jsfiddle.net/dt509x8h/1/
在 fiddle 的 html 部分中,有一个 div 包含我正在读取的 obj 文件中的所有数据,以生成环面(尽管分辨率较低)。

顶点着色器:

attribute vec4 aVertexPosition;
attribute vec3 aNormalDirection;

uniform mat4 uMVPMatrix;
uniform mat3 uNMatrix;

varying vec3 nrm;

void main(void) {
    gl_Position = uMVPMatrix * aVertexPosition;
    nrm = aNormalDirection * uNMatrix;
}

片段着色器:
varying vec3 nrm;

void main(void) {
    gl_FragColor = vec4(nrm, 1.0);
}

更新矩阵(在有输入时运行):
mat4.perspective(pMatrix, Math.PI*0.25, width/height, clipNear, clipFar); //This is actually not run on input, it is just here to show the creation of the perspective matrix
mat4.fromRotationTranslation(mvMatrix, rotation, position);
mat3.normalFromMat4(nMatrix, mvMatrix);

mat4.multiply(mvpMatrix, pMatrix, mvMatrix);

var uMVPMatrix = gl.getUniformLocation(shaderProgram, "uMVPMatrix");
var uNMatrix = gl.getUniformLocation(shaderProgram, "uNMatrix");
gl.uniformMatrix4fv(uMVPMatrix, false, mvpMatrix);
gl.uniformMatrix3fv(uNMatrix, false, nMatrix);

创建旋转四元数(鼠标移动时调用):
var d = vec3.fromValues(lastmousex-mousex, mousey-lastmousey, 0.0);
var l = vec3.length(d);
vec3.normalize(d,d);
var axis = vec3.cross(vec3.create(), d, [0,0,1]);
vec3.normalize(axis, axis);

var q = quat.setAxisAngle(quat.create(), a, l*scale);
quat.multiply(rotation, q, rotation);

仅围绕 Y 轴旋转环面,法线指向正确的方向:
Rotating the torus only around the Y-axis
围绕两个轴旋转环面。法线指向各处:
Rotating around two axes

我正在使用 glMatrix v2.3.2 适用于所有矩阵和四元数运算。

更新:
似乎仅围绕 Z 轴旋转(通过将 quat.setAxisAngle 的输入轴明确设置为 [0,0,1] 或使用 quat.rotateZ )也会导致法线向相反方向旋转。
axis 的 z 分量归零没有帮助。

更新2:
旋转 quat.rotateX(q, q, l*scale); quat.rotateY(q, q, l*scale); quat.multiply(rotation, q, rotation);看起来是正确的,但是一旦引入围绕 Z 的旋转,z 法线就开始四处移动。
使用 x 或 y 鼠标值的差异而不是 l导致所有法线移动,使用大不相同的 scale 也是如此。 - x 和 y 的值。

更新 3:将着色器中的乘法顺序更改为 uNMatrix * aNormalDirection导致法线总是以错误的方式旋转。

最佳答案

就我而言,问题在于我如何从 .obj 文件加载数据。我已经反转了所有顶点的 z 位置,但法线是从非反转顶点生成的。
使用非反转 z 位置和翻转法线矩阵乘法修复了问题。

关于matrix - 对象旋转时法线旋转错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32053411/

相关文章:

matrix - python : Transformation Matrix

javascript - 如何在webgl中获得像素化效果?

python - numpy 将 RGB 图像转换为 YIQ 颜色空间

c++ - 在立体校准中,如果我改变立体相机的分辨率,外部矩阵如何变化

javascript - 学习 3D 基础知识的资源 (Python/JavaScript)

c++ - GL_INVALID_OPERATION 尝试采样立方体贴图纹理时

python - 如何使用 Python 创建 3D 网格?

opengl-es - Webgl GLSL/Open GL ES 2.0

unit-testing - 有没有办法在 headless 浏览器中为 WebGL webapp 运行单元测试

python - 有没有一种好方法可以在特征 p>0 的字段中找到矩阵的秩?