QGLWidget gluPerspective 升级到 QOpenGLWidget

在将 QGLWidget 的 gluPerspective 函数升级到 QOpenGLWidget 时,需要使用 OpenGL 的核心函数来替代 gluPerspective 函数。

使用 glFrustum 实现透视投影

以下是一个示例代码,展示了如何使用 QOpenGLWidget 来实现透视投影:

#include <QOpenGLWidget>
#include <QOpenGLFunctions>

class MyOpenGLWidget : public QOpenGLWidget, protected QOpenGLFunctions
{
public:
    MyOpenGLWidget(QWidget *parent = nullptr) : QOpenGLWidget(parent)
    {
    }

protected:
    void initializeGL() override
    {
        initializeOpenGLFunctions();
        glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    }

    void resizeGL(int w, int h) override
    {
        glViewport(0, 0, w, h);
    }

    void paintGL() override
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glLoadIdentity();

        // 设置透视投影
        float aspectRatio = static_cast<float>(width()) / static_cast<float>(height());
        float nearPlane = 0.1f;
        float farPlane = 100.0f;
        float fov = 45.0f;
        float top = nearPlane * tan(qDegreesToRadians(fov) / 2.0f);
        float bottom = -top;
        float left = bottom * aspectRatio;
        float right = top * aspectRatio;
        glFrustum(left, right, bottom, top, nearPlane, farPlane);

        // 绘制场景
        // ...

        // 交换缓冲区
        swapBuffers();
    }
};

在上述示例中,initializeGL 函数用于初始化 OpenGL 相关的函数,resizeGL 函数用于设置视口大小,paintGL 函数用于绘制场景。

paintGL 函数中,我们使用 glFrustum 函数来设置透视投影。glFrustum 函数接受 6 个参数,分别表示左、右、上、下、近、远平面的坐标范围。使用 QOpenGLWidget 的 widthheight 函数来获取窗口大小,然后根据窗口的宽高比例计算出左、右、上、下平面的坐标范围。最后使用 glFrustum 函数设置透视投影。

在绘制场景之后,使用 swapBuffers 函数交换缓冲区,将绘制的内容显示在窗口上。

总结

通过使用 OpenGL 核心函数 glFrustum,我们可以轻松地将 QGLWidget 的 gluPerspective 函数升级到 QOpenGLWidget,并实现透视投影效果。

QGLWidget gluPerspective 升级到 QOpenGLWidget - 使用 OpenGL 核心函数实现透视投影

原文地址: https://www.cveoy.top/t/topic/pjZe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录