Salome HOME
bos #24596 [CEA] New MeshGems license
[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     const_cast< std::string& >( cmdLine ) += " --key " + key;
843   }
844
845   int err = system( cmdLine.c_str() ); // run
846
847   if ( err )
848     errStr = SMESH_Comment("system(mg-tetra.exe ...) command failed with error: ")
849       << strerror( errno );
850
851   return !err;
852
853 }
854
855 //================================================================================
856 /*!
857  * \brief Prepare for reading a mesh data
858  */
859 //================================================================================
860
861 int  MG_Tetra_API::GmfOpenMesh(const char* theFile, int rdOrWr, int * ver, int * dim)
862 {
863   if ( _useLib ) {
864 #ifdef USE_MG_LIBS
865     return 1;
866 #endif
867   }
868   int id = ::GmfOpenMesh(theFile, rdOrWr, ver, dim );
869   _openFiles.insert( id );
870   return id;
871 }
872
873 //================================================================================
874 /*!
875  * \brief Return nb of entities
876  */
877 //================================================================================
878
879 int MG_Tetra_API::GmfStatKwd( int iMesh, GmfKwdCod what )
880 {
881   if ( _useLib ) {
882 #ifdef USE_MG_LIBS
883     switch ( what )
884     {
885     case GmfSubDomainFromGeom: return _libData->ReadNbSubDomains();
886     case GmfVertices:          return _libData->ReadNbNodes();
887     case GmfEdges:             return _libData->ReadNbEdges();
888     case GmfTriangles:         return _libData->ReadNbTria();
889     case GmfQuadrilaterals:    return _libData->ReadNbQuads();
890     case GmfTetrahedra:        return _libData->ReadNbTetra();
891     case GmfHexahedra:         return _libData->ReadNbHexa();
892     default:                   return 0;
893     }
894     return 0;
895 #endif
896   }
897   return ::GmfStatKwd( iMesh, what );
898 }
899
900 //================================================================================
901 /*!
902  * \brief Prepare for reading some data
903  */
904 //================================================================================
905
906 void MG_Tetra_API::GmfGotoKwd( int iMesh, GmfKwdCod what )
907 {
908   if ( _useLib ) {
909 #ifdef USE_MG_LIBS
910     _libData->ResetCounter();
911     return;
912 #endif
913   }
914   ::GmfGotoKwd( iMesh, what );
915 }
916
917 //================================================================================
918 /*!
919  * \brief Return index of a domain identified by a triangle normal
920  *  \param [in] iMesh - mesh file index
921  *  \param [in] what - must be GmfSubDomainFromGeom
922  *  \param [out] nbNodes - nb nodes in a face
923  *  \param [out] faceInd - face index
924  *  \param [out] ori - face orientation
925  *  \param [out] domain - domain index
926  *  \param [in] dummy - an artificial param used to discriminate from GmfGetLin() reading
927  *              a triangle
928  */
929 //================================================================================
930
931 void MG_Tetra_API::GmfGetLin( int iMesh, GmfKwdCod what, int* nbNodes, int* faceInd, int* ori, int* domain, int /*dummy*/ )
932 {
933   if ( _useLib ) {
934 #ifdef USE_MG_LIBS
935     _libData->ReadSubDomain( nbNodes, faceInd, ori, domain );
936     return;
937 #endif
938   }
939   ::GmfGetLin( iMesh, what, nbNodes, faceInd, ori, domain );
940 }
941
942 //================================================================================
943 /*!
944  * \brief Return coordinates of a next node
945  */
946 //================================================================================
947
948 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
949                              double* x, double* y, double *z, int* domain )
950 {
951   if ( _useLib ) {
952 #ifdef USE_MG_LIBS
953     _libData->ReadNodeXYZ( x, y, z, domain );
954     return;
955 #endif
956   }
957   ::GmfGetLin(iMesh, what, x, y, z, domain );
958 }
959
960 //================================================================================
961 /*!
962  * \brief Return coordinates of a next node
963  */
964 //================================================================================
965
966 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
967                              float* x, float* y, float *z, int* domain )
968 {
969   if ( _useLib ) {
970 #ifdef USE_MG_LIBS
971     double X,Y,Z;
972     _libData->ReadNodeXYZ( &X, &Y, &Z, domain );
973     *x = X;
974     *y = Y;
975     *z = Z;
976     return;
977 #endif
978   }
979   ::GmfGetLin(iMesh, what, x, y, z, domain );
980 }
981
982 //================================================================================
983 /*!
984  * \brief Return node index of a next corner
985  */
986 //================================================================================
987
988 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what, int* node )
989 {
990   if ( _useLib ) {
991 #ifdef USE_MG_LIBS
992     node = 0;
993     return;
994 #endif
995   }
996   ::GmfGetLin(iMesh, what, node );
997 }
998
999 //================================================================================
1000 /*!
1001  * \brief Return node indices of a next edge
1002  */
1003 //================================================================================
1004
1005 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what, int* node1, int* node2, int* domain )
1006 {
1007   if ( _useLib ) {
1008 #ifdef USE_MG_LIBS
1009     _libData->ReadEdgeNodes( node1, node2, domain );
1010     return;
1011 #endif
1012   }
1013   ::GmfGetLin( iMesh, what, node1, node2, domain );
1014 }
1015
1016 //================================================================================
1017 /*!
1018  * \brief Return node indices of a next triangle
1019  */
1020 //================================================================================
1021
1022 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
1023                              int* node1, int* node2, int* node3, int* domain )
1024 {
1025   if ( _useLib ) {
1026 #ifdef USE_MG_LIBS
1027     _libData->ReadTriaNodes( node1, node2, node3, domain );
1028     return;
1029 #endif
1030   }
1031   ::GmfGetLin(iMesh, what, node1, node2, node3, domain );
1032 }
1033
1034 //================================================================================
1035 /*!
1036  * \brief Return node indices of a next tetrahedron or quadrangle
1037  */
1038 //================================================================================
1039
1040 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
1041                              int* node1, int* node2, int* node3, int* node4, int* domain )
1042 {
1043   if ( _useLib ) {
1044 #ifdef USE_MG_LIBS
1045     if ( what == GmfQuadrilaterals )
1046       _libData->ReadQuadNodes( node1, node2, node3, node4, domain );
1047     else
1048       _libData->ReadTetraNodes( node1, node2, node3, node4, domain );
1049     return;
1050 #endif
1051   }
1052   ::GmfGetLin(iMesh, what, node1, node2, node3, node4, domain );
1053 }
1054
1055 //================================================================================
1056 /*!
1057  * \brief Return node indices of a next hexahedron
1058  */
1059 //================================================================================
1060
1061 void MG_Tetra_API::GmfGetLin(int iMesh, GmfKwdCod what,
1062                              int* node1, int* node2, int* node3, int* node4,
1063                              int* node5, int* node6, int* node7, int* node8,
1064                              int* domain )
1065 {
1066   if ( _useLib ) {
1067 #ifdef USE_MG_LIBS
1068     _libData->ReadHexaNodes( node1, node2, node3, node4,
1069                              node5, node6, node7, node8, domain );
1070     return;
1071 #endif
1072   }
1073   ::GmfGetLin(iMesh, what, node1, node2, node3, node4, node5, node6, node7, node8, domain );
1074 }
1075
1076 //================================================================================
1077 /*!
1078  * \brief Prepare for passing data to MeshGems
1079  */
1080 //================================================================================
1081
1082 int  MG_Tetra_API::GmfOpenMesh(const char* theFile, int rdOrWr, int ver, int dim)
1083 {
1084   if ( _useLib ) {
1085 #ifdef USE_MG_LIBS
1086     return 1;
1087 #endif
1088   }
1089   int id = ::GmfOpenMesh(theFile, rdOrWr, ver, dim);
1090   _openFiles.insert( id );
1091   return id;
1092 }
1093
1094 //================================================================================
1095 /*!
1096  * \brief Set number of entities
1097  */
1098 //================================================================================
1099
1100 void MG_Tetra_API::GmfSetKwd(int iMesh, GmfKwdCod what, int nb )
1101 {
1102   if ( iMesh == 1 )
1103   {
1104     switch ( what ) {
1105     case GmfVertices:  _nbNodes = nb; break;
1106     case GmfEdges:     _nbEdges = nb; break;
1107     case GmfTriangles: _nbFaces = nb; break;
1108     default:;
1109     }
1110   }
1111
1112   if ( _useLib ) {
1113 #ifdef USE_MG_LIBS
1114     switch ( what ) {
1115     case GmfVertices:          _libData->SetNbVertices( nb ); break;
1116     case GmfEdges:             _libData->SetNbEdges   ( nb ); break;
1117     case GmfRequiredEdges:     _libData->SetNbReqEdges( nb ); break;
1118     case GmfTriangles:         _libData->SetNbTria    ( nb ); break;
1119     case GmfRequiredTriangles: _libData->SetNbReqTria ( nb ); break;
1120     default:;
1121     }
1122     return;
1123 #endif
1124   }
1125   ::GmfSetKwd(iMesh, what, nb );
1126 }
1127
1128 //================================================================================
1129 /*!
1130  * \brief Add coordinates of a node
1131  */
1132 //================================================================================
1133
1134 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, double x, double y, double z, int domain)
1135 {
1136   if ( _useLib ) {
1137 #ifdef USE_MG_LIBS
1138     _libData->AddNode( x, y, z, domain );
1139     return;
1140 #endif
1141   }
1142   ::GmfSetLin(iMesh, what, x, y, z, domain);
1143 }
1144
1145 //================================================================================
1146 /*!
1147  * \brief Set number of field entities
1148  *  \param [in] iMesh - solution file index
1149  *  \param [in] what - solution type
1150  *  \param [in] nbNodes - nb of entities
1151  *  \param [in] nbTypes - nb of data entries in each entity
1152  *  \param [in] type - types of the data entries
1153  *
1154  * Used to prepare to storing size at nodes
1155  */
1156 //================================================================================
1157
1158 void MG_Tetra_API::GmfSetKwd(int iMesh, GmfKwdCod what, int nbNodes, int dummy, int type[] )
1159 {
1160   if ( _useLib ) {
1161 #ifdef USE_MG_LIBS
1162     if ( what == GmfSolAtVertices ) _libData->SetNbReqVertices( nbNodes );
1163     return;
1164 #endif
1165   }
1166   ::GmfSetKwd(iMesh, what, nbNodes, dummy, type );
1167 }
1168
1169 //================================================================================
1170 /*!
1171  * \brief Add solution data
1172  */
1173 //================================================================================
1174
1175 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, double vals[])
1176 {
1177   if ( _useLib ) {
1178 #ifdef USE_MG_LIBS
1179     _libData->AddSizeAtNode( vals[0] );
1180     return;
1181 #endif
1182   }
1183   ::GmfSetLin(iMesh, what, vals);
1184 }
1185
1186 //================================================================================
1187 /*!
1188  * \brief Add edge nodes
1189  */
1190 //================================================================================
1191
1192 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, int node1, int node2, int domain )
1193 {
1194   if ( _useLib ) {
1195 #ifdef USE_MG_LIBS
1196     _libData->AddEdgeNodes( node1, node2, domain );
1197     return;
1198 #endif
1199   }
1200   ::GmfSetLin(iMesh, what, node1, node2, domain );
1201 }
1202
1203 //================================================================================
1204 /*!
1205  * \brief Add a 'required' flag
1206  */
1207 //================================================================================
1208
1209 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, int id )
1210 {
1211   if ( _useLib ) {
1212 #ifdef USE_MG_LIBS
1213     return;
1214 #endif
1215   }
1216   ::GmfSetLin(iMesh, what, id );
1217 }
1218
1219 //================================================================================
1220 /*!
1221  * \brief Add triangle nodes
1222  */
1223 //================================================================================
1224
1225 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what, int node1, int node2, int node3, int domain )
1226 {
1227   if ( _useLib ) {
1228 #ifdef USE_MG_LIBS
1229     _libData->AddTriaNodes( node1, node2, node3, domain );
1230     return;
1231 #endif
1232   }
1233   ::GmfSetLin(iMesh, what, node1, node2, node3, domain );
1234 }
1235
1236 //================================================================================
1237 /*!
1238  * \brief Add tetra nodes
1239  */
1240 //================================================================================
1241
1242 void MG_Tetra_API::GmfSetLin(int iMesh, GmfKwdCod what,
1243                              int node1, int node2, int node3, int node4, int domain )
1244 {
1245   if ( _useLib ) {
1246 #ifdef USE_MG_LIBS
1247     _libData->AddTetraNodes( node1, node2, node3, node4, domain );
1248     return;
1249 #endif
1250   }
1251   ::GmfSetLin(iMesh, what, node1, node2, node3, node4, domain );
1252 }
1253
1254 //================================================================================
1255 /*!
1256  * \brief Close a file
1257  */
1258 //================================================================================
1259
1260 void MG_Tetra_API::GmfCloseMesh( int iMesh )
1261 {
1262   if ( _useLib ) {
1263 #ifdef USE_MG_LIBS
1264     return;
1265 #endif
1266   }
1267   ::GmfCloseMesh( iMesh );
1268   _openFiles.erase( iMesh );
1269 }
1270
1271 //================================================================================
1272 /*!
1273  * \brief Return true if the log is not empty
1274  */
1275 //================================================================================
1276
1277 bool MG_Tetra_API::HasLog()
1278 {
1279   if ( _useLib ) {
1280 #ifdef USE_MG_LIBS
1281     return !_libData->GetErrors().empty();
1282 #endif
1283   }
1284   SMESH_File file( _logFile );
1285   return file.size() > 0;
1286 }
1287
1288 //================================================================================
1289 /*!
1290  * \brief Return log contents
1291  */
1292 //================================================================================
1293
1294 std::string MG_Tetra_API::GetLog()
1295 {
1296   if ( _useLib ) {
1297 #ifdef USE_MG_LIBS
1298     const std::string& err = _libData->GetErrors();
1299     if ( !_logFile.empty() && !err.empty() )
1300     {
1301       SMESH_File file( _logFile, /*openForReading=*/false );
1302       file.openForWriting();
1303       file.write( err.c_str(), err.size() );
1304     }
1305     return err;
1306 #endif
1307   }
1308   SMESH_File file( _logFile );
1309   return file.getPos();
1310 }