Advertisement
PaulGalindoIsart

tiny_obj_loader example

Nov 27th, 2019
409
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1.     // Load mesh
  2.     std::vector<vertex_t> objModel;
  3.     bool hasNormals = false;
  4.     {
  5.         // A constant scale to apply to all vertex positions
  6.         float scale = 0.5f;
  7.  
  8.         std::string warn;
  9.         std::string err;
  10.         tinyobj::attrib_t attrib;
  11.         std::vector<tinyobj::shape_t> shapes;
  12.        
  13.         tinyobj::LoadObj(&attrib, &shapes, NULL, &warn, &err, "media/teapot.obj", NULL, true);
  14.         if (!err.empty())
  15.             printf("Error loading obj: %s\n", err.c_str());
  16.         if (!warn.empty())
  17.             printf("Warning loading obj: %s\n", warn.c_str());
  18.  
  19.         hasNormals = !attrib.normals.empty();
  20.  
  21.         for (const tinyobj::shape_t& shape : shapes)
  22.         {
  23.             for (const tinyobj::index_t& index : shape.mesh.indices)
  24.             {
  25.                 vertex_t v;
  26.                 v.position = {
  27.                     scale * attrib.vertices[index.vertex_index * 3 + 0],
  28.                     scale * attrib.vertices[index.vertex_index * 3 + 1],
  29.                     scale * attrib.vertices[index.vertex_index * 3 + 2]
  30.                 };
  31.  
  32.                 if (hasNormals)
  33.                 {
  34.                     v.normal = {
  35.                         attrib.normals[index.normal_index * 3 + 0],
  36.                         attrib.normals[index.normal_index * 3 + 1],
  37.                         attrib.normals[index.normal_index * 3 + 2]
  38.                     };
  39.                 }
  40.                
  41.                 objModel.push_back(v);
  42.             }
  43.         }
  44.     }
  45.  
  46.     if (!hasNormals)
  47.     {
  48.         for (int i = 0; i < objModel.size(); i += 3)
  49.         {
  50.             vertex_t& v0 = objModel[i+0];
  51.             vertex_t& v1 = objModel[i+1];
  52.             vertex_t& v2 = objModel[i+2];
  53.  
  54.             vec3_t normal = vec3_cross((v1.position - v0.position), (v2.position - v0.position));
  55.             v0.normal = v1.normal = v2.normal = normal;
  56.         }
  57.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement