-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.cpp
More file actions
102 lines (88 loc) · 2.82 KB
/
model.cpp
File metadata and controls
102 lines (88 loc) · 2.82 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
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
101
102
// Author: Dimitry V. Sokolov (I think?)
// Modified by: Tate Maguire
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include "model.h"
Model::Model(const char *obj_filename, const char* uv_filename) :
verts_(), texture_verts_(), normal_verts_(), faces_(), min(), max(), uv_image()
{
// find min and max coordinates
for (int i=0; i<3; i++) {
min.raw[i] = std::numeric_limits<float>::max();
max.raw[i] = std::numeric_limits<float>::lowest();
}
// parse obj file to verts_, texture_verts_, normal_verts_, and faces_
std::ifstream in;
in.open(obj_filename, std::ifstream::in);
if (in.fail()) return;
std::string line;
while (!in.eof()) {
std::getline(in, line);
std::istringstream iss(line.c_str());
char trash;
if (!line.compare(0, 2, "v ")) {
iss >> trash;
Vec3f v;
for (int i=0;i<3;i++) {
iss >> v.raw[i];
if (v.raw[i] < min.raw[i]) min.raw[i] = v.raw[i];
if (v.raw[i] > max.raw[i]) max.raw[i] = v.raw[i];
}
verts_.push_back(v);
} else if (!line.compare(0, 3, "vt ")) {
Vec2f vt;
iss >> trash >> trash; // for some reason there's two spaces after vt
for (int i=0; i<2; i++) iss >> vt.raw[i];
texture_verts_.push_back(vt);
} else if (!line.compare(0, 3, "vn ")) {
Vec3f vn;
iss >> trash >> trash;
for (int i=0; i<3; i++) iss >> vn.raw[i];
normal_verts_.push_back(vn);
} else if (!line.compare(0, 2, "f ")) {
std::vector<Vec3i> f;
int ivert, iuv, inorm;
iss >> trash;
while (iss >> ivert >> trash >> iuv >> trash >> inorm) {
// in wavefront obj all indices start at 1, not zero
f.push_back(Vec3i(--ivert, --iuv, --inorm));
}
std::swap(f[1].iuv, f[2].iuv); // idk why but this is necessary for textures to work
faces_.push_back(f);
}
}
// print model size
std::cerr << "# v# " << verts_.size() << " f# " << faces_.size() << std::endl;
// read uv_image and flip for compatibility
uv_image.read_tga_file(uv_filename);
uv_image.flip_vertically();
}
Model::~Model() {
}
int Model::nverts() {
return (int)verts_.size();
}
int Model::ntexture_verts() {
return (int)texture_verts_.size();
}
int Model::nnormal_verts() {
return (int)normal_verts_.size();
}
int Model::nfaces() {
return (int)faces_.size();
}
Vec3f Model::vert(int i) {
return verts_[i];
}
Vec2f Model::texture_vert(int i) {
return texture_verts_[i];
}
Vec3f Model::normal_vert(int i) {
return normal_verts_[i];
}
std::vector<Vec3i> Model::face(int idx) {
return faces_[idx];
}