OpenGL ES 3. 基本变换

大家好,接下来将为大家介绍OpenGL ES 3. 基本变换。

OpenGL ES 3. 基本变换 包括 平移、旋转、缩放等几类。

如上这3种变换的矩阵都将会改变物体在3D空间中的位置和姿态,我们把“物体的位置和姿态”矩阵称为模型矩阵。

1、平移变换

其变换矩阵的基本格式如下:

上述矩阵中的 mx、my、mz 分别表示平移变换中沿 x、y、z 轴方向的位移。通过简单的线性代 数计算即可验证,矩阵 M 乘以变换前 P 点的齐次坐标后确实得到了相当于将 P 点沿 x、y、z 轴平 移 mx、my、mz 的结果,具体情况如下。

其矩阵变换的关键代码如下:

public static void translate(float x, float y, float z) 
{
    Matrix.translateM(mMMatrix, 0, x, y, z); //沿x、y、z轴方向进行平移变换的方法
}


2、旋转变换

其变换矩阵的基本格式如下:

上述矩阵表示将指定的点 P 绕轴向量 u 旋转 θ 度,其中的 u x 、 u y 、 u z 表示 u 向量在 x、y、z 轴上的分量。

其矩阵变换的关键代码如下:

public static void rotate(float angle,float x,float y,float z)//设置绕xyz轴转动
{
    Matrix.rotateM(mMMatrix,0,angle,x,y,z);
}

3、缩放变换

其变换矩阵的基本格式如下:

上述矩阵中的 sx、sy、sz 分别表示缩放变换中的沿 x、y、z 轴方向的缩放率。通过简单的线性 代数计算即可验证,矩阵 M 乘以变换前 P 点的齐次坐标后确实得到了相当于将 P 点坐标沿 z、y、 z 轴方向缩放 sx、sy、sz 倍的结果,具体情况如下。

其矩阵变换的关键代码如下:

public static void scale(float x,float y,float z)
{
    Matrix.scaleM(mMMatrix,0,x,y,z);
}

4、矩阵变换操作类的整体封装

import android.opengl.Matrix;

//存储系统矩阵状态的类
public class MatrixState 
{
	private static float[] mProjMatrix = new float[16];//4x4矩阵 投影用
    private static float[] mVMatrix = new float[16];//摄像机位置朝向9参数矩阵
    private static float[] mMVPMatrix;//最后起作用的总变换矩阵
    static float[] mMMatrix=new float[16] ;//具体物体的移动旋转缩放矩阵
    
    public static void setInitStack()//获取不变换初始矩阵
    {
    	Matrix.setRotateM(mMMatrix, 0, 0, 1, 0, 0);
    }
    
    public static void translate(float x,float y,float z)//设置沿xyz轴移动
    {
    	Matrix.translateM(mMMatrix, 0, x, y, z);
    }
    
    public static void rotate(float angle,float x,float y,float z)//设置绕xyz轴转动
    {
    	Matrix.rotateM(mMMatrix,0,angle,x,y,z);
    }
    
    public static void scale(float x,float y,float z)
    {
    	Matrix.scaleM(mMMatrix,0,x,y,z);
    }


    //设置摄像机
    public static void setCamera(
        float cx, float cy, float cz,
        float tx, float ty, float tz,
        float upx, float upy, float upz
    ){
        Matrix.setLookAtM(mVMatrix, 0, cx, cy, cz, tx, ty, tz, upx, upy, upz);
    }
    
    //设置透视投影参数
    public static void setProjectFrustum
    (
    	float left,		//near面的left
    	float right,    //near面的right
    	float bottom,   //near面的bottom
    	float top,      //near面的top
    	float near,		//near面距离
    	float far       //far面距离
    )
    {
    	Matrix.frustumM(mProjMatrix, 0, left, right, bottom, top, near, far);
    }
   
    //获取具体物体的总变换矩阵
    public static float[] getFinalMatrix()
    {
    	mMVPMatrix=new float[16];
    	Matrix.multiplyMM(mMVPMatrix, 0, mVMatrix, 0, mMMatrix, 0);
        Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mMVPMatrix, 0);        
        return mMVPMatrix;
    }
}

其中:mProjMatrix 为投影矩阵;mVMatrix 为摄像机矩阵; mMMatrix 为物体的移动旋转缩放矩阵,也即模型矩阵。 mMVPMatrix 为最后起作用的总变换矩阵。

最后,欢迎大家一起交流学习:微信:liaosy666 ; QQ:2209115372 。

发布了25 篇原创文章 · 获赞 36 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/u010281924/article/details/105311931