-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathStaticMesh.cpp
100 lines (78 loc) · 2.51 KB
/
StaticMesh.cpp
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include "StaticMesh.h"
#include <tiny_obj_loader.h>
StaticMesh::StaticMesh()
: m_uv(false), m_normal(false)
{
}
StaticMesh StaticMesh::LoadMesh(const std::string &filename)
{
std::vector<tinyobj::shape_t> shapes;
{
std::vector<tinyobj::material_t> materials;
std::string error_string;
if (!tinyobj::LoadObj(shapes, materials, error_string, filename.c_str())) {
// GG
}
/*
if (shapes.size() == 0)
GG
if (shapes[0].mesh.texcoords.size() == 0 || shapes[0].mesh.normals.size() == 0)
GG*/
}
StaticMesh ret;
glGenVertexArrays(1, &ret.vao);
glBindVertexArray(ret.vao);
glGenBuffers(3, ret.vbo);
glGenBuffers(1, &ret.ibo);
glBindBuffer(GL_ARRAY_BUFFER, ret.vbo[0]);
// Upload postion array
glBindBuffer(GL_ARRAY_BUFFER, ret.vbo[0]);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * shapes[0].mesh.positions.size(),
shapes[0].mesh.positions.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
if (shapes[0].mesh.texcoords.size() > 0) {
// Upload texCoord array
glBindBuffer(GL_ARRAY_BUFFER, ret.vbo[1]);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * shapes[0].mesh.texcoords.size(),
shapes[0].mesh.texcoords.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);
ret.m_uv = true;
}
if (shapes[0].mesh.normals.size() > 0) {
// Upload normal array
glBindBuffer(GL_ARRAY_BUFFER, ret.vbo[2]);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * shapes[0].mesh.normals.size(),
shapes[0].mesh.normals.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0);
ret.m_normal = true;
}
// Setup index buffer for glDrawElements
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ret.ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * shapes[0].mesh.indices.size(),
shapes[0].mesh.indices.data(), GL_STATIC_DRAW);
ret.numIndices = shapes[0].mesh.indices.size();
glBindVertexArray(0);
return ret;
}
void StaticMesh::release()
{
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(3, vbo);
glDeleteBuffers(1, &ibo);
}
void StaticMesh::draw()
{
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_INT, nullptr);
}
bool StaticMesh::hasNormal() const
{
return m_normal;
}
bool StaticMesh::hasUV() const
{
return m_uv;
}