-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjMesh.cpp
More file actions
93 lines (75 loc) · 2.85 KB
/
Copy pathObjMesh.cpp
File metadata and controls
93 lines (75 loc) · 2.85 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
#include "header/ObjMesh.h"
#include <fstream>
#include <ostream>
#include <iostream>
#include <bits/stdc++.h>
#include "color.h"
ObjMesh::ObjMesh(string& filePath, const point3& coord, double scale, rayTracingMaterial mat): object(mat) {
coordinates = coord;
this->scale = scale;
populateTriangles(filePath);
}
void ObjMesh::populateTriangles(string& filePath) {
std::ifstream objFile;
objFile.open(filePath);
if (!objFile) {
cout << "Unable to open file:" << filePath;
exit(1);
}
string currentLine;
vector<point3> listVertex;
double maxSize = 0;
while (getline (objFile, currentLine)) {
if (currentLine[0] == 'v' && currentLine[1] == ' ') {
currentLine.erase(0, 1);
point3 currentPoint;
std::regex pattern("\\S+");
std::smatch match;
for (int i = 0; i < 3; i++) {
if (std::regex_search(currentLine, match, pattern)) {
int start = match.position(0);
int end = start + match.length(0);
currentPoint[i] = atof(currentLine.substr(start, end).data());
maxSize = max(abs(currentPoint[i]), maxSize);
currentLine.erase(0, end);
}
}
listVertex.push_back(currentPoint);
}
if (currentLine[0] == 'f' && currentLine[1] == ' ') {
point3 vertices[3];
currentLine.erase(0, 1);
std::regex pattern(R"(^\s*(\d+)(?:/\d*)?(?:/\d*)?)");
std::smatch match;
for (int i = 0; i < 3; i++) {
if (std::regex_search(currentLine, match, pattern)) {
int start = match.position(0);
int end = start + match.length(0);
int currentPoint = atoi(currentLine.substr(start, end).data());
currentLine.erase(start, end);
vertices[i] = listVertex[currentPoint - 1];
}
}
auto tri = make_shared<triangle>(triangle(vertices[0], vertices[1], vertices[2], material));
triangles.push_back(tri);
}
}
for (auto tri : triangles) {
tri->vertices[0] = tri->vertices[0] * scale + coordinates;
tri->vertices[1] = tri->vertices[1] * scale + coordinates;
tri->vertices[2] = tri->vertices[2] * scale + coordinates;
}
objFile.close();
}
hitInfo ObjMesh::hit(const ray& r) const {
hitInfo closestTriangleHit;
closestTriangleHit.distance = std::numeric_limits<double>::infinity();
for (auto& tri : triangles) {
hitInfo hit = tri->hit(r);
if (hit.didHit == true && hit.distance < closestTriangleHit.distance) {
closestTriangleHit = hit;
closestTriangleHit.material = tri->material;
}
}
return closestTriangleHit;
}