PolyFEM
Loading...
Searching...
No Matches
GeometryLoader.cpp
Go to the documentation of this file.
1#include "GeometryLoader.hpp"
2
9
10#include <Eigen/Core>
11
12#include <igl/edges.h>
13#include <igl/boundary_facets.h>
14
15#include <strnatcmp.h>
16
17namespace polyfem::mesh
18{
19 using namespace polyfem::utils;
20
22 const json &geometry,
23 const std::vector<json> &obstacle_displacements,
24 const std::vector<json> &dirichlet_conditions,
25 const bool non_conforming) const
26 {
27 LoadedGeometry result;
28 result.fem = load_fem(geometry, non_conforming);
29 if (!result.fem)
30 log_and_throw_error("Configured geometry contains no enabled FEM mesh.");
31 result.obstacle = load_obstacles(
32 geometry, obstacle_displacements, dirichlet_conditions,
33 result.fem->dimension(), non_conforming);
34 return result;
35 }
36
38 Mesh &mesh,
39 const json &geometry_selection) const
40 {
41 if (geometry_selection.is_object() && geometry_selection.contains("same_as_volume"))
42 {
43 if (!geometry_selection["same_as_volume"].get<bool>())
44 return;
45
46 std::vector<int> geometry_ids(mesh.n_elements());
47 for (int e = 0; e < mesh.n_elements(); ++e)
48 geometry_ids[e] = mesh.get_body_id(e);
49 mesh.set_geometry_ids(geometry_ids);
50 return;
51 }
52
53 Selection::BBox bbox;
54 mesh.bounding_box(bbox[0], bbox[1]);
55 const auto selections = Selection::build_selections(geometry_selection, bbox, resources_);
56
57 Eigen::MatrixXd barycenters;
58 mesh.compute_element_barycenters(barycenters);
59 std::vector<int> geometry_ids(mesh.n_elements(), 0);
60 for (int e = 0; e < mesh.n_elements(); ++e)
61 {
62 const auto vertices = mesh.element_vertices(e);
63 for (const auto &selection : selections)
64 {
65 if (selection->inside(e, vertices, barycenters.row(e)))
66 {
67 geometry_ids[e] = selection->id(e, vertices, barycenters.row(e));
68 break;
69 }
70 }
71 }
72 mesh.set_geometry_ids(geometry_ids);
73 }
74
75 std::unique_ptr<Mesh> GeometryLoader::load_fem_entry(
76 const json &j_mesh,
77 const bool non_conforming) const
78 {
79 if (!is_param_valid(j_mesh, "mesh"))
80 log_and_throw_error("Mesh {} is mising a \"mesh\" field!", j_mesh);
81
82 if (j_mesh["extract"].get<std::string>() != "volume")
83 log_and_throw_error("Only volumetric elements are implemented for FEM meshes!");
84
85 std::unique_ptr<Mesh> mesh = MeshLoader(resources_).load_fem(j_mesh["mesh"].get<std::string>(), non_conforming);
86 // --------------------------------------------------------------------
87
88 // NOTE: Normaliziation is done before transformations are applied and/or any selection operators
89 if (j_mesh["advanced"]["normalize_mesh"])
90 mesh->normalize();
91
92 // --------------------------------------------------------------------
93
94 Selection::BBox bbox;
95 mesh->bounding_box(bbox[0], bbox[1]);
96
97 const std::string unit = j_mesh["unit"];
98 double unit_scale = 1;
99 if (!unit.empty())
100 unit_scale = Units::convert(1, unit, units_.length());
101
102 {
103 MatrixNd A;
104 VectorNd b;
106 unit_scale,
107 j_mesh["transformation"],
108 (bbox[1] - bbox[0]).cwiseAbs().transpose(),
109 A, b);
110 mesh->apply_affine_transformation(A, b);
111 }
112
113 mesh->bounding_box(bbox[0], bbox[1]);
114
115 // --------------------------------------------------------------------
116 std::vector<std::shared_ptr<Selection>> surface_selections =
117 is_param_valid(j_mesh, "surface_selection") ? Selection::build_selections(j_mesh["surface_selection"], bbox, resources_) : std::vector<std::shared_ptr<Selection>>();
118
119 // --------------------------------------------------------------------
120
121 const int n_refs = j_mesh["n_refs"];
122 const double refinement_location = j_mesh["advanced"]["refinement_location"];
123 // TODO: renable this
124 // if (n_refs <= 0 && args["poly_bases"] == "MFSHarmonic" && mesh->has_poly())
125 // {
126 // if (args["force_no_ref_for_harmonic"])
127 // logger().warn("Using harmonic bases without refinement");
128 // else
129 // n_refs = 1;
130 // }
131 if (n_refs > 0)
132 {
133 if (mesh->has_boundary_ids() && surface_selections.empty())
134 log_and_throw_error("Unable to refine a mesh with stored surface selections; provide an explicit surface_selection to recompute them after refinement.");
135 if (mesh->has_node_ids() && !is_param_valid(j_mesh, "point_selection"))
136 log_and_throw_error("Unable to refine a mesh with stored point selections; provide an explicit point_selection to recompute them after refinement.");
137 if (mesh->has_geometry_ids() && !is_param_valid(j_mesh, "geometry_selection"))
138 log_and_throw_error("Unable to refine a mesh with stored geometry selections; provide an explicit geometry_selection to recompute them after refinement.");
139 if (mesh->orders().size() > 0 && mesh->orders().maxCoeff() > 1)
140 logger().warn("Refinement drops the higher-order geometry of the mesh; the refined mesh is linear.");
141
142 // Check if the stored volume selection is uniform.
143 assert(mesh->n_elements() > 0);
144 const int uniform_value = mesh->get_body_id(0);
145 for (int i = 1; i < mesh->n_elements(); ++i)
146 if (mesh->get_body_id(i) != uniform_value)
147 log_and_throw_error("Unable to apply stored nonuniform volume_selection because n_refs={} > 0!", n_refs);
148
149 logger().info("Performing global h-refinement with {} refinements", n_refs);
150 mesh->refine(n_refs, refinement_location);
151 mesh->set_body_ids(std::vector<int>(mesh->n_elements(), uniform_value));
152 }
153
154 // --------------------------------------------------------------------
155
156 if (j_mesh["advanced"]["min_component"].get<int>() != -1)
157 log_and_throw_error("Option \"min_component\" in geometry not implement yet!");
158 // TODO:
159 // if (args["min_component"] > 0) {
160 // Eigen::SparseMatrix<int> adj;
161 // igl::facet_adjacency_matrix(boundary_triangles, adj);
162 // Eigen::MatrixXi C, counts;
163 // igl::connected_components(adj, C, counts);
164 // std::vector<int> valid;
165 // const int min_count = args["min_component"];
166 // for (int i = 0; i < counts.size(); ++i) {
167 // if (counts(i) >= min_count) {
168 // valid.push_back(i);
169 // }
170 // }
171 // tris.clear();
172 // for (int i = 0; i < C.size(); ++i) {
173 // for (int v : valid) {
174 // if (v == C(i)) {
175 // tris.emplace_back(boundary_triangles(i, 0), boundary_triangles(i, 1), boundary_triangles(i, 2));
176 // break;
177 // }
178 // }
179 // }
180 // boundary_triangles.resize(tris.size(), 3);
181 // for (int i = 0; i < tris.size(); ++i) {
182 // boundary_triangles.row(i) << std::get<0>(tris[i]), std::get<1>(tris[i]), std::get<2>(tris[i]);
183 // }
184 // }
185
186 // --------------------------------------------------------------------
187
188 if (j_mesh["advanced"]["force_linear_geometry"].get<bool>())
189 log_and_throw_error("Option \"force_linear_geometry\" in geometry not implement yet!");
190 // TODO:
191 // if (!iso_parametric()) {
192 // if (args["force_linear_geometry"] || mesh->orders().size() <= 0) {
193 // geom_disc_orders.resizeLike(disc_orders);
194 // geom_disc_orders.setConstant(1);
195 // } else {
196 // geom_disc_orders = mesh->orders();
197 // }
198 // }
199
200 // --------------------------------------------------------------------
201
202 const std::vector<std::shared_ptr<Selection>> node_selections =
203 is_param_valid(j_mesh, "point_selection") ? Selection::build_selections(j_mesh["point_selection"], bbox, resources_) : std::vector<std::shared_ptr<Selection>>();
204
205 if (!node_selections.empty())
206 {
207 bool boundary_only = true;
208 for (const auto &selection : node_selections)
209 {
210 if (!selection->boundary_only())
211 {
212 boundary_only = false;
213 break;
214 }
215 }
216
217 mesh->compute_node_ids([&](const size_t n_id, const RowVectorNd &p, bool is_boundary) {
218 if (boundary_only && !is_boundary)
219 return -1;
220
221 const std::vector<int> tmp = {int(n_id)};
222 for (const auto &selection : node_selections)
223 {
224 if (selection->boundary_only() && !is_boundary)
225 continue;
226
227 if (selection->inside(n_id, tmp, p))
228 return selection->id(n_id, tmp, p);
229 }
230 return std::numeric_limits<int>::max(); // default for no selected boundary
231 });
232 }
233
234 if (!j_mesh["curve_selection"].is_null())
235 log_and_throw_error("Geometry curve selections are not implemented!");
236
237 // --------------------------------------------------------------------
238
239 if (!surface_selections.empty())
240 {
241 bool boundary_only = true;
242 for (const auto &selection : surface_selections)
243 {
244 if (!selection->boundary_only())
245 {
246 boundary_only = false;
247 break;
248 }
249 }
250
251 mesh->compute_boundary_ids([&](const size_t p_id, const std::vector<int> &vs, const RowVectorNd &p, bool is_boundary) {
252 if (boundary_only && !is_boundary)
253 return -1;
254
255 for (const auto &selection : surface_selections)
256 {
257 if (selection->boundary_only() && !is_boundary)
258 continue;
259
260 if (selection->inside(p_id, vs, p))
261 return selection->id(p_id, vs, p);
262 }
263 return std::numeric_limits<int>::max(); // default for no selected boundary
264 });
265 }
266
267 // --------------------------------------------------------------------
268
269 // If the selection is of the form {"id_offset": ...}
270 const json volume_selection = j_mesh["volume_selection"];
271 if (volume_selection.is_object()
272 && volume_selection.size() == 1
273 && volume_selection.contains("id_offset"))
274 {
275 const int id_offset = volume_selection["id_offset"].get<int>();
276 if (id_offset != 0)
277 {
278 const int n_body_ids = mesh->n_elements();
279 std::vector<int> body_ids(n_body_ids);
280 for (int i = 0; i < n_body_ids; ++i)
281 body_ids[i] = mesh->get_body_id(i) + id_offset;
282 mesh->set_body_ids(body_ids);
283 }
284 }
285 else
286 {
287 // Specified volume selection has priority over mesh's stored ids
288 std::vector<std::shared_ptr<Selection>> volume_selections =
289 Selection::build_selections(volume_selection, bbox, resources_);
290
291 // Append the mesh's stored ids to the volume selection as a lowest priority selection
292 if (mesh->has_body_ids())
293 volume_selections.push_back(std::make_shared<SpecifiedSelection>(mesh->get_body_ids()));
294
295 mesh->compute_body_ids([&](const size_t cell_id, const std::vector<int> &vs, const RowVectorNd &p) -> int {
296 for (const auto &selection : volume_selections)
297 {
298 // TODO: add vs to compute_body_ids
299 if (selection->inside(cell_id, vs, p))
300 return selection->id(cell_id, vs, p);
301 }
302 return 0;
303 });
304 }
305
306 // --------------------------------------------------------------------
307
308 if (is_param_valid(j_mesh, "geometry_selection"))
309 apply_geometry_selection(*mesh, j_mesh["geometry_selection"]);
310
311 // --------------------------------------------------------------------
312
313 return mesh;
314 }
315
316 // ========================================================================
317
318 std::unique_ptr<Mesh> GeometryLoader::load_fem(
319 const json &geometry,
320 const bool non_conforming) const
321 {
322 // --------------------------------------------------------------------
323
324 if (geometry.empty())
325 log_and_throw_error("Provided geometry is empty!");
326
327 std::vector<json> geometries = utils::json_as_array(geometry);
328
329 // --------------------------------------------------------------------
330
331 std::unique_ptr<Mesh> mesh = nullptr;
332
333 for (const json &geometry : geometries)
334 {
335 if (!geometry["enabled"].get<bool>() || geometry["is_obstacle"].get<bool>())
336 continue;
337
338 if (geometry["type"] != "mesh" && geometry["type"] != "mesh_array")
339 log_and_throw_error("Invalid geometry type \"{}\" for FEM mesh!", geometry["type"]);
340
341 const std::unique_ptr<Mesh> tmp_mesh = load_fem_entry(geometry, non_conforming);
342
343 if (mesh == nullptr)
344 mesh = tmp_mesh->copy();
345 else
346 mesh->append(tmp_mesh);
347
348 if (geometry["type"] == "mesh_array")
349 {
350 Selection::BBox bbox;
351 tmp_mesh->bounding_box(bbox[0], bbox[1]);
352
353 const long dim = tmp_mesh->dimension();
354 const bool is_offset_relative = geometry["array"]["relative"];
355 const double offset = geometry["array"]["offset"];
356 const VectorNd dimensions = (bbox[1] - bbox[0]);
357 const VectorNi size = geometry["array"]["size"];
358 if (size.size() != dim)
359 log_and_throw_error("mesh_array: \"array/size\" needs one entry per dimension ({}), got {}.", dim, size.size());
360
361 for (int i = 0; i < size[0]; ++i)
362 {
363 for (int j = 0; j < size[1]; ++j)
364 {
365 for (int k = 0; k < (size.size() > 2 ? size[2] : 1); ++k)
366 {
367 if (i == 0 && j == 0 && k == 0)
368 continue;
369
370 RowVectorNd translation = offset * Eigen::RowVector3d(i, j, k).head(dim);
371 if (is_offset_relative)
372 translation.array() *= dimensions.array();
373
374 const std::unique_ptr<Mesh> copy_mesh = tmp_mesh->copy();
375 copy_mesh->apply_affine_transformation(MatrixNd::Identity(dim, dim), translation);
376 mesh->append(copy_mesh);
377 }
378 }
379 }
380 }
381 }
382
383 // --------------------------------------------------------------------
384
385 return mesh;
386 }
387
388 // ========================================================================
389
391 const json &j_mesh,
392 const int dim) const
393 {
394 if (!is_param_valid(j_mesh, "mesh"))
395 log_and_throw_error("Mesh obstacle {} is mising a \"mesh\" field!", j_mesh);
396
397 SurfaceMesh result = MeshLoader(resources_).load_surface(j_mesh["mesh"].get<std::string>(), /*keep_volume=*/true);
398 auto &vertices = result.vertices;
399 auto &codim_vertices = result.points;
400 auto &codim_edges = result.edges;
401 auto &faces = result.faces;
402 auto &tets = result.tets;
403
404 const int prev_dim = vertices.cols();
405 vertices.conservativeResize(vertices.rows(), dim);
406 if (prev_dim < dim)
407 vertices.rightCols(dim - prev_dim).setZero();
408
409 // --------------------------------------------------------------------
410
411 {
412 const std::string unit = j_mesh["unit"];
413 double unit_scale = 1;
414 if (!unit.empty())
415 unit_scale = Units::convert(1, unit, units_.length());
416
417 const VectorNd mesh_dimensions = (vertices.colwise().maxCoeff() - vertices.colwise().minCoeff()).cwiseAbs();
418 MatrixNd A;
419 VectorNd b;
420 construct_affine_transformation(unit_scale, j_mesh["transformation"], mesh_dimensions, A, b);
421 vertices = vertices * A.transpose();
422 vertices.rowwise() += b.transpose();
423 }
424
425 // Preserve volumetric (2D triangle) connectivity for optional volumetric paraview export.
426 // In 3D a tet mesh's tets come from load_surface with keep_volume.
427 if (dim == 2 && tets.rows() == 0 && faces.rows() > 0 && faces.cols() == 3)
428 tets = faces;
429
430 std::string extract = j_mesh["extract"];
431 // Default: "volume" clashes with defaults for non obstacle, here assume volume is suface
432 if (extract == "volume")
433 extract = "surface";
434
435 if (extract == "points")
436 {
437 // points -> vertices (drop edges and faces)
438 codim_edges.resize(0, 0);
439 faces.resize(0, 0);
440 codim_vertices.resize(vertices.rows());
441 for (int i = 0; i < codim_vertices.size(); ++i)
442 codim_vertices[i] = i;
443 }
444 else if (extract == "edges" && faces.size() != 0)
445 {
446 // edges -> edges (drop faces)
447 Eigen::MatrixXi edges;
448 igl::edges(faces, edges);
449 faces.resize(0, 0);
450 codim_edges.conservativeResize(codim_edges.rows() + edges.rows(), 2);
451 codim_edges.bottomRows(edges.rows()) = edges;
452 }
453 else if (extract == "surface" && dim == 2 && faces.size() != 0)
454 {
455 // surface (2D) -> boundary edges (drop faces and interior edges)
456 Eigen::MatrixXi boundary_edges;
457 igl::boundary_facets(faces, boundary_edges);
458 codim_edges.conservativeResize(codim_edges.rows() + boundary_edges.rows(), 2);
459 codim_edges.bottomRows(boundary_edges.rows()) = boundary_edges;
460 faces.resize(0, 0); // Clear faces
461 }
462 // surface (3D) -> boundary faces
463 // Surface extraction in 3D already has the desired faces from MeshLoader.
464 else if (extract == "volume")
465 {
466 // volume -> undefined
467 log_and_throw_error("Volumetric elements not supported for collision obstacles!");
468 }
469
470 if (j_mesh["n_refs"].get<int>() != 0)
471 {
472 if (faces.size() != 0)
473 log_and_throw_error("Option \"n_refs\" for triangle obstacles not implement yet!");
474
475 const int n_refs = j_mesh["n_refs"];
476 const double refinement_location = j_mesh["advanced"]["refinement_location"];
477 for (int i = 0; i < n_refs; i++)
478 {
479 const size_t n_vertices = vertices.rows();
480 const size_t n_edges = codim_edges.rows();
481 vertices.conservativeResize(n_vertices + n_edges, vertices.cols());
482 codim_edges.conservativeResize(2 * n_edges, codim_edges.cols());
483 for (size_t ei = 0; ei < n_edges; ei++)
484 {
485 const int v0i = codim_edges(ei, 0);
486 const int v1i = codim_edges(ei, 1);
487 const int v2i = n_vertices + ei;
488 vertices.row(v2i) = (vertices.row(v1i) - vertices.row(v0i)) * refinement_location + vertices.row(v0i);
489 codim_edges.row(ei) << v0i, v2i;
490 codim_edges.row(n_edges + ei) << v2i, v1i;
491 }
492 }
493 }
494 return result;
495 }
496
497 // ========================================================================
498
500 const json &geometry,
501 const std::vector<json> &displacements,
502 const std::vector<json> &dirichlets,
503 const int dim,
504 const bool) const
505 {
506 Obstacle obstacle;
507
508 if (geometry.empty())
509 return obstacle;
510
511 std::vector<json> geometries = utils::json_as_array(geometry);
512
513 for (const json &geometry : geometries)
514 {
515
516 if (!geometry["is_obstacle"].get<bool>())
517 continue;
518
519 if (!geometry["enabled"].get<bool>())
520 continue;
521
522 if (geometry["type"] == "mesh" || geometry["type"] == "mesh_array")
523 {
524 SurfaceMesh loaded = load_surface(geometry, dim);
525 Eigen::MatrixXd &vertices = loaded.vertices;
526 Eigen::VectorXi &codim_vertices = loaded.points;
527 Eigen::MatrixXi &codim_edges = loaded.edges;
528 Eigen::MatrixXi &faces = loaded.faces;
529 Eigen::MatrixXi &tets = loaded.tets;
530
531 if (geometry["type"] == "mesh_array")
532 {
533 const Selection::BBox bbox{{vertices.colwise().minCoeff(), vertices.colwise().maxCoeff()}};
534
535 const bool is_offset_relative = geometry["array"]["relative"];
536 const double offset = geometry["array"]["offset"];
537 const VectorNd dimensions = (bbox[1] - bbox[0]);
538 const VectorNi size = geometry["array"]["size"];
539 if (size.size() != dim)
540 log_and_throw_error("mesh_array: \"array/size\" needs one entry per dimension ({}), got {}.", dim, size.size());
541
542 const int N = size.head(dim).prod();
543 const int nV = vertices.rows(), nCV = codim_vertices.rows(), nCE = codim_edges.rows(), nF = faces.rows(), nT = tets.rows();
544
545 vertices.conservativeResize(N * nV, Eigen::NoChange);
546 codim_vertices.conservativeResize(N * nCV, Eigen::NoChange);
547 codim_edges.conservativeResize(N * nCE, Eigen::NoChange);
548 faces.conservativeResize(N * nF, Eigen::NoChange);
549 tets.conservativeResize(N * nT, tets.cols());
550
551 for (int i = 0; i < size[0]; ++i)
552 {
553 for (int j = 0; j < size[1]; ++j)
554 {
555 for (int k = 0; k < (size.size() > 2 ? size[2] : 1); ++k)
556 {
557 RowVectorNd translation = offset * Eigen::RowVector3d(i, j, k).head(vertices.cols());
558 if (is_offset_relative)
559 translation.array() *= dimensions.array();
560
561 int n = i * size[1] + j;
562 if (size.size() > 2)
563 n = n * size[2] + k;
564 if (n == 0)
565 continue;
566
567 vertices.middleRows(n * nV, nV) = vertices.topRows(nV).rowwise() + translation;
568 if (nCV)
569 codim_vertices.segment(n * nCV, nCV) = codim_vertices.head(nCV).array() + n * nV;
570 if (nCE)
571 codim_edges.middleRows(n * nCE, nCE) = codim_edges.topRows(nCE).array() + n * nV;
572 if (nF)
573 faces.middleRows(n * nF, nF) = faces.topRows(nF).array() + n * nV;
574 if (nT)
575 tets.middleRows(n * nT, nT) = tets.topRows(nT).array() + n * nV;
576 }
577 }
578 }
579 }
580
581 json displacement = "{\"value\":[0, 0, 0]}"_json;
582 if (is_param_valid(geometry, "surface_selection"))
583 {
584 if (!geometry["surface_selection"].is_number())
585 log_and_throw_error("Invalid surface_selection for obstacle, needs to be an integer!");
586
587 const int id = geometry["surface_selection"];
588 for (const json &disp : dirichlets)
589 {
590 if ((disp["id"].is_string() && disp["id"].get<std::string>() == "all")
591 || (disp["id"].is_number_integer() && disp["id"].get<int>() == id))
592 {
593 displacement = disp;
594 break;
595 }
596 else if (disp["id"].is_array())
597 {
598 for (const json &disp_id : disp["id"])
599 {
600 assert(disp_id.is_number_integer());
601 if (disp_id.get<int>() == id)
602 {
603 displacement = disp;
604 break;
605 }
606 }
607 }
608 }
609 for (const json &disp : displacements)
610 {
611 if ((disp["id"].is_string() && disp["id"].get<std::string>() == "all")
612 || (disp["id"].is_number_integer() && disp["id"].get<int>() == id))
613 {
614 displacement = disp;
615 break;
616 }
617 else if (disp["id"].is_array())
618 {
619 for (const json &disp_id : disp["id"])
620 {
621 assert(disp_id.is_number_integer());
622 if (disp_id.get<int>() == id)
623 {
624 displacement = disp;
625 break;
626 }
627 }
628 }
629 }
630 }
631
632 obstacle.append_mesh(
633 vertices, codim_vertices, codim_edges, faces, displacement, resources_, tets);
634 }
635 else if (geometry["type"] == "plane")
636 {
637 obstacle.append_plane(geometry["point"], geometry["normal"]);
638 }
639 else if (geometry["type"] == "ground")
640 {
641 VectorNd gravity = VectorNd::Zero(dim); // TODO: Expose as parameter
642 gravity[1] = -9.81;
643 const double height = geometry["height"];
644 assert(gravity.norm() != 0);
645 const VectorNd normal = -gravity.normalized();
646 const VectorNd point = height * normal; // origin + height * normal
647 obstacle.append_plane(point, normal);
648 }
649 else if (geometry["type"] == "mesh_sequence")
650 {
651 std::vector<std::string> mesh_files;
652 if (geometry["mesh_sequence"].is_array())
653 {
654 mesh_files = geometry["mesh_sequence"].get<std::vector<std::string>>();
655 }
656 else
657 {
658 assert(geometry["mesh_sequence"].is_string());
659 const std::string sequence = geometry["mesh_sequence"].get<std::string>();
660 mesh_files = resources_.is_group(sequence) ? resources_.list(sequence) : resources_.glob(sequence);
661 // Sort the file names naturally
662 std::sort(mesh_files.begin(), mesh_files.end(), [](const std::string &p1, const std::string &p2) {
663 return strnatcmp(p1.c_str(), p2.c_str()) < 0;
664 });
665 }
666
667 std::vector<Eigen::MatrixXd> vertices(mesh_files.size());
668 Eigen::VectorXi codim_vertices;
669 Eigen::MatrixXi codim_edges;
670 Eigen::MatrixXi faces;
671 Eigen::MatrixXi tets;
672
673 for (int i = 0; i < mesh_files.size(); ++i)
674 {
675 json jmesh = geometry;
676 jmesh["mesh"] = mesh_files[i];
677 jmesh["n_refs"] = 0;
678
679 SurfaceMesh loaded = load_surface(jmesh, dim);
680 vertices[i] = std::move(loaded.vertices);
681 Eigen::VectorXi &tmp_codim_vertices = loaded.points;
682 Eigen::MatrixXi &tmp_codim_edges = loaded.edges;
683 Eigen::MatrixXi &tmp_faces = loaded.faces;
684 Eigen::MatrixXi &tmp_tets = loaded.tets;
685 if (i == 0)
686 {
687 codim_vertices = tmp_codim_vertices;
688 codim_edges = tmp_codim_edges;
689 faces = tmp_faces;
690 tets = tmp_tets;
691 }
692 else
693 {
694 assert((codim_vertices.array() == tmp_codim_vertices.array()).all());
695 assert((codim_edges.array() == tmp_codim_edges.array()).all());
696 assert((faces.array() == tmp_faces.array()).all());
697 assert((tets.array() == tmp_tets.array()).all());
698 }
699 }
700
701 obstacle.append_mesh_sequence(
702 vertices, codim_vertices, codim_edges, faces, geometry["fps"], tets);
703 }
704 else
705 {
706 log_and_throw_error("Invalid geometry type \"{}\" for obstacle!", geometry["type"]);
707 }
708 }
709
710 obstacle.set_units(units_);
711 return obstacle;
712 }
713
714 // ========================================================================
715
717 const double unit_scale,
718 const json &transform,
719 const VectorNd &mesh_dimensions,
720 MatrixNd &A,
721 VectorNd &b)
722 {
723 const int dim = mesh_dimensions.size();
724
725 // -----
726 // Scale
727 // -----
728
729 RowVectorNd scale;
730 if (transform["dimensions"].is_array()) // default is nullptr
731 {
732 VectorNd modified_dimensions =
733 (mesh_dimensions.array() == 0).select(1, mesh_dimensions);
734
735 scale = transform["dimensions"];
736 const int scale_size = scale.size();
737 scale.conservativeResize(dim);
738 if (scale_size < dim)
739 scale.tail(dim - scale_size).setZero();
740
741 scale.array() /= modified_dimensions.array();
742 }
743 else if (transform["scale"].is_number())
744 {
745 scale.setConstant(dim, transform["scale"].get<double>());
746 }
747 else
748 {
749 assert(transform["scale"].is_array());
750 scale = transform["scale"];
751 const int scale_size = scale.size();
752 scale.conservativeResize(dim);
753 if (scale_size < dim)
754 scale.tail(dim - scale_size).setZero();
755
756 if (scale_size == 0)
757 scale.setOnes();
758 }
759
760 A = (unit_scale * scale).asDiagonal();
761
762 // ------
763 // Rotate
764 // ------
765
766 // Rotate around the models origin NOT the bodies center of mass.
767 // We could expose this choice as a "rotate_around" field.
768 MatrixNd R = MatrixNd::Identity(dim, dim);
769 if (!transform["rotation"].is_null())
770 {
771 if (dim == 2)
772 {
773 if (transform["rotation"].is_number())
774 R = Eigen::Rotation2Dd(deg2rad(transform["rotation"].get<double>()))
775 .toRotationMatrix();
776 else if (!transform["rotation"].is_array() || !transform["rotation"].empty())
777 log_and_throw_error("Invalid 2D rotation; 2D rotations can only be a angle in degrees.");
778 }
779 else if (dim == 3)
780 {
781 R = to_rotation_matrix(transform["rotation"], transform["rotation_mode"]);
782 }
783 }
784
785 A = R * A; // Scale first, then rotate
786
787 // ---------
788 // Translate
789 // ---------
790
791 b = transform["translation"];
792 const int translation_size = b.size();
793 b.conservativeResize(dim);
794 if (translation_size < dim)
795 b.tail(dim - translation_size).setZero();
796 }
797
798} // namespace polyfem::mesh
Eigen::RowVectorXd point
std::vector< Eigen::VectorXi > faces
static double convert(const json &val, const std::string &unit_type)
Definition Units.cpp:35
const std::string & length() const
Definition Units.hpp:19
virtual std::vector< std::string > list(const std::string &path) const =0
std::vector< std::string > glob(const std::string &pattern) const
Glob normalized logical paths using POSIX '*' and '?' wildcards.
virtual bool is_group(const std::string &path) const =0
std::unique_ptr< Mesh > load_fem(const json &geometry, bool non_conforming=false) const
Load and combine the enabled FEM entries in a geometry configuration.
Obstacle load_obstacles(const json &geometry, const std::vector< json > &obstacle_displacements, const std::vector< json > &dirichlet_conditions, int dimension, bool non_conforming=false) const
const io::ResourceIO & resources_
LoadedGeometry load(const json &geometry, const std::vector< json > &obstacle_displacements, const std::vector< json > &dirichlet_conditions, bool non_conforming=false) const
static void construct_affine_transformation(double unit_scale, const json &transform, const VectorNd &mesh_dimensions, MatrixNd &A, VectorNd &b)
Construct the affine map used by geometry and collision-proxy inputs.
void apply_geometry_selection(Mesh &mesh, const json &geometry_selection) const
Apply configured geometry IDs to an already constructed mesh.
SurfaceMesh load_surface(const json &geometry, int dimension) const
Load and prepare one configured surface/codimensional geometry entry.
std::unique_ptr< Mesh > load_fem_entry(const json &geometry, bool non_conforming=false) const
std::unique_ptr< Mesh > fem
Abstract mesh class to capture 2d/3d conforming and non-conforming meshes.
Definition Mesh.hpp:77
int n_elements() const
utitlity to return the number of elements, cells or faces in 3d and 2d
Definition Mesh.hpp:181
virtual int get_body_id(const int primitive) const
Get the volume selection of an element (cell in 3d, face in 2d)
Definition Mesh.hpp:521
virtual void compute_element_barycenters(Eigen::MatrixXd &barycenters) const =0
utility for 2d/3d.
virtual void bounding_box(RowVectorNd &min, RowVectorNd &max) const =0
computes the bbox of the mesh
void set_geometry_ids(const std::vector< int > &geometry_ids)
Set the geometry selection, one ID per element.
Definition Mesh.hpp:536
std::vector< int > element_vertices(const int el_id) const
list of vids of an element
Definition Mesh.hpp:249
The only non-legacy decoder from a logical resource path to mesh data.
SurfaceMesh load_surface(const std::string &path, bool keep_volume=false) const
std::unique_ptr< Mesh > load_fem(const std::string &path, bool non_conforming=false) const
void append_mesh(const Eigen::MatrixXd &vertices, const Eigen::VectorXi &codim_vertices, const Eigen::MatrixXi &codim_edges, const Eigen::MatrixXi &faces, const json &displacement, const io::ResourceIO &resources, const Eigen::MatrixXi &tets=Eigen::MatrixXi())
Definition Obstacle.cpp:119
void append_mesh_sequence(const std::vector< Eigen::MatrixXd > &vertices, const Eigen::VectorXi &codim_vertices, const Eigen::MatrixXi &codim_edges, const Eigen::MatrixXi &faces, const int fps, const Eigen::MatrixXi &tets=Eigen::MatrixXi())
Definition Obstacle.cpp:150
void append_plane(const VectorNd &point, const VectorNd &normal)
Definition Obstacle.cpp:196
void set_units(const Units &units)
Definition Obstacle.cpp:282
Eigen::MatrixXi tets
Volumetric cells indexing vertices; only filled when a 3D tet mesh is read with keep_volume.
static std::vector< std::shared_ptr< utils::Selection > > build_selections(const json &j_selections, const BBox &mesh_bbox, const io::ResourceIO &resources)
Build a vector of selection objects from a JSON selection(s).
Definition Selection.cpp:47
std::array< RowVectorNd, 2 > BBox
Definition Selection.hpp:14
Eigen::Matrix3d to_rotation_matrix(const json &jr, std::string mode)
std::vector< T > json_as_array(const json &j)
Return the value of a json object as an array.
Definition JSONUtils.hpp:49
T deg2rad(T deg)
Definition JSONUtils.hpp:29
bool is_param_valid(const json &params, const std::string &key)
Determine if a key exists and is non-null in a json object.
spdlog::logger & logger()
Retrieves the current logger.
Definition Logger.cpp:44
Eigen::Matrix< double, Eigen::Dynamic, 1, 0, 3, 1 > VectorNd
Definition Types.hpp:11
nlohmann::json json
Definition Common.hpp:9
Eigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor, 3, 3 > MatrixNd
Definition Types.hpp:14
Eigen::Matrix< int, Eigen::Dynamic, 1, 0, 3, 1 > VectorNi
Definition Types.hpp:12
Eigen::Matrix< double, 1, Eigen::Dynamic, Eigen::RowMajor, 1, 3 > RowVectorNd
Definition Types.hpp:13
void log_and_throw_error(const std::string &msg)
Definition Logger.cpp:73