PolyFEM
Loading...
Searching...
No Matches
MeshReader.cpp
Go to the documentation of this file.
1#include "MeshReader.hpp"
2
7
8#include <igl/read_triangle_mesh.h>
9
10#include <algorithm>
11#include <cctype>
12#include <cerrno>
13#include <cstdlib>
14#include <numeric>
15#include <set>
16#include <sstream>
17#include <string>
18
19namespace polyfem::mesh
20{
21 namespace
22 {
23 Eigen::MatrixXi padded_elements(const std::vector<std::vector<int>> &elements)
24 {
25 int width = 0;
26 for (const auto &element : elements)
27 width = std::max(width, int(element.size()));
28 Eigen::MatrixXi result;
29 result.setConstant(elements.size(), width, -1);
30 for (int i = 0; i < elements.size(); ++i)
31 for (int j = 0; j < elements[i].size(); ++j)
32 result(i, j) = elements[i][j];
33 return result;
34 }
35
39 MeshData polygon_soup_to_mesh_data(
40 const Eigen::MatrixXd &vertices3d, const std::vector<std::vector<int>> &facets)
41 {
42 if (is_planar(vertices3d))
43 return MeshData(vertices3d.leftCols(2), padded_elements(facets));
44
45 if (facets.empty())
46 log_and_throw_error("Mesh contains neither cells nor facets.");
47 std::set<int> used_vertices;
48 for (const auto &face : facets)
49 used_vertices.insert(face.begin(), face.end());
50 std::vector<std::vector<int>> elements(1);
51 elements[0].assign(used_vertices.begin(), used_vertices.end());
52 MeshData data(vertices3d, padded_elements(elements));
53 data.faces = facets;
54 data.cell_faces.resize(1);
55 data.cell_faces[0].resize(data.faces.size());
56 std::iota(data.cell_faces[0].begin(), data.cell_faces[0].end(), 0);
57 data.cell_face_orientations = {std::vector<int>(data.faces.size(), 1)};
58 data.cell_is_hex = {false};
59 data.cell_kernel_points.resize(1, 3);
60 const int last = vertices3d.rows() - 1;
61 if (used_vertices.find(last) == used_vertices.end())
62 data.cell_kernel_points.row(0) = data.vertices.row(last);
63 else
64 {
65 data.cell_kernel_points.setZero();
66 for (const int vertex : elements[0])
67 data.cell_kernel_points.row(0) += data.vertices.row(vertex);
68 data.cell_kernel_points.row(0) /= elements[0].size();
69 }
70 return data;
71 }
72
74 std::vector<std::string> split_fields(const std::string &line)
75 {
76 std::vector<std::string> fields;
77 size_t begin = line.find_first_not_of(" \t\r\n");
78 while (begin != std::string::npos)
79 {
80 const size_t end = line.find_first_of(" \t\r\n", begin);
81 fields.push_back(line.substr(begin, end == std::string::npos ? std::string::npos : end - begin));
82 begin = end == std::string::npos ? end : line.find_first_not_of(" \t\r\n", end);
83 }
84 return fields;
85 }
86
87 double parse_obj_double(const std::string &field, const int line, const std::string &description)
88 {
89 errno = 0;
90 char *end = nullptr;
91 const double value = std::strtod(field.c_str(), &end);
92 if (end == field.c_str() || *end != '\0' || errno != 0)
93 log_and_throw_error("{}:{}: invalid coordinate '{}'.", description, line, field);
94 return value;
95 }
96
99 int parse_obj_corner(const std::string &field, const int n_vertices, const int line, const std::string &description)
100 {
101 errno = 0;
102 char *end = nullptr;
103 const long long index = std::strtoll(field.c_str(), &end, 10);
104 if (end == field.c_str() || (*end != '\0' && *end != '/') || errno != 0)
105 log_and_throw_error("{}:{}: invalid face corner '{}'.", description, line, field);
106 const long long vertex = index < 0 ? n_vertices + 1 + index : index;
107 if (vertex < 1 || vertex > n_vertices)
108 log_and_throw_error("{}:{}: face corner '{}' references an invalid vertex.", description, line, field);
109 return int(vertex - 1);
110 }
111
113 void finalize_surface(SurfaceMeshData &surface, const std::string &description)
114 {
115 const int n_vertices = surface.vertices.rows();
116 for (const Eigen::MatrixXi *ids : {&surface.edges, &surface.faces})
117 if (ids->size() > 0 && (ids->minCoeff() < 0 || ids->maxCoeff() >= n_vertices))
118 log_and_throw_error("{} references an invalid vertex: expected indices in [0, {}), got [{}, {}].",
119 description, n_vertices, ids->minCoeff(), ids->maxCoeff());
120
121 std::vector<bool> used(n_vertices, false);
122 for (int i = 0; i < surface.edges.rows(); ++i)
123 for (int j = 0; j < surface.edges.cols(); ++j)
124 used[surface.edges(i, j)] = true;
125 for (int i = 0; i < surface.faces.rows(); ++i)
126 for (int j = 0; j < surface.faces.cols(); ++j)
127 used[surface.faces(i, j)] = true;
128 const int count = std::count(used.begin(), used.end(), false);
129 surface.points.resize(count);
130 for (int i = 0, point = 0; i < used.size(); ++i)
131 if (!used[i])
132 surface.points[point++] = i;
133 }
134 } // namespace
135
136 MeshData MeshReader::read_msh(const std::filesystem::path &path)
137 {
138 Eigen::MatrixXd vertices;
139 Eigen::MatrixXi cells;
140 std::vector<std::vector<int>> higher_order_connectivity;
141 std::vector<std::vector<double>> weights;
142 std::vector<int> body_ids;
143 std::vector<std::vector<int>> boundary_elements;
144 std::vector<int> boundary_ids;
146 path.string(), vertices, cells, higher_order_connectivity, weights,
147 body_ids, boundary_elements, boundary_ids))
148 log_and_throw_error("Unable to decode MSH mesh {}.", path.string());
149
150 MeshData data(std::move(vertices), std::move(cells));
151 data.body_ids = std::move(body_ids);
152 data.boundary_elements = std::move(boundary_elements);
153 data.boundary_ids = std::move(boundary_ids);
154 if ((data.dimension() == 2 && data.elements.cols() == 3)
155 || (data.dimension() == 3 && data.elements.cols() == 4))
156 {
157 data.higher_order_nodes = data.vertices;
158 data.higher_order_connectivity = std::move(higher_order_connectivity);
159 data.higher_order_weights = std::move(weights);
160 }
161 return data;
162 }
163
164 MeshData MeshReader::read_hybrid(std::istream &input, const std::string &description)
165 {
166 int vertex_count = 0;
167 int face_count = 0;
168 int encoded_cell_count = 0;
169 if (!(input >> vertex_count >> face_count >> encoded_cell_count)
170 || vertex_count <= 0 || face_count <= 0 || encoded_cell_count <= 0 || encoded_cell_count % 3 != 0)
171 log_and_throw_error("Invalid HYBRID header in {}.", description);
172 const int cell_count = encoded_cell_count / 3;
173
174 Eigen::MatrixXd vertices(vertex_count, 3);
175 for (int i = 0; i < vertex_count; ++i)
176 if (!(input >> vertices(i, 0) >> vertices(i, 1) >> vertices(i, 2)))
177 log_and_throw_error("HYBRID vertex data ended early in {}.", description);
178
179 std::vector<std::vector<int>> faces(face_count);
180 for (auto &face : faces)
181 {
182 int size = 0;
183 if (!(input >> size) || size < 3)
184 log_and_throw_error("Invalid HYBRID face in {}.", description);
185 face.resize(size);
186 for (int &vertex : face)
187 {
188 if (!(input >> vertex))
189 log_and_throw_error("HYBRID face data ended early in {}.", description);
190 if (vertex < 0 || vertex >= vertex_count)
191 log_and_throw_error("Invalid HYBRID face vertex {} in {}: expected an index in [0, {}).", vertex, description, vertex_count);
192 }
193 }
194
195 std::vector<std::vector<int>> cell_faces(cell_count);
196 std::vector<std::vector<int>> orientations(cell_count);
197 std::vector<std::vector<int>> elements(cell_count);
198 for (int i = 0; i < cell_count; ++i)
199 {
200 int face_size = 0;
201 if (!(input >> face_size) || face_size <= 0)
202 log_and_throw_error("Invalid HYBRID cell in {}.", description);
203 cell_faces[i].resize(face_size);
204 for (int &face : cell_faces[i])
205 if (!(input >> face) || face < 0 || face >= face_count)
206 log_and_throw_error("Invalid HYBRID cell face in {}.", description);
207
208 int orientation_size = 0;
209 if (!(input >> orientation_size) || orientation_size != face_size)
210 log_and_throw_error("Invalid HYBRID face orientations in {}.", description);
211 orientations[i].resize(orientation_size);
212 for (int &orientation : orientations[i])
213 if (!(input >> orientation))
214 log_and_throw_error("HYBRID orientation data ended early in {}.", description);
215
216 std::set<int> vertices_in_cell;
217 for (const int face : cell_faces[i])
218 vertices_in_cell.insert(faces[face].begin(), faces[face].end());
219 elements[i].assign(vertices_in_cell.begin(), vertices_in_cell.end());
220 }
221
222 std::vector<bool> cell_is_hex(cell_count);
223 for (int i = 0; i < cell_count; ++i)
224 {
225 int value = 0;
226 if (!(input >> value))
227 log_and_throw_error("HYBRID cell-type data ended early in {}.", description);
228 cell_is_hex[i] = value != 0;
229 }
230
231 Eigen::MatrixXd kernels(cell_count, 3);
232 kernels.setZero();
233 std::string marker;
234 if (input >> marker)
235 {
236 int count = 0;
237 if (marker != "KERNEL" || !(input >> count) || count != cell_count)
238 log_and_throw_error("Invalid HYBRID kernel block in {}.", description);
239 for (int i = 0; i < cell_count; ++i)
240 if (!(input >> kernels(i, 0) >> kernels(i, 1) >> kernels(i, 2)))
241 log_and_throw_error("HYBRID kernel data ended early in {}.", description);
242 }
243 input.clear();
244 // Preserve the established HYBRID decoder semantics: the stored kernel
245 // points are validated above, but historically they were replaced by cell
246 // barycenters before constructing the runtime mesh.
247 kernels.setZero();
248 for (int i = 0; i < cell_count; ++i)
249 {
250 for (const int vertex : elements[i])
251 kernels.row(i) += vertices.row(vertex);
252 kernels.row(i) /= elements[i].size();
253 }
254
255 MeshData data(std::move(vertices), padded_elements(elements));
256 data.elements_are_ordered = false;
257 data.faces = std::move(faces);
258 data.cell_faces = std::move(cell_faces);
259 data.cell_face_orientations = std::move(orientations);
260 data.cell_is_hex = std::move(cell_is_hex);
261 data.cell_kernel_points = std::move(kernels);
262 return data;
263 }
264
265 MeshData MeshReader::read_obj(std::istream &input, const std::string &description)
266 {
267 // Same OBJ semantics as the reader previously used (geogram's):
268 // "v" lines give three coordinates (missing ones are 0, extra ones are
269 // ignored), "f" lines give polygons with at least two corners, and
270 // every other statement (vt, vn, l, g, o, #, ...) is ignored. Lines that
271 // do not start with a printable character are skipped, and a trailing
272 // backslash continues a line.
273 std::vector<Eigen::RowVector3d> vertices;
274 std::vector<std::vector<int>> facets;
275 std::string line, next;
276 int line_number = 0;
277 while (std::getline(input, line))
278 {
279 ++line_number;
280 if (line.empty() || !std::isprint(static_cast<unsigned char>(line[0])))
281 continue;
282 while (!line.empty() && line.back() == '\\' && std::getline(input, next))
283 {
284 ++line_number;
285 line.back() = ' ';
286 line += next;
287 }
288
289 const std::vector<std::string> fields = split_fields(line);
290 if (fields.empty())
291 continue;
292 if (fields[0] == "v")
293 {
294 Eigen::RowVector3d p = Eigen::RowVector3d::Zero();
295 for (int c = 0; c < 3 && c + 1 < fields.size(); ++c)
296 p[c] = parse_obj_double(fields[c + 1], line_number, description);
297 vertices.push_back(p);
298 }
299 else if (fields[0] == "f")
300 {
301 if (fields.size() < 3)
302 log_and_throw_error("{}:{}: facet has fewer than two corners.", description, line_number);
303 std::vector<int> facet(fields.size() - 1);
304 for (int i = 1; i < fields.size(); ++i)
305 facet[i - 1] = parse_obj_corner(fields[i], vertices.size(), line_number, description);
306 facets.push_back(std::move(facet));
307 }
308 }
309
310 Eigen::MatrixXd V(vertices.size(), 3);
311 for (int i = 0; i < V.rows(); ++i)
312 V.row(i) = vertices[i];
313 return polygon_soup_to_mesh_data(V, facets);
314 }
315
316 SurfaceMeshData MeshReader::read_msh_surface(const std::filesystem::path &path, const bool keep_volume)
317 {
318 SurfaceMeshData result;
319 Eigen::MatrixXi cells;
320 std::vector<std::vector<int>> elements;
321 std::vector<std::vector<double>> weights;
322 std::vector<int> body_ids;
323 if (!io::MshReader::load(path.string(), result.vertices, cells, elements, weights, body_ids))
324 log_and_throw_error("Unable to decode MSH surface {}.", path.string());
325
326 if (cells.cols() == 1)
327 result.points = cells;
328 else if (cells.cols() == 2)
329 result.edges = cells;
330 else if (cells.cols() == 3)
331 result.faces = cells;
332 else if (cells.cols() == 4 && result.vertices.cols() == 3 && keep_volume)
333 {
334 // Interior vertices belong to the tets, so they are not codimensional
335 // points: skip finalize_surface.
336 result.tets = cells;
338 return result;
339 }
340 else if (cells.cols() == 4 && result.vertices.cols() == 3)
341 {
342 Eigen::MatrixXd surface_vertices;
344 result.vertices, cells, surface_vertices, result.faces);
345 result.vertices = std::move(surface_vertices);
346 }
347 else
348 log_and_throw_error("Unsupported MSH surface cell type in {}.", path.string());
349
350 finalize_surface(result, path.string());
351 return result;
352 }
353
354 SurfaceMeshData MeshReader::read_obj_surface(const std::filesystem::path &path)
355 {
356 SurfaceMeshData result;
357 if (!io::OBJReader::read(path.string(), result.vertices, result.edges, result.faces))
358 log_and_throw_error("Unable to decode OBJ surface {}.", path.string());
359 finalize_surface(result, path.string());
360 return result;
361 }
362
364 const std::filesystem::path &path,
365 SurfaceMeshData &result)
366 {
367 result = SurfaceMeshData();
368 if (!igl::read_triangle_mesh(path.string(), result.vertices, result.faces))
369 return false;
370 finalize_surface(result, path.string());
371 return true;
372 }
373} // namespace polyfem::mesh
int V
Eigen::RowVectorXd point
std::vector< std::pair< int, double > > weights
std::vector< Eigen::VectorXi > faces
static bool load(const std::string &path, Eigen::MatrixXd &vertices, Eigen::MatrixXi &cells, std::vector< std::vector< int > > &elements, std::vector< std::vector< double > > &weights, std::vector< int > &body_ids)
Definition MshReader.cpp:43
static bool read(const std::string obj_file_name, std::vector< std::vector< double > > &V, std::vector< std::vector< double > > &TC, std::vector< std::vector< double > > &N, std::vector< std::vector< int > > &F, std::vector< std::vector< int > > &FTC, std::vector< std::vector< int > > &FN, std::vector< std::vector< int > > &L)
Read a mesh from an ascii obj file.
Definition OBJReader.cpp:32
Format-independent input used to construct a runtime Mesh.
Definition MeshData.hpp:12
Eigen::MatrixXd vertices
Definition MeshData.hpp:21
Eigen::MatrixXd higher_order_nodes
Definition MeshData.hpp:33
std::vector< std::vector< int > > higher_order_connectivity
Definition MeshData.hpp:34
std::vector< std::vector< int > > boundary_elements
Definition MeshData.hpp:30
std::vector< std::vector< int > > faces
Optional topology for arbitrary polyhedral cells.
Definition MeshData.hpp:38
std::vector< int > body_ids
Definition MeshData.hpp:27
bool elements_are_ordered
Whether each element row carries a format-defined local vertex order.
Definition MeshData.hpp:25
std::vector< int > boundary_ids
Definition MeshData.hpp:31
Eigen::MatrixXi elements
Definition MeshData.hpp:22
Eigen::MatrixXd cell_kernel_points
Definition MeshData.hpp:42
std::vector< std::vector< int > > cell_faces
Definition MeshData.hpp:39
std::vector< std::vector< int > > cell_face_orientations
Definition MeshData.hpp:40
std::vector< std::vector< double > > higher_order_weights
Definition MeshData.hpp:35
std::vector< bool > cell_is_hex
Definition MeshData.hpp:41
static MeshData read_hybrid(std::istream &input, const std::string &description)
static MeshData read_msh(const std::filesystem::path &path)
static SurfaceMeshData read_msh_surface(const std::filesystem::path &path, bool keep_volume=false)
static bool read_triangle_surface(const std::filesystem::path &path, SurfaceMeshData &result)
static MeshData read_obj(std::istream &input, const std::string &description)
Reads a 2D polygonal mesh (planar OBJ) or a single polyhedron given by its boundary (non-planar OBJ).
static SurfaceMeshData read_obj_surface(const std::filesystem::path &path)
Eigen::MatrixXi tets
Volumetric cells indexing vertices; only filled when a 3D tet mesh is read with keep_volume.
list vertices
Definition p_bases.py:238
void find_triangle_surface_from_tets(const Eigen::MatrixXi &tets, Eigen::MatrixXi &faces)
Boundary triangles of a tet mesh, indexing the tets' vertices.
bool is_planar(const Eigen::MatrixXd &V, const double tol=1e-5)
Determine if the given V x (2|3) vertices are planar (2D or z-range below tol).
Definition MeshUtils.cpp:26
void extract_triangle_surface_from_tets(const Eigen::MatrixXd &vertices, const Eigen::MatrixXi &tets, Eigen::MatrixXd &surface_vertices, Eigen::MatrixXi &tris)
Extract triangular surface from a tetmesh.
void log_and_throw_error(const std::string &msg)
Definition Logger.cpp:73