LearnOpenGL

Translation in progress of learnopengl.com.
git clone https://git.mtkn.jp/LearnOpenGL
Log | Files | Refs

Model.html (24123B)


      1     <div id="content">
      2     <h1 id="content-title">Model</h1>
      3 <h1 id="content-url" style='display:none;'>Model-Loading/Model</h1>
      4 <p>
      5   Now it is time to get our hands dirty with Assimp and start creating the actual loading and translation code. The goal of this chapter is to create another class that represents a model in its entirety, that is, a model that contains multiple meshes, possibly with multiple textures. A house, that contains a wooden balcony, a tower, and perhaps a swimming pool, could still be loaded as a single model. We'll load the model via Assimp and translate it to multiple <fun>Mesh</fun> objects we've created in the <a href="https://learnopengl.com/Model-Loading/Mesh" target="_blank">previous</a> chapter.
      6 </p>
      7 
      8 <p>
      9   Without further ado, I present you the class structure of the <fun>Model</fun> class:
     10 </p>
     11 
     12 <pre><code>
     13 class Model 
     14 {
     15     public:
     16         Model(char *path)
     17         {
     18             loadModel(path);
     19         }
     20         void Draw(Shader &shader);	
     21     private:
     22         // model data
     23         vector&lt;Mesh&gt; meshes;
     24         string directory;
     25 
     26         void loadModel(string path);
     27         void processNode(aiNode *node, const aiScene *scene);
     28         Mesh processMesh(aiMesh *mesh, const aiScene *scene);
     29         vector&lt;Texture&gt; loadMaterialTextures(aiMaterial *mat, aiTextureType type, 
     30                                              string typeName);
     31 };
     32 </code></pre>
     33 
     34 <p>
     35   The <fun>Model</fun> class contains a vector of <fun>Mesh</fun> objects and requires us to give it a file location in its constructor. It then loads the file right away via the <fun>loadModel</fun> function that is called in the constructor. The private functions are all designed to process a part of Assimp's import routine and we'll cover them shortly. We also store the directory of the file path that we'll later need when loading textures.
     36 </p>
     37 
     38 <p>
     39   The <fun>Draw</fun> function is nothing special and basically loops over each of the meshes to call their respective <fun>Draw</fun> function:
     40 </p>
     41 
     42 <pre><code>
     43 void Draw(Shader &shader)
     44 {
     45     for(unsigned int i = 0; i &lt; meshes.size(); i++)
     46         meshes[i].Draw(shader);
     47 }  
     48 </code></pre>
     49 
     50 <h2>Importing a 3D model into OpenGL</h2>
     51 <p>
     52   To import a model and translate it to our own structure, we first need to include the appropriate headers of Assimp:
     53 </p>
     54 
     55 <pre><code>
     56 #include &lt;assimp/Importer.hpp&gt;
     57 #include &lt;assimp/scene.h&gt;
     58 #include &lt;assimp/postprocess.h&gt;
     59 </code></pre>
     60 
     61 <p>
     62   The first function we're calling is <fun>loadModel</fun>, that's directly called from the constructor. Within <fun>loadModel</fun>, we use Assimp to load the model into a data structure of Assimp called a <u>scene</u> object. You may remember from the <a href="https://learnopengl.com/Model-Loading/Assimp" target="_blank">first</a> chapter of the model loading series that this is the root object of Assimp's data interface. Once we have the scene object, we can access all the data we need from the loaded model.
     63 </p>
     64 
     65 <p>
     66   The great thing about Assimp is that it neatly abstracts from all the technical details of loading all the different file formats and does all this with a single one-liner:
     67 </p>
     68 
     69 <pre><code>
     70 Assimp::Importer importer;
     71 const aiScene *scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs); 
     72 </code></pre>
     73 
     74 <p>
     75   We first declare an <fun>Importer</fun> object from Assimp's namespace and then call its <fun>ReadFile</fun> function. The function expects a file path and several <def>post-processing</def> options as its second argument. Assimp allows us to specify several options that forces Assimp to do extra calculations/operations on the imported data. By setting <var>aiProcess_Triangulate</var> we tell Assimp that if the model does not (entirely) consist of triangles, it should transform all the model's primitive shapes to triangles first. The <var>aiProcess_FlipUVs</var> flips the texture coordinates on the y-axis where necessary during processing (you may remember from the <a href="https://learnopengl.com/Getting-started/Textures" target="_blank">Textures</a> chapter that most images in OpenGL were reversed around the y-axis; this little postprocessing option fixes that for us). A few other useful options are:
     76   
     77   <ul>
     78     <li><var>aiProcess_GenNormals</var>: creates normal vectors for each vertex if the model doesn't contain normal vectors.</li>
     79     <li><var>aiProcess_SplitLargeMeshes</var>: splits large meshes into smaller sub-meshes which is useful if your rendering has a maximum number of vertices allowed and can only process smaller meshes.</li>
     80     <li><var>aiProcess_OptimizeMeshes</var>: does the reverse by trying to join several meshes into one larger mesh, reducing drawing calls for optimization.</li>
     81   </ul>
     82   
     83   Assimp provides a great set of postprocessing options and you can find all of them <a href="http://assimp.sourceforge.net/lib_html/postprocess_8h.html" target="_blank">here</a>. Loading a model via Assimp is (as you can see) surprisingly easy. The hard work is in using the returned scene object to translate the loaded data to an array of <code>Mesh</code> objects.
     84 </p>
     85 
     86 <p>
     87   The complete <fun>loadModel</fun> function is listed here:
     88 </p>
     89 
     90 <pre><code>
     91 void loadModel(string path)
     92 {
     93     Assimp::Importer import;
     94     const aiScene *scene = import.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs);	
     95 	
     96     if(!scene || scene-&gt;mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene-&gt;mRootNode) 
     97     {
     98         cout &lt;&lt; "ERROR::ASSIMP::" &lt;&lt; import.GetErrorString() &lt;&lt; endl;
     99         return;
    100     }
    101     directory = path.substr(0, path.find_last_of('/'));
    102 
    103     processNode(scene-&gt;mRootNode, scene);
    104 }  
    105 </code></pre>
    106 
    107 <p>
    108   After we load the model, we check if the scene and the root node of the scene are not null and check one of its flags to see if the returned data is incomplete. If any of these error conditions are met, we report the error retrieved from the importer's <fun>GetErrorString</fun> function and return. We also retrieve the directory path of the given file path.
    109 </p>
    110 
    111 <p>
    112   If nothing went wrong, we want to process all of the scene's nodes. We pass the first node (root node) to the recursive <fun>processNode</fun> function. Because each node (possibly) contains a set of children we want to first process the node in question, and then continue processing all the node's children and so on. This fits a recursive structure, so we'll be defining a recursive function. A recursive function is a function that does some processing and <def>recursively</def> calls the same function with different parameters until a certain condition is met. In our case the <def>exit condition</def> is met when all nodes have been processed.
    113 </p>
    114 
    115 <p>
    116   As you may remember from Assimp's structure, each node contains a set of mesh indices where each index points to a specific mesh located in the scene object. We thus want to retrieve these mesh indices, retrieve each mesh, process each mesh, and then do this all again for each of the node's children nodes. The content of the <fun>processNode</fun> function is shown below:
    117 </p>
    118 
    119 <pre><code>
    120 void processNode(aiNode *node, const aiScene *scene)
    121 {
    122     // process all the node's meshes (if any)
    123     for(unsigned int i = 0; i &lt; node-&gt;mNumMeshes; i++)
    124     {
    125         aiMesh *mesh = scene-&gt;mMeshes[node-&gt;mMeshes[i]]; 
    126         meshes.push_back(processMesh(mesh, scene));			
    127     }
    128     // then do the same for each of its children
    129     for(unsigned int i = 0; i &lt; node-&gt;mNumChildren; i++)
    130     {
    131         processNode(node-&gt;mChildren[i], scene);
    132     }
    133 }  
    134 </code></pre>
    135 
    136 <p>
    137   We first check each of the node's mesh indices and retrieve the corresponding mesh by indexing the scene's <var>mMeshes</var> array. The returned mesh is then passed to the <fun>processMesh</fun> function that returns a <fun>Mesh</fun> object that we can store in the <var>meshes</var> list/vector. 
    138 </p>
    139 
    140 <p>
    141   Once all the meshes have been processed, we iterate through all of the node's children and call the same <fun>processNode</fun> function for each its children. Once a node no longer has any children, the recursion stops.
    142 </p>
    143 
    144 <note>
    145   A careful reader may have noticed that we could forget about processing any of the nodes and simply loop through all of the scene's meshes directly, without doing all this complicated stuff with indices. The reason we're doing this is that the initial idea for using nodes like this is that it defines a parent-child relation between meshes. By recursively iterating through these relations, we can define certain meshes to be parents of other meshes.<br/>
    146   An example use case for such a system is when you want to translate a car mesh and make sure that all its children (like an engine mesh, a steering wheel mesh, and its tire meshes) translate as well; such a system is easily created using parent-child relations.<br/><br/>
    147   Right now however we're not using such a system, but it is generally recommended to stick with this approach for whenever you want extra control over your mesh data. These node-like relations are after all defined by the artists who created the models.
    148 </note>
    149 
    150 <p>
    151   The next step is to process Assimp's data into the <fun>Mesh</fun> class from the previous chapter.
    152 </p>
    153 
    154 <h3>Assimp to Mesh</h3>
    155 <p>
    156   Translating an <code>aiMesh</code> object to a mesh object of our own is not too difficult. All we need to do, is access each of the mesh's relevant properties and store them in our own object. The general structure of the <fun>processMesh</fun> function then becomes:
    157 </p>
    158 
    159 <pre><code>
    160 Mesh processMesh(aiMesh *mesh, const aiScene *scene)
    161 {
    162     vector&lt;Vertex&gt; vertices;
    163     vector&lt;unsigned int&gt; indices;
    164     vector&lt;Texture&gt; textures;
    165 
    166     for(unsigned int i = 0; i &lt; mesh-&gt;mNumVertices; i++)
    167     {
    168         Vertex vertex;
    169         // process vertex positions, normals and texture coordinates
    170         [...]
    171         vertices.push_back(vertex);
    172     }
    173     // process indices
    174     [...]
    175     // process material
    176     if(mesh-&gt;mMaterialIndex &gt;= 0)
    177     {
    178         [...]
    179     }
    180 
    181     return Mesh(vertices, indices, textures);
    182 }  
    183 </code></pre>
    184 
    185 <p>
    186   Processing a mesh is a 3-part process: retrieve all the vertex data, retrieve the mesh's indices, and finally retrieve the relevant material data. The processed data is stored in one of the <code>3</code> vectors and from those a <fun>Mesh</fun> is created and returned to the function's caller.
    187 </p>
    188 
    189 <p>
    190   Retrieving the vertex data is pretty simple: we define a <fun>Vertex</fun> struct that we add to the <var>vertices</var> array after each loop iteration. We loop for as much vertices there exist within the mesh (retrieved via <code>mesh-&gt;mNumVertices</code>). Within the iteration we want to fill this struct with all the relevant data. For vertex positions this is done as follows:
    191 </p>
    192 
    193 <pre><code>
    194 glm::vec3 vector; 
    195 vector.x = mesh-&gt;mVertices[i].x;
    196 vector.y = mesh-&gt;mVertices[i].y;
    197 vector.z = mesh-&gt;mVertices[i].z; 
    198 vertex.Position = vector;
    199 </code></pre>
    200 
    201 <p>
    202   Note that we define a temporary <code>vec3</code> for transferring Assimp's data to. This is necessary as Assimp maintains its own data types for vector, matrices, strings etc. and they don't convert that well to glm's data types.
    203 </p>
    204 
    205 <note>
    206   Assimp calls their vertex position array <var>mVertices</var> which isn't the most intuitive name.
    207 </note>
    208 
    209 <p>
    210   The procedure for normals should come as no surprise now:
    211 </p>
    212 
    213 <pre><code>
    214 vector.x = mesh-&gt;mNormals[i].x;
    215 vector.y = mesh-&gt;mNormals[i].y;
    216 vector.z = mesh-&gt;mNormals[i].z;
    217 vertex.Normal = vector;  
    218 </code></pre>
    219 
    220 <p>
    221   Texture coordinates are roughly the same, but Assimp allows a model to have up to 8 different texture coordinates per vertex. We're not going to use 8, we only care about the first set of texture coordinates. We'll also want to check if the mesh actually contains texture coordinates (which may not be always the case):
    222 </p>
    223 
    224 <pre><code>
    225 if(mesh-&gt;mTextureCoords[0]) // does the mesh contain texture coordinates?
    226 {
    227     glm::vec2 vec;
    228     vec.x = mesh-&gt;mTextureCoords[0][i].x; 
    229     vec.y = mesh-&gt;mTextureCoords[0][i].y;
    230     vertex.TexCoords = vec;
    231 }
    232 else
    233     vertex.TexCoords = glm::vec2(0.0f, 0.0f);  
    234 </code></pre>
    235 
    236 <p>
    237   The <var>vertex</var> struct is now completely filled with the required vertex attributes and we can push it to the back of the <var>vertices</var> vector at the end of the iteration. This process is repeated for each of the mesh's vertices. 
    238 </p>
    239 
    240 <h3>Indices</h3>
    241 <p>
    242   Assimp's interface defines each mesh as having an array of faces, where each face represents a single primitive, which in our case (due to the <var>aiProcess_Triangulate</var> option) are always triangles. A face contains the indices of the vertices we need to draw in what order for its primitive. So if we iterate over all the faces and store all the face's indices in the <var>indices</var> vector we're all set:
    243 </p>
    244 
    245 <pre><code>
    246 for(unsigned int i = 0; i &lt; mesh-&gt;mNumFaces; i++)
    247 {
    248     aiFace face = mesh-&gt;mFaces[i];
    249     for(unsigned int j = 0; j &lt; face.mNumIndices; j++)
    250         indices.push_back(face.mIndices[j]);
    251 }  
    252 </code></pre>
    253 
    254 <p>
    255   After the outer loop has finished, we now have a complete set of vertices and index data for drawing the mesh via <fun><function id='2'>glDrawElements</function></fun>. However, to finish the discussion and to add some detail to the mesh, we want to process the mesh's material as well.
    256 </p>
    257 
    258 <h3>Material</h3>
    259 <p>
    260   Similar to nodes, a mesh only contains an index to a material object. To retrieve the material of a mesh, we need to index the scene's <var>mMaterials</var> array. The mesh's material index is set in its <var>mMaterialIndex</var> property, which we can also query to check if the mesh contains a material or not:
    261 </p>
    262 
    263 <pre><code>
    264 if(mesh-&gt;mMaterialIndex &gt;= 0)
    265 {
    266     aiMaterial *material = scene-&gt;mMaterials[mesh-&gt;mMaterialIndex];
    267     vector&lt;Texture&gt; diffuseMaps = loadMaterialTextures(material, 
    268                                         aiTextureType_DIFFUSE, "texture_diffuse");
    269     textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
    270     vector&lt;Texture&gt; specularMaps = loadMaterialTextures(material, 
    271                                         aiTextureType_SPECULAR, "texture_specular");
    272     textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
    273 }  
    274 </code></pre>
    275 
    276 <p>
    277   We first retrieve the <code>aiMaterial</code> object from the scene's <var>mMaterials</var> array. Then we want to load the mesh's diffuse and/or specular textures. A material object internally stores an array of texture locations for each texture type. The different texture types are all prefixed with <code>aiTextureType_</code>. We use a helper function called <fun>loadMaterialTextures</fun> to retrieve, load, and initialize the textures from the material. The function returns a vector of <fun>Texture</fun> structs that we store at the end of the model's <var>textures</var> vector.
    278 </p>
    279 
    280 <p>
    281   The <fun>loadMaterialTextures</fun> function iterates over all the texture locations of the given texture type, retrieves the texture's file location and then loads and generates the texture and stores the information in a <fun>Vertex</fun> struct. It looks like this:
    282 </p>
    283 
    284 <pre><code>
    285 vector&lt;Texture&gt; loadMaterialTextures(aiMaterial *mat, aiTextureType type, string typeName)
    286 {
    287     vector&lt;Texture&gt; textures;
    288     for(unsigned int i = 0; i &lt; mat-&gt;GetTextureCount(type); i++)
    289     {
    290         aiString str;
    291         mat-&gt;GetTexture(type, i, &str);
    292         Texture texture;
    293         texture.id = TextureFromFile(str.C_Str(), directory);
    294         texture.type = typeName;
    295         texture.path = str;
    296         textures.push_back(texture);
    297     }
    298     return textures;
    299 }  
    300 </code></pre>
    301 
    302 <p>
    303   We first check the amount of textures stored in the material via its <fun>GetTextureCount</fun> function that expects one of the texture types we've given. We retrieve each of the texture's file locations via the <fun>GetTexture</fun> function that stores the result in an <code>aiString</code>. We then use another helper function called <fun>TextureFromFile</fun> that loads a texture (with <code>stb_image.h</code>) for us and returns the texture's ID. You can check the complete code listing at the end for its content if you're not sure how such a function is written.
    304 </p>
    305 
    306 <note>
    307   Note that we make the assumption that texture file paths in model files are local to the actual model object e.g. in the same directory as the location of the model itself. We can then simply concatenate the texture location string and the directory string we retrieved earlier (in the <fun>loadModel</fun> function) to get the complete texture path (that's why the <fun>GetTexture</fun> function also needs the directory string).<br/><br/>Some models found over the internet use absolute paths for their texture locations, which won't work on each machine. In that case you probably want to manually edit the file to use local paths for the textures (if possible).
    308 </note>
    309 
    310 <p>
    311   And that is all there is to importing a model with Assimp. 
    312 </p>
    313 
    314 <h1>An optimization</h1>
    315 <p>
    316   We're not completely done yet, since there is still a large (but not completely necessary) optimization we want to make. Most scenes re-use several of their textures onto several meshes; think of a house again that has a granite texture for its walls. This texture could also be applied to the floor, its ceilings, the staircase, perhaps a table, and maybe even a small well close by. Loading textures is not a cheap operation and in our current implementation a new texture is loaded and generated for each mesh, even though the exact same texture could have been loaded several times before. This quickly becomes the bottleneck of your model loading implementation.
    317 </p>
    318 
    319 <p>
    320   So we're going to add one small tweak to the model code by storing all of the loaded textures globally. Wherever we want to load a texture, we first check if it hasn't been loaded already. If so, we take that texture and skip the entire loading routine, saving us a lot of processing power. To be able to compare textures we need to store their path as well:
    321 </p>
    322 
    323 <pre><code>
    324 struct Texture {
    325     unsigned int id;
    326     string type;
    327     string path;  // we store the path of the texture to compare with other textures
    328 };
    329 </code></pre>
    330 
    331 <p>
    332   Then we store all the loaded textures in another vector declared at the top of the model's class file as a private variable:
    333 </p>
    334 
    335 <pre><code>
    336 vector&lt;Texture&gt; textures_loaded; 
    337 </code></pre>
    338 
    339 <p>
    340   In the <fun>loadMaterialTextures</fun> function, we want to compare the texture path with all the textures in the <var>textures_loaded</var> vector to see if the current texture path equals any of those. If so, we skip the texture loading/generation part and simply use the located texture struct as the mesh's texture. The (updated) function is shown below:
    341 </p>
    342 
    343 <pre><code>
    344 vector&lt;Texture&gt; loadMaterialTextures(aiMaterial *mat, aiTextureType type, string typeName)
    345 {
    346     vector&lt;Texture&gt; textures;
    347     for(unsigned int i = 0; i &lt; mat-&gt;GetTextureCount(type); i++)
    348     {
    349         aiString str;
    350         mat-&gt;GetTexture(type, i, &str);
    351         bool skip = false;
    352         for(unsigned int j = 0; j &lt; textures_loaded.size(); j++)
    353         {
    354             if(std::strcmp(textures_loaded[j].path.data(), str.C_Str()) == 0)
    355             {
    356                 textures.push_back(textures_loaded[j]);
    357                 skip = true; 
    358                 break;
    359             }
    360         }
    361         if(!skip)
    362         {   // if texture hasn't been loaded already, load it
    363             Texture texture;
    364             texture.id = TextureFromFile(str.C_Str(), directory);
    365             texture.type = typeName;
    366             texture.path = str.C_Str();
    367             textures.push_back(texture);
    368             textures_loaded.push_back(texture); // add to loaded textures
    369         }
    370     }
    371     return textures;
    372 }  
    373 </code></pre>
    374 
    375 <warning>
    376   Some versions of Assimp tend to load models quite slow when using the debug version and/or the debug mode of your IDE, so be sure to test it out with release versions as well if you run into slow loading times.
    377 </warning>
    378 
    379 <p>
    380   You can find the complete source code of the <fun>Model</fun> class <a href="/code_viewer_gh.php?code=includes/learnopengl/model.h" target="_blank">here</a>.
    381 </p>
    382 
    383 <h1>No more containers!</h1>
    384 <p>
    385   So let's give our implementation a spin by actually importing a model created by genuine artists, not something done by the creative genius that I am. Because I don't want to give myself too much credit, I'll occasionally allow some other artists to join the ranks and this time we're going to load this amazing  <a href="https://sketchfab.com/3d-models/survival-guitar-backpack-low-poly-799f8c4511f84fab8c3f12887f7e6b36" target="_blank">Survival Guitar Backpack</a> by Berk Gedik. I've modified the material and paths a bit so it works directly with the way we've set up the model loading. The model is exported as a <code>.obj</code> file together with a <code>.mtl</code> file that links to the model's diffuse, specular, and normal maps (we'll get to those later). You can download the adjusted model for this chapter <a href="/data/models/backpack.zip" target="_blank">here</a>. Note that there's a few extra texture types we won't be using yet, and that all the textures and the model file(s) should be located in the same directory for the textures to load.
    386 </p>
    387 
    388 <note>
    389   The modified version of the backpack uses local relative texture paths, and renamed the albedo and metallic textures to diffuse and specular respectively. 
    390 </note>
    391 
    392 <p>
    393   Now, declare a <fun>Model</fun> object and pass in the model's file location. The model should then automatically load and (if there were no errors) render the object in the render loop using its <fun>Draw</fun> function and that is it. No more buffer allocations, attribute pointers, and render commands, just a simple one-liner. If you create a simple set of shaders where the fragment shader only outputs the object's diffuse texture, the result looks a bit like this:
    394 </p>
    395 
    396 <img src="/img/model_loading/model_diffuse.png"/>
    397 
    398 <p>
    399   You can find the complete source code <a href="/code_viewer_gh.php?code=src/3.model_loading/1.model_loading/model_loading.cpp" target="_blank">here</a>. Note that we tell <code>stb_image.h</code> to flip textures vertically, if you haven't done so already, before we load the model. Otherwise the textures will look all messed up.
    400 </p>
    401 
    402 <p>
    403   We can also get more creative and introduce point lights to the render equation as we learned from the <a href="https://learnopengl.com/Lighting/Light-casters" target="_blank">Lighting</a> chapters and together with specular maps get amazing results:
    404 </p>
    405 
    406 <img src="/img/model_loading/model_lighting.png"/>
    407 
    408 <p>
    409   Even I have to admit that this is maybe a bit more fancy than the containers we've used so far.  
    410   Using Assimp you can load tons of models found over the internet. There are quite a few resource websites that offer free 3D models for you to download in several file formats. Do note that some models still won't load properly, have texture paths that won't work, or are simply exported in a format even Assimp can't read. 
    411 </p>
    412 
    413 <h2>Further reading</h2>
    414 <ul>
    415     <li><a href="https://www.youtube.com/watch?v=4DQquG_o-Ac" target="_blank">How-To Texture Wavefront (.obj) Models for OpenGL</a>: great video guide by Matthew Early on how to set up 3D models in Blender so they directly work with the current model loader (as the texture setup we've chosen doesn't always work out of the box).</li>
    416 </ul>
    417 <!--
    418 <h2>Exercises</h2>
    419 <p>
    420   <ul>
    421     <li>Can you re-create the last scene with the two point lights?: <a href="/code_viewer.php?code=model_loading/model-exercise1" target="_blank">solution</a>, <a href="/code_viewer.php?code=model_loading/model-exercise1-shaders" target="_blank">shaders</a>.</li>
    422   </ul>
    423 </p>
    424 -->
    425        
    426 
    427     </div>
    428