Salome HOME
2df5cc251c312872c07762213c58c5fec30279e1
[plugins/ghs3dplugin.git] / src / GHS3DPlugin / MG_Tetra_API.cxx
1 // Copyright (C) 2004-2020  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "MG_Tetra_API.hxx"
21
22 #ifdef WIN32
23 #define NOMINMAX
24 #endif
25 #include <SMESH_Comment.hxx>
26 #include <SMESH_File.hxx>
27 #include <Utils_SALOME_Exception.hxx>
28
29 #include <vector>
30 #include <iterator>
31 #include <cstring>
32
33 #ifdef USE_MG_LIBS
34
35 extern "C"{
36 #include <meshgems/meshgems.h>
37 #include <meshgems/tetra.h>
38 }
39
40 struct MG_Tetra_API::LibData
41 {
42   // MG objects
43   context_t *       _context;
44   tetra_session_t * _session;
45   mesh_t *          _tria_mesh;
46   sizemap_t *       _sizemap;
47   mesh_t *          _tetra_mesh;
48
49   // data to pass to MG
50   std::vector<double> _xyz;
51   std::vector<double> _nodeSize; // required nodes
52   std::vector<int>    _edgeNodes;
53   int                 _nbRequiredEdges;
54   std::vector<int>    _triaNodes;
55   int                 _nbRequiredTria;
56   std::vector<int>    _tetraNodes;
57
58   int                 _count;
59   volatile bool&      _cancelled_flag;
60   std::string         _errorStr;
61   double&             _progress;
62   bool                _progressInCallBack;
63
64   LibData( volatile bool & cancelled_flag, double& progress )
65     : _context(0), _session(0), _tria_mesh(0), _sizemap(0), _tetra_mesh(0),
66       _nbRequiredEdges(0), _nbRequiredTria(0),
67       _cancelled_flag( cancelled_flag ), _progress( progress ), _progressInCallBack( false )
68   {
69   }
70   // methods setting callbacks implemented after callback definitions
71   void Init();
72   bool Compute();
73
74   ~LibData()
75   {
76     if ( _tetra_mesh )
77       tetra_regain_mesh( _session, _tetra_mesh );
78     if ( _session )
79       tetra_session_delete( _session );
80     if ( _tria_mesh )
81       mesh_delete( _tria_mesh );
82     if ( _sizemap )
83       sizemap_delete( _sizemap );
84     if ( _context )
85       context_delete( _context );
86
87     _tetra_mesh = 0;
88     _session = 0;
89     _tria_mesh = 0;
90     _sizemap = 0;
91     _context = 0;
92   }
93
94   void AddError( const char *txt )
95   {
96     if ( txt )
97       _errorStr += txt;
98   }
99
100   const std::string& GetErrors()
101   {
102     return _errorStr;
103   }
104
105   void MG_Error(const char* txt="")
106   {
107     SMESH_Comment msg("\nMeshGems error. ");
108     msg << txt << "\n";
109     AddError( msg.c_str() );
110   }
111
112   bool SetParam( const std::string& param, const std::string& value )
113   {
114     status_t ret = tetra_set_param( _session, param.c_str(), value.c_str() );
115 #ifdef _DEBUG_
116     //std::cout << param << " = " << value << std::endl;
117 #endif
118     return ( ret == STATUS_OK );
119   }
120
121   bool Cancelled()
122   {
123     return _cancelled_flag;
124   }
125
126   int ReadNbSubDomains()
127   {
128     integer nb = 0;
129     status_t ret = mesh_get_subdomain_count( _tetra_mesh, & nb );
130
131     if ( ret != STATUS_OK ) MG_Error("mesh_get_subdomain_count problem");
132     return nb;
133   }
134
135   int ReadNbNodes()
136   {
137     integer nb = 0;
138     status_t ret = mesh_get_vertex_count( _tetra_mesh, & nb );
139
140     if ( ret != STATUS_OK ) MG_Error("mesh_get_vertex_count problem");
141     return nb;
142   }
143
144   int ReadNbEdges()
145   {
146     integer nb = 0;
147     status_t ret = mesh_get_edge_count( _tetra_mesh, & nb );
148
149     if ( ret != STATUS_OK ) MG_Error("mesh_get_edge_count problem");
150     return nb;
151   }
152
153   int ReadNbTria()
154   {
155     integer nb = 0;
156     status_t ret = mesh_get_triangle_count( _tetra_mesh, & nb );
157
158     if ( ret != STATUS_OK ) MG_Error("mesh_get_triangle_count problem");
159     return nb;
160   }
161
162   int ReadNbQuads()
163   {
164     integer nb = 0;
165     status_t ret = mesh_get_quadrangle_count( _tetra_mesh, & nb );
166
167     if ( ret != STATUS_OK ) MG_Error("mesh_get_quadrangle_count problem");
168     return nb;
169   }
170
171   int ReadNbTetra()
172   {
173     integer nb = 0;
174     status_t ret = mesh_get_tetrahedron_count( _tetra_mesh, & nb );
175
176     if ( ret != STATUS_OK ) MG_Error("mesh_get_tetrahedron_count problem");
177     return nb;
178   }
179
180   int ReadNbHexa()
181   {
182     integer nb = 0;
183     status_t ret = mesh_get_hexahedron_count( _tetra_mesh, & nb );
184
185     if ( ret != STATUS_OK ) MG_Error("mesh_get_hexahedron_count problem");
186     return nb;
187   }
188
189   void ResetCounter()
190   {
191     _count = 1;
192   }
193
194   void ReadSubDomain( int* nbNodes, int* faceInd, int* ori, int* domain )
195   {
196     integer tag, seed_type, seed_idx, seed_orientation;
197     status_t ret = mesh_get_subdomain_description( _tetra_mesh, _count,
198                                                    &tag, &seed_type, &seed_idx, &seed_orientation);
199
200     if ( ret != STATUS_OK ) MG_Error( "unable to get a sub-domain description");
201
202     *nbNodes = 3;
203     *faceInd = seed_idx;
204     *domain  = tag;
205     *ori     = seed_orientation;
206
207     ++_count;
208   }
209   void ReadNodeXYZ( double* x, double* y, double *z, int* /*domain*/  )
210   {
211     real coo[3];
212     status_t ret = mesh_get_vertex_coordinates( _tetra_mesh, _count, coo );
213     if ( ret != STATUS_OK ) MG_Error( "unable to get resulting vertices" );
214
215     *x = coo[0];
216     *y = coo[1];
217     *z = coo[2];
218
219     ++_count;
220   }
221
222   void ReadEdgeNodes( int* node1, int* node2, int* domain )
223   {
224     integer vtx[2], tag;
225     status_t ret = mesh_get_edge_vertices( _tetra_mesh, _count, vtx);
226     if (ret != STATUS_OK) MG_Error( "unable to get resulting edge" );
227
228     *node1 = vtx[0];
229     *node2 = vtx[1];
230
231     ret = mesh_get_edge_tag( _tetra_mesh, _count, &tag );
232     if (ret != STATUS_OK) MG_Error( "unable to get resulting edge tag" );
233
234     *domain = tag;
235
236     ++_count;
237   }
238
239   void ReadTriaNodes( int* node1, int* node2, int* node3, int* domain )
240   {
241     integer vtx[3], tag;
242     status_t ret = mesh_get_triangle_vertices( _tetra_mesh, _count, vtx);
243     if (ret != STATUS_OK) MG_Error( "unable to get resulting triangle" );
244
245     *node1 = vtx[0];
246     *node2 = vtx[1];
247     *node3 = vtx[2];
248
249     ret = mesh_get_triangle_tag( _tetra_mesh, _count, &tag );
250     if (ret != STATUS_OK) MG_Error( "unable to get resulting triangle tag" );
251
252     *domain = tag;
253
254     ++_count;
255   }
256
257   void ReadQuadNodes( int* node1, int* node2, int* node3, int* node4, int* domain )
258   {
259     integer vtx[4], tag;
260     status_t ret = mesh_get_quadrangle_vertices( _tetra_mesh, _count, vtx);
261     if (ret != STATUS_OK) MG_Error( "unable to get resulting quadrangle" );
262
263     *node1 = vtx[0];
264     *node2 = vtx[1];
265     *node3 = vtx[2];
266     *node4 = vtx[3];
267
268     ret = mesh_get_quadrangle_tag( _tetra_mesh, _count, &tag );
269     if (ret != STATUS_OK) MG_Error( "unable to get resulting quadrangle tag" );
270
271     *domain = tag;
272
273     ++_count;
274   }
275
276   void ReadTetraNodes( int* node1, int* node2, int* node3, int* node4, int* domain )
277   {
278     integer vtx[4], tag;
279     status_t ret = mesh_get_tetrahedron_vertices( _tetra_mesh, _count, vtx);
280     if (ret != STATUS_OK) MG_Error( "unable to get resulting tetrahedron" );
281
282     *node1 = vtx[0];
283     *node2 = vtx[1];
284     *node3 = vtx[2];
285     *node4 = vtx[3];
286
287     ret = mesh_get_tetrahedron_tag( _tetra_mesh, _count, &tag );
288     if (ret != STATUS_OK) MG_Error( "unable to get resulting tetrahedron tag" );
289
290     *domain = tag;
291
292     ++_count;
293   }
294
295   void ReadHexaNodes( int* node1, int* node2, int* node3, int* node4,
296                      int* node5, int* node6, int* node7, int* node8, int* domain )
297   {
298     integer vtx[8], tag;
299     status_t ret = mesh_get_hexahedron_vertices( _tetra_mesh, _count, vtx);
300     if (ret != STATUS_OK) MG_Error( "unable to get resulting hexahedron" );
301
302     *node1 = vtx[0];
303     *node2 = vtx[1];
304     *node3 = vtx[2];
305     *node4 = vtx[3];
306     *node5 = vtx[4];
307     *node6 = vtx[5];
308     *node7 = vtx[6];
309     *node8 = vtx[7];
310
311     ret = mesh_get_hexahedron_tag( _tetra_mesh, _count, &tag );
312     if (ret != STATUS_OK) MG_Error( "unable to get resulting hexahedron tag" );
313
314     *domain = tag;
315
316     ++_count;
317   }
318
319   void SetNbVertices( int nb )
320   {
321     _xyz.reserve( _xyz.capacity() + nb );
322   }
323
324   void SetNbEdges( int nb )
325   {
326     _edgeNodes.reserve( nb * 2 );
327   }
328
329   void SetNbTria( int nb )
330   {
331     _triaNodes.reserve( nb * 3 );
332   }
333
334   void SetNbTetra( int nb )
335   {
336     _tetraNodes.reserve( nb * 4 );
337   }
338
339   void SetNbReqVertices( int nb )
340   {
341     _nodeSize.reserve( nb );
342   }
343
344   void SetNbReqEdges( int nb )
345   {
346     _nbRequiredEdges = nb;
347   }
348
349   void SetNbReqTria( int nb )
350   {
351     _nbRequiredTria = nb;
352   }
353
354   void AddNode( double x, double y, double z, int domain )
355   {
356     _xyz.push_back( x );
357     _xyz.push_back( y );
358     _xyz.push_back( z );
359   }
360
361   void AddSizeAtNode( double size )
362   {
363     _nodeSize.push_back( size );
364   }
365   
366   void AddEdgeNodes( int node1, int node2, int domain )
367   {
368     _edgeNodes.push_back( node1 );
369     _edgeNodes.push_back( node2 );
370   }
371   
372   void AddTriaNodes( int node1, int node2, int node3, int domain )
373   {
374     _triaNodes.push_back( node1 );
375     _triaNodes.push_back( node2 );
376     _triaNodes.push_back( node3 );
377   }
378
379   void AddTetraNodes( int node1, int node2, int node3, int node4, int domain )
380   {
381     _tetraNodes.push_back( node1 );
382     _tetraNodes.push_back( node2 );
383     _tetraNodes.push_back( node3 );
384     _tetraNodes.push_back( node4 );
385   }
386
387   int NbNodes()
388   {
389     return _xyz.size() / 3;
390   }
391
392   double* NodeCoord( int iNode )
393   {
394     return & _xyz[ iNode * 3 ];
395   }
396
397   int NbEdges()
398   {
399     return _edgeNodes.size() / 2;
400   }
401
402   int* GetEdgeNodes( int iEdge )
403   {
404     return & _edgeNodes[ iEdge * 2 ];
405   }
406
407   int NbTriangles()
408   {
409     return _triaNodes.size() / 3;
410   }
411
412   int NbTetra()
413   {
414     return _tetraNodes.size() / 4;
415   }
416
417   int * GetTriaNodes( int iTria )
418   {
419     return & _triaNodes[ iTria * 3 ];
420   }
421
422   int * GetTetraNodes( int iTet )
423   {
424     return & _tetraNodes[ iTet * 4 ];
425   }
426
427   int IsVertexRequired( int iNode )
428   {
429     return ! ( iNode < int( NbNodes() - _nodeSize.size() ));
430   }
431
432   double GetSizeAtVertex( int iNode )
433   {
434     return IsVertexRequired( iNode ) ? _nodeSize[ iNode - NbNodes() + _nodeSize.size() ] : 0.;
435   }
436 };
437
438 namespace // functions called by MG library to exchange with the application
439 {
440   status_t get_vertex_count(integer * nbvtx, void *user_data)
441   {
442     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
443     *nbvtx = data->NbNodes();
444
445     return STATUS_OK;
446   }
447
448   status_t get_vertex_coordinates(integer ivtx, real * xyz, void *user_data)
449   {
450     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
451     double* coord = data->NodeCoord( ivtx-1 );
452     for (int j = 0; j < 3; j++)
453       xyz[j] = coord[j];
454
455     return STATUS_OK;
456   }
457   status_t get_edge_count(integer * nbedge, void *user_data)
458   {
459     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
460     *nbedge = data->NbEdges();
461
462     return STATUS_OK;
463   }
464
465   status_t get_edge_vertices(integer iedge, integer * vedge, void *user_data)
466   {
467     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
468     int* nodes = data->GetEdgeNodes( iedge-1 );
469     vedge[0] = nodes[0];
470     vedge[1] = nodes[1];
471
472     return STATUS_OK;
473   }
474
475   status_t get_triangle_count(integer * nbtri, void *user_data)
476   {
477     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
478     *nbtri = data->NbTriangles();
479
480     return STATUS_OK;
481   }
482
483   status_t get_triangle_vertices(integer itri, integer * vtri, void *user_data)
484   {
485     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
486     int* nodes = data->GetTriaNodes( itri-1 );
487     vtri[0] = nodes[0];
488     vtri[1] = nodes[1];
489     vtri[2] = nodes[2];
490
491     return STATUS_OK;
492   }
493
494   // status_t get_triangle_extra_vertices(integer itri, integer * typetri,
495   //                                      integer * evtri, void *user_data)
496   // {
497   //   int j;
498   //   MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
499
500   //   if (1) {
501   //     /* We want to describe a linear "3 nodes" triangle */
502   //     *typetri = MESHGEMS_MESH_ELEMENT_TYPE_TRIA3;
503   //   } else {
504   //     /* We want to describe a quadratic "6 nodes" triangle */
505   //     *typetri = MESHGEMS_MESH_ELEMENT_TYPE_TRIA6;
506   //     for (j = 0; j < 3; j++)
507   //       evtri[j] = 0;             /* the j'th quadratic vertex index of the itri'th triangle */
508   //   }
509
510   //   return STATUS_OK;
511   // }
512
513   status_t get_tetrahedron_count(integer * nbtetra, void *user_data)
514   {
515     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
516     *nbtetra = data->NbTetra();
517
518     return STATUS_OK;
519   }
520
521   status_t get_tetrahedron_vertices(integer itetra, integer * vtetra,
522                                     void *user_data)
523   {
524     int j;
525     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
526     int* nodes = data->GetTetraNodes( itetra-1 );
527     for (j = 0; j < 4; j++)
528       vtetra[j] = nodes[j];
529
530     return STATUS_OK;
531   }
532
533   status_t get_vertex_required_property(integer ivtx, integer * rvtx, void *user_data)
534   {
535     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
536     *rvtx = data->IsVertexRequired( ivtx - 1 );
537
538     return STATUS_OK;
539   }
540
541   status_t get_vertex_weight(integer ivtx, real * wvtx, void *user_data)
542   {
543     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
544     *wvtx = data->GetSizeAtVertex( ivtx - 1 );
545
546     return STATUS_OK;
547   }
548
549   status_t my_message_cb(message_t * msg, void *user_data)
550   {
551     char *desc;
552     message_get_description(msg, &desc);
553
554     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
555     data->AddError( desc );
556
557 #ifdef _DEBUG_
558     //std::cout << desc << std::endl;
559 #endif
560
561     if ( strncmp( "MGMESSAGE  1009001 ", desc, 19 ) == 0 )
562     {
563       // progress message (10%): "MGMESSAGE  1009001  0 1 1.000000e+01"
564       data->_progress = atof( desc + 24 );
565
566       data->_progressInCallBack = true;
567     }
568
569     if ( !data->_progressInCallBack )
570     {
571       // Compute progress
572       // corresponding messages are:
573       // "  -- PHASE 1 COMPLETED"               => 10 %
574       // "  -- PHASE 2 COMPLETED"               => 25 %
575       // "     ** ITERATION   1"                => 25.* %
576       // "     ** ITERATION   2"                => 25.* %
577       // "  -- PHASE 3 COMPLETED"               => 70 %
578       // "  -- PHASE 4 COMPLETED"               => 98 %
579
580       if ( strncmp( "-- PHASE ", desc + 2, 9 ) == 0 && desc[ 13 ] == 'C' )
581       {
582         const double progress[] = { 10., 25., 70., 98., 100., 100., 100. };
583         int       phase = atoi( desc + 11 );
584         data->_progress = std::max( data->_progress, progress[ phase - 1 ] / 100. );
585       }
586       else if ( strncmp( "** ITERATION ", desc + 5, 13 ) == 0 )
587       {
588         int         iter = atoi( desc + 20 );
589         double   percent = 25. + iter * ( 70 - 25 ) / 20.;
590         data->_progress = std::max( data->_progress, ( percent / 100. ));
591       }
592     }
593
594     return STATUS_OK;
595   }
596
597   status_t my_interrupt_callback(integer *interrupt_status, void *user_data)
598   {
599     MG_Tetra_API::LibData* data = (MG_Tetra_API::LibData *) user_data;
600     *interrupt_status = ( data->Cancelled() ? INTERRUPT_STOP : INTERRUPT_CONTINUE );
601
602
603     return STATUS_OK;
604   }
605
606 } // end namespace
607
608
609 void MG_Tetra_API::LibData::Init()
610 {
611   status_t ret;
612
613   // Create the meshgems working context
614   _context = context_new();
615   if ( !_context ) MG_Error( "unable to create a new context" );
616
617   // Set the message callback for the _context.
618   ret = context_set_message_callback( _context, my_message_cb, this );
619   if ( ret != STATUS_OK ) MG_Error("in context_set_message_callback");
620
621   // Create the structure holding the callbacks giving access to triangle mesh
622   _tria_mesh = mesh_new( _context );
623   if ( !_tria_mesh ) MG_Error("unable to create a new mesh");
624
625   // Set callbacks to provide triangle mesh data
626   mesh_set_get_vertex_count( _tria_mesh, get_vertex_count, this );
627   mesh_set_get_vertex_coordinates( _tria_mesh, get_vertex_coordinates, this );
628   mesh_set_get_vertex_required_property( _tria_mesh, get_vertex_required_property, this );
629   mesh_set_get_edge_count( _tria_mesh, get_edge_count, this);
630   mesh_set_get_edge_vertices( _tria_mesh, get_edge_vertices, this );
631   mesh_set_get_triangle_count( _tria_mesh, get_triangle_count, this );
632   mesh_set_get_triangle_vertices( _tria_mesh, get_triangle_vertices, this );
633   mesh_set_get_tetrahedron_count( _tria_mesh, get_tetrahedron_count, this );
634   mesh_set_get_tetrahedron_vertices( _tria_mesh, get_tetrahedron_vertices, this );
635
636   // Create a tetra session
637   _session = tetra_session_new( _context );
638   if ( !_session ) MG_Error( "unable to create a new tetra session");
639
640   ret = tetra_set_interrupt_callback( _session, my_interrupt_callback, this );
641   if ( ret != STATUS_OK ) MG_Error("in tetra_set_interrupt_callback");
642
643 }
644
645 bool MG_Tetra_API::LibData::Compute()
646 {
647   status_t ret;
648
649   if ( _tetraNodes.empty() )
650   {
651     // Set surface mesh
652     ret = tetra_set_surface_mesh( _session, _tria_mesh );
653     if ( ret != STATUS_OK ) MG_Error( "unable to set surface mesh");
654   }
655   else
656   {
657     ret = tetra_set_volume_mesh( _session, _tria_mesh );
658     if ( ret != STATUS_OK ) MG_Error( "unable to set volume mesh");
659   }
660
661   // Set a sizemap
662   if ( !_nodeSize.empty() )
663   {
664     _sizemap = meshgems_sizemap_new( _tria_mesh, meshgems_sizemap_type_iso_mesh_vertex,
665                                      (void*) &get_vertex_weight, this );
666     if ( !_sizemap ) MG_Error("unable to create a new sizemap");
667
668     ret = tetra_set_sizemap( _session, _sizemap );
669     if ( ret != STATUS_OK ) MG_Error( "unable to set sizemap");
670   }
671
672   //////////////////////////////////////////////////////////////////////////////////////////
673   // const char* file  =  "/tmp/ghs3d_IN.mesh";
674   // mesh_write_mesh( _tria_mesh,file);
675   // std::cout << std::endl << std::endl << "Write " << file << std::endl << std::endl << std::endl;
676
677   ret = tetra_compute_mesh( _session );
678   if ( ret != STATUS_OK ) return false;
679
680   ret = tetra_get_mesh( _session, &_tetra_mesh);
681   if (ret != STATUS_OK) MG_Error( "unable to get resulting mesh");
682
683   //////////////////////////////////////////////////////////////////////////////////////////
684   // {
685   //   const char* file  =  "/tmp/ghs3d_OUT.mesh";
686   //   mesh_write_mesh( _tetra_mesh,file);
687   //   std::cout << std::endl << std::endl << "Write " << file << std::endl << std::endl << std::endl;
688   // }
689   return true;
690 }
691
692
693 #endif // ifdef USE_MG_LIBS
694
695
696 //================================================================================
697 /*!
698  * \brief Constructor
699  */
700 //================================================================================
701
702 MG_Tetra_API::MG_Tetra_API(volatile bool& cancelled_flag, double& progress)
703 {
704   _useLib = false;
705 #ifdef USE_MG_LIBS
706   _useLib = true;
707   _libData = new LibData( cancelled_flag, progress );
708   _libData->Init();
709   if ( getenv("MG_TETRA_USE_EXE"))
710     _useLib = false;
711 #endif
712 }
713
714 //================================================================================
715 /*!
716  * \brief Destructor
717  */
718 //================================================================================
719
720 MG_Tetra_API::~MG_Tetra_API()
721 {
722 #ifdef USE_MG_LIBS
723   delete _libData;
724   _libData = 0;
725 #endif
726   std::set<int>::iterator id = _openFiles.begin();
727   for ( ; id != _openFiles.end(); ++id )
728     ::GmfCloseMesh( *id );
729   _openFiles.clear();
730 }
731
732 //================================================================================
733 /*!
734  * \brief Return the way of MG usage
735  */
736 //================================================================================
737
738 bool MG_Tetra_API::IsLibrary()
739 {
740   return _useLib;
741 }
742
743 //================================================================================
744 /*!
745  * \brief Switch to usage of MG-Tetra executable
746  */
747 //================================================================================
748
749 void MG_Tetra_API::SetUseExecutable()
750 {
751   _useLib = false;
752 }
753
754 //================================================================================
755 /*!
756  * \brief Compute the tetra mesh
757  *  \param [in] cmdLine - a command to run mg_tetra.exe
758  *  \return bool - Ok or not
759  */
760 //================================================================================
761
762 bool MG_Tetra_API::Compute( const std::string& cmdLine, std::string& errStr )
763 {
764   if ( _useLib ) {
765 #ifdef USE_MG_LIBS
766
767     // split cmdLine
768     std::istringstream strm( cmdLine );
769     std::istream_iterator<std::string> sIt( strm ), sEnd;
770     std::vector< std::string > args( sIt, sEnd );
771
772     // set parameters
773     std::string param, value;
774     for ( size_t i = 1; i < args.size(); ++i )
775     {
776       // look for a param name; it starts from "-"
777       param = args[i];
778       if ( param.size() < 2 || param[0] != '-')
779         continue;
780       while ( param[0] == '-')
781         param = param.substr( 1 );
782
783       value = "";
784       while ( i+1 < args.size() && args[i+1][0] != '-' )
785       {
786         if ( strncmp( "1>", args[i+1].c_str(), 2 ) == 0 )
787           break;
788         if ( !value.empty() ) value += " ";
789         value += args[++i];
790       }
791       if ( !_libData->SetParam( param, value ))
792         std::cout << "Warning: wrong param: '" << param <<"' = '" << value << "'" << std::endl;
793     }
794
795     // compute
796     bool ok =  _libData->Compute();
797
798     GetLog(); // write a log file
799     _logFile = ""; // not to write it again
800
801     return ok;
802 #endif
803   }
804
805   int err = system( cmdLine.c_str() ); // run
806
807   if ( err )
808     errStr = SMESH_Comment("system(mg-tetra.exe ...) command failed with error: ")
809       << strerror( errno );
810
811   return !err;
812
813 }
814
815 //================================================================================
816 /*!
817  * \brief Prepare for reading a mesh data
818  */
819 //================================================================================
820
821 int  MG_Tetra_API::GmfOpenMesh(const char* theFile, int rdOrWr, int * ver, int * dim)
822 {
823   if ( _useLib ) {
824 #ifdef USE_MG_LIBS
825     return 1;
826 #endif
827   }
828   int id = ::GmfOpenMesh(theFile, rdOrWr, ver, dim );
829   _openFiles.insert( id );
830   return id;
831 }
832
833 //================================================================================
834 /*!
835  * \brief Return nb of entities
836  */
837 //================================================================================
838
839 int MG_Tetra_API::GmfStatKwd( int iMesh, GmfKwdCod what )
840 {
841   if ( _useLib ) {
842 #ifdef USE_MG_LIBS
843     switch ( what )
844     {
845     case GmfSubDomainFromGeom: return _libData->ReadNbSubDomains();
846     case GmfVertices:          return _libData->ReadNbNodes();
847     case GmfEdges:             return _libData->ReadNbEdges();
848     case GmfTriangles:         return _libData->ReadNbTria();
849     case GmfQuadrilaterals:    return _libData->ReadNbQuads();
850     case GmfTetrahedra:        return _libData->ReadNbTetra();
851     case GmfHexahedra:         return _libData->ReadNbHexa();
852     default:                   return 0;
853     }
854     return 0;
855 #endif
856   }
857   return ::GmfStatKwd( iMesh, what );
858 }
859
860 //================================================================================
861 /*!
862  * \brief Prepare for reading some data
863  */
864 //================================================================================
865
866 void MG_Tetra_API::GmfGotoKwd( int iMesh, GmfKwdCod what )
867 {
868   if ( _useLib ) {
869 #ifdef USE_MG_LIBS
870     _libData->ResetCounter();
871     return;
872 #endif
873   }
874   ::GmfGotoKwd( iMesh, what );
875 }
876
877 //================================================================================
878 /*!
879  * \brief Return index of a domain identified by a triangle normal
880  *  \param [in] iMesh - mesh file index
881  *  \param [in] what - must be GmfSubDomainFromGeom
882  *  \param [out] nbNodes - nb nodes in a face
883  *  \param [out] faceInd - face index
884  *  \param [out] ori - face orientation
885  *  \param [out] domain - domain index
886  *  \param [in] dummy - an artificial param used to discriminate from GmfGetLin() reading
887  *              a triangle
888  */
889 //================================================================================
890
891 void MG_Tetra_API::GmfGetLin( int iMesh, GmfKwdCod what, int* nbNodes, int* faceInd, int* ori, int* domain, int dummy )
892 {
893   if ( _useLib ) {
894 #ifdef USE_MG_LIBS
895     _libData->ReadSubDomain( nbNodes, faceInd, ori, domain );
896     return;
897 #endif
898   }
899   ::GmfGetLin( iMesh, what, nbNodes, faceInd, ori, domain );
900 }
901
902 //================================================================================
903 /*!
904  * \brief Return coordinates of a next node
905  */
906 //================================================================================
907
908 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
909                              double* x, double* y, double *z, int* domain )
910 {
911   if ( _useLib ) {
912 #ifdef USE_MG_LIBS
913     _libData->ReadNodeXYZ( x, y, z, domain );
914     return;
915 #endif
916   }
917   ::GmfGetLin(iMesh, what, x, y, z, domain );
918 }
919
920 //================================================================================
921 /*!
922  * \brief Return coordinates of a next node
923  */
924 //================================================================================
925
926 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
927                              float* x, float* y, float *z, int* domain )
928 {
929   if ( _useLib ) {
930 #ifdef USE_MG_LIBS
931     double X,Y,Z;
932     _libData->ReadNodeXYZ( &X, &Y, &Z, domain );
933     *x = X;
934     *y = Y;
935     *z = Z;
936     return;
937 #endif
938   }
939   ::GmfGetLin(iMesh, what, x, y, z, domain );
940 }
941
942 //================================================================================
943 /*!
944  * \brief Return node index of a next corner
945  */
946 //================================================================================
947
948 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what, int* node )
949 {
950   if ( _useLib ) {
951 #ifdef USE_MG_LIBS
952     node = 0;
953     return;
954 #endif
955   }
956   ::GmfGetLin(iMesh, what, node );
957 }
958
959 //================================================================================
960 /*!
961  * \brief Return node indices of a next edge
962  */
963 //================================================================================
964
965 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what, int* node1, int* node2, int* domain )
966 {
967   if ( _useLib ) {
968 #ifdef USE_MG_LIBS
969     _libData->ReadEdgeNodes( node1, node2, domain );
970     return;
971 #endif
972   }
973   ::GmfGetLin( iMesh, what, node1, node2, domain );
974 }
975
976 //================================================================================
977 /*!
978  * \brief Return node indices of a next triangle
979  */
980 //================================================================================
981
982 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
983                              int* node1, int* node2, int* node3, int* domain )
984 {
985   if ( _useLib ) {
986 #ifdef USE_MG_LIBS
987     _libData->ReadTriaNodes( node1, node2, node3, domain );
988     return;
989 #endif
990   }
991   ::GmfGetLin(iMesh, what, node1, node2, node3, domain );
992 }
993
994 //================================================================================
995 /*!
996  * \brief Return node indices of a next tetrahedron or quadrangle
997  */
998 //================================================================================
999
1000 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
1001                              int* node1, int* node2, int* node3, int* node4, int* domain )
1002 {
1003   if ( _useLib ) {
1004 #ifdef USE_MG_LIBS
1005     if ( what == GmfQuadrilaterals )
1006       _libData->ReadQuadNodes( node1, node2, node3, node4, domain );
1007     else
1008       _libData->ReadTetraNodes( node1, node2, node3, node4, domain );
1009     return;
1010 #endif
1011   }
1012   ::GmfGetLin(iMesh, what, node1, node2, node3, node4, domain );
1013 }
1014
1015 //================================================================================
1016 /*!
1017  * \brief Return node indices of a next hexahedron
1018  */
1019 //================================================================================
1020
1021 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
1022                              int* node1, int* node2, int* node3, int* node4,
1023                              int* node5, int* node6, int* node7, int* node8,
1024                              int* domain )
1025 {
1026   if ( _useLib ) {
1027 #ifdef USE_MG_LIBS
1028     _libData->ReadHexaNodes( node1, node2, node3, node4,
1029                              node5, node6, node7, node8, domain );
1030     return;
1031 #endif
1032   }
1033   ::GmfGetLin(iMesh, what, node1, node2, node3, node4, node5, node6, node7, node8, domain );
1034 }
1035
1036 //================================================================================
1037 /*!
1038  * \brief Prepare for passing data to MeshGems
1039  */
1040 //================================================================================
1041
1042 int  MG_Tetra_API::GmfOpenMesh(const char* theFile, int rdOrWr, int ver, int dim)
1043 {
1044   if ( _useLib ) {
1045 #ifdef USE_MG_LIBS
1046     return 1;
1047 #endif
1048   }
1049   int id = ::GmfOpenMesh(theFile, rdOrWr, ver, dim);
1050   _openFiles.insert( id );
1051   return id;
1052 }
1053
1054 //================================================================================
1055 /*!
1056  * \brief Set number of entities
1057  */
1058 //================================================================================
1059
1060 void MG_Tetra_API::GmfSetKwd(int iMesh, GmfKwdCod what, int nb )
1061 {
1062   if ( _useLib ) {
1063 #ifdef USE_MG_LIBS
1064     switch ( what ) {
1065     case GmfVertices:          _libData->SetNbVertices( nb ); break;
1066     case GmfEdges:             _libData->SetNbEdges   ( nb ); break;
1067     case GmfRequiredEdges:     _libData->SetNbReqEdges( nb ); break;
1068     case GmfTriangles:         _libData->SetNbTria    ( nb ); break;
1069     case GmfRequiredTriangles: _libData->SetNbReqTria ( nb ); break;
1070     default:;
1071     }
1072     return;
1073 #endif
1074   }
1075   ::GmfSetKwd(iMesh, what, nb );
1076 }
1077
1078 //================================================================================
1079 /*!
1080  * \brief Add coordinates of a node
1081  */
1082 //================================================================================
1083
1084 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, double x, double y, double z, int domain)
1085 {
1086   if ( _useLib ) {
1087 #ifdef USE_MG_LIBS
1088     _libData->AddNode( x, y, z, domain );
1089     return;
1090 #endif
1091   }
1092   ::GmfSetLin(iMesh, what, x, y, z, domain);
1093 }
1094
1095 //================================================================================
1096 /*!
1097  * \brief Set number of field entities
1098  *  \param [in] iMesh - solution file index
1099  *  \param [in] what - solution type
1100  *  \param [in] nbNodes - nb of entities
1101  *  \param [in] nbTypes - nb of data entries in each entity
1102  *  \param [in] type - types of the data entries
1103  *
1104  * Used to prepare to storing size at nodes
1105  */
1106 //================================================================================
1107
1108 void MG_Tetra_API::GmfSetKwd(int iMesh, GmfKwdCod what, int nbNodes, int dummy, int type[] )
1109 {
1110   if ( _useLib ) {
1111 #ifdef USE_MG_LIBS
1112     if ( what == GmfSolAtVertices ) _libData->SetNbReqVertices( nbNodes );
1113     return;
1114 #endif
1115   }
1116   ::GmfSetKwd(iMesh, what, nbNodes, dummy, type );
1117 }
1118
1119 //================================================================================
1120 /*!
1121  * \brief Add solution data
1122  */
1123 //================================================================================
1124
1125 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, double vals[])
1126 {
1127   if ( _useLib ) {
1128 #ifdef USE_MG_LIBS
1129     _libData->AddSizeAtNode( vals[0] );
1130     return;
1131 #endif
1132   }
1133   ::GmfSetLin(iMesh, what, vals);
1134 }
1135
1136 //================================================================================
1137 /*!
1138  * \brief Add edge nodes
1139  */
1140 //================================================================================
1141
1142 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, int node1, int node2, int domain )
1143 {
1144   if ( _useLib ) {
1145 #ifdef USE_MG_LIBS
1146     _libData->AddEdgeNodes( node1, node2, domain );
1147     return;
1148 #endif
1149   }
1150   ::GmfSetLin(iMesh, what, node1, node2, domain );
1151 }
1152
1153 //================================================================================
1154 /*!
1155  * \brief Add a 'required' flag
1156  */
1157 //================================================================================
1158
1159 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, int id )
1160 {
1161   if ( _useLib ) {
1162 #ifdef USE_MG_LIBS
1163     return;
1164 #endif
1165   }
1166   ::GmfSetLin(iMesh, what, id );
1167 }
1168
1169 //================================================================================
1170 /*!
1171  * \brief Add triangle nodes
1172  */
1173 //================================================================================
1174
1175 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, int node1, int node2, int node3, int domain )
1176 {
1177   if ( _useLib ) {
1178 #ifdef USE_MG_LIBS
1179     _libData->AddTriaNodes( node1, node2, node3, domain );
1180     return;
1181 #endif
1182   }
1183   ::GmfSetLin(iMesh, what, node1, node2, node3, domain );
1184 }
1185
1186 //================================================================================
1187 /*!
1188  * \brief Add tetra nodes
1189  */
1190 //================================================================================
1191
1192 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what,
1193                              int node1, int node2, int node3, int node4, int domain )
1194 {
1195   if ( _useLib ) {
1196 #ifdef USE_MG_LIBS
1197     _libData->AddTetraNodes( node1, node2, node3, node4, domain );
1198     return;
1199 #endif
1200   }
1201   ::GmfSetLin(iMesh, what, node1, node2, node3, node4, domain );
1202 }
1203
1204 //================================================================================
1205 /*!
1206  * \brief Close a file
1207  */
1208 //================================================================================
1209
1210 void MG_Tetra_API::GmfCloseMesh( int iMesh )
1211 {
1212   if ( _useLib ) {
1213 #ifdef USE_MG_LIBS
1214     return;
1215 #endif
1216   }
1217   ::GmfCloseMesh( iMesh );
1218   _openFiles.erase( iMesh );
1219 }
1220
1221 //================================================================================
1222 /*!
1223  * \brief Return true if the log is not empty
1224  */
1225 //================================================================================
1226
1227 bool MG_Tetra_API::HasLog()
1228 {
1229   if ( _useLib ) {
1230 #ifdef USE_MG_LIBS
1231     return !_libData->GetErrors().empty();
1232 #endif
1233   }
1234   SMESH_File file( _logFile );
1235   return file.size() > 0;
1236 }
1237
1238 //================================================================================
1239 /*!
1240  * \brief Return log contents
1241  */
1242 //================================================================================
1243
1244 std::string MG_Tetra_API::GetLog()
1245 {
1246   if ( _useLib ) {
1247 #ifdef USE_MG_LIBS
1248     const std::string& err = _libData->GetErrors();
1249     if ( !_logFile.empty() && !err.empty() )
1250     {
1251       SMESH_File file( _logFile, /*openForReading=*/false );
1252       file.openForWriting();
1253       file.write( err.c_str(), err.size() );
1254     }
1255     return err;
1256 #endif
1257   }
1258   SMESH_File file( _logFile );
1259   return file.getPos();
1260 }