opengl模型(導(dǎo)入3D模型)
OpenGL
模型
導(dǎo)入3D模型
優(yōu)化
使用3D模型
使用Assimp并創(chuàng)建實(shí)際的加載和轉(zhuǎn)換代碼。Model類(lèi)結(jié)構(gòu)如下:
class Model?
{
? ? public:
? ? ? ? /*? 函數(shù)? ?*/
? ? ? ? Model(char *path)
? ? ? ? {
? ? ? ? ? ? loadModel(path);
? ? ? ? }
? ? ? ? void Draw(Shader shader);? ?
? ? private:
? ? ? ? /*? 模型數(shù)據(jù)? */
? ? ? ? vector<Mesh> meshes;
? ? ? ? string directory;
? ? ? ? /*? 函數(shù)? ?*/
? ? ? ? void loadModel(string path);
? ? ? ? void processNode(aiNode *node, const aiScene *scene);
? ? ? ? Mesh processMesh(aiMesh *mesh, const aiScene *scene);
? ? ? ? vector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type,?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?string typeName);
};
Model類(lèi)包含一個(gè)Mesh對(duì)象的vector,構(gòu)造器參數(shù)需要一個(gè)文件路徑。
?構(gòu)造器通過(guò)loadModel來(lái)加載文件。私有函數(shù)將會(huì)處理Assimp導(dǎo)入過(guò)程中的一部分,私有函數(shù)還存儲(chǔ)了 文件路徑的目錄,加載紋理時(shí)會(huì)用到。
?Draw函數(shù)的作用:遍歷所有網(wǎng)格,調(diào)用網(wǎng)格 各自的Draw函數(shù):
void Draw(Shader shader)
{
? ? for(unsigned int i = 0; i < meshes.size(); i++)
? ? ? ? meshes[i].Draw(shader);
}
導(dǎo)入3D模型
導(dǎo)入一個(gè)模型,并將其轉(zhuǎn)換到自己的數(shù)據(jù)結(jié)構(gòu)中。則首先需要包含Assimp對(duì)應(yīng)的頭文件:
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
首先調(diào)用函數(shù)loadModel,直接從構(gòu)造器中調(diào)用。在該函數(shù)匯總,使用Assimp加載模型到Assimp的一個(gè)叫做scene的數(shù)據(jù)結(jié)構(gòu)中。這個(gè)是場(chǎng)景對(duì)象,通過(guò)它可以訪問(wèn)到加載后的模型中所有需要的數(shù)據(jù)。
?Assimp抽象了加載不同文件格式的所有技術(shù)細(xì)節(jié),只需要一行代碼即可:
Assimp::Importer importer;
const aiScene *scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs);
代碼解讀:聲明了Assimp命名空間內(nèi)的一個(gè)Importer,之后調(diào)用ReadFile函數(shù)。該函數(shù)需要一個(gè)文件路徑,第二個(gè)參數(shù)是后期處理的選項(xiàng)。除了加載文件外,Assimp允許設(shè)定一些選項(xiàng)來(lái)強(qiáng)制它對(duì)導(dǎo)入的數(shù)據(jù)做一些額外的計(jì)算。
?通過(guò)設(shè)定aiProcess_Triangulate ,能告訴Assimp,如果模型不是全部由三角形組成,那么需要將模型的所有圖元轉(zhuǎn)換成三角形。
?aiProcess_FlipUVs,將在處理的時(shí)候翻轉(zhuǎn)y軸的紋理坐標(biāo),因?yàn)樵贠penGL中大部分的圖像的y軸都是反的,所系這個(gè)后期處理選項(xiàng)可以修復(fù)該問(wèn)題。
?其他有用的選項(xiàng)還有:assimp.sourceforge.net/lib_html/postprocess_8h.html
aiProcess_GenNormals:如果模型不包含法向量的話(huà),就為每個(gè)頂點(diǎn)創(chuàng)建法線(xiàn)。
aiProcess_SplitLargeMeshes:將比較大的網(wǎng)格分割成更小的子網(wǎng)格,如果你的渲染有最大頂點(diǎn)數(shù)限制,只能渲染較小的網(wǎng)格,那么它會(huì)非常有用。
aiProcess_OptimizeMeshes:和上個(gè)選項(xiàng)相反,它會(huì)將多個(gè)小網(wǎng)格拼接為一個(gè)大的網(wǎng)格,減少繪制調(diào)用從而進(jìn)行優(yōu)化。
可以看出使用Assimp加載模型是非常容易的。難的是之后使用返回的場(chǎng)景對(duì)象將加載的數(shù)據(jù)轉(zhuǎn)換到一個(gè)Mesh對(duì)象的數(shù)組。
?完整的loadModel函數(shù)如下:
void loadModel(string path)
{
? ? Assimp::Importer import;
? ? const aiScene *scene = import.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs);? ??
? ? if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)?
? ? {
? ? ? ? cout << "ERROR::ASSIMP::" << import.GetErrorString() << endl;
? ? ? ? return;
? ? }
? ? directory = path.substr(0, path.find_last_of('/'));
? ? processNode(scene->mRootNode, scene);
}
在我們加載了模型之后,我們會(huì)檢查場(chǎng)景和其根節(jié)點(diǎn)不為null,并且檢查了它的一個(gè)標(biāo)記(Flag),來(lái)查看返回的數(shù)據(jù)是不是不完整的。如果遇到了任何錯(cuò)誤,我們都會(huì)通過(guò)導(dǎo)入器的GetErrorString函數(shù)來(lái)報(bào)告錯(cuò)誤并返回。我們也獲取了文件路徑的目錄路徑。
?如果什么錯(cuò)誤都沒(méi)有發(fā)生,我們希望處理場(chǎng)景中的所有節(jié)點(diǎn),所以我們將第一個(gè)節(jié)點(diǎn)(根節(jié)點(diǎn))傳入了遞歸的processNode函數(shù)。因?yàn)槊總€(gè)節(jié)點(diǎn)(可能)包含有多個(gè)子節(jié)點(diǎn),我們希望首先處理參數(shù)中的節(jié)點(diǎn),再繼續(xù)處理該節(jié)點(diǎn)所有的子節(jié)點(diǎn),以此類(lèi)推。這正符合一個(gè)遞歸結(jié)構(gòu),所以我們將定義一個(gè)遞歸函數(shù)。遞歸函數(shù)在做一些處理之后,使用不同的參數(shù)遞歸調(diào)用這個(gè)函數(shù)自身,直到某個(gè)條件被滿(mǎn)足停止遞歸。在我們的例子中退出條件(Exit Condition)是所有的節(jié)點(diǎn)都被處理完畢。
Assimp結(jié)構(gòu)中,每個(gè)節(jié)點(diǎn)包含一系列網(wǎng)格索引,每個(gè)索引指向場(chǎng)景對(duì)象中的那個(gè)特定網(wǎng)格。接下來(lái)需要去獲取這些網(wǎng)格索引,獲取每個(gè)網(wǎng)格,處理每個(gè)網(wǎng)格,接著對(duì)每個(gè)節(jié)點(diǎn)的子節(jié)點(diǎn)重復(fù)這個(gè)過(guò)程,則processNode函數(shù)如下:
void processNode(aiNode *node, const aiScene *scene)
{
? ? // 處理節(jié)點(diǎn)所有的網(wǎng)格(如果有的話(huà))
? ? for(unsigned int i = 0; i < node->mNumMeshes; i++)
? ? {
? ? ? ? aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];?
? ? ? ? meshes.push_back(processMesh(mesh, scene));? ? ? ? ?
? ? }
? ? // 接下來(lái)對(duì)它的子節(jié)點(diǎn)重復(fù)這一過(guò)程
? ? for(unsigned int i = 0; i < node->mNumChildren; i++)
? ? {
? ? ? ? processNode(node->mChildren[i], scene);
? ? }
}
我們首先檢查每個(gè)節(jié)點(diǎn)的網(wǎng)格索引,并索引場(chǎng)景的mMeshes數(shù)組來(lái)獲取對(duì)應(yīng)的網(wǎng)格。返回的網(wǎng)格將會(huì)傳遞到processMesh函數(shù)中,它會(huì)返回一個(gè)Mesh對(duì)象,我們可以將它存儲(chǔ)在meshes列表/vector。
所有網(wǎng)格都被處理之后,我們會(huì)遍歷節(jié)點(diǎn)的所有子節(jié)點(diǎn),并對(duì)它們調(diào)用相同的processMesh函數(shù)。當(dāng)一個(gè)節(jié)點(diǎn)不再有任何子節(jié)點(diǎn)之后,這個(gè)函數(shù)將會(huì)停止執(zhí)行。
下一步是將Assimp的數(shù)據(jù)解析到Mesh類(lèi)中。就是將一根aiMesh對(duì)象轉(zhuǎn)化為自己的網(wǎng)格對(duì)象。只需要訪問(wèn)網(wǎng)格的相關(guān)屬性并將它們存儲(chǔ)到自己的對(duì)象中。processMesh函數(shù)如下:
Mesh processMesh(aiMesh *mesh, const aiScene *scene)
{
? ? vector<Vertex> vertices;
? ? vector<unsigned int> indices;
? ? vector<Texture> textures;
? ? for(unsigned int i = 0; i < mesh->mNumVertices; i++)
? ? {
? ? ? ? Vertex vertex;
? ? ? ? // 處理頂點(diǎn)位置、法線(xiàn)和紋理坐標(biāo)
? ? ? ? ...
? ? ? ? vertices.push_back(vertex);
? ? }
? ? // 處理索引
? ? ...
? ? // 處理材質(zhì)
? ? if(mesh->mMaterialIndex >= 0)
? ? {
? ? ? ? ...
? ? }
? ? return Mesh(vertices, indices, textures);
}
處理網(wǎng)格的過(guò)程主要有三部分:獲取所有的頂點(diǎn)數(shù)據(jù),獲取它們的網(wǎng)格索引,并獲取相關(guān)的材質(zhì)數(shù)據(jù)。處理后的數(shù)據(jù)將會(huì)儲(chǔ)存在三個(gè)vector當(dāng)中,我們會(huì)利用它們構(gòu)建一個(gè)Mesh對(duì)象,并返回它到函數(shù)的調(diào)用者那里。
?1。獲取頂點(diǎn)數(shù)據(jù):定義了一個(gè)Vertex結(jié)構(gòu)體,將在每個(gè)迭代之后將它加入到vertices數(shù)組中。會(huì)遍歷網(wǎng)格中的所有頂點(diǎn)——使用mesh->mNumVertices來(lái)獲取。每個(gè)迭代中,使用所有的相關(guān)數(shù)據(jù)填充這個(gè)結(jié)構(gòu)體,頂點(diǎn)的位置如下:
glm::vec3 vector;?
vector.x = mesh->mVertices[i].x;
vector.y = mesh->mVertices[i].y;
vector.z = mesh->mVertices[i].z;?
vertex.Position = vector;
使用了vec3的臨時(shí)變量,是因?yàn)锳ssimp對(duì)向量,矩陣,字符串等都有自己的一套數(shù)據(jù)類(lèi)型,并不能完美地轉(zhuǎn)換到GLM的數(shù)據(jù)類(lèi)型中。
?處理法線(xiàn)的過(guò)程類(lèi)似:
vector.x = mesh->mNormals[i].x;
vector.y = mesh->mNormals[i].y;
vector.z = mesh->mNormals[i].z;
vertex.Normal = vector;
紋理坐標(biāo)的處理也大體相似,但Assimp允許一個(gè)模型在一個(gè)頂點(diǎn)上有最多8個(gè)不同的紋理坐標(biāo),我們不會(huì)用到那么多,我們只關(guān)心第一組紋理坐標(biāo)。我們同樣也想檢查網(wǎng)格是否真的包含了紋理坐標(biāo):
if(mesh->mTextureCoords[0]) // 網(wǎng)格是否有紋理坐標(biāo)?
{
? ? glm::vec2 vec;
? ? vec.x = mesh->mTextureCoords[0][i].x;?
? ? vec.y = mesh->mTextureCoords[0][i].y;
? ? vertex.TexCoords = vec;
}
else
? ? vertex.TexCoords = glm::vec2(0.0f, 0.0f);
vertex結(jié)構(gòu)體現(xiàn)在已經(jīng)填充好了需要的頂點(diǎn)屬性,我們會(huì)在迭代的最后將它壓入vertices這個(gè)vector的尾部。這個(gè)過(guò)程會(huì)對(duì)每個(gè)網(wǎng)格的頂點(diǎn)都重復(fù)一遍。
Assimp的接口定義了每個(gè)網(wǎng)格都有一個(gè)面(Face)數(shù)組,每個(gè)面代表了一個(gè)圖元,在例子中(由于使用了aiProcess_Triangulate選項(xiàng))它總是三角形。一個(gè)面包含了多個(gè)索引,它們定義了在每個(gè)圖元中,我們應(yīng)該繪制哪個(gè)頂點(diǎn),并以什么順序繪制,所以如果我們遍歷了所有的面,并儲(chǔ)存了面的索引到indices這個(gè)vector中就可以了。
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]);
}
到目前為止,有了一系列的頂點(diǎn)和索引數(shù)據(jù),可以通過(guò)glDrawElements函數(shù)來(lái)繪制網(wǎng)格。為了提供一些細(xì)節(jié),還需要處理網(wǎng)格的材質(zhì)。
?一個(gè)網(wǎng)格只包含了一個(gè)指向材質(zhì)對(duì)象的索引。如果要獲取網(wǎng)格真正的材質(zhì),還需要索引場(chǎng)景的mMaterials數(shù)組。網(wǎng)格材質(zhì)索引位于其mMaterialIndex屬性,同樣可以用它來(lái)檢測(cè)一個(gè)網(wǎng)格是否包含有材質(zhì):
if(mesh->mMaterialIndex >= 0)
{
? ? aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex];
? ? vector<Texture> diffuseMaps = loadMaterialTextures(material,?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? aiTextureType_DIFFUSE, "texture_diffuse");
? ? textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
? ? vector<Texture> specularMaps = loadMaterialTextures(material,?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? aiTextureType_SPECULAR, "texture_specular");
? ? textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
}
我們首先從場(chǎng)景的mMaterials數(shù)組中獲取aiMaterial對(duì)象。接下來(lái)我們希望加載網(wǎng)格的漫反射和/或鏡面光貼圖。一個(gè)材質(zhì)對(duì)象的內(nèi)部對(duì)每種紋理類(lèi)型都存儲(chǔ)了一個(gè)紋理位置數(shù)組。不同的紋理類(lèi)型都以aiTextureType_為前綴。我們使用一個(gè)叫做loadMaterialTextures的工具函數(shù)來(lái)從材質(zhì)中獲取紋理。這個(gè)函數(shù)將會(huì)返回一個(gè)Texture結(jié)構(gòu)體的vector,我們將在模型的textures的尾部之后存儲(chǔ)它。
loadMaterialTextures函數(shù)遍歷了給定紋理類(lèi)型的所有紋理位置,獲取了紋理的文件位置,并加載并和生成了紋理,將信息儲(chǔ)存在了一個(gè)Vertex結(jié)構(gòu)體中。loadMaterialTextures函數(shù)它看起來(lái)會(huì)像這樣:
vector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, string typeName)
{
? ? vector<Texture> textures;
? ? for(unsigned int i = 0; i < mat->GetTextureCount(type); i++)
? ? {
? ? ? ? aiString str;
? ? ? ? mat->GetTexture(type, i, &str);
? ? ? ? Texture texture;
? ? ? ? texture.id = TextureFromFile(str.C_Str(), directory);
? ? ? ? texture.type = typeName;
? ? ? ? texture.path = str;
? ? ? ? textures.push_back(texture);
? ? }
? ? return textures;
}
我們首先通過(guò)GetTextureCount函數(shù)檢查儲(chǔ)存在材質(zhì)中紋理的數(shù)量,這個(gè)函數(shù)需要一個(gè)紋理類(lèi)型。我們會(huì)使用GetTexture獲取每個(gè)紋理的文件位置,它會(huì)將結(jié)果儲(chǔ)存在一個(gè)aiString中。我們接下來(lái)使用另外一個(gè)叫做TextureFromFile的工具函數(shù),它將會(huì)(用stb_image.h)加載一個(gè)紋理并返回該紋理的ID。第二個(gè)參數(shù)是模型的文件路徑。
注意:我們假設(shè)了模型文件中紋理文件的路徑是相對(duì)于模型文件的本地(Local)路徑,比如說(shuō)與模型文件處于同一目錄下。我們可以將紋理位置字符串拼接到之前獲取的目錄字符串上(TextureFromFile),來(lái)獲取完整的紋理路徑(這也是為什么GetTexture函數(shù)也需要一個(gè)目錄字符串)。
在網(wǎng)絡(luò)上找到的某些模型會(huì)對(duì)紋理位置使用絕對(duì)(Absolute)路徑,這就不能在每臺(tái)機(jī)器上都工作了。在這種情況下,你可能會(huì)需要手動(dòng)修改這個(gè)文件,來(lái)讓它對(duì)紋理使用本地路徑(如果可能的話(huà))。
綜上,是使用Assimp導(dǎo)入模型的全部。
優(yōu)化
優(yōu)化不是必須的,但是可以提高加載過(guò)程。
?大多數(shù)場(chǎng)景都會(huì)在多個(gè)網(wǎng)絡(luò)中 重用部分紋理。比如:一個(gè)紋理不僅可以用到人身上,也能用到物體身上。當(dāng)然就是用同一個(gè)紋理進(jìn)行加載。但是同樣的紋理已經(jīng)被加載過(guò)了很多遍,對(duì)每個(gè)網(wǎng)格仍會(huì)加載并生成一個(gè)新的紋理。很快就會(huì)變成模型加載實(shí)現(xiàn)的性能瓶頸。
?可以被模型的代碼進(jìn)行調(diào)整,將所有加載過(guò)的紋理全局存儲(chǔ)。每當(dāng)要加載一個(gè)紋理的時(shí)候,首先去檢查是否被加載過(guò),如果有的話(huà),直接使用那個(gè)紋理,并跳過(guò)整個(gè)加載流程。為了能夠比較紋理,還需要存儲(chǔ)它們的路徑:
struct Texture {
? ? unsigned int id;
? ? string type;
? ? aiString path;? // 我們儲(chǔ)存紋理的路徑用于與其它紋理進(jìn)行比較
};
接下來(lái)我們將所有加載過(guò)的紋理儲(chǔ)存在另一個(gè)vector中,在模型類(lèi)的頂部聲明為一個(gè)私有變量:
vector<Texture> textures_loaded;
在loadMaterialTextures函數(shù)中,我們希望將紋理的路徑與儲(chǔ)存在textures_loaded這個(gè)vector中的所有紋理進(jìn)行比較,看看當(dāng)前紋理的路徑是否與其中的一個(gè)相同。如果是的話(huà),則跳過(guò)紋理加載/生成的部分,直接使用定位到的紋理結(jié)構(gòu)體為網(wǎng)格的紋理。更新后的函數(shù)如下:
vector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, string typeName)
{
? ? vector<Texture> textures;
? ? for(unsigned int i = 0; i < mat->GetTextureCount(type); i++)
? ? {
? ? ? ? aiString str;
? ? ? ? mat->GetTexture(type, i, &str);
? ? ? ? bool skip = false;
? ? ? ? for(unsigned int j = 0; j < textures_loaded.size(); j++)
? ? ? ? {
? ? ? ? ? ? if(std::strcmp(textures_loaded[j].path.data(), str.C_Str()) == 0)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? textures.push_back(textures_loaded[j]);
? ? ? ? ? ? ? ? skip = true;?
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? if(!skip)
? ? ? ? {? ?// 如果紋理還沒(méi)有被加載,則加載它
? ? ? ? ? ? Texture texture;
? ? ? ? ? ? texture.id = TextureFromFile(str.C_Str(), directory);
? ? ? ? ? ? texture.type = typeName;
? ? ? ? ? ? texture.path = str.C_Str();
? ? ? ? ? ? textures.push_back(texture);
? ? ? ? ? ? textures_loaded.push_back(texture); // 添加到已加載的紋理中
? ? ? ? }
? ? }
? ? return textures;
}
所以現(xiàn)在我們不僅有了個(gè)靈活的模型加載系統(tǒng),我們也獲得了一個(gè)加載對(duì)象很快的優(yōu)化版本。
綜上,完整代碼如下:
#ifndef MODEL_H
#define MODEL_H
#include <glad/glad.h>?
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <stb_image.h>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <learnopengl/mesh.h>
#include <learnopengl/shader.h>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
unsigned int TextureFromFile(const char *path, const string &directory, bool gamma = false);
class Model?
{
public:
? ? // model data?
? ? vector<Texture> textures_loaded; // stores all the textures loaded so far, optimization to make sure textures aren't loaded more than once.
? ? vector<Mesh>? ? meshes;
? ? string directory;
? ? bool gammaCorrection;
? ? // constructor, expects a filepath to a 3D model.
? ? Model(string const &path, bool gamma = false) : gammaCorrection(gamma)
? ? {
? ? ? ? loadModel(path);
? ? }
? ? // draws the model, and thus all its meshes
? ? void Draw(Shader &shader)
? ? {
? ? ? ? for(unsigned int i = 0; i < meshes.size(); i++)
? ? ? ? ? ? meshes[i].Draw(shader);
? ? }
? ??
private:
? ? // loads a model with supported ASSIMP extensions from file and stores the resulting meshes in the meshes vector.
? ? void loadModel(string const &path)
? ? {
? ? ? ? // read file via ASSIMP
? ? ? ? Assimp::Importer importer;
? ? ? ? const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);
? ? ? ? // check for errors
? ? ? ? if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero
? ? ? ? {
? ? ? ? ? ? cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << endl;
? ? ? ? ? ? return;
? ? ? ? }
? ? ? ? // retrieve the directory path of the filepath
? ? ? ? directory = path.substr(0, path.find_last_of('/'));
? ? ? ? // process ASSIMP's root node recursively
? ? ? ? processNode(scene->mRootNode, scene);
? ? }
? ? // processes a node in a recursive fashion. Processes each individual mesh located at the node and repeats this process on its children nodes (if any).
? ? void processNode(aiNode *node, const aiScene *scene)
? ? {
? ? ? ? // process each mesh located at the current node
? ? ? ? for(unsigned int i = 0; i < node->mNumMeshes; i++)
? ? ? ? {
? ? ? ? ? ? // the node object only contains indices to index the actual objects in the scene.?
? ? ? ? ? ? // the scene contains all the data, node is just to keep stuff organized (like relations between nodes).
? ? ? ? ? ? aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
? ? ? ? ? ? meshes.push_back(processMesh(mesh, scene));
? ? ? ? }
? ? ? ? // after we've processed all of the meshes (if any) we then recursively process each of the children nodes
? ? ? ? for(unsigned int i = 0; i < node->mNumChildren; i++)
? ? ? ? {
? ? ? ? ? ? processNode(node->mChildren[i], scene);
? ? ? ? }
? ? }
? ? Mesh processMesh(aiMesh *mesh, const aiScene *scene)
? ? {
? ? ? ? // data to fill
? ? ? ? vector<Vertex> vertices;
? ? ? ? vector<unsigned int> indices;
? ? ? ? vector<Texture> textures;
? ? ? ? // walk through each of the mesh's vertices
? ? ? ? for(unsigned int i = 0; i < mesh->mNumVertices; i++)
? ? ? ? {
? ? ? ? ? ? Vertex vertex;
? ? ? ? ? ? glm::vec3 vector; // we declare a placeholder vector since assimp uses its own vector class that doesn't directly convert to glm's vec3 class so we transfer the data to this placeholder glm::vec3 first.
? ? ? ? ? ? // positions
? ? ? ? ? ? vector.x = mesh->mVertices[i].x;
? ? ? ? ? ? vector.y = mesh->mVertices[i].y;
? ? ? ? ? ? vector.z = mesh->mVertices[i].z;
? ? ? ? ? ? vertex.Position = vector;
? ? ? ? ? ? // normals
? ? ? ? ? ? if (mesh->HasNormals())
? ? ? ? ? ? {
? ? ? ? ? ? ? ? vector.x = mesh->mNormals[i].x;
? ? ? ? ? ? ? ? vector.y = mesh->mNormals[i].y;
? ? ? ? ? ? ? ? vector.z = mesh->mNormals[i].z;
? ? ? ? ? ? ? ? vertex.Normal = vector;
? ? ? ? ? ? }
? ? ? ? ? ? // texture coordinates
? ? ? ? ? ? if(mesh->mTextureCoords[0]) // does the mesh contain texture coordinates?
? ? ? ? ? ? {
? ? ? ? ? ? ? ? glm::vec2 vec;
? ? ? ? ? ? ? ? // a vertex can contain up to 8 different texture coordinates. We thus make the assumption that we won't?
? ? ? ? ? ? ? ? // use models where a vertex can have multiple texture coordinates so we always take the first set (0).
? ? ? ? ? ? ? ? vec.x = mesh->mTextureCoords[0][i].x;?
? ? ? ? ? ? ? ? vec.y = mesh->mTextureCoords[0][i].y;
? ? ? ? ? ? ? ? vertex.TexCoords = vec;
? ? ? ? ? ? ? ? // tangent
? ? ? ? ? ? ? ? vector.x = mesh->mTangents[i].x;
? ? ? ? ? ? ? ? vector.y = mesh->mTangents[i].y;
? ? ? ? ? ? ? ? vector.z = mesh->mTangents[i].z;
? ? ? ? ? ? ? ? vertex.Tangent = vector;
? ? ? ? ? ? ? ? // bitangent
? ? ? ? ? ? ? ? vector.x = mesh->mBitangents[i].x;
? ? ? ? ? ? ? ? vector.y = mesh->mBitangents[i].y;
? ? ? ? ? ? ? ? vector.z = mesh->mBitangents[i].z;
? ? ? ? ? ? ? ? vertex.Bitangent = vector;
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? ? ? vertex.TexCoords = glm::vec2(0.0f, 0.0f);
? ? ? ? ? ? vertices.push_back(vertex);
? ? ? ? }
? ? ? ? // now wak through each of the mesh's faces (a face is a mesh its triangle) and retrieve the corresponding vertex indices.
? ? ? ? for(unsigned int i = 0; i < mesh->mNumFaces; i++)
? ? ? ? {
? ? ? ? ? ? aiFace face = mesh->mFaces[i];
? ? ? ? ? ? // retrieve all indices of the face and store them in the indices vector
? ? ? ? ? ? for(unsigned int j = 0; j < face.mNumIndices; j++)
? ? ? ? ? ? ? ? indices.push_back(face.mIndices[j]);? ? ? ??
? ? ? ? }
? ? ? ? // process materials
? ? ? ? aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];? ??
? ? ? ? // we assume a convention for sampler names in the shaders. Each diffuse texture should be named
? ? ? ? // as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER.?
? ? ? ? // Same applies to other texture as the following list summarizes:
? ? ? ? // diffuse: texture_diffuseN
? ? ? ? // specular: texture_specularN
? ? ? ? // normal: texture_normalN
? ? ? ? // 1. diffuse maps
? ? ? ? vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
? ? ? ? textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
? ? ? ? // 2. specular maps
? ? ? ? vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
? ? ? ? textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
? ? ? ? // 3. normal maps
? ? ? ? std::vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_normal");
? ? ? ? textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
? ? ? ? // 4. height maps
? ? ? ? std::vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_height");
? ? ? ? textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());
? ? ? ??
? ? ? ? // return a mesh object created from the extracted mesh data
? ? ? ? return Mesh(vertices, indices, textures);
? ? }
? ? // checks all material textures of a given type and loads the textures if they're not loaded yet.
? ? // the required info is returned as a Texture struct.
? ? vector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, string typeName)
? ? {
? ? ? ? vector<Texture> textures;
? ? ? ? for(unsigned int i = 0; i < mat->GetTextureCount(type); i++)
? ? ? ? {
? ? ? ? ? ? aiString str;
? ? ? ? ? ? mat->GetTexture(type, i, &str);
? ? ? ? ? ? // check if texture was loaded before and if so, continue to next iteration: skip loading a new texture
? ? ? ? ? ? bool skip = false;
? ? ? ? ? ? for(unsigned int j = 0; j < textures_loaded.size(); j++)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? if(std::strcmp(textures_loaded[j].path.data(), str.C_Str()) == 0)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? textures.push_back(textures_loaded[j]);
? ? ? ? ? ? ? ? ? ? skip = true; // a texture with the same filepath has already been loaded, continue to next one. (optimization)
? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? if(!skip)
? ? ? ? ? ? {? ?// if texture hasn't been loaded already, load it
? ? ? ? ? ? ? ? Texture texture;
? ? ? ? ? ? ? ? texture.id = TextureFromFile(str.C_Str(), this->directory);
? ? ? ? ? ? ? ? texture.type = typeName;
? ? ? ? ? ? ? ? texture.path = str.C_Str();
? ? ? ? ? ? ? ? textures.push_back(texture);
? ? ? ? ? ? ? ? textures_loaded.push_back(texture);? // store it as texture loaded for entire model, to ensure we won't unnecessary load duplicate textures.
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return textures;
? ? }
};
unsigned int TextureFromFile(const char *path, const string &directory, bool gamma)
{
? ? string filename = string(path);
? ? filename = directory + '/' + filename;
? ? unsigned int textureID;
? ? glGenTextures(1, &textureID);
? ? int width, height, nrComponents;
? ? unsigned char *data = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0);
? ? if (data)
? ? {
? ? ? ? GLenum format;
? ? ? ? if (nrComponents == 1)
? ? ? ? ? ? format = GL_RED;
? ? ? ? else if (nrComponents == 3)
? ? ? ? ? ? format = GL_RGB;
? ? ? ? else if (nrComponents == 4)
? ? ? ? ? ? format = GL_RGBA;
? ? ? ? glBindTexture(GL_TEXTURE_2D, textureID);
? ? ? ? glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
? ? ? ? glGenerateMipmap(GL_TEXTURE_2D);
? ? ? ? glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
? ? ? ? glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
? ? ? ? glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
? ? ? ? glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
? ? ? ? stbi_image_free(data);
? ? }
? ? else
? ? {
? ? ? ? std::cout << "Texture failed to load at path: " << path << std::endl;
? ? ? ? stbi_image_free(data);
? ? }
? ? return textureID;
}
#endif
使用3D模型
加載一個(gè)3D模型,這個(gè)模型被輸出為一個(gè).obj文件和一個(gè).mtl文件,.mtl文件包含了模型的漫反射,鏡面光,法線(xiàn)貼圖。
注意:所有的紋理和模型文件應(yīng)該位于同一個(gè)目錄下,以供加載紋理。
?在代碼中,聲明一個(gè)Model對(duì)象,將模型的文件位置傳入。接下來(lái)模型會(huì)自動(dòng)加載并在渲染循環(huán)中使用它的Draw函數(shù)來(lái)繪制物體。不再需要緩沖分配、屬性指針和渲染指令,只需要一行代碼就可以了。