55 lines
1.6 KiB
C++
55 lines
1.6 KiB
C++
|
|
#include "vde/foundation/io_obj.h"
|
||
|
|
#include <fstream>
|
||
|
|
#include <sstream>
|
||
|
|
|
||
|
|
namespace vde::foundation {
|
||
|
|
|
||
|
|
ObjMeshData read_obj(const std::string& filepath) {
|
||
|
|
ObjMeshData data;
|
||
|
|
std::ifstream file(filepath);
|
||
|
|
if (!file) return data;
|
||
|
|
|
||
|
|
std::string line;
|
||
|
|
while (std::getline(file, line)) {
|
||
|
|
if (line.empty() || line[0] == '#') continue;
|
||
|
|
std::istringstream iss(line);
|
||
|
|
std::string token;
|
||
|
|
iss >> token;
|
||
|
|
if (token == "v") {
|
||
|
|
double x, y, z;
|
||
|
|
iss >> x >> y >> z;
|
||
|
|
data.vertices.emplace_back(x, y, z);
|
||
|
|
} else if (token == "vn") {
|
||
|
|
double nx, ny, nz;
|
||
|
|
iss >> nx >> ny >> nz;
|
||
|
|
data.normals.emplace_back(nx, ny, nz);
|
||
|
|
} else if (token == "f") {
|
||
|
|
std::vector<int> face;
|
||
|
|
std::string vertex;
|
||
|
|
while (iss >> vertex) {
|
||
|
|
std::istringstream viss(vertex);
|
||
|
|
std::string vi_str;
|
||
|
|
std::getline(viss, vi_str, '/');
|
||
|
|
face.push_back(std::stoi(vi_str) - 1);
|
||
|
|
}
|
||
|
|
data.faces.push_back(std::move(face));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return data;
|
||
|
|
}
|
||
|
|
|
||
|
|
void write_obj(const std::string& filepath, const ObjMeshData& data) {
|
||
|
|
std::ofstream file(filepath);
|
||
|
|
for (const auto& v : data.vertices)
|
||
|
|
file << "v " << v.x() << " " << v.y() << " " << v.z() << "\n";
|
||
|
|
for (const auto& n : data.normals)
|
||
|
|
file << "vn " << n.x() << " " << n.y() << " " << n.z() << "\n";
|
||
|
|
for (const auto& f : data.faces) {
|
||
|
|
file << "f";
|
||
|
|
for (int vi : f) file << " " << (vi + 1);
|
||
|
|
file << "\n";
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
} // namespace vde::foundation
|