QT+OpenGL模型加载 - Assimp

简介: 我们不大可能手工定义房子、汽车或者人形角色这种复杂形状所有的顶点、法线和纹理坐标。我们想要的是将这些模型导入到程序当中。

QT+OpenGL模型加载 - Assimp

本篇完整工程见gitee:OpenGL 对应点的tag,由turbolove提供技术支持,您可以关注博主或者私信博主


模型加载

先来张图:

1545f7eb212e4b51a5348f3e3fcf99e6.png我们不大可能手工定义房子、汽车或者人形角色这种复杂形状所有的顶点、法线和纹理坐标。我们想要的是将这些模型导入到程序当中。


但是不同种类的文件格式中,它们之间通常没有一个通用的结构,因此我们将使用到模型加载库Assimp


Assimp

●  一个非常流行的模型导入库

●  将所有的模型数据加载到Assimp的通用数据结构中


这里不介绍对应的编译,如果你熟悉CMake的话编译起来是非常简单的,项目中提供的是使用vs2019编译的64位的动态库和lib。如果您不好运行,可以将对应的开发环境更换成跟我一致的环境。或者您自己编译对应的库文件。


介绍:

●  场景(Scene): 所有场景/模型数据(材质和网格)都包含在场景对象中。场景对象也包含了场景根节点的引用。


●  根节点(Root Node): 场景根节点可能包含子节点(和其他节点一样),他会有一系列指向场景对象中的mMeshes数组中存储的网格数据索引。


Scene下 的mMeshes数组存储了真正的Mesh对象,节点中的mMeshes数组保存的知识场景中网格数组的索引


●  Mesh对象: 一个Mesh对象本身包含了渲染所需要的所有相关数据,像是顶点位置,法向向量、纹理坐标、面和物体的材质。


●  面(Face): 一个网格包含了多个面。面代表的是物体的渲染图元(三角形、方形、点)。一个面包含了组成图元的顶点的索引


●  材料(Material):一个网格也包含了一个Material对象,他包含了一些函数能让我们获取物体的材质属性,比如颜色和纹理贴图(比如漫反射和镜面光贴图)。


封装Mesh:

一个网格至少需要:

●  顶点数据:至少包含一个位置向量、一个法向量和一个纹理坐标向量

●  材质数据:漫反射/镜面反射

●  索引数据:


mesh.h

#ifndef QTOPENGL_MESH_H
#define QTOPENGL_MESH_H
#include <QOpenGLFunctions_4_5_Core>
#include <QOpenGLShaderProgram>
#include <QOpenGLTexture>
struct Vertex
{
    QVector3D position;
    QVector3D normal;
    QVector2D tex_coords;
};
struct Texture
{
    QOpenGLTexture *texture;
    std::string path;
    std::string type;
};
class Mesh
{
public:
    Mesh(QOpenGLFunctions_4_5_Core *glFn, const QVector<Vertex> &vertices,
         const QVector<unsigned int> &indices, const QVector<Texture> &textures);
    ~Mesh();
    void draw(QOpenGLShaderProgram &shader);
protected:
    void setupMesh();
private:
    unsigned int VAO,VBO,EBO;
    QOpenGLFunctions_4_5_Core *gl_fn_;
    QVector<Vertex> vertices_;
    QVector<unsigned int> indices_;
    QVector<Texture> textures_;
};
#endif //QTOPENGL_MESH_H

mesh.cpp

#include "mesh.h"
Mesh::Mesh(QOpenGLFunctions_4_5_Core *glFn, const QVector<Vertex> &vertices, const QVector<unsigned int> &indices,
           const QVector<Texture> &textures)
{
    gl_fn_ = glFn;
    vertices_ = vertices;
    indices_ = indices;
    textures_ = textures;
    setupMesh();
}
Mesh::~Mesh()
{
}
void Mesh::setupMesh()
{
    //创建VBO和VAO对象,并赋予ID
    gl_fn_->glGenVertexArrays(1, &VAO);
    gl_fn_->glGenBuffers(1, &VBO);
    gl_fn_->glGenBuffers(1,&EBO);
    //绑定VBO和VAO对象
    gl_fn_->glBindVertexArray(VAO);
    gl_fn_->glBindBuffer(GL_ARRAY_BUFFER, VBO);
    //为当前绑定到target的缓冲区对象创建一个新的数据存储。
    //如果data不是NULL,则使用来自此指针的数据初始化数据存储
    gl_fn_->glBufferData(GL_ARRAY_BUFFER, vertices_.size()*sizeof(Vertex),
                           &vertices_[0], GL_STATIC_DRAW);
    gl_fn_->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    gl_fn_->glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                           indices_.size() * sizeof(unsigned int),&indices_[0], GL_STATIC_DRAW);
    //告知显卡如何解析缓冲里的属性值
    gl_fn_->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    gl_fn_->glEnableVertexAttribArray(0);
    gl_fn_->glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
                                    (void*)offsetof(Vertex, normal));
    gl_fn_->glEnableVertexAttribArray(1);
    gl_fn_->glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex),
                                    (void*)offsetof(Vertex, tex_coords));
    gl_fn_->glEnableVertexAttribArray(2);
}
void Mesh::draw(QOpenGLShaderProgram &shader)
{
    unsigned int diffuseNum = 1;
    unsigned int specularNum = 1;
    for(int i = 0; i < textures_.size(); i++)
    {
        std::string name = textures_[i].type;
        shader.setUniformValue(("material." + name).c_str(), i);
        textures_[i].texture->bind(i);
    }
    gl_fn_->glBindVertexArray(VAO);
    gl_fn_->glDrawArrays(GL_TRIANGLES,0,36);
}

封装Model:

我们需要通过Assimp加载模型,并且将其转换成多个网格数据


Assimp里的结构: 每个节点包含一组网格索引,每个索引指向场景对象中的特定网络。


model.h

#ifndef QTOPENGL_MODEL_H
#define QTOPENGL_MODEL_H
#include "assimp/scene.h"
#include "assimp/postprocess.h"
#include "mesh.h"
class Model
{
public:
    Model(QOpenGLFunctions_4_5_Core *glFn, const std::string &path);
    ~Model();
    void draw(QOpenGLShaderProgram &shader)
    {
        for(unsigned int i = 0; i < meshes_.size(); i++)
        {
            meshes_[i].draw(shader);
        }
    }
protected:
    void loadModel(const std::string &path);
    void processNode(aiNode *node, const aiScene *scene);
    Mesh processMesh(aiMesh *mesh, const aiScene *scene);
    QVector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, std::string typeName);
    QOpenGLTexture *textureFromFile(const std::string &file);
private:
    QOpenGLFunctions_4_5_Core *gl_fn_;
    QVector<Texture> texture_loaded_;
    QVector<Mesh>    meshes_;
    std::string      directory_;
};
#endif //QTOPENGL_MODEL_H

model.cpp

#include "model.h"
#include "assimp/Importer.hpp"
#include <iostream>
using namespace std;
Model::Model(QOpenGLFunctions_4_5_Core *glFn, const std::string &path)
{
    gl_fn_ = glFn;
    loadModel(path);
}
Model::~Model()
{
}
void Model::loadModel(const std::string &path)
{
    Assimp::Importer importer;
    const aiScene *scene = importer.ReadFile(path.c_str(), aiProcess_Triangulate | aiProcess_FlipUVs);
    if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
    {
        cout << "ERROR::ASSIMP::" << importer.GetErrorString() <<endl;
        return;
    }
    directory_ = path.substr(0, path.find_last_of('/'));
    processNode(scene->mRootNode, scene);
}
void Model::processNode(aiNode *node, const aiScene *scene)
{
    for(unsigned int i = 0; i < node->mNumMeshes; i++)
    {
        aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];
        meshes_.push_back(processMesh(mesh, scene));
    }
    for(unsigned int i = 0; i < node->mNumChildren; i++)
    {
        processNode(node->mChildren[i], scene);
    }
}
Mesh Model::processMesh(aiMesh *mesh, const aiScene *scene)
{
    QVector<Vertex> vertices;
    QVector<unsigned int> indices;
    QVector<Texture> textures;
    // 顶点数据
    for(unsigned int i = 0; i < mesh->mNumVertices; i++)
    {
        Vertex vertex;
        QVector3D vector;
        vector.setX(mesh->mVertices[i].x);
        vector.setY(mesh->mVertices[i].y);
        vector.setZ(mesh->mVertices[i].z);
        vertex.position = vector;
        vector.setX(mesh->mNormals[i].x);
        vector.setY(mesh->mNormals[i].y);
        vector.setZ(mesh->mNormals[i].z);
        vertex.normal = vector;
        if(mesh->mTextureCoords[0])
        {
            QVector2D tex;
            tex.setX(mesh->mTextureCoords[0][i].x);
            tex.setY(mesh->mTextureCoords[0][i].y);
            vertex.tex_coords = tex;
        }
        else
        {
            vertex.tex_coords = QVector2D(0.0, 0.0);
        }
        vertices.push_back(vertex);
    }
    // 索引数据
    for(unsigned int i = 0; i < mesh->mNumFaces; i++)
    {
        aiFace face = mesh->mFaces[i];
        for(unsigned int j = 0; j < face.mNumIndices; j++)
        {
            indices.push_back(face.mIndices[j]);
        }
    }
    // 纹理数据
    if(mesh->mMaterialIndex >= 0)
    {
        aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex];
        QVector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "diffuse");
        textures.append(diffuseMaps);
        QVector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "specular");
        textures.append(specularMaps);
    }
    return Mesh(gl_fn_, vertices, indices, textures);
}
QVector<Texture> Model::loadMaterialTextures(aiMaterial *mat, aiTextureType type, std::string typeName)
{
    QVector<Texture> textures;
    for(unsigned int i = 0; i < mat->GetTextureCount(type); i++)
    {
        aiString str;
        mat->GetTexture(type, i, &str);
        bool skip = false;
        for(int j = 0; j < texture_loaded_.size(); j++)
        {
            if(std::strcmp(texture_loaded_[j].path.data(), str.C_Str()) == 0)
            {
                textures.push_back(texture_loaded_[j]);
                skip = true;
                break;
            }
        }
        if(!skip)
        {
            Texture texture;
            texture.texture = textureFromFile(directory_ + "/" + str.C_Str());
            texture.type = typeName;
            texture.path = str.C_Str();
            textures.push_back(texture);
            texture_loaded_.push_back(texture);
        }
    }
    return textures;
}
QOpenGLTexture *Model::textureFromFile(const std::string &file)
{
    QOpenGLTexture *texture = new QOpenGLTexture(QImage(file.c_str()).mirrored());
    if(!texture->isCreated())
    {
        cout << "texture load failed!" << endl;
    }
    return texture;
}

之后我们可以使用QT加载模型,该部分代码已经上传到gitee,请在gitee中使用。

目录
相关文章
|
4月前
QT4.7版本的OPENGL的3D旋转模型例子
QT4.7版本的OPENGL的3D旋转模型例子
102 0
QT+OpenGL鼠标操作和模型控制
光线追踪法 从鼠标投射 3D 射线, 通过摄像机,进入场景,然后检查该光线是否与某个对象相交。
284 0
|
1月前
|
Linux
关于linux的qt发布(linuxdeployqt)中opengl版本过高的解决
关于linux的qt发布(linuxdeployqt)中opengl版本过高的解决
|
4月前
|
机器学习/深度学习 API vr&ar
Qt, OpenCV与OpenGL协同作战:图像处理与三维图形界面的完美结合
Qt, OpenCV与OpenGL协同作战:图像处理与三维图形界面的完美结合
750 4
|
异构计算
QT+OpenGL高级数据和高级GLSL
● OpenGL中的缓冲区 对象管理特定的GPU内存 ● 在将缓冲区绑定到特定的缓冲区目标时候赋予它意义 ● OpenGL在内部会保存每个目标(缓冲区)的引用,并且根据目标以不同的方式处理缓冲区。
135 0
QT+OpenGL高级数据和高级GLSL
|
4月前
|
Linux API iOS开发
【Qt 渲染引擎】一文带你了解qt的三种 渲染引擎,包括栅格引擎(Raster)、OpenGL 和本地绘图系统
【Qt 渲染引擎】一文带你了解qt的三种 渲染引擎,包括栅格引擎(Raster)、OpenGL 和本地绘图系统
155 0
|
4月前
Qt+OpenGL 打砖块游戏
Qt+OpenGL 打砖块游戏
60 0
|
存储 异构计算
QT+OpenGL深度测试
在前面的文章中,我们渲染了一个3D箱子,并且运用了深度缓冲来防止阻挡的面渲染到其他面的前面。 现在大部分的GPU都提供一个叫做提前深度测试(Early Depth Testing)的硬件特性。提前深度测试允许深度测试在片段着色器之前运行。只要我们清楚一个片段永远不会是可见的(它在其他物体之后),我们就能提前丢弃这个片段。
107 0
|
4月前
|
数据可视化 API vr&ar
qt“五彩斑斓“ opengl
qt“五彩斑斓“ opengl
|
算法
QT+OpenGL高级光照 Blinn-Phong和Gamma校正
冯氏光照:视线与反射方向之间的夹角不小于90度,镜面光分量会变成0.0(不是很合理,会有清晰的分界线) Blinn-Phone模型采用了半程向量,即光线与视线夹角一般方向上的一个单位向量。当半程向量与法线向量越接近,镜面光分量就越大。
109 0