美文网首页
QOpenGLWidget 显示点云

QOpenGLWidget 显示点云

作者: 寽虎非虫003 | 来源:发表于2022-07-06 13:56 被阅读0次

参考

Qt OPenGL 入门教程之一 基于QOpenGLWidget 绘点
以及qt自带的显示那个Q的示例的修改,暂时不能很好的旋转平移等操作,后面再补齐。

代码

着色器代码shader.cpp.in

// 单个点的数据为“xyzbgr”,前半段是坐标,后半段是颜色
static const char *vertexShaderSourceCore =
    "#version 460\n"
    "layout(location = 0) in vec3 aPos;\n" //输入坐标
    "layout(location = 1) in vec3 aColor;\n" //输入颜色
    "out vec3 color;\n"
    "uniform mat4 projMatrix;\n"
    "uniform mat4 mvMatrix;\n"
    "uniform mat3 normalMatrix;\n"
    "void main() {\n"
    "   gl_Position = vec4(aPos,1.0);\n"//把坐标转换成齐次坐标,再做转换
    "   gl_PointSize = (gl_Position.z +10.0f);\n"//点大小
    "   color = aColor.zyx;\n"//把颜色从bgr转到rgb
    "}\n";

static const char *fragmentShaderSourceCore =
    "#version 460\n"
    "in highp vec3 color;\n" //输入颜色
    "out highp vec4 fragColor;\n" //渲染颜色
    "void main() {\n"
    "   fragColor = vec4(color, 1.0);\n"
    "}\n";

头文件cloudUI.h

#pragma once

#include <QWidget>
#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QOpenGLVertexArrayObject>
#include <QOpenGLBuffer>
#include <QMatrix4x4>

QT_FORWARD_DECLARE_CLASS(QOpenGLShaderProgram)

class GLWidget : public QOpenGLWidget, protected QOpenGLFunctions
{
    Q_OBJECT

public:
    GLWidget(QWidget *parent = nullptr);
    ~GLWidget();

    static bool isTransparent() { return m_transparent; }
    static void setTransparent(bool t) { m_transparent = t; }

    QSize minimumSizeHint() const override;
    QSize sizeHint() const override;

public slots:
    void setXRotation(int angle);
    void setYRotation(int angle);
    void setZRotation(int angle);
    void cleanup();

signals:
    // 设置绕这几个轴旋转的角度的信号
    void xRotationChanged(int angle);
    void yRotationChanged(int angle);
    void zRotationChanged(int angle);

protected:
    //都是重载基本的函数
    void initializeGL() override;
    void paintGL() override;
    void resizeGL(int width, int height) override;
    void mousePressEvent(QMouseEvent *event) override;
    void mouseMoveEvent(QMouseEvent *event) override;

private:

    void setupVertexAttribs();

    bool m_core;///<???
    int m_xRot = 0;
    int m_yRot = 0;
    int m_zRot = 0;
    QPoint m_lastPos;
    QOpenGLVertexArrayObject m_vao;
    QOpenGLBuffer m_logoVbo; //顶点缓冲对象
    QOpenGLShaderProgram *m_program = nullptr;///<着色器程序

    int m_aPos = 0;///<坐标的存放位置
    int m_aColor = 1;///<颜色的存放位置

    int m_projMatrixLoc = 0;
    int m_mvMatrixLoc = 0;
    int m_normalMatrixLoc = 0;
    int m_lightPosLoc = 0;
    QMatrix4x4 m_proj;
    QMatrix4x4 m_camera;
    QMatrix4x4 m_world;
    static bool m_transparent;
};

源文件cloudUI.cpp

#include "cloudUI.h"
#include <QMouseEvent>
#include <QOpenGLShaderProgram>
#include <QCoreApplication>
#include <math.h>

bool GLWidget::m_transparent = false;

GLWidget::GLWidget(QWidget *parent)
    : QOpenGLWidget(parent)
{
    m_core = QSurfaceFormat::defaultFormat().profile() == QSurfaceFormat::CoreProfile;
    // --transparent causes the clear color to be transparent. Therefore, on systems that
    // support it, the widget will become transparent apart from the logo.
    if (m_transparent)
    {
        QSurfaceFormat fmt = format();
        fmt.setAlphaBufferSize(8);
        setFormat(fmt);
    }
}

GLWidget::~GLWidget()
{
    cleanup();
}

QSize GLWidget::minimumSizeHint() const
{
    return QSize(50, 50);
}

QSize GLWidget::sizeHint() const
{
    return QSize(400, 400);
}

static void qNormalizeAngle(int &angle)
{
    while (angle < 0)
        angle += 360 * 16;
    while (angle > 360 * 16)
        angle -= 360 * 16;
}

void GLWidget::setXRotation(int angle)
{
    qNormalizeAngle(angle);
    if (angle != m_xRot)
    {
        m_xRot = angle;
        emit xRotationChanged(angle);
        update();
    }
}

void GLWidget::setYRotation(int angle)
{
    qNormalizeAngle(angle);
    if (angle != m_yRot)
    {
        m_yRot = angle;
        emit yRotationChanged(angle);
        update();
    }
}

void GLWidget::setZRotation(int angle)
{
    qNormalizeAngle(angle);
    if (angle != m_zRot)
    {
        m_zRot = angle;
        emit zRotationChanged(angle);
        update();
    }
}

void GLWidget::cleanup()
{
    if (m_program == nullptr)
        return;
    makeCurrent();
    m_logoVbo.destroy();
    delete m_program;
    m_program = nullptr;
    doneCurrent();
}

#include "shaderSrc.cpp.in"
void GLWidget::initializeGL()
{

    //弄来的一个三角形的顶点集
    float vertices[] = {
        -0.5f, -0.5f, 0.0f,1.0f, 0.0f, 0.0f,
        0.5f, -0.5f, 0.0f,0.0f, 1.0f, 0.0f,
        0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f};
    // In this example the widget's corresponding top-level window can change
    // several times during the widget's lifetime. Whenever this happens, the
    // QOpenGLWidget's associated context is destroyed and a new one is created.
    // Therefore we have to be prepared to clean up the resources on the
    // aboutToBeDestroyed() signal, instead of the destructor. The emission of
    // the signal will be followed by an invocation of initializeGL() where we
    // can recreate all resources.
    connect(context(), &QOpenGLContext::aboutToBeDestroyed, this, &GLWidget::cleanup);

    initializeOpenGLFunctions(); //初始化一些opengl的函数

    glClearColor(0, 0, 0, m_transparent ? 0 : 1);

    //启用修改顶点着色器的顶点大小
    glEnable(GL_PROGRAM_POINT_SIZE);

    //创建着色器程序并设置一些属性
    m_program = new QOpenGLShaderProgram;
    //着色器程序添加顶点着色器
    m_program->addShaderFromSourceCode(
        QOpenGLShader::Vertex,
        // m_core ? vertexShaderSourceCore : vertexShaderSource);
        vertexShaderSourceCore);
    //着色器程序添加片段着色器
    m_program->addShaderFromSourceCode(
        QOpenGLShader::Fragment,
        // m_core ? fragmentShaderSourceCore : fragmentShaderSource);
        fragmentShaderSourceCore);
    //绑定 名称 到指定 位置
    // 这儿的名称是着色器代码里面给出的
    // m_program->bindAttributeLocation("vertex", 0);
    // m_program->bindAttributeLocation("normal", 1);

    m_program->bindAttributeLocation("aPos", 0);
    m_program->bindAttributeLocation("aColor", 1);

    m_program->link();//链接
    m_program->bind();//绑定

    //返回统一变量名在着色器程序参数列表中的位置。如果name不是这个着色程序的有效统一变量,返回-1。
    // 字符串里面的变量是在着色器程序里面设置的
    m_projMatrixLoc = m_program->uniformLocation("projMatrix");
    m_mvMatrixLoc = m_program->uniformLocation("mvMatrix");
    m_normalMatrixLoc = m_program->uniformLocation("normalMatrix");
    m_lightPosLoc = m_program->uniformLocation("lightPos");

    // 创建一个顶点阵列对象。在opengles 2.0和opengl2.x实现中这是可选的,可能根本不支持。
    // 尽管如此,下面的代码在所有情况下都可以工作,并确保在需要VAO的时候有一个VAO。
    m_vao.create();
    QOpenGLVertexArrayObject::Binder vaoBinder(&m_vao);

    // Setup our vertex buffer object.
    m_logoVbo.create();
    m_logoVbo.bind();
    // m_logoVbo.allocate(m_logo.constData(), m_logo.count() * sizeof(GLfloat));
    m_logoVbo.allocate(vertices, 18 * sizeof(GLfloat));

    // Store the vertex attribute bindings for the program.
    setupVertexAttribs();

    // Our camera never changes in this example.
    m_camera.setToIdentity();
    m_camera.translate(0, 0, -1);

    // Light position is fixed.
    m_program->setUniformValue(m_lightPosLoc, QVector3D(0, 0, 70));

    m_program->release();
}

void GLWidget::setupVertexAttribs()
{
    m_logoVbo.bind();
    QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions();
    f->glEnableVertexAttribArray(0);
    f->glEnableVertexAttribArray(1);
    f->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat),
                             nullptr);
    f->glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat),
                             reinterpret_cast<void *>(3 * sizeof(GLfloat)));
    m_logoVbo.release();
}

void GLWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);

    m_world.setToIdentity();
    m_world.rotate(180.0f - (m_xRot / 16.0f), 1, 0, 0);
    m_world.rotate(m_yRot / 16.0f, 0, 1, 0);
    m_world.rotate(m_zRot / 16.0f, 0, 0, 1);

    QOpenGLVertexArrayObject::Binder vaoBinder(&m_vao);
    m_program->bind();
    // 把着色器程序需要使用的全局变量设置进着色器程序
    m_program->setUniformValue(m_projMatrixLoc, m_proj);
    m_program->setUniformValue(m_mvMatrixLoc, m_camera * m_world);
    QMatrix3x3 normalMatrix = m_world.normalMatrix();
    m_program->setUniformValue(m_normalMatrixLoc, normalMatrix);

    // 绘制目标
    // GL_TRIANGLES 是三角面片形式
    // GL_POINTS 是点云形式
    // 设置不同的绘制模式可能需要对着色器代码也进行更改才行
    glDrawArrays(GL_POINTS, 0, 3);

    m_program->release();
}

void GLWidget::resizeGL(int w, int h)
{
    m_proj.setToIdentity();
    m_proj.perspective(45.0f, GLfloat(w) / h, 0.01f, 100.0f);
}

void GLWidget::mousePressEvent(QMouseEvent *event)
{
    m_lastPos = event->position().toPoint();
}

void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
    int dx = event->position().toPoint().x() - m_lastPos.x();
    int dy = event->position().toPoint().y() - m_lastPos.y();

    if (event->buttons() & Qt::LeftButton)
    {
        setXRotation(m_xRot + 8 * dy);
        setYRotation(m_yRot + 8 * dx);
    }
    else if (event->buttons() & Qt::RightButton)
    {
        setXRotation(m_xRot + 8 * dy);
        setZRotation(m_zRot + 8 * dx);
    }
    m_lastPos = event->position().toPoint();
}

主函数文件main.cpp

#include<iostream>
#include <QApplication>
#include "cloudUI.h"

#include <QOffscreenSurface>


using namespace std;
int main(int argc,char ** argv)
{
    cout<<"build sucessful!"<<endl;
    
    QApplication app(argc, argv); //初始化

    QOffscreenSurface surf;
    surf.create();

    ///////////////////////////////////
    // 查看opengl版本
    ///////////////////////////////////
    // QOpenGLContext  ctx;
    // ctx.create();
    // ctx.makeCurrent(&surf);
    
    // GLint major,minor;
    // ctx.functions()->glGetIntegerv(GL_MAJOR_VERSION,&major);
    // ctx.functions()->glGetIntegerv(GL_MINOR_VERSION,&minor);

    // qDebug()<<"GL version info"<<(const char*)ctx.functions()->glGetString(GL_VERSION);
    // qDebug()<<"GL version "<<major<<"."<<minor;

    
    GLWidget w;
    // GenPhaseUI w;
    w.show();
    
    app.exec(); //主事件循环
    
    return 0;
}

编译的用的CMakeLists.txt

# 版本最低需求
cmake_minimum_required(VERSION 3.1)

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

#输出路径
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_CURRENT_SOURCE_DIR}/out/bin)
set(LIBRARY_OUTPUT_PATH ${CMAKE_CURRENT_SOURCE_DIR}/out/lib)


# 项目 并设置为C++语言(只有头文件时也能编译)
project(3DSoft VERSION 0.0.1
    LANGUAGES CXX)

list(APPEND CMAKE_PREFIX_PATH "~/Qt/6.2.1/gcc_64/lib/cmake")
find_package(Qt6 COMPONENTS  REQUIRED
    Widgets
    OpenGLWidgets
    )

add_executable(cloud_test
    main.cpp
    cloudUI.cpp)


target_link_libraries(cloud_test
    PRIVATE Qt6::Widgets
    Qt6::OpenGLWidgets
)

结果显示

这个widget可以像其他的一样嵌在别的窗口里。


测试点显示结果

相关文章

网友评论

      本文标题:QOpenGLWidget 显示点云

      本文链接:https://www.haomeiwen.com/subject/jiusbrtx.html