FEAT 3
Finite Element Analysis Toolbox
Loading...
Searching...
No Matches
gmsh_reader.hpp
1// FEAT3: Finite Element Analysis Toolbox, Version 3
2// Copyright (C) 2010 by Stefan Turek & the FEAT group
3// FEAT3 is released under the GNU General Public License version 3,
4// see the file 'copyright.txt' in the top level directory for details.
5
6#pragma once
7
8#include <cstring>
9#include <filesystem>
10#include <fstream>
11#include <ios>
12#include <istream>
13#include <string_view>
14
16#include <kernel/geometry/io_common.hpp>
17#include <kernel/geometry/mesh_atlas.hpp>
18#include <kernel/geometry/mesh_node.hpp>
19#include <kernel/shape.hpp>
21#include <kernel/util/string.hpp>
22#include <kernel/util/tiny_algebra.hpp>
23
24namespace FEAT::Geometry
25{
49 {
51 struct FileView
52 {
54 const char* end;
56 const char* current;
57
59 explicit FileView(const String& bytes) : FileView(bytes, bytes.data())
60 {
61 }
62
64 FileView(const String& bytes, const char* pos) :
65 end(bytes.data() + bytes.size()),
66 current(pos)
67 {
68 }
69
71 const char* position() const
72 {
73 return current;
74 }
75
76 bool done() const
77 {
78 return current == end;
79 }
80
83 std::string_view next_line()
84 {
85 // Calling this at the end of the buffer is an error
87
88 // If this is called, we assume that the next part of the data is valid ascii
89 // We can thus safely skip to the next non-whitespace char
90 while(current < end && (std::isspace(static_cast<unsigned char>(*current)) != 0))
91 {
92 current++;
93 }
94
95 // Search for next newline
96 const char* eol = static_cast<const char*>(std::memchr(current, '\n', std::size_t(end - current)));
97
98 if(eol == nullptr)
99 {
100 eol = end;
101 }
102
103 // String views are constructed via a (start, len) pair
104 // So convert from end-of-line pointer to length
105 const auto line_len = std::size_t(eol - current);
106
107 const std::string_view line{current, line_len};
108
109 // Advance past line. +1 to skip over newline
110 current = eol + 1 < end ? eol + 1 : end;
111
112 // Check we are still in bounds
113 XASSERT(current <= end);
114
115 return line;
116 }
117
119 void advance(std::size_t len)
120 {
121 XASSERT(current + len <= end);
122 current += len;
123 }
124
126 template<typename... Args>
127 void parse_line(Args&... args)
128 {
129 const std::string_view line = next_line();
130 std::istringstream stream((std::string(line)));
131
132 ((stream >> args), ...);
133
134 XASSERT(!stream.fail());
135 }
136
138 template<typename T>
139 void memcpy(T* t)
140 {
141 XASSERT(current + sizeof(T) <= end);
142 std::memcpy(t, current, sizeof(T));
143 advance(sizeof(T));
144 }
145 };
146
149 {
151 int type;
156
158 const char* elements_start;
159 };
160
163
164 bool _have_root_markup = false;
165
166 // The following is all the data that gets parsed from the file
167 // during read_root_markup
168
170 double _version = 0.0;
172 bool _is_binary = false;
174 std::size_t _data_size = 8;
176 std::size_t _num_nodes = 0;
178 std::size_t _num_elements = 0;
182 const char* _nodes_start = nullptr;
184 const char* _elements_start = nullptr;
186 std::vector<BinaryElementsHeader> _element_headers;
187
188 // FEAT specific data
189
195 int _shape_dim = 0;
196
197 public:
199 explicit GmshFileReader(const std::istream& stream)
200 {
201 // NOTE: We are reading the whole file into memory here.
202 // Because .msh files may contain meshes with mixed elements
203 // we have to scan through all elements anyway to determine if
204 // FEAT can even represent the mesh.
205 // Binary .msh files also contains a mix of ASCII and binary data
206 // which makes reading the file line by line annoying.
207 read_data(stream);
208 }
209
211 explicit GmshFileReader(const std::filesystem::path& path) : GmshFileReader(std::ifstream(path, std::ios::binary))
212 {
213 XASSERTM(std::filesystem::exists(path), "GmshFileReader: File " + stringify(path) + " does not exist");
214 std::ifstream file(path, std::ios::binary);
215 XASSERTM(file.good(), "GmshFileReader: Bad stream");
216 read_data(file);
217 }
218
230 {
231 return _mesh_type_string;
232 }
233
245 {
247 }
248
260 {
261 return _shape_type;
262 }
263
274 int get_shape_dim() const
275 {
276 return _shape_dim;
277 }
278
289 int get_world_dim() const
290 {
291 return 3;
292 }
293
298 {
299 // NOTE(mmuegge): Unlike FEATs .xml format, .msh allows meshes with mixed
300 // elements. In ASCII meshes each element is tagged with its type, in
301 // binary meshes elements are split into chunks of elements of the same
302 // type. We thus need to scan through the whole file to ensure it contains
303 // a single element type that is representable by FEAT.
304
306
307 XASSERT(view.next_line() == "$MeshFormat");
308
309 // Next line is:
310 // version-number file-type data-size
311 view.parse_line(_version, _is_binary, _data_size);
312 XASSERTM(_version == 2.2, "Unsupported .msh file format version!");
313 XASSERTM(_data_size == 8, "Unsupported .msh data size!");
314
315 if(_is_binary)
316 {
317 int one(0);
318 view.memcpy(&one);
319
320 XASSERTM(one == 1, ".msh files with non-native endianess are not supported!");
321 }
322
323 XASSERT(view.next_line() == "$EndMeshFormat");
324
325 while(!view.done())
326 {
327 std::string_view line = view.next_line();
328
329 if(line == "$Nodes")
330 {
331 scan_nodes(view);
332 }
333 else if(line == "$Elements")
334 {
335 scan_elements(view);
336 }
337 }
338
339 XASSERTM(_element_type != -1, ".msh file with no elements");
342 _mesh_type_string = "conformal:" + stringify(_shape_type) + ":" + stringify(_shape_dim) + ":3";
343 _have_root_markup = true;
344 }
345
359 template<typename MeshType_>
360 std::unique_ptr<RootMeshNode<MeshType_>> parse(MeshAtlas<MeshType_>& mesh_atlas, PartitionSet* part_set = nullptr)
361 {
362 using MeshShapeType = typename MeshType_::ShapeType;
363 using DataType = typename MeshType_::CoordType;
364 using VertexType = typename MeshType_::VertexType;
365
366 static constexpr std::size_t num_verts = Shape::FaceTraits<MeshShapeType, 0>::count;
367 static constexpr int shape_dim = MeshType_::shape_dim;
368
369 if(!_have_root_markup)
370 {
372 }
373
375
376 // Validate that the chosen mesh type fits to the data
377 if(sizeof(DataType) != _data_size)
378 {
379 XABORTM("CoordType of MeshType_ does not match data type of .msh file");
380 }
381
382 XASSERT(MeshShapeType::dimension == _shape_dim);
383
385 {
386 XASSERT((std::is_same_v<MeshShapeType, Shape::Hypercube<2>>));
387 }
389 {
390 XASSERT((std::is_same_v<MeshShapeType, Shape::Hypercube<3>>));
391 }
393 {
394 XASSERT((std::is_same_v<MeshShapeType, Shape::Simplex<2>>));
395 }
397 {
398 XASSERT((std::is_same_v<MeshShapeType, Shape::Simplex<3>>));
399 }
400
401 // part_set is only for compatibility
402 (void)part_set;
403
404 // Create mesh
405 std::array<Index, shape_dim + 1> size;
406 size.fill(0);
407 size[0] = _num_nodes;
408 size[shape_dim] = _num_elements;
409
410 auto mesh = std::make_unique<MeshType_>(size.data());
411
412 // Parse nodes
413 auto& vertex_set = mesh->get_vertex_set();
415 if(_is_binary)
416 {
417 // Safety: If we reached this point, then scan_nodes succeeded,
418 // which means there are the expected number of bytes between $Nodes and $EndNodes.
419 // The following memory accesses are thus safe.
420 for(std::size_t node(0); node < _num_nodes; node++)
421 {
422 // Read node index
423 int vertex_index(0);
424 node_view.memcpy(&vertex_index);
425
426 // This might occur in meshes with non-contiguous indices for vertices.
427 // We currently do not support those.
428 XASSERT(std::size_t(vertex_index - 1) < _num_nodes);
429
430 // Copy coords
431 for(int j(0); j < get_world_dim(); j++)
432 {
433 // NOTE: .msh files are 1-indexed, hence vertex_index - 1 to transform to 0-based indices
434 node_view.memcpy(&vertex_set[Index(vertex_index - 1)][j]);
435 }
436 }
437 }
438 else
439 {
440 // Safety: Cast to int is safe because _num_nodes is stored as an int as per .msh docs.
441 for(int i(0); i < (int)_num_nodes; i++)
442 {
443 Index vertex_index(~Index(0));
444 double x(0.0);
445 double y(0.0);
446 double z(0.0);
447
448 node_view.parse_line(vertex_index, x, y, z);
449
450 // This might occur in meshes with non-contiguous indices for vertices.
451 // We currently do not support those.
452 XASSERT(std::size_t(vertex_index - 1) < _num_nodes);
453
454 // NOTE: .msh files are 1-indexed, hence vertex_index - 1 to transform to 0-based indices
455 vertex_set[vertex_index - 1] = VertexType{x, y, z};
456 }
457 }
458
459 // Parse elements
460 auto& element_index_set = mesh->template get_index_set<shape_dim, 0>();
461 if(_is_binary)
462 {
464 {
465 FileView chunk_view(_file_contents, header.elements_start);
466
467 // Safety: If we reached this point, then scan_elements succeeded,
468 // which means there are the expected number of bytes between $Elements and $EndElements.
469 // The following memory accesses are thus safe.
470 for(std::size_t e(0); e < std::size_t(header.num_elements); e++)
471 {
472 // Determine element index
473 int element_index(0);
474 chunk_view.memcpy(&element_index);
475
476 // This might occur in meshes with non-contiguous indices for elements.
477 // We currently do not support those.
478 XASSERT(std::size_t(element_index - 1) < _num_elements);
479
480 // Skip past tags
481 chunk_view.advance(std::size_t(header.tags_per_element) * sizeof(int));
482
483 for(int n(0); n < (int)num_verts; n++)
484 {
485 int node_index(0);
486 chunk_view.memcpy(&node_index);
487
488 // NOTE: .msh indexing is one-based
489 element_index_set(Index(element_index - 1), msh_to_feat_order(header.type, n)) = Index(node_index - 1);
490 }
491 }
492 }
493 }
494 else
495 {
497
498 for(int i(0); i < (int)_num_elements; i++)
499 {
500 std::string_view line = view.next_line();
501 std::istringstream stream((std::string(line)));
502
503 int element_index(0);
504 int type(0);
505 int num_tags(0);
506
507 stream >> element_index >> type >> num_tags;
508
509 // This might occur in meshes with non-contiguous indices for elements.
510 // We currently do not support those.
511 XASSERT(std::size_t(element_index - 1) < _num_elements);
512
513 // Skip over tags
514 for(int tag(0); tag < num_tags; tag++)
515 {
516 int dummy(0);
517 stream >> dummy;
518 }
519
520 for(int n(0); n < (int)num_verts; n++)
521 {
522 int node_number(0);
523 stream >> node_number;
524
525 element_index_set(Index(element_index - 1), msh_to_feat_order(type, n)) = Index(node_number - 1);
526 }
527
528 XASSERT(!stream.fail());
529 }
530 }
531
532 // Validate element orientation
533
534 mesh->deduct_topology_from_top();
535 return std::make_unique<RootMeshNode<MeshType_>>(std::move(mesh), &mesh_atlas);
536 }
537
538 private:
540 static std::size_t binary_element_chunk_size(const BinaryElementsHeader& header)
541 {
542 // 4 bytes for element index, 4 bytes per tag, 4 bytes per vertex index
543 return std::size_t(header.num_elements) * (sizeof(int) + (sizeof(int) * std::size_t(header.tags_per_element)) +
544 (sizeof(int) * std::size_t(nodes_per_element(header.type))));
545 }
546
549 {
550 switch(type)
551 {
552 case 2: return ParsedShapeType::simplex; // Triangle
553 case 3: return ParsedShapeType::hypercube; // Quadrangle
554 case 4: return ParsedShapeType::simplex; // 4-point tetrahedron
555 case 5: return ParsedShapeType::hypercube; // 8-point hexahedron
556 default: XABORTM("Unsupported .msh element type!");
557 }
558 }
559
561 static int element_type_to_shape_dim(int type)
562 {
563 switch(type)
564 {
565 case 2: return 2; // Triangle
566 case 3: return 2; // Quadrangle
567 case 4: return 3; // 4-point tetrahedron
568 case 5: return 3; // 8-point hexahedron
569 default: XABORTM("Unsupported .msh element type!");
570 }
571 }
572
574 static int nodes_per_element(int type)
575 {
576 switch(type)
577 {
578 case 2: return 3; // Triangle
579 case 3: return 4; // Quadrangle
580 case 4: return 4; // 4-point tetrahedron
581 case 5: return 8; // 8-point hexahedron
582 default: XABORTM("Unsupported .msh element type!");
583 }
584 }
585
593 static int msh_to_feat_order(int type, int node)
594 {
595 // Re-ordering for quadrangles
596 // .msh are ordered counter-clockwise, FEAT in a zig-zag pattern
597 static constexpr std::array<int, 4> quadrangle_ordering{0, 1, 3, 2};
598
599 // Re-ordering for hexahedrons
600 static constexpr std::array<int, 8> hexahedron_ordering{0, 1, 3, 2, 4, 5, 7, 6};
601
602 // Re-ordering
603 switch(type)
604 {
605 case 2: return node; // triangles are ordered the same
606 case 3: return quadrangle_ordering.at(std::size_t(node));
607 case 4: return node; // tetrahedrons are ordered the same
608 case 5: return hexahedron_ordering.at(std::size_t(node));
609 default: XABORTM("Unsupported .msh element type!");
610 }
611 }
612
615 {
616 // Next line contains number of nodes
617 view.parse_line(_num_nodes);
618
619 // Skip past nodes
620 _nodes_start = view.position();
621 if(_is_binary)
622 {
623 // Each node consists of an integer index and 3 coordinates
624 view.advance(_num_nodes * (sizeof(int) + (3 * _data_size)));
625 }
626 else
627 {
628 for(Index i(0); i < _num_nodes; i++)
629 {
630 view.next_line();
631 }
632 }
633
634 XASSERT(view.next_line() == "$EndNodes");
635 }
636
639 {
640 view.parse_line(_num_elements);
641
642 _elements_start = view.position();
643 if(_is_binary)
644 {
645 // Each chunk has a header containing:
646 // - the element type,
647 // - the number of elements of the chunk,
648 // - the number of tags per element of the chunk
649 // We handle each chunk one by one until we have seen all elements
650 std::size_t elements_handled(0);
651 while(elements_handled < _num_elements)
652 {
653 BinaryElementsHeader header{};
654
655 // Read header values
656 view.memcpy(&header.type);
657 view.memcpy(&header.num_elements);
658 view.memcpy(&header.tags_per_element);
659
660 // Record current positions as start of elements for this header
661 header.elements_start = view.position();
662
663 // Skip past actual element entries
664 view.advance(binary_element_chunk_size(header));
665
666 if(_element_type == -1)
667 {
668 _element_type = header.type;
669 }
670 else
671 {
672 XASSERT(_element_type == header.type);
673 }
674
675 elements_handled += std::size_t(header.num_elements);
676 _element_headers.push_back(header);
677 }
678 }
679 else
680 {
681 for(Index i(0); i < _num_elements; i++)
682 {
683 int number(0);
684 int type(0);
685
686 view.parse_line(number, type);
687
688 if(_element_type == -1)
689 {
690 _element_type = type;
691 }
692 else
693 {
694 XASSERT(_element_type == type);
695 }
696 }
697 }
698
699 XASSERT(view.next_line() == "$EndElements");
700 }
701
703 void read_data(const std::istream& stream)
704 {
705 XASSERT(!stream.fail());
706
707 // TODO: Is this an unnecessary copy?
708 std::stringstream buffer;
709 buffer << stream.rdbuf();
710
711 _file_contents = buffer.str();
712 }
713 }; // class MshFileReader
714} // namespace FEAT::Geometry
#define XABORTM(msg)
Abortion macro definition with custom message.
Definition: assertion.hpp:192
#define XASSERT(expr)
Assertion macro definition.
Definition: assertion.hpp:262
#define XASSERTM(expr, msg)
Assertion macro definition with custom message.
Definition: assertion.hpp:263
FEAT Kernel base header.
Gmsh file reader class.
Definition: gmsh_reader.hpp:49
ParsedMeshType get_mesh_type() const
Returns the mesh-type of the parsed mesh.
std::vector< BinaryElementsHeader > _element_headers
Element chunks, for binary files.
int _shape_dim
Shape dimension.
int get_shape_dim() const
Returns the shape-dimension of the parsed mesh.
const char * _nodes_start
Start of nodes in the file.
void read_data(const std::istream &stream)
Read file into string.
double _version
.msh file version
GmshFileReader(const std::istream &stream)
Input stream constructor.
String _file_contents
Contents of the .msh file.
void scan_elements(FileView &view)
Gather start position(s) of element data and ensure the mesh contains only a single element type.
static int nodes_per_element(int type)
.msh element type to number of nodes per element
String _mesh_type_string
Mesh type string.
static ParsedShapeType element_type_to_shape_type(int type)
.msh element type to ShapeType mapping
int _element_type
.msh element type
static int msh_to_feat_order(int type, int node)
Re-ordering for cell vertices.
static int element_type_to_shape_dim(int type)
.msh element type to shape dimension mapping
ParsedShapeType _shape_type
Shape type.
static std::size_t binary_element_chunk_size(const BinaryElementsHeader &header)
Size (in bytes) of one chunk of elements in a binary .msh file.
std::size_t _num_nodes
Number of nodes in the file.
GmshFileReader(const std::filesystem::path &path)
File path constructor.
void scan_nodes(FileView &view)
Gather number of nodes and start position of node data.
ParsedShapeType get_shape_type() const
Returns the shape-type of the parsed mesh.
int get_world_dim() const
Returns the world-dimension of the parsed mesh.
std::size_t _num_elements
Number of elements in the file.
bool _is_binary
.msh ascii/binary indicator
const char * _elements_start
Start of elements in the file, for ascii files.
const String & get_meshtype_string() const
Returns the mesh-type string of the parsed mesh.
void read_root_markup()
Reads the root markup from the input stream and analyses it.
std::unique_ptr< RootMeshNode< MeshType_ > > parse(MeshAtlas< MeshType_ > &mesh_atlas, PartitionSet *part_set=nullptr)
Parses the mesh file into a mesh node and a mesh atlas.
std::size_t _data_size
.msh size for reals
Mesh Atlas class template.
Definition: mesh_atlas.hpp:32
String class implementation.
Definition: string.hpp:47
Geometry namespace.
ParsedMeshType
mesh type enumeration
Definition: io_common.hpp:14
@ conformal
conformal mesh type
ParsedShapeType
shape type enumeration
Definition: io_common.hpp:57
@ simplex
simplex shape type
@ hypercube
hypercube shape type
@ unknown
unknown shape type
String stringify(const T_ &item)
Converts an item into a String.
Definition: string.hpp:993
std::uint64_t Index
Index data type.
Header for a chunk of elements in binary .msh files.
const char * elements_start
Start of elements of chunk in mesh (excluding the chunks header)
int tags_per_element
Tags per element of the chunk.
Utility class for walking through potentially mixed ascii and binary .msh files.
Definition: gmsh_reader.hpp:52
const char * end
End of buffer (for bounds checks)
Definition: gmsh_reader.hpp:54
void advance(std::size_t len)
Advance the view len chars.
FileView(const String &bytes, const char *pos)
Constructor.
Definition: gmsh_reader.hpp:64
void memcpy(T *t)
Copy a value from the buffer and then advance that many bytes.
const char * current
Current position in buffer.
Definition: gmsh_reader.hpp:56
const char * position() const
Current position in buffer.
Definition: gmsh_reader.hpp:71
FileView(const String &bytes)
Constructor.
Definition: gmsh_reader.hpp:59
void parse_line(Args &... args)
Parses a line (split by whitespace) into the given parameters.
Face traits tag struct template.
Definition: shape.hpp:106
Hypercube shape tag struct template.
Definition: shape.hpp:64
Simplex shape tag struct template.
Definition: shape.hpp:44