-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModelLoader.cpp
More file actions
62 lines (50 loc) · 1.61 KB
/
ModelLoader.cpp
File metadata and controls
62 lines (50 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include "ModelLoader.hpp"
#include <tiny_obj_loader.h>
#include <glm/gtx/hash.hpp>
#include <stdexcept>
#include <unordered_map>
namespace std {
template <>
struct hash<Vertex> {
size_t operator()(Vertex const& vertex) const {
return ((hash<glm::vec3>()(vertex.pos) ^
(hash<glm::vec3>()(vertex.color) << 1)) >>
1) ^
(hash<glm::vec2>()(vertex.texCoord) << 1);
}
};
} // namespace std
void ModelLoader::loadObj(
const std::string& modelPath,
std::vector<Vertex>& vertices,
std::vector<uint32_t>& indices
) {
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string warn, err;
if (!tinyobj::LoadObj(
&attrib, &shapes, &materials, &warn, &err, modelPath.c_str()
)) {
throw std::runtime_error(warn + err);
}
std::unordered_map<Vertex, uint32_t> uniqueVertices{};
for (const auto& shape : shapes) {
for (const auto& index : shape.mesh.indices) {
Vertex vertex{};
vertex.pos = {
attrib.vertices[3 * index.vertex_index + 0],
attrib.vertices[3 * index.vertex_index + 1],
attrib.vertices[3 * index.vertex_index + 2]};
vertex.texCoord = {
attrib.texcoords[2 * index.texcoord_index + 0],
1.0f - attrib.texcoords[2 * index.texcoord_index + 1]};
vertex.color = {1.0f, 1.0f, 1.0f};
if (uniqueVertices.count(vertex) == 0) {
uniqueVertices[vertex] = static_cast<uint32_t>(vertices.size());
vertices.emplace_back(vertex);
}
indices.emplace_back(uniqueVertices[vertex]);
}
}
}