Stretching Issue with Custom View Matrix

徘徊边缘 提交于 2019-12-02 07:57:12

On the viewport the X-axis points to the left, the Y-axis up and the Z-axis out of the view (Note in a right hand system the Z-Axis is the cross product of the X-Axis and the Y-Axis).

Note that a transformation matrix usually looks like this:

( X-axis.x, X-axis.y, X-axis.z, 0 )
( Y-axis.x, Y-axis.y, Y-axis.z, 0 )
( Z-axis.x, Z-axis.y, Z-axis.z, 0 )
( trans.x,  trans.y,  trans.z,  1 )

The code below defines a matrix that exactly encapsulates the steps necessary to calculate a look at the scene:

  • Converting model coordinates into viewport coordinates.
  • Rotation, to look in the direction of the view.
  • Movement to the eye position


Matrix4x4 LookAt( const Vector3f &pos, const Vector3f &target, const Vector3f &up )
{ 
    Vector3f mz( pos[0] - target[0], pos[1] - target[1], pos[2] - target[2] };
    Normalize( mz );
    Vector3f my( up[0], up[1], up[2] );
    Vector3f mx = Cross( my, mz );
    Normalize( mx );
    my = Cross( mz, mx );

    Matrix4x4 m;
    m.elements[0][0] = mx[0]; m.elements[0][1] = my[0]; m.elements[0][2] = mz[0]; m.elements[0][3] = 0.0f;
    m.elements[1][0] = mx[1]; m.elements[1][1] = my[1]; m.elements[1][2] = mz[1]; m.elements[1][3] = 0.0f;
    m.elements[2][0] = mx[2]; m.elements[2][1] = my[2]; m.elements[2][2] = mz[2]; m.elements[2][3] = 0.0f;

    m.elements[3][0] = Dot(mx, pos);
    m.elements[3][1] = Dot(my, pos);
    m.elements[3][2] = Dot(Vector3f(-mz[0], -mz[1], -mz[2]), pos);
    m.elements[3][3] = 1.0f;

    return m;
}

Vector3f Cross( const Vector3f &a, const Vector3f &b )
{ 
    return Vector3f( a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ); 
}

float Dot( const Vector3f &a, const Vector3f &b )
{ 
    return a[0]*b[0] + a[1]*b[1] + a[2]*b[2];
}

void Normalize( Vector3f &v )
{ 
    float len = sqrt( v[0] * v[0] + v[1] * v[1] + v[2] * v[2] );
    v = Vector3f( v[0] / len, v[1] / len, v[2] / len );
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!