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