Qt+OpenGL——摄像机类实现

参考链接:
从零实现3D图像引擎:(12)构建支持欧拉和UVN的相机系统
LearnOpenGL CN——摄像机

头文件

#ifndef GLCAMERA_H
#define GLCAMERA_H

#include <QVector2D>
#include <QVector3D>
#include <QMatrix4x4>
#include <QObject>

class GLCamera
{
public:
    GLCamera(float aspectRatio);
    ~GLCamera();

    QMatrix4x4 getCameraMatrix();

    void adjustFocus(const float &val);
    void translate(const float &xOffset,const float &yOffset);
    void rotate(const float &xOffset, const float &yOffset);

    void resetCamera();
protected:
    void initialize();
    void updateProjection();
    void updateFront();
private:
    float m_fAspectRatio = 1.0f;
    float m_fVerticalAngle = 45.0f;
    float m_fNearPlane = 0.1f;
    float m_fFarPlane = 100.0f;

    float m_fYaw = -90.0f;
    float m_fPitch = 0.0f;

    QMatrix4x4 m_mat4Projection;

    QVector3D m_position = QVector3D(0.0f,0.0f,10.0f);
    QVector3D m_front = QVector3D(0.0f,0.0f,-10.0f);
    QVector3D m_up = QVector3D(0.0f,1.0f,0.0f);

    QVector3D m_realTimePostion = m_position;
    QVector3D m_realTimeFront = m_front;
};

#endif // GLCAMERA_H

源文件

#include "glcamera.h"
#include <QtMath>
#include <QDebug>

GLCamera::GLCamera(float aspectRatio)
{
    m_fAspectRatio = aspectRatio;

    initialize();
}

GLCamera::~GLCamera()
{

}

QMatrix4x4 GLCamera::getCameraMatrix()
{
    QMatrix4x4 view;

    view.lookAt(m_realTimePostion,m_realTimePostion + m_realTimeFront,m_up);
    return m_mat4Projection * view;
}

void GLCamera::adjustFocus(const float &val)
{
    m_realTimePostion += m_realTimeFront * (val - 1);
}

void GLCamera::translate(const float &xOffset,
                              const float &yOffset)
{
    m_realTimePostion += QVector3D(xOffset,-yOffset,0);
}

void GLCamera::rotate(const float &xOffset,const float &yOffset)
{
    m_fYaw += xOffset;
    m_fPitch -= yOffset;

    if (m_fPitch > 89.0f)
        m_fPitch = 89.0f;
    if (m_fPitch < -89.0f)
        m_fPitch = -89.0f;

    updateFront();
}

void GLCamera::resetCamera()
{
    m_realTimePostion = m_position;
    m_realTimeFront = m_front;
}

void GLCamera::initialize()
{
    updateProjection();
    updateFront();
}

void GLCamera::updateProjection()
{
    m_mat4Projection = QMatrix4x4();
    m_mat4Projection.perspective(m_fVerticalAngle,m_fAspectRatio,m_fNearPlane,m_fFarPlane);
}

void GLCamera::updateFront()
{
    QVector3D front;
    front.setX(qCos(qDegreesToRadians(m_fYaw)) * qCos(qDegreesToRadians(m_fPitch)));
    front.setY(qSin(qDegreesToRadians(m_fPitch)));
    front.setZ(qSin(qDegreesToRadians(m_fYaw)) * qCos(qDegreesToRadians(m_fPitch)));

    m_realTimeFront = front.normalized();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值