Mesh Oriented datABase  (version 5.6.0)
An array-based unstructured mesh library
HelloMOAB.cpp
Go to the documentation of this file.
1 /** @example HelloMOAB.cpp
2  * @brief A simple example demonstrating basic MOAB functionality.
3  *
4  * This example demonstrates the fundamental operations in MOAB:
5  * - Creating a MOAB instance
6  * - Loading a mesh from a file
7  * - Querying entities by type and dimension
8  * - Basic error handling with MB_CHK_ERR
9  *
10  * The program reads a mesh file (default: 3k-tri-sphere.vtk) and reports
11  * the number of vertices, edges, faces, and elements in the mesh.
12  *
13  * To run: ./HelloMOAB [meshfile]
14  * (default values can run if users don't specify a mesh file)
15  */
16 
17 #include "moab/Core.hpp"
18 #include <iostream>
19 #include <memory>
20 #include <string>
21 
22 // Using declarations for cleaner code
23 using moab::Core;
24 using moab::ErrorCode;
25 using moab::MBEDGE;
26 using moab::MBVERTEX;
27 using moab::Range;
28 
29 // Constants
30 namespace
31 {
32 const char* const DEFAULT_MESH_FILE = "3k-tri-sphere.vtk";
33 } // namespace
34 
35 int main( int argc, char** argv )
36 {
37  try
38  {
39  // Create MOAB instance with smart pointer for automatic cleanup
40  auto moab = std::make_unique< Core >();
41  if( !moab )
42  {
43  std::cerr << "Error: Failed to create MOAB instance\n";
44  return 1;
45  }
46 
47  // Parse input filename
48  const std::string mesh_file =
49  ( argc > 1 ) ? argv[1] : std::string( MESH_DIR ) + "/" + std::string( DEFAULT_MESH_FILE );
50 
51  // Load the mesh from file with error checking
52  MB_CHK_SET_ERR( moab->load_mesh( mesh_file.c_str() ), "Error: Could not load mesh file: " << mesh_file );
53 
54  // Get entities by type/dimension
55  Range vertices, edges, faces, elements;
56  MB_CHK_ERR( moab->get_entities_by_type( 0, MBVERTEX, vertices ) );
57  MB_CHK_ERR( moab->get_entities_by_type( 0, MBEDGE, edges ) );
58  MB_CHK_ERR( moab->get_entities_by_dimension( 0, 2, faces ) );
59  MB_CHK_ERR( moab->get_entities_by_dimension( 0, 3, elements ) );
60 
61  // Output the number of entities with formatted output
62  const auto print_entity_count = []( const std::string& name, const auto& range ) {
63  std::cout << "Number of " << name << ": " << range.size() << "\n";
64  };
65 
66  print_entity_count( "vertices", vertices );
67  print_entity_count( "edges ", edges );
68  print_entity_count( "faces ", faces );
69  print_entity_count( "elements", elements );
70 
71  return 0;
72  }
73  catch( const std::exception& e )
74  {
75  std::cerr << "Error: " << e.what() << "\n";
76  return 1;
77  }
78  catch( ... )
79  {
80  std::cerr << "Error: Unknown exception occurred\n";
81  return 1;
82  }
83 }