[OpenGL]模型

文章目录[x]
  1. 1:第三方库

第三方库


常见的模型有obj,fbx等,对于不同的模型文件需要不同的方式加载到内存,这里使用 Assimp 这个开源项目帮我们完成加载的操作。下载好之后用CMake编译就行啦。

 

定义顶点
struct Vertex
{
    // position
    glm::vec3 position;
    // normal
    glm::vec3 normal;
    // texCoords
    glm::vec2 texCoords;
    // tangent
    glm::vec3 tangent;
    // bitangent
    glm::vec3 bitangent;
};

 

纹理前面我们已经自定义过啦,这里只是再添加一点东西

定义纹理
#include "assimp/scene.h"

class Texture
{
public:
    static std::string TEXTURE_TYPE_DIFFUSE;
    static std::string TEXTURE_TYPE_SPECULAR;
    static std::string TEXTURE_TYPE_NORMAL;
    static std::string TEXTURE_TYPE_AMBIENT;

    aiString fileName;
    // TEXTURE_TYPE_XXXX
    std::string type;
    
    // ...略
};

// .cpp
std::string Texture::TEXTURE_TYPE_DIFFUSE = "texture_diffuse";
std::string Texture::TEXTURE_TYPE_SPECULAR = "texture_specular";
std::string Texture::TEXTURE_TYPE_NORMAL = "texture_normal";
std::string Texture::TEXTURE_TYPE_AMBIENT = "texture_ambient";

 

网格
class Mesh
{
public:
    /* 网格数据 */
    std::vector<Vertex> vertices;
    std::vector<unsigned int> indices;
    std::vector<Texture> textures;

    Mesh(std::vector<Vertex>& vertices, std::vector<unsigned int>& indices, std::vector<Texture>& textures);

    void Draw(Shader* shader) const;
private:
    VertexArray* m_VA;
    VertexBuffer* m_VB;
    IndexBuffer* m_IB;

    Renderer m_Renderer;

    void SetupMesh();
};
#include "Mesh.h"
#include "RenderSystem/VertexBufferLayout.h"
#include <string>

Mesh::Mesh(std::vector<Vertex>& vertices, std::vector<unsigned int>& indices, std::vector<Texture>& textures)
{
    this->vertices = vertices;
    this->indices = indices;
    this->textures = textures;

    SetupMesh();
}

void Mesh::Draw(Shader* shader) const
{
    unsigned int diffuseNr = 1;
    unsigned int specularNr = 1;
    unsigned int normalNr = 1;
    unsigned int heightNr = 1;
    for (unsigned int i = 0; i < textures.size(); i++)
    {
        Texture texture = textures[i];
        texture.Bind(i);
        std::string number;
        std::string type = textures[i].type;
        if (type == Texture::TEXTURE_TYPE_DIFFUSE)
            number = std::to_string(diffuseNr++);
        else if (type == Texture::TEXTURE_TYPE_SPECULAR)
            number = std::to_string(specularNr++);
        else if (type == Texture::TEXTURE_TYPE_NORMAL)
            number = std::to_string(normalNr++);
        else if (type == Texture::TEXTURE_TYPE_AMBIENT)
            number = std::to_string(heightNr++);

        shader->SetInt(("material." + type + number).c_str(), i);
    }

    m_Renderer.Draw(m_VA, m_IB, shader);
    glActiveTexture(GL_TEXTURE0);
}

void Mesh::SetupMesh()
{
    m_VA = new VertexArray();
    m_VB = new VertexBuffer(&this->vertices[0], this->vertices.size() * sizeof(Vertex));
    VertexBufferLayout layout;
    layout.Push<float>(3);
    layout.Push<float>(3);
    layout.Push<float>(2);
    layout.Push<float>(3);
    layout.Push<float>(3);
    m_VA->AddBuffer(*m_VB, layout);

    m_IB = new IndexBuffer(&this->indices[0], indices.size());

}

 

模型
#pragma once

#include "Mesh.h"
#include "assimp/scene.h"

class Model
{
public:
    Model(const std::string& path) { LoadModel(path); }

    void Draw(Shader* shader) const;
private:
    std::vector<Texture> m_TexturesCache;

    std::vector<Mesh> m_Meshes;
    std::string m_Directory;

    // 加载模型到场景
    void LoadModel(const std::string& path);
    // 处理节点
    void ProcessNode(aiNode* node, const aiScene* scene);
    // 处理网格
    Mesh ProcessMesh(aiMesh* mesh, const aiScene* scene);
    std::vector<Texture> LoadMaterialTextures(aiMaterial* mat, aiTextureType type, std::string typeName);
};
#include "Model.h"
#include "assimp/Importer.hpp"
#include "assimp/postprocess.h"

void Model::Draw(Shader* shader) const
{
    for (unsigned int i = 0; i < m_Meshes.size(); i++)
    {
        m_Meshes[i].Draw(shader);
    }
}


void Model::LoadModel(const std::string& path)
{
    // 通过Assimp加载模型
    Assimp::Importer importer;
    const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);

    // 错误处理
    if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
    {
        std::cout << "[ERROR::ASSIMP]::" << importer.GetErrorString() << std::endl;
        return;
    }

    // 获取模型文件所在目录
    m_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]];
        m_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)
{
    std::vector<Vertex> vertices;
    std::vector<unsigned int> indices;
    std::vector<Texture> textures;

    for (unsigned int i = 0; i < mesh->mNumVertices; i++)
    {
        Vertex vertex;
        // 处理顶点位置、法线和纹理坐标
        glm::vec3 vec;
        vec.x = mesh->mVertices[i].x;
        vec.y = mesh->mVertices[i].y;
        vec.z = mesh->mVertices[i].z;
        vertex.position = vec;

        vec.x = mesh->mNormals[i].x;
        vec.z = mesh->mNormals[i].y;
        vec.y = mesh->mNormals[i].z;
        vertex.normal = vec;

        if (mesh->mTextureCoords[0])  // 是否有UV坐标
        {
            glm::vec2 uv;
            uv.x = mesh->mTextureCoords[0][i].x;
            uv.y = mesh->mTextureCoords[0][i].y;
            vertex.texCoords = uv;
        }
        else
        {
            vertex.texCoords = glm::vec2(0.0f, 0.0f);
        }

        // tangent
        vec.x = mesh->mTangents[i].x;
        vec.y = mesh->mTangents[i].y;
        vec.z = mesh->mTangents[i].z;
        vertex.tangent = vec;
        // bitangent
        vec.x = mesh->mBitangents[i].x;
        vec.y = mesh->mBitangents[i].y;
        vec.z = mesh->mBitangents[i].z;
        vertex.bitangent = vec;

        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];
        // 1.加载漫反射贴图
        std::vector<Texture> diffuseMaps = LoadMaterialTextures(material, aiTextureType_DIFFUSE, Texture::TEXTURE_TYPE_DIFFUSE);
        textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
        // 2.加载高光贴图
        std::vector<Texture> specularMaps = LoadMaterialTextures(material, aiTextureType_SPECULAR, Texture::TEXTURE_TYPE_SPECULAR);
        textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
        // 3.加载法线贴图
        std::vector<Texture> normalMaps = LoadMaterialTextures(material, aiTextureType_HEIGHT, Texture::TEXTURE_TYPE_NORMAL);
        textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
        // 4.加载环境光贴图
        std::vector<Texture> heightMaps = LoadMaterialTextures(material, aiTextureType_AMBIENT, Texture::TEXTURE_TYPE_AMBIENT);
        textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());
    }

    return Mesh(vertices, indices, textures);
}

std::vector<Texture> Model::LoadMaterialTextures(aiMaterial* mat, aiTextureType type, std::string typeName)
{
    std::vector<Texture> textures;
    for (unsigned int i = 0; i < mat->GetTextureCount(type); i++)
    {
        aiString name;
        mat->GetTexture(type, i, &name);
        bool skip = false;
        // Get texture from cache
        for (unsigned int j = 0; j < m_TexturesCache.size(); j++)
        {
            // 纪念: 2019-9-22 17:41:53,由于没有写 == 0,本人在此浪费1小时。
            if (std::strcmp(m_TexturesCache[j].fileName.data, name.C_Str()) == 0)
            {
                textures.push_back(m_TexturesCache[j]);
                skip = true;
                break;
            }
        }

        if (!skip)
        {
            Texture* texture = new Texture(m_Directory + "/" + name.C_Str());
            texture->type = typeName;
            texture->fileName = name;
            textures.push_back(*texture);
            m_TexturesCache.push_back(*texture);
        }
    }

    return textures;
}

 

Usage
class HelloModel
{
public:
    class Basic : public SubTestBed
    {
        BaseCamera* m_Camera;

        DirectionalLight m_DirLight;
        PointLight m_PointLight;
        SpotLight m_SpotLight;

        float m_Radius = 1.0f;
        float m_Speed = 10.0f;
        float m_Angle = 0.0f;
    public:
        virtual void Setup() override
        {
#pragma region vertices
            float vertices[] = {
                // 位置              
                -0.5f, -0.5f, -0.5f,
                 0.5f, -0.5f, -0.5f,
                 0.5f,  0.5f, -0.5f,
                 0.5f,  0.5f, -0.5f,
                -0.5f,  0.5f, -0.5f,
                -0.5f, -0.5f, -0.5f,

                -0.5f, -0.5f,  0.5f,
                 0.5f, -0.5f,  0.5f,
                 0.5f,  0.5f,  0.5f,
                 0.5f,  0.5f,  0.5f,
                -0.5f,  0.5f,  0.5f,
                -0.5f, -0.5f,  0.5f,

                -0.5f,  0.5f,  0.5f,
                -0.5f,  0.5f, -0.5f,
                -0.5f, -0.5f, -0.5f,
                -0.5f, -0.5f, -0.5f,
                -0.5f, -0.5f,  0.5f,
                -0.5f,  0.5f,  0.5f,

                 0.5f,  0.5f,  0.5f,
                 0.5f,  0.5f, -0.5f,
                 0.5f, -0.5f, -0.5f,
                 0.5f, -0.5f, -0.5f,
                 0.5f, -0.5f,  0.5f,
                 0.5f,  0.5f,  0.5f,

                -0.5f, -0.5f, -0.5f,
                 0.5f, -0.5f, -0.5f,
                 0.5f, -0.5f,  0.5f,
                 0.5f, -0.5f,  0.5f,
                -0.5f, -0.5f,  0.5f,
                -0.5f, -0.5f, -0.5f,

                -0.5f,  0.5f, -0.5f,
                 0.5f,  0.5f, -0.5f,
                 0.5f,  0.5f,  0.5f,
                 0.5f,  0.5f,  0.5f,
                -0.5f,  0.5f,  0.5f,
                -0.5f,  0.5f, -0.5f
            };
#pragma endregion
            // 画表示光源的箱子
            m_VA[1] = new VertexArray();
            m_VB[1] = new VertexBuffer(vertices, sizeof(vertices));
            VertexBufferLayout layout;
            layout.Push<float>(3);
            m_VA[1]->AddBuffer(*m_VB[1], layout);
            m_Shader[1] = new Shader("SandBox/14_Model/Light.shader");

            m_Model[0] = new Model("Resources/Model/nanosuit/nanosuit.obj");
            if (!m_TestScene)
            {
                TestScene::CameraData data;
                data.eye = glm::vec3(-1.2f, 3.6f, 2.5f);
                data.at = glm::vec3(1.5f, 0.3f, -1.6f);
                data.up = glm::vec3(0.0f, 1.0f, 0.0f);
                data.fov = 60.0f;
                data.nearClip = 0.1f;
                data.farClip = 100.0f;
                m_TestScene = new TestScene(TestScene::FREE_CAMERA, data, TestScene::TT_DARK);
                m_TestScene->Setup();
                m_Camera = (::FreeCamera*)m_TestScene->Camera();
            }

            m_Shader[0] = new Shader("SandBox/14_Model/Basic.shader");

            m_DirLight.direction = glm::vec3(-0.2f, -0.2f, -0.3f);
            m_DirLight.ambient = glm::vec3(0.05f);
            m_DirLight.diffuse = glm::vec3(0.5f);
            m_DirLight.specular = glm::vec3(1.0f);

            m_PointLight.position = glm::vec3(m_Radius, 1.8f, m_Radius);
            m_PointLight.ambient = glm::vec3(0.2f);
            m_PointLight.diffuse = glm::vec3(0.6f);
            m_PointLight.specular = glm::vec3(1.0f);
            m_PointLight.constant = 1.0f;
            m_PointLight.linear = 0.09f;
            m_PointLight.quadratic = 0.032f; // 50m衰减

            m_ClearColor = glm::vec4(0.05f, 0.05f, 0.05f, 1.0f);
        }

        virtual void Update(float dt) override
        {
            m_TestScene->Update(dt);

            m_Angle += dt * m_Speed;
            float x = cos(m_Angle) * m_Radius;
            float z = sin(m_Angle) * m_Radius;
            m_PointLight.position.x = x;
            m_PointLight.position.z = z;
        }

        virtual void Render() override
        {
            // m_TestScene->Render();

            m_Shader[0]->Bind();
            glm::mat4 model = glm::mat4(1.0f);
            model = glm::scale(model, glm::vec3(0.18f)); // 1米8
            m_Shader[0]->SetMat4f("model", model);
            m_Shader[0]->SetMat4f("projection", m_Camera->GetProjectionMatrix());
            m_Shader[0]->SetMat4f("view", m_Camera->GetViewMatrix());
            m_Shader[0]->SetVec3("uViewPos", m_Camera->GetEye());
            m_Model[0]->Draw(m_Shader[0]);

            m_Shader[0]->SetVec3("dirLight.direction", m_DirLight.direction);
            m_Shader[0]->SetVec3("dirLight.ambient", m_DirLight.ambient);
            m_Shader[0]->SetVec3("dirLight.diffuse", m_DirLight.diffuse);
            m_Shader[0]->SetVec3("dirLight.specular", m_DirLight.specular);

            m_Shader[0]->SetVec3("pointLight.position", m_PointLight.position);
            m_Shader[0]->SetVec3("pointLight.ambient", m_PointLight.ambient);
            m_Shader[0]->SetVec3("pointLight.diffuse", m_PointLight.diffuse);
            m_Shader[0]->SetVec3("pointLight.specular", m_PointLight.specular);
            m_Shader[0]->SetFloat("pointLight.constant", m_PointLight.constant);
            m_Shader[0]->SetFloat("pointLight.linear", m_PointLight.linear);
            m_Shader[0]->SetFloat("pointLight.quadratic", m_PointLight.quadratic);

            m_Shader[0]->SetFloat("material.shininess", 32.0f);

            m_Renderer.Draw(m_VA[1], 36, m_Shader[1]);
            model = glm::mat4(1.0f);
            model = glm::translate(model, m_PointLight.position);
            model = glm::scale(model, glm::vec3(0.2f));
            m_Shader[1]->SetMat4f("model", model);
            m_Shader[1]->SetMat4f("projection", m_Camera->GetProjectionMatrix());
            m_Shader[1]->SetMat4f("view", m_Camera->GetViewMatrix());
        }

        virtual void OnGUI() override
        {
            ImGui::Begin("ModelTest");
            if (ImGui::DragFloat3("PointLightPosition", (float*)&m_PointLight.position))
            {
            }
            ImGui::End();
        }

    };
};
#Shader Vertex
#version 330 core
layout(location = 0) in vec3 a_position;
layout(location = 1) in vec3 a_normal;
layout(location = 2) in vec2 a_texCoords;

out vec3 iNormal;
out vec3 iFragPos;
out vec2 iTexCoords;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view * model * vec4(a_position, 1.0);

    iFragPos = vec3(model * vec4(a_position, 1.0));
    iNormal = mat3(transpose(inverse(model))) * a_normal;

    iTexCoords = a_texCoords;
}


#Shader Fragment
#version 330 core

struct Material
{
    sampler2D texture_diffuse1;
    sampler2D texture_diffuse2;
    sampler2D texture_diffuse3;
    sampler2D texture_specular1;
    sampler2D texture_normal1;

    float shininess;
};
uniform Material material;

struct DirectionalLight
{
    vec3 direction;

    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};
uniform DirectionalLight dirLight;

struct PointLight
{
    vec3 position;

    vec3 ambient;
    vec3 diffuse;
    vec3 specular;

    float constant;
    float linear;
    float quadratic;
};

uniform PointLight pointLight;

struct SpotLight
{
    vec3 position;
    vec3 direction;
    float cutOff;
    float outterCutOff;

    float constant;
    float linear;
    float quadratic;

    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};
uniform SpotLight spotLight;

uniform vec3 uViewPos;

out vec4 fragColor;

in vec3 iNormal;
in vec3 iFragPos;
in vec2 iTexCoords;

vec3 CalcDirLight(DirectionalLight light, vec3 normal, vec3 viewDir, vec3 diffColor);
vec3 CalcPointLight(PointLight light, vec3 normal, vec3 fragPos, vec3 viewDir, vec3 diffColor);
void main()
{
    vec3 N = normalize(iNormal);
    vec3 viewDir = normalize(uViewPos - iFragPos);

    vec3 diffColor = vec3(texture(material.texture_diffuse1, iTexCoords)
        + texture(material.texture_diffuse2, iTexCoords) + texture(material.texture_diffuse3, iTexCoords));

    vec3 result = CalcDirLight(dirLight, N, viewDir, diffColor);

    result += CalcPointLight(pointLight, N, iFragPos, viewDir, diffColor);

    fragColor = vec4(result, 1.0);
}


vec3 CalcDirLight(DirectionalLight light, vec3 normal, vec3 viewDir, vec3 diffColor)
{
    vec3 lightDir = normalize(-light.direction);
    // 计算漫反射
    float diff = max(dot(normal, lightDir), 0.0);
    // 计算镜面反射
    vec3 reflectDir = reflect(-lightDir, normal);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);

    vec3 ambient = light.ambient * diffColor;
    vec3 diffuse = light.diffuse * (diff * diffColor);
    vec3 specular = light.specular * spec * vec3(texture(material.texture_specular1, iTexCoords));

    return (ambient + diffuse + specular);
}

vec3 CalcPointLight(PointLight light, vec3 normal, vec3 fragPos, vec3 viewDir, vec3 diffColor)
{
    vec3 lightDir = normalize(light.position - fragPos);

    float diff = max(dot(normal, lightDir), 0.0);
    vec3 reflectDir = reflect(-lightDir, normal);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);

    vec3 ambient = light.ambient * diffColor;
    vec3 diffuse = light.diffuse * (diff * diffColor);
    vec3 specular = light.specular * spec * vec3(texture(material.texture_specular1, iTexCoords));

    float distanceFromLightToFrag = length(light.position - fragPos);
    float attenuation = 1.0 / (light.constant + light.linear * distanceFromLightToFrag +
        light.quadratic * (distanceFromLightToFrag * distanceFromLightToFrag));

    return ((ambient + diffuse + specular) * attenuation);
}

 

Model

 

点赞

发表评论

昵称和uid可以选填一个,填邮箱必填(留言回复后将会发邮件给你)
tips:输入uid可以快速获得你的昵称和头像