A demo for mesh-voxel conversion
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
2.0 KiB

#pragma once
#include "Geometry.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <unordered_map>
bool readSTL(const std::string& filename, Mesh& mesh) {
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Failed to open file: " << filename << std::endl;
return false;
}
std::string line;
std::unordered_map<Vec3<float>, unsigned int> vertexMap; // 用于去重
unsigned int vertexIndex = 0;
while (std::getline(file, line)) {
std::istringstream stream(line);
std::string keyword;
if (line.find("facet normal") != std::string::npos) {
std::getline(file, line); // Read the outer loop
Vec3<float> vertices[3];
for (int i = 0; i < 3; ++i) {
std::getline(file, line);
stream.clear();
stream.str(line);
stream >> keyword >> vertices[i].x >> vertices[i].y >> vertices[i].z;
// 检查是否已存在该顶点
if (vertexMap.find(vertices[i]) == vertexMap.end()) {
vertexMap[vertices[i]] = vertexIndex;
mesh.vertices.push_back(vertices[i]);
vertexIndex++;
}
}
// 添加面索引
mesh.faces.emplace_back(vertexMap[vertices[0]], vertexMap[vertices[1]], vertexMap[vertices[2]]);
std::getline(file, line); // Read endloop
std::getline(file, line); // Read endfacet
}
}
file.close();
return true;
}
//int main() {
// Mesh mesh;
// if (readSTL("../plate.stl", mesh)) {
// std::cout << "Successfully read STL file." << std::endl;
// std::cout << "Vertices count: " << mesh.vertices.size() << std::endl;
// std::cout << "Faces count: " << mesh.faces.size() << std::endl;
// } else {
// std::cerr << "Failed to read STL file." << std::endl;
// }
// return 0;
//}