]> SALOME platform Git repositories - plugins/gmshplugin.git/blob - src/GMSHPlugin/GMSHPlugin_Mesher.cxx
Salome HOME
#30450 [CEA][Windows][Forum] SHAPER activation after GMSHPLUGIN call
[plugins/gmshplugin.git] / src / GMSHPlugin / GMSHPlugin_Mesher.cxx
1 // Copyright (C) 2012-2015  ALNEOS
2 // Copyright (C) 2016-2022  EDF R&D
3 //
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Lesser General Public
6 // License as published by the Free Software Foundation; either
7 // version 2.1 of the License, or (at your option) any later version.
8 //
9 // This library is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 // Lesser General Public License for more details.
13 //
14 // You should have received a copy of the GNU Lesser General Public
15 // License along with this library; if not, write to the Free Software
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 //
18 // See http://www.alneos.com/ or email : contact@alneos.fr
19 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 //
21 #include "GMSHPlugin_Mesher.hxx"
22 #include "GMSHPlugin_Hypothesis_2D.hxx"
23
24 #include <SMDS_MeshElement.hxx>
25 #include <SMDS_MeshNode.hxx>
26 #include <SMESHDS_Mesh.hxx>
27 #include <SMESH_Comment.hxx>
28 #include <SMESH_ComputeError.hxx>
29 #include <SMESH_Gen_i.hxx>
30 #include <SMESH_Mesh.hxx>
31 #include <SMESH_MesherHelper.hxx>
32 #include <SMESH_subMesh.hxx>
33 #include <StdMeshers_FaceSide.hxx>
34 #include <utilities.h>
35
36 #include <vector>
37 #include <limits>
38
39 #include <TopExp_Explorer.hxx>
40 #include <TopoDS.hxx>
41
42 #include <MLine.h>
43 #include <MTriangle.h>
44 #include <MQuadrangle.h>
45 #if GMSH_MAJOR_VERSION >=4
46 #include <GmshGlobal.h>
47 #include <gmsh/Context.h>
48 #endif
49
50 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
51 #include <omp.h>
52 #endif
53
54 using namespace std;
55
56 namespace
57 {
58   struct ShapeBounds
59   {
60     SBoundingBox3d _bounds;
61     TopoDS_Shape   _shape;
62   };
63
64   //================================================================================
65   /*!
66    * \brief Retrieve ShapeBounds from a compound GEdge
67    */
68   //================================================================================
69
70   bool getBoundsOfShapes( GEdge*                       gEdge,
71                           std::vector< ShapeBounds > & topoEdges )
72   {
73     topoEdges.clear();
74 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
75     for ( size_t i = 0; i < gEdge->compound.size(); ++i )
76     {
77       GEdge* gE = static_cast< GEdge* >( gEdge->compound[ i ]);
78       topoEdges.push_back( ShapeBounds{ gE->bounds(), *((TopoDS_Edge*)gE->getNativePtr()) });
79     }
80 #else
81     for ( size_t i = 0; i < gEdge->_compound.size(); ++i )
82     {
83       GEdge* gE = static_cast< GEdge* >( gEdge->_compound[ i ]);
84       topoEdges.push_back( ShapeBounds{ gE->bounds(), *((TopoDS_Edge*)gE->getNativePtr()) });
85     }
86 #endif
87     return topoEdges.size();
88   }
89
90   //================================================================================
91   /*!
92    * \brief Retrieve ShapeBounds from a compound GFace
93    */
94   //================================================================================
95
96   bool getBoundsOfShapes( GFace*                       gFace,
97                           std::vector< ShapeBounds > & topoFaces )
98   {
99     topoFaces.clear();
100 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
101     for ( size_t i = 0; i < gFace->compound.size(); ++i )
102     {
103       GFace* gF = static_cast< GFace* >( gFace->compound[ i ]);
104       topoFaces.push_back( ShapeBounds{ gF->bounds(), *((TopoDS_Face*)gF->getNativePtr()) });
105     }
106 #else
107     for ( size_t i = 0; i < gFace->_compound.size(); ++i )
108     {
109       GFace* gF = static_cast< GFace* >( gFace->_compound[ i ]);
110       topoFaces.push_back( ShapeBounds{ gF->bounds(), *((TopoDS_Face*)gF->getNativePtr()) });
111     }
112 #endif
113     return topoFaces.size();
114   }
115   //================================================================================
116   /*!
117    * \brief Find a shape whose bounding box includes a given point
118    */
119   //================================================================================
120
121   TopoDS_Shape getShapeAtPoint( const SPoint3& point, const std::vector< ShapeBounds > & shapes )
122   {
123     TopoDS_Shape shape;
124     float distmin = std::numeric_limits<float>::max();
125     for ( size_t i = 0; i < shapes.size(); ++i )
126     {
127       float dist = GMSHPlugin_Mesher::DistBoundingBox( shapes[i]._bounds, point );
128       if (dist < distmin)
129       {
130         shape = shapes[i]._shape;
131         distmin = dist;
132         if ( distmin == 0. )
133           break;
134       }
135     }
136     return shape;
137   }
138
139   double segmentSize( const UVPtStructVec& nodeParam, size_t i )
140   {
141     double l1 = SMESH_NodeXYZ( nodeParam[i].node ).Distance( nodeParam[i-1].node );
142     double l2 = SMESH_NodeXYZ( nodeParam[i].node ).Distance( nodeParam[i+1].node );
143     return 0.5 * ( l1 + l2 );
144   }
145 }
146
147 //=============================================================================
148 /*!
149  *
150  */
151 //=============================================================================
152
153 GMSHPlugin_Mesher::GMSHPlugin_Mesher (SMESH_Mesh*         mesh,
154                                       const TopoDS_Shape& aShape,
155                                       bool                is2D)
156   : _mesh    (mesh),
157     _shape   (aShape),
158     _is2d    (is2D)
159 {
160   // il faudra peut être mettre un truc par defaut si l'utilisateur ne rentre rien en para
161   //defaultParameters();
162 }
163
164 //void GMSHPlugin_Mesher::defaultParameters(){}
165
166 void GMSHPlugin_Mesher::SetParameters(const GMSHPlugin_Hypothesis* hyp)
167 {
168   if (hyp != NULL)
169   {
170     _algo2d          = hyp->Get2DAlgo();
171     _algo3d          = hyp->Get3DAlgo();
172     _recomb2DAlgo    = hyp->GetRecomb2DAlgo();
173     _recombineAll    = hyp->GetRecombineAll();
174     _subdivAlgo      = hyp->GetSubdivAlgo();
175     _remeshAlgo      = hyp->GetRemeshAlgo();
176     _remeshPara      = hyp->GetRemeshPara();
177     _smouthSteps     = hyp->GetSmouthSteps();
178     _sizeFactor      = hyp->GetSizeFactor();
179     _minSize         = hyp->GetMinSize();
180     _maxSize         = hyp->GetMaxSize();
181     _secondOrder     = hyp->GetSecondOrder();
182     _useIncomplElem  = hyp->GetUseIncomplElem();
183     _compounds       = hyp->GetCompoundOnEntries();
184   }
185   else
186   {
187     _algo2d          = 0;
188     _algo3d          = 0;
189     _recomb2DAlgo    = 0;
190     _recombineAll    = false;
191     _subdivAlgo      = 0;
192     _remeshAlgo      = 0;
193     _remeshPara      = 0;
194     _smouthSteps     = 1;
195     _sizeFactor      = 1;
196     _minSize         = 0;
197     _maxSize         = 1e22;
198     _secondOrder     = false;
199     _useIncomplElem  = true;
200     _compounds.clear();
201   }
202 }
203
204
205 //================================================================================
206 /*!
207  * \brief Set maximum number of threads to be used by Gmsh
208  */
209 //================================================================================
210
211 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
212 void GMSHPlugin_Mesher::SetMaxThreadsGmsh()
213 {
214   MESSAGE("GMSHPlugin_Mesher::SetMaxThreadsGmsh");
215   if (_compounds.size() > 0)
216     _maxThreads = 1;
217   else
218     _maxThreads = omp_get_max_threads();
219 }
220 #endif
221
222 //================================================================================
223 /*!
224  * \brief Set Gmsh Options
225  */
226 //================================================================================
227
228 void GMSHPlugin_Mesher::SetGmshOptions()
229 {
230   MESSAGE("GMSHPlugin_Mesher::SetGmshOptions");
231   /*
232   printf("We chose _algo2d         %d \n", _algo2d        );
233   printf("We chose _algo3d         %d \n", _algo3d        );
234   printf("We chose _recomb2DAlgo   %d \n", _recomb2DAlgo  );
235   printf("We chose _recombineAll   %d \n", (_recombineAll)?1:0);
236   printf("We chose _subdivAlgo     %d \n", _subdivAlgo    );
237   printf("We chose _remeshAlgo     %d \n", _remeshAlgo    );
238   printf("We chose _remeshPara     %d \n", _remeshPara    );
239   printf("We chose _smouthSteps    %e \n", _smouthSteps   );
240   printf("We chose _sizeFactor     %e \n", _sizeFactor    );
241   printf("We chose _minSize        %e \n", _minSize       );
242   printf("We chose _maxSize        %e \n", _maxSize       );
243   printf("We chose _secondOrder    %d \n", (_secondOrder)?1:0);
244   printf("We chose _useIncomplElem %d \n", (_useIncomplElem)?1:0);
245   printf("We are in dimension      %d \n", (_is2d)?2:3);
246   //*/
247
248   std::map <int,double> mapAlgo2d;
249   mapAlgo2d[0]=2; // Automatic
250   mapAlgo2d[1]=1; // MeshAdapt
251   mapAlgo2d[2]=5; // Delaunay
252   mapAlgo2d[3]=6; // Frontal-Delaunay
253   mapAlgo2d[4]=8; // DelQuad (Frontal-Delaunay for Quads)
254   mapAlgo2d[5]=9; // Packing of parallelograms
255
256   std::map <int,double> mapAlgo3d;
257   mapAlgo3d[0]=1; // Delaunay
258   mapAlgo3d[1]=4; // Frontal
259   mapAlgo3d[2]=7; // MMG3D
260   mapAlgo3d[3]=9; // R-tree
261   mapAlgo3d[4]=10;// HXT
262
263   int ok;
264   ok = GmshSetOption("Mesh", "Algorithm"                , mapAlgo2d[_algo2d])    ;
265   ASSERT(ok);
266   if ( !_is2d)
267   {
268     ok = GmshSetOption("Mesh", "Algorithm3D"            , mapAlgo3d[_algo3d])    ;
269     ASSERT(ok);
270   }
271   ok = GmshSetOption("Mesh", "RecombinationAlgorithm"   , (double)_recomb2DAlgo) ;
272   ASSERT(ok);
273   ok = GmshSetOption("Mesh", "RecombineAll"             , (_recombineAll)?1.:0.) ;
274   ASSERT(ok);
275   ok = GmshSetOption("Mesh", "SubdivisionAlgorithm"     , (double)_subdivAlgo)   ;
276   ASSERT(ok);
277   ok = GmshSetOption("Mesh", "RemeshAlgorithm"          , (double)_remeshAlgo)   ;
278   //ASSERT(ok);
279   ok = GmshSetOption("Mesh", "RemeshParametrization"    , (double)_remeshPara)   ;
280   //ASSERT(ok);
281   ok = GmshSetOption("Mesh", "Smoothing"                , (double)_smouthSteps)  ;
282   //ASSERT(ok);
283 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
284   ok = GmshSetOption("Mesh", "MeshSizeFactor"              , _sizeFactor)     ;
285   ASSERT(ok);
286   ok = GmshSetOption("Mesh", "MeshSizeMin"                 , _minSize)        ;
287   ASSERT(ok);
288   ok = GmshSetOption("Mesh", "MeshSizeMax"                 , _maxSize)        ;
289   ASSERT(ok);
290 #else
291   ok = GmshSetOption("Mesh", "CharacteristicLengthFactor"  , _sizeFactor)     ;
292   ASSERT(ok);
293   ok = GmshSetOption("Mesh", "CharacteristicLengthMin"     , _minSize)        ;
294   ASSERT(ok);
295   ok = GmshSetOption("Mesh", "CharacteristicLengthMax"     , _maxSize)        ;
296   ASSERT(ok);
297 #endif
298   ok = GmshSetOption("Mesh", "ElementOrder"             , (_secondOrder)?2.:1.)  ;
299   ASSERT(ok);
300   if (_secondOrder)
301   {
302     ok = GmshSetOption("Mesh", "SecondOrderIncomplete"  ,(_useIncomplElem)?1.:0.);
303     ASSERT(ok);
304   }
305
306 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
307 /*ok = GmshSetOption("Mesh", "MaxNumThreads1D"          , 0. )  ; // Coarse-grain algo threads
308   ASSERT(ok);
309   ok = GmshSetOption("Mesh", "MaxNumThreads2D"          , 0. )  ; // Coarse-grain algo threads
310   ASSERT(ok);
311   ok = GmshSetOption("Mesh", "MaxNumThreads3D"          , 0. )  ; // Fine-grain algo threads HXT
312   ASSERT(ok);
313 **/
314   ok = GmshSetOption("General", "NumThreads"            , _maxThreads )  ; // system default i.e. OMP_NUM_THREADS
315   ASSERT(ok);
316 #endif
317 }
318
319 //================================================================================
320 /*!
321  * \brief Create and add Compounds into GModel _gModel.
322  */
323 //================================================================================
324
325 void GMSHPlugin_Mesher::CreateGmshCompounds()
326 {
327   MESSAGE("GMSHPlugin_Mesher::CreateGmshCompounds");
328
329   SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
330
331   OCC_Internals* occgeo = _gModel->getOCCInternals();
332   bool toSynchronize = false;
333
334   for(std::set<std::string>::const_iterator its = _compounds.begin();its != _compounds.end(); ++its )
335   {
336     GEOM::GEOM_Object_var aGeomObj;
337     TopoDS_Shape geomShape = TopoDS_Shape();
338     SALOMEDS::SObject_var aSObj = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( (*its).c_str() );
339     SALOMEDS::GenericAttribute_var anAttr;
340     if (!aSObj->_is_nil() && aSObj->FindAttribute(anAttr, "AttributeIOR"))
341     {
342       SALOMEDS::AttributeIOR_var anIOR = SALOMEDS::AttributeIOR::_narrow(anAttr);
343       CORBA::String_var aVal = anIOR->Value();
344       CORBA::Object_var obj = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->ConvertIORToObject(aVal);
345       aGeomObj = GEOM::GEOM_Object::_narrow(obj);
346     }
347     geomShape = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
348     if ( geomShape.IsNull() )
349       continue;
350
351     TopAbs_ShapeEnum geomType = geomShape.ShapeType();
352     if ( geomType == TopAbs_COMPOUND)// voir s'il ne faut pas mettre une erreur dans le cas contraire
353     {
354       MESSAGE("shapeType == TopAbs_COMPOUND");
355       TopoDS_Iterator it(geomShape);
356       if ( !it.More() )
357         continue;
358       TopAbs_ShapeEnum shapeType = it.Value().ShapeType();
359       std::vector< std::pair< int, int > > dimTags;
360       for ( ; it.More(); it.Next())
361       {
362         const TopoDS_Shape& topoShape = it.Value();
363         ASSERT(topoShape.ShapeType() == shapeType);
364         if ( _mesh->GetMeshDS()->ShapeToIndex( topoShape ) > 0 )
365           occgeo->importShapes( &topoShape, false, dimTags );
366         else
367         {
368           TopoDS_Shape face = TopExp_Explorer( _shape, shapeType ).Current();
369           SMESH_subMesh* sm = _mesh->GetSubMesh( face );
370           sm->GetComputeError() =
371             SMESH_ComputeError::New
372             ( COMPERR_WARNING, "Compound shape does not belong to the main geometry. Ignored");
373         }
374       }
375       std::vector<int> tags;
376       int dim = ( shapeType == TopAbs_EDGE ) ? 1 : 2;
377       for ( size_t i = 0; i < dimTags.size(); ++i )
378       {
379         if ( dimTags[i].first == dim )
380           tags.push_back( dimTags[i].second );
381       }
382       if ( !tags.empty() )
383       {
384         _gModel->getGEOInternals()->setCompoundMesh( dim, tags );
385         toSynchronize = true;
386       }
387       if ( toSynchronize )
388         _gModel->getGEOInternals()->synchronize(_gModel);
389     }
390   }
391 }
392
393 //================================================================================
394 /*!
395  * \brief For a compound mesh set the mesh components to be transmitted to SMESH
396  */
397 //================================================================================
398
399 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
400 void GMSHPlugin_Mesher::SetCompoundMeshVisibility()
401 {
402
403   // Loop over all faces, if the face belongs to a compound entry then
404   // for all (boundary) edges whithin the face visibility is set to 0,
405   // if the face doesn't belong to a compound entry then visibility is
406   // set to 1 for all its (boundary) edges. Later, in FillSMesh() func
407   // getVisibility() (returns either 1 or 0) is used to decide weather
408   // the mesh of edge should be transmitted  to SMESH or not.
409
410   for ( GModel::fiter itF = _gModel->firstFace(); itF != _gModel->lastFace(); ++itF )
411   {
412     std::vector< GEdge *> faceEdges = (*itF)->edges();
413
414     for ( auto itE = faceEdges.begin(); itE != faceEdges.end(); ++itE )
415     {
416       if ( ((*itF)->compound.size()) )
417         (*itE)->setVisibility(0);
418       else
419         (*itE)->setVisibility(1);
420     }
421   }
422
423
424   // Loop over all edges, if the  edge belongs to a compound entry then
425   // for all (boundary) vertices whithin the  edge visibility is set to
426   // 0, if the edge doesn't belong to a  compound entry then visibility
427   // is set to 1 for all its (boundary) vertices. Later, in FillSMesh()
428   // func getVisibility() (returns either 1 or 0) is used to decide we-
429   // ather the mesh of vertices should be transmitted  to SMESH or not.
430
431   for ( GModel::eiter itE = _gModel->firstEdge(); itE != _gModel->lastEdge(); ++itE )
432   {
433     std::vector<GVertex *> bndVerticies = (*itE)->vertices();
434
435     for( auto itV = bndVerticies.begin(); itV != bndVerticies.end(); ++itV )
436     {
437       if(((*itE)->compound.size()))
438         (*itV)->setVisibility(0);
439       else
440         (*itV)->setVisibility(1);
441     }
442   }
443
444 }
445 #endif
446
447 //================================================================================
448 /*!
449  * \brief Get a node by a GMSH mesh vertex
450  */
451 //================================================================================
452
453 const SMDS_MeshNode* GMSHPlugin_Mesher::Node( const MVertex* v )
454 {
455   std::map< const MVertex *, const SMDS_MeshNode* >::iterator v2n = _nodeMap.find( v );
456   if ( v2n != _nodeMap.end() )
457     return v2n->second;
458
459   return nullptr;
460 }
461
462 //================================================================================
463 /*!
464  * \brief Return a corresponding sub-mesh if a shape is meshed
465  */
466 //================================================================================
467
468 SMESHDS_SubMesh* GMSHPlugin_Mesher::HasSubMesh( const TopoDS_Shape& s )
469 {
470   if ( SMESHDS_SubMesh*  sm = _mesh->GetMeshDS()->MeshElements( s ))
471   {
472     if ( s.ShapeType() == TopAbs_VERTEX )
473       return ( sm->NbNodes() > 0 ) ? sm : nullptr;
474     else
475       return ( sm->NbElements() > 0 ) ? sm : nullptr;
476   }
477   return nullptr;
478 }
479
480 //================================================================================
481 /*!
482  * \brief Write mesh from GModel instance to SMESH instance
483  */
484 //================================================================================
485
486 void GMSHPlugin_Mesher::FillSMesh()
487 {
488   SMESHDS_Mesh* meshDS = _mesh->GetMeshDS();
489
490   // ADD 0D ELEMENTS
491   for ( GModel::viter it = _gModel->firstVertex(); it != _gModel->lastVertex(); ++it)
492   {
493     GVertex *gVertex = *it;
494
495     // GET topoVertex CORRESPONDING TO gVertex
496     TopoDS_Vertex topoVertex = *((TopoDS_Vertex*)gVertex->getNativePtr());
497
498     if (gVertex->getVisibility() == 0) // belongs to a compound
499     {
500       SMESH_subMesh* sm = _mesh->GetSubMesh(topoVertex);
501       sm->SetIsAlwaysComputed(true); // prevent from displaying errors
502       continue;
503     }
504
505     // FILL SMESH FOR topoVertex
506     //nodes
507     for( size_t i = 0; i < gVertex->mesh_vertices.size(); i++)
508     {
509       MVertex *v = gVertex->mesh_vertices[i];
510       if(v->getIndex() >= 0)
511       {
512         if ( SMESHDS_SubMesh* sm = HasSubMesh( topoVertex ))
513         {
514           const SMDS_MeshNode *node = sm->GetNodes()->next();
515           _nodeMap.insert({ v, node });
516         }
517         else
518         {
519           SMDS_MeshNode *node = meshDS->AddNode( v->x(),v->y(),v->z() );
520           meshDS->SetNodeOnVertex( node, topoVertex );
521           _nodeMap.insert({ v, node });
522         }
523       }
524     }
525     // WE DON'T ADD 0D ELEMENTS because it does not follow the salome meshers philosophy
526     //elements
527     // for(unsigned int i = 0; i < gVertex->getNumMeshElements(); i++)
528     // {
529     //   MElement *e = gVertex->getMeshElement(i);
530     //   std::vector<MVertex*> verts;
531     //   e->getVertices(verts);
532     //   ASSERT(verts.size()==1);
533     //   SMDS_Mesh0DElement* zeroDElement = 0;
534     //   zeroDElement = meshDS->Add0DElementWithID(verts[0]->getNum(),e->getNum());
535     //   meshDS->SetMeshElementOnShape(zeroDElement, topoVertex);
536     // }
537   }
538
539   // ADD 1D ELEMENTS
540   for(GModel::eiter it = _gModel->firstEdge(); it != _gModel->lastEdge(); ++it)
541   {
542     GEdge *gEdge = *it;
543
544     // GET topoEdge CORRESPONDING TO gEdge
545     TopoDS_Edge topoEdge;
546     std::vector< ShapeBounds > topoEdges;
547 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
548     if(gEdge->haveParametrization())
549 #else
550     if ( gEdge->geomType() != GEntity::CompoundCurve )
551 #endif
552     {
553       topoEdge = *((TopoDS_Edge*)gEdge->getNativePtr());
554       if (gEdge->getVisibility() == 0) // belongs to a compound
555       {
556         SMESH_subMesh* sm = _mesh->GetSubMesh(topoEdge);
557         sm->SetIsAlwaysComputed(true); // prevent from displaying errors
558         continue;
559       }
560       if ( HasSubMesh( topoEdge ))
561         continue; // a meshed sub-mesh
562     }
563     bool isCompound = getBoundsOfShapes( gEdge, topoEdges );
564
565     // FILL SMESH FOR topoEdge
566     //nodes
567     for ( size_t i = 0; i < gEdge->mesh_vertices.size(); i++ )
568     {
569       MVertex *v = gEdge->mesh_vertices[i];
570       if ( v->getIndex() >= 0 )
571       {
572         SMDS_MeshNode *node = meshDS->AddNode( v->x(),v->y(),v->z() );
573
574         if ( isCompound )
575           topoEdge = TopoDS::Edge( getShapeAtPoint( v->point(), topoEdges ));
576
577         meshDS->SetNodeOnEdge( node, topoEdge );
578         _nodeMap.insert({ v, node });
579       }
580     }
581   }
582
583   for ( GModel::eiter it = _gModel->firstEdge(); it != _gModel->lastEdge(); ++it )
584   {
585     GEdge *gEdge = *it;
586     if ( gEdge->getVisibility() == 0) // belongs to a compound
587       continue;
588
589     TopoDS_Edge topoEdge;
590     std::vector< ShapeBounds > topoEdges;
591     bool isCompound = getBoundsOfShapes( gEdge, topoEdges );
592     if ( !isCompound )
593       topoEdge = *((TopoDS_Edge*)gEdge->getNativePtr());
594
595     if ( HasSubMesh( topoEdge ))
596       continue; // a meshed sub-mesh
597
598     //elements
599     std::vector<MVertex*> verts(3);
600     for ( size_t i = 0; i < gEdge->getNumMeshElements(); i++ )
601     {
602       MElement *e = gEdge->getMeshElement(i);
603       verts.clear();
604       e->getVertices(verts);
605
606       // if a node wasn't set, it is assigned here
607       for ( size_t j = 0; j < verts.size(); j++ )
608       {
609         if ( verts[j]->onWhat()->getVisibility() == 0 )
610         {
611           SMDS_MeshNode *node = meshDS->AddNode(verts[j]->x(),verts[j]->y(),verts[j]->z() );
612           meshDS->SetNodeOnEdge( node, topoEdge );
613           verts[j]->setEntity(gEdge);
614           _nodeMap.insert({ verts[j], node });
615         }
616       }
617
618       SMDS_MeshEdge* edge = 0;
619       switch (verts.size())
620       {
621         case 2:
622           edge = meshDS->AddEdge(Node( verts[0]),
623                                  Node( verts[1]));
624           break;
625         case 3:
626           edge = meshDS->AddEdge(Node( verts[0]),
627                                  Node( verts[1]),
628                                  Node( verts[2]));
629           break;
630         default:
631           ASSERT(false);
632           continue;
633       }
634       if ( isCompound )
635         topoEdge = TopoDS::Edge( getShapeAtPoint( e->barycenter(), topoEdges ));
636
637       meshDS->SetMeshElementOnShape( edge, topoEdge );
638     }
639   }
640
641   // ADD 2D ELEMENTS
642   for ( GModel::fiter it = _gModel->firstFace(); it != _gModel->lastFace(); ++it)
643   {
644     GFace *gFace = *it;
645
646 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
647     // Gmsh since version 4.3 is now producing extra surface and mesh when
648     // compounds are involved. Since in Gmsh meshing procedure needs acess
649     // to each of the original topology and the meshed topology. Hence  we
650     // bypass the additional mesh in case of compounds. Note, similar cri-
651     // teria also occurs in the following 'for' loop.
652     if ( _compounds.size() && gFace->geomType() == GEntity::DiscreteSurface )
653       continue;
654 #endif
655
656     // GET topoFace CORRESPONDING TO gFace
657     TopoDS_Face topoFace;
658     std::vector< ShapeBounds > topoFaces;
659
660 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
661     if(gFace->haveParametrization())
662 #else
663     if ( gFace->geomType() != GEntity::CompoundSurface )
664 #endif
665     {
666       topoFace = *((TopoDS_Face*)gFace->getNativePtr());
667       if (gFace->getVisibility() == 0) // belongs to a compound
668       {
669         SMESH_subMesh* sm = _mesh->GetSubMesh(topoFace);
670         sm->SetIsAlwaysComputed(true); // prevent from displaying errors
671         continue;
672       }
673       if ( HasSubMesh( topoFace ))
674         continue; // a meshed sub-mesh
675     }
676     bool isCompound = getBoundsOfShapes( gFace, topoFaces );
677
678     // FILL SMESH FOR topoFace
679     //nodes
680     for ( size_t i = 0; i < gFace->mesh_vertices.size(); i++ )
681     {
682       MVertex *v = gFace->mesh_vertices[i];
683       if ( v->getIndex() >= 0 )
684       {
685         SMDS_MeshNode *node = meshDS->AddNode( v->x(),v->y(),v->z() );
686
687         if ( isCompound )
688           topoFace = TopoDS::Face( getShapeAtPoint( v->point(), topoFaces ));
689
690         meshDS->SetNodeOnFace( node, topoFace );
691         _nodeMap.insert({ v, node });
692       }
693     }
694   }
695
696   for ( GModel::fiter it = _gModel->firstFace(); it != _gModel->lastFace(); ++it)
697   {
698     GFace *gFace = *it;
699
700 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
701     if ( _compounds.size() && gFace->geomType() == GEntity::DiscreteSurface )
702       continue;
703
704     bool isCompound = (!gFace->haveParametrization());
705 #else
706     bool isCompound = ( gFace->geomType() == GEntity::CompoundSurface );
707 #endif
708
709     if ( !isCompound && gFace->getVisibility() == 0 )
710       continue;  // belongs to a compound
711
712     TopoDS_Face topoFace;
713     std::vector< ShapeBounds > topoFaces;
714     if ( isCompound )
715       getBoundsOfShapes( gFace, topoFaces );
716     else
717       topoFace = *((TopoDS_Face*)gFace->getNativePtr());
718
719     if ( HasSubMesh( topoFace ))
720       continue; // a meshed sub-mesh
721
722     //elements
723     std::vector<MVertex*> verts;
724     for ( size_t i = 0; i < gFace->getNumMeshElements(); i++ )
725     {
726       MElement *e = gFace->getMeshElement(i);
727       verts.clear();
728       e->getVertices(verts);
729       SMDS_MeshFace* face = 0;
730
731       // if a node wasn't set, it is assigned here
732       for ( size_t j = 0; j < verts.size(); j++)
733       {
734         if(verts[j]->onWhat()->getVisibility() == 0)
735         {
736           SMDS_MeshNode *node = meshDS->AddNode(verts[j]->x(),verts[j]->y(),verts[j]->z());
737           meshDS->SetNodeOnFace( node, topoFace );
738           _nodeMap.insert({ verts[j], node });
739           verts[j]->setEntity(gFace);
740         }
741       }
742       switch (verts.size())
743       {
744         case 3:
745           face = meshDS->AddFace(Node( verts[0]),
746                                  Node( verts[1]),
747                                  Node( verts[2]));
748           break;
749         case 4:
750           face = meshDS->AddFace(Node( verts[0]),
751                                  Node( verts[1]),
752                                  Node( verts[2]),
753                                  Node( verts[3]));
754           break;
755         case 6:
756           face = meshDS->AddFace(Node( verts[0]),
757                                  Node( verts[1]),
758                                  Node( verts[2]),
759                                  Node( verts[3]),
760                                  Node( verts[4]),
761                                  Node( verts[5]));
762           break;
763         case 8:
764           face = meshDS->AddFace(Node( verts[0]),
765                                  Node( verts[1]),
766                                  Node( verts[2]),
767                                  Node( verts[3]),
768                                  Node( verts[4]),
769                                  Node( verts[5]),
770                                  Node( verts[6]),
771                                  Node( verts[7]));
772           break;
773         case 9:
774           face = meshDS->AddFace(Node( verts[0]),
775                                  Node( verts[1]),
776                                  Node( verts[2]),
777                                  Node( verts[3]),
778                                  Node( verts[4]),
779                                  Node( verts[5]),
780                                  Node( verts[6]),
781                                  Node( verts[7]),
782                                  Node( verts[8]));
783           break;
784         default:
785           ASSERT(false);
786           continue;
787       }
788
789       if ( isCompound )
790         topoFace = TopoDS::Face( getShapeAtPoint( e->barycenter(), topoFaces ));
791
792       meshDS->SetMeshElementOnShape(face, topoFace);
793     }
794   }
795
796   // ADD 3D ELEMENTS
797   for ( GModel::riter it = _gModel->firstRegion(); it != _gModel->lastRegion(); ++it)
798   {
799     GRegion *gRegion = *it;
800     if (gRegion->getVisibility() == 0)
801       continue;
802
803     // GET topoSolid CORRESPONDING TO gRegion
804     TopoDS_Solid topoSolid = *((TopoDS_Solid*)gRegion->getNativePtr());
805
806     // FILL SMESH FOR topoSolid
807
808     //nodes
809     for( size_t i = 0; i < gRegion->mesh_vertices.size(); i++)
810     {
811       MVertex *v = gRegion->mesh_vertices[i];
812       if(v->getIndex() >= 0)
813       {
814         SMDS_MeshNode *node = meshDS->AddNode( v->x(),v->y(),v->z() );
815         meshDS->SetNodeInVolume( node, topoSolid );
816         _nodeMap.insert({ v, node });
817       }
818     }
819
820     //elements
821     std::vector<MVertex*> verts;
822     for( size_t i = 0; i < gRegion->getNumMeshElements(); i++)
823     {
824       MElement *e = gRegion->getMeshElement(i);
825       verts.clear();
826       e->getVertices(verts);
827       SMDS_MeshVolume* volume = 0;
828       switch (verts.size()){
829       case 4:
830         volume = meshDS->AddVolume(Node( verts[0]),
831                                    Node( verts[2]),
832                                    Node( verts[1]),
833                                    Node( verts[3]));
834         break;
835       case 5:
836         volume = meshDS->AddVolume(Node( verts[0]),
837                                    Node( verts[3]),
838                                    Node( verts[2]),
839                                    Node( verts[1]),
840                                    Node( verts[4]));
841         break;
842       case 6:
843         volume = meshDS->AddVolume(Node( verts[0]),
844                                    Node( verts[2]),
845                                    Node( verts[1]),
846                                    Node( verts[3]),
847                                    Node( verts[5]),
848                                    Node( verts[4]));
849         break;
850       case 8:
851         volume = meshDS->AddVolume(Node( verts[0]),
852                                    Node( verts[3]),
853                                    Node( verts[2]),
854                                    Node( verts[1]),
855                                    Node( verts[4]),
856                                    Node( verts[7]),
857                                    Node( verts[6]),
858                                    Node( verts[5]));
859         break;
860       case 10:
861         volume = meshDS->AddVolume(Node( verts[0]),
862                                    Node( verts[2]),
863                                    Node( verts[1]),
864                                    Node( verts[3]),
865                                    Node( verts[6]),
866                                    Node( verts[5]),
867                                    Node( verts[4]),
868                                    Node( verts[7]),
869                                    Node( verts[8]),
870                                    Node( verts[9]));
871         break;
872       case 13:
873         volume = meshDS->AddVolume(Node( verts[0] ),
874                                    Node( verts[3] ),
875                                    Node( verts[2] ),
876                                    Node( verts[1] ),
877                                    Node( verts[4] ),
878                                    Node( verts[6] ),
879                                    Node( verts[10] ),
880                                    Node( verts[8] ),
881                                    Node( verts[5] ),
882                                    Node( verts[7] ),
883                                    Node( verts[12] ),
884                                    Node( verts[11] ),
885                                    Node( verts[9]));
886         break;
887       case 14: // same as case 13, because no pyra14 in smesh
888         volume = meshDS->AddVolume(Node( verts[0] ),
889                                    Node( verts[3] ),
890                                    Node( verts[2] ),
891                                    Node( verts[1] ),
892                                    Node( verts[4] ),
893                                    Node( verts[6] ),
894                                    Node( verts[10] ),
895                                    Node( verts[8] ),
896                                    Node( verts[5] ),
897                                    Node( verts[7] ),
898                                    Node( verts[12] ),
899                                    Node( verts[11] ),
900                                    Node( verts[9]));
901         break;
902       case 15:
903         volume = meshDS->AddVolume(Node( verts[0] ),
904                                    Node( verts[2] ),
905                                    Node( verts[1] ),
906                                    Node( verts[3] ),
907                                    Node( verts[5] ),
908                                    Node( verts[4] ),
909                                    Node( verts[7] ),
910                                    Node( verts[9] ),
911                                    Node( verts[6] ),
912                                    Node( verts[13] ),
913                                    Node( verts[14] ),
914                                    Node( verts[12] ),
915                                    Node( verts[8] ),
916                                    Node( verts[11] ),
917                                    Node( verts[10]));
918         break;
919       case 18: // same as case 15, because no penta18 in smesh
920         volume = meshDS->AddVolume(Node( verts[0] ),
921                                    Node( verts[2] ),
922                                    Node( verts[1] ),
923                                    Node( verts[3] ),
924                                    Node( verts[5] ),
925                                    Node( verts[4] ),
926                                    Node( verts[7] ),
927                                    Node( verts[9] ),
928                                    Node( verts[6] ),
929                                    Node( verts[13] ),
930                                    Node( verts[14] ),
931                                    Node( verts[12] ),
932                                    Node( verts[8] ),
933                                    Node( verts[11] ),
934                                    Node( verts[10]));
935         break;
936       case 20:
937         volume = meshDS->AddVolume(Node( verts[0] ),
938                                    Node( verts[3] ),
939                                    Node( verts[2] ),
940                                    Node( verts[1] ),
941                                    Node( verts[4] ),
942                                    Node( verts[7] ),
943                                    Node( verts[6] ),
944                                    Node( verts[5] ),
945                                    Node( verts[9] ),
946                                    Node( verts[13] ),
947                                    Node( verts[11] ),
948                                    Node( verts[8] ),
949                                    Node( verts[17] ),
950                                    Node( verts[19] ),
951                                    Node( verts[18] ),
952                                    Node( verts[16] ),
953                                    Node( verts[10] ),
954                                    Node( verts[15] ),
955                                    Node( verts[14] ),
956                                    Node( verts[12]));
957         break;
958       case 27:
959         volume = meshDS->AddVolume(Node( verts[0] ),
960                                    Node( verts[3] ),
961                                    Node( verts[2] ),
962                                    Node( verts[1] ),
963                                    Node( verts[4] ),
964                                    Node( verts[7] ),
965                                    Node( verts[6] ),
966                                    Node( verts[5] ),
967                                    Node( verts[9] ),
968                                    Node( verts[13] ),
969                                    Node( verts[11] ),
970                                    Node( verts[8] ),
971                                    Node( verts[17] ),
972                                    Node( verts[19] ),
973                                    Node( verts[18] ),
974                                    Node( verts[16] ),
975                                    Node( verts[10] ),
976                                    Node( verts[15] ),
977                                    Node( verts[14] ),
978                                    Node( verts[12] ),
979                                    Node( verts[20] ),
980                                    Node( verts[22] ),
981                                    Node( verts[24] ),
982                                    Node( verts[23] ),
983                                    Node( verts[21] ),
984                                    Node( verts[25] ),
985                                    Node( verts[26] ));
986         break;
987       default:
988         ASSERT(false);
989         continue;
990       }
991       meshDS->SetMeshElementOnShape(volume, topoSolid);
992     }
993   }
994
995   //return 0;
996 }
997
998 //================================================================================
999 /*!
1000  * \brief Find if SPoint point is in SBoundingBox3d bounds
1001  */
1002 //================================================================================
1003
1004 float GMSHPlugin_Mesher::DistBoundingBox(const SBoundingBox3d& bounds, const SPoint3& point)
1005 {
1006   SPoint3 min = bounds.min();
1007   SPoint3 max = bounds.max();
1008
1009   float x,y,z;
1010
1011   if (point.x() < min.x())
1012     x = min.x()-point.x();
1013   else if (point.x() > max.x())
1014     x = point.x()-max.x();
1015   else
1016     x = 0.;
1017
1018   if (point.y() < min.y())
1019     y = min.y()-point.y();
1020   else if (point.y() > max.y())
1021     y = point.y()-max.y();
1022   else
1023     y = 0.;
1024
1025   if (point.z() < min.z())
1026     z = min.z()-point.z();
1027   else if (point.z() > max.z())
1028     z = point.z()-max.z();
1029   else
1030     z = 0.;
1031
1032   return x*x+y*y+z*z;
1033 }
1034 //================================================================================
1035 /*!
1036  * \brief Reimplemented GmshMessage call. Actions done if errors occurs
1037  *        during gmsh meshing. We define here what to display and what to do.
1038  */
1039 //================================================================================
1040 void  GMSHPlugin_Mesher::mymsg::operator()(std::string level, std::string msg)
1041 {
1042   //MESSAGE("level="<< level.c_str() << ", msg=" << msg.c_str()<< "\n");
1043   printf("level=%s msg=%s\n", level.c_str(), msg.c_str());
1044
1045   if(level == "Fatal" || level == "Error")
1046   {
1047     std::ostringstream oss;
1048     if (level == "Fatal")
1049       oss << "Fatal error during Generation of Gmsh Mesh\n";
1050     else
1051       oss << "Error during Generation of Gmsh Mesh\n";
1052     oss << "  " << msg.c_str() << "\n";
1053     GEntity *e = _gModel->getCurrentMeshEntity();
1054     if(e)
1055     {
1056       oss << "  error occurred while meshing entity:\n" <<
1057              "    tag=" << e->tag() << "\n" <<
1058              "    dimension=" << e->dim() << "\n" <<
1059              "    native pointer=" << e->getNativePtr();
1060       //if(e->geomType() != GEntity::CompoundCurve and e->geomType() != GEntity::CompoundSurface)
1061       //{
1062         //SMESH_subMesh *sm = _mesh->GetSubMesh(*((TopoDS_Shape*)e->getNativePtr()));
1063         //SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
1064         //SMESH_Comment comment;
1065         //comment << SMESH_Comment(oss.str);
1066         //std::string str = oss.str();
1067         //smError.reset( new SMESH_ComputeError( str ));
1068
1069         // plutot que de faire de la merde ici, on pourait simplement
1070         // remplir une liste pour dire sur quelles entités gmsh se plante
1071         // (puis faire le fillsmesh)
1072         // puis faire une nouvelle routine qui réécrit les messages d'erreur
1073         // probleme : gmsh peut planté en Fatal, dans ce cas pas de fillsmesh
1074       //}
1075     }
1076     if (level == "Fatal")
1077     {
1078         CTX::instance()->lock = 0;
1079         throw oss.str();
1080     }
1081     else
1082         printf("%s\n", oss.str().c_str());
1083   }
1084 }
1085
1086 //=============================================================================
1087 /*!
1088  * Here we are going to use the GMSH mesher
1089  */
1090 //=============================================================================
1091
1092 bool GMSHPlugin_Mesher::Compute()
1093 {
1094   MESSAGE("GMSHPlugin_Mesher::Compute");
1095
1096   int err = 0;
1097
1098 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
1099   SetMaxThreadsGmsh();
1100 #endif
1101   //RNV: to avoid modification of PATH and PYTHONPATH
1102   char* argv[] = {"-noenv"};
1103   GmshInitialize(1,argv);
1104   SetGmshOptions();
1105   _gModel = new GModel();
1106   mymsg msg(_gModel);
1107   GmshSetMessageHandler(&msg);
1108   _gModel->importOCCShape((void*)&_shape);
1109   if (_compounds.size() > 0) CreateGmshCompounds();
1110   try
1111   {
1112     //Msg::SetVerbosity(100);
1113     //CTX::instance()->mesh.maxNumThreads1D=1;
1114
1115     HideComputedEntities( _gModel );
1116
1117     _gModel->mesh( /*dim=*/ 1 );
1118
1119     Set1DSubMeshes( _gModel );
1120
1121     //_gModel->writeUNV("/tmp/1D.unv", 1,0,0);
1122     //CTX::instance()->mesh.maxNumThreads2D=1;
1123
1124     _gModel->mesh( /*dim=*/ 2 );
1125
1126     if ( !_is2d )
1127     {
1128       Set2DSubMeshes( _gModel );
1129
1130       //CTX::instance()->mesh.maxNumThreads3D=1;
1131
1132       _gModel->mesh( /*dim=*/ 3 );
1133     }
1134     RestoreVisibility( _gModel );
1135
1136 #ifdef WITH_SMESH_CANCEL_COMPUTE
1137
1138 #endif
1139   }
1140   catch (std::string& str)
1141   {
1142     err = 1;
1143     std::cerr << "GMSH: exception caught: " << str << std::endl;
1144     MESSAGE(str);
1145   }
1146   catch (...)
1147   {
1148     err = 1;
1149     std::cerr << "GMSH: Unknown exception caught: " << std::endl;
1150     MESSAGE("Unrecoverable error during Generation of Gmsh Mesh");
1151   }
1152
1153   if (!err)
1154   {
1155 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
1156     if (_compounds.size() > 0)
1157       SetCompoundMeshVisibility();
1158 #endif
1159     FillSMesh();
1160   }
1161   GmshSetMessageHandler(nullptr);
1162   delete _gModel;
1163   GmshFinalize();
1164   MESSAGE("GMSHPlugin_Mesher::Compute:End");
1165   return !err;
1166 }
1167
1168 //================================================================================
1169 /*!
1170  * \brief Set 1D sub-meshes to GModel. GMSH 1D mesh is made by now.
1171  *  \param [inout] _gModel - GMSH model
1172  */
1173 //================================================================================
1174
1175 void GMSHPlugin_Mesher::Set1DSubMeshes( GModel* gModel )
1176 {
1177   SMESHDS_Mesh* meshDS = _mesh->GetMeshDS();
1178
1179   for(GModel::eiter it = gModel->firstEdge(); it != gModel->lastEdge(); ++it)
1180   {
1181     GEdge *gEdge = *it;
1182
1183 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
1184     if ( !gEdge->haveParametrization())
1185 #else
1186     if ( gEdge->geomType() == GEntity::CompoundCurve )
1187 #endif
1188       continue;
1189     
1190     TopoDS_Edge topoEdge = *((TopoDS_Edge*)gEdge->getNativePtr());
1191     if ( !HasSubMesh( topoEdge ))
1192       continue; // empty sub-mesh
1193
1194     gEdge->deleteMesh();
1195
1196     // get node parameters on topoEdge
1197     StdMeshers_FaceSide side( TopoDS_Face(), topoEdge, _mesh, /*fwd=*/true, /*skpMedium=*/true);
1198     const UVPtStructVec& nodeParam = side.GetUVPtStruct();
1199     if ( nodeParam.empty() )
1200       throw std::string("Pb with StdMeshers_FaceSide::GetUVPtStruct()");
1201
1202     // get GMSH mesh vertices on VERTEX'es
1203     std::vector<MVertex *> mVertices( nodeParam.size(), nullptr );
1204     GVertex * gV0 = gEdge->getBeginVertex(), *gV1 = gEdge->getEndVertex();
1205     mVertices[0]     = gV0->mesh_vertices[ 0 ];
1206     mVertices.back() = gV1->mesh_vertices[ 0 ];
1207     TopoDS_Vertex v01 = *((TopoDS_Vertex*) gV0->getNativePtr());
1208     TopoDS_Shape  v02 = SMESH_MesherHelper::GetSubShapeByNode( nodeParam[0].node, meshDS );
1209     bool      reverse = !v01.IsSame( v02 );
1210     if ( mVertices[0] == mVertices.back() )
1211       reverse = ( nodeParam[0].param > nodeParam.back().param );
1212     const SMDS_MeshNode* n0 = reverse ? nodeParam.back().node : nodeParam[0].node;
1213     const SMDS_MeshNode* n1 = reverse ? nodeParam[0].node : nodeParam.back().node;
1214     _nodeMap.insert({ mVertices[ 0 ],   n0 });
1215     _nodeMap.insert({ mVertices.back(), n1 });
1216
1217     // create GMSH mesh vertices on gEdge
1218     for ( size_t i = 1; i < nodeParam.size() - 1; ++i )
1219     {
1220       size_t iN = reverse ? ( nodeParam.size() - 1 - i ) : i;
1221       SMESH_NodeXYZ xyz = nodeParam[ iN ].node;
1222       double lc = segmentSize( nodeParam, iN );
1223       // SVector3 der = gEdge->firstDer(nodeParam[ iN ].param);
1224       // double lc = norm(der) / segmentSize( nodeParam, i );
1225
1226       mVertices[ i ] = new MEdgeVertex( xyz.X(), xyz.Y(), xyz.Z(),
1227                                         gEdge, nodeParam[ iN ].param, 0, lc);
1228       gEdge->mesh_vertices.push_back( mVertices[ i ]);
1229       _nodeMap.insert({ mVertices[ i ], nodeParam[ iN ].node });
1230     }
1231     // create GMSH mesh edges
1232     for ( size_t i = 1; i < mVertices.size(); ++i )
1233     {
1234       gEdge->lines.push_back( new MLine( mVertices[ i - 1 ],
1235                                          mVertices[ i ]));
1236     }
1237     /*{
1238       cout << endl << "EDGE " << gEdge->tag() <<
1239         ( topoEdge.Orientation() == TopAbs_FORWARD ? " F" : " R") << endl;
1240       MVertex* mv = gV0->mesh_vertices[ 0 ];
1241       cout << "V0: " << mv->x() << ", " << mv->y() << ", " << mv->z() << ", "<<endl;
1242       for ( size_t i = 0; i < gEdge->mesh_vertices.size(); ++i )
1243       {
1244         MEdgeVertex* mv = (MEdgeVertex*) gEdge->mesh_vertices[i];
1245         cout << i << ": " << mv->x() << ", " << mv->y() << ", " << mv->z() << ", ";
1246         double t;
1247         mv->getParameter(0, t );
1248         cout << ":\t t = "<< t << " lc = " << mv->getLc() << endl;
1249       }
1250       mv = gV1->mesh_vertices[ 0 ];
1251       cout << "V1: " << mv->x() << ", " << mv->y() << ", " << mv->z() << ", "<<endl;
1252       }*/
1253   }
1254   return;
1255 }
1256
1257 //================================================================================
1258 /*!
1259  * \brief Set 2D sub-meshes to GModel. GMSH 2D mesh is made by now.
1260  *  \param [inout] _gModel - GMSH model
1261  */
1262 //================================================================================
1263
1264 void GMSHPlugin_Mesher::Set2DSubMeshes( GModel* gModel )
1265 {
1266   if ( _nodeMap.empty() )
1267     return; // no sub-meshes
1268
1269   SMESH_MesherHelper helper( *_mesh );
1270
1271   std::map< const SMDS_MeshNode* , const MVertex * > nodes2mvertMap;
1272   for ( auto & v2n : _nodeMap )
1273     nodes2mvertMap.insert({ v2n.second, v2n.first });
1274
1275   std::vector<MVertex *> mVertices;
1276
1277   for(GModel::fiter it = gModel->firstFace(); it != gModel->lastFace(); ++it)
1278   {
1279     GFace *gFace = *it;
1280
1281 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
1282     if ( !gFace->haveParametrization())
1283 #else
1284       if ( gFace->geomType() == GEntity::CompoundSurface )
1285 #endif
1286         continue;
1287
1288     TopoDS_Face topoFace = *((TopoDS_Face*)gFace->getNativePtr());
1289     SMESHDS_SubMesh*  sm = HasSubMesh( topoFace );
1290     if ( !sm )
1291       continue;
1292     //_gModel->writeUNV("/tmp/befDEl.unv", 1,0,0);
1293
1294     gFace->deleteMesh();
1295
1296     bool reverse = false;
1297     if ( gFace->getRegion(0) )
1298     {
1299       //GRegion * gRegion = gFace->getRegion(0);
1300       TopoDS_Shape topoSolid = *((TopoDS_Shape*)gFace->getNativePtr());
1301       TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( topoSolid, topoFace );
1302       if ( faceOriInSolid >= 0 )
1303         reverse =
1304           helper.IsReversedSubMesh( TopoDS::Face( topoFace.Oriented( faceOriInSolid )));
1305     }
1306
1307     for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
1308     {
1309       const SMDS_MeshElement* f = fIt->next();
1310
1311       int nbN = f->NbCornerNodes();
1312       if ( nbN > 4 )
1313         throw std::string("Polygon sub-meshes not supported");
1314
1315       mVertices.resize( nbN );
1316       for ( int i = 0; i < nbN; ++i )
1317       {
1318         const SMDS_MeshNode* n = f->GetNode( i );
1319         MVertex *           mv = nullptr;
1320         auto n2v = nodes2mvertMap.find( n );
1321         if ( n2v != nodes2mvertMap.end() )
1322         {
1323           mv = const_cast< MVertex*>( n2v->second );
1324         }
1325         else
1326         {
1327           if ( n->GetPosition()->GetDim() < 2 )
1328             throw std::string("Wrong mapping of edge nodes to GMSH nodes");
1329           SMESH_NodeXYZ xyz = n;
1330           bool ok = true;
1331           gp_XY uv = helper.GetNodeUV( topoFace, n, nullptr, &ok );
1332           mv = new MFaceVertex( xyz.X(), xyz.Y(), xyz.Z(), gFace, uv.X(), uv.Y() );
1333           gFace->mesh_vertices.push_back( mv );
1334           nodes2mvertMap.insert({ n, mv });
1335           _nodeMap.insert      ({ mv, n });
1336         }
1337         mVertices[ i ] = mv;
1338       }
1339       // create GMSH mesh faces
1340       switch ( nbN ) {
1341       case 3:
1342         if ( reverse )
1343           gFace->triangles.push_back (new MTriangle(mVertices[0], mVertices[2], mVertices[1]));
1344         else
1345           gFace->triangles.push_back (new MTriangle(mVertices[0], mVertices[1], mVertices[2]));
1346         break;
1347       case 4:
1348         if ( reverse )
1349           gFace->quadrangles.push_back (new MQuadrangle(mVertices[0], mVertices[3],
1350                                                         mVertices[2], mVertices[1]));
1351         else
1352           gFace->quadrangles.push_back (new MQuadrangle(mVertices[0], mVertices[1],
1353                                                         mVertices[2], mVertices[3]));
1354         break;
1355       default:;
1356       }
1357     }
1358   } // loop on GMSH faces
1359
1360   return;
1361 }
1362
1363 //================================================================================
1364 /*!
1365  * \brief Set visibility 0 to already computed geom entities
1366  *        to prevent their meshing
1367  */
1368 //================================================================================
1369
1370 void GMSHPlugin_Mesher::HideComputedEntities( GModel* gModel )
1371 {
1372   CTX::instance()->mesh.meshOnlyVisible = true;
1373
1374   for(GModel::eiter it = gModel->firstEdge(); it != gModel->lastEdge(); ++it)
1375   {
1376     GEdge *gEdge = *it;
1377
1378 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
1379     if ( !gEdge->haveParametrization())
1380 #else
1381       if ( gEdge->geomType() == GEntity::CompoundCurve )
1382 #endif
1383         continue;
1384
1385     TopoDS_Edge topoEdge = *((TopoDS_Edge*)gEdge->getNativePtr());
1386     if ( HasSubMesh( topoEdge ))
1387       gEdge->setVisibility(0);
1388   }
1389
1390
1391   for(GModel::fiter it = gModel->firstFace(); it != gModel->lastFace(); ++it)
1392   {
1393     GFace *gFace = *it;
1394
1395 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
1396     if ( !gFace->haveParametrization())
1397 #else
1398       if ( gFace->geomType() == GEntity::CompoundSurface )
1399 #endif
1400         continue;
1401
1402     TopoDS_Face topoFace = *((TopoDS_Face*)gFace->getNativePtr());
1403     if ( HasSubMesh( topoFace ))
1404       gFace->setVisibility(0);
1405   }
1406 }
1407
1408 //================================================================================
1409 /*!
1410  * \brief Restore visibility of all geom entities
1411  */
1412 //================================================================================
1413
1414 void GMSHPlugin_Mesher::RestoreVisibility( GModel* gModel )
1415 {
1416   for(GModel::eiter it = gModel->firstEdge(); it != gModel->lastEdge(); ++it)
1417   {
1418     GEdge *gEdge = *it;
1419     gEdge->setVisibility(1);
1420   }
1421   for(GModel::fiter it = gModel->firstFace(); it != gModel->lastFace(); ++it)
1422   {
1423     GFace *gFace = *it;
1424     gFace->setVisibility(1);
1425   }
1426 }
1427
1428 /*
1429   void GMSHPlugin_Mesher::toPython( GModel* )
1430   {
1431   const char*  pyFile = "/tmp/gMesh.py";
1432   ofstream outfile( pyFile, ios::out );
1433   if ( !outfile ) return;
1434
1435   outfile << "import salome, SMESH" << std::endl
1436           << "from salome.smesh import smeshBuilder" << std::endl
1437           << "smesh = smeshBuilder.New()" << std::endl
1438           << "mesh = smesh.Mesh()" << std::endl << std::endl;
1439
1440   outfile << "## VERTICES" << endl;
1441   for ( GModel::viter it = _gModel->firstVertex(); it != _gModel->lastVertex(); ++it)
1442   {
1443     GVertex *gVertex = *it;
1444
1445     for(unsigned int i = 0; i < gVertex->mesh_vertices.size(); i++)
1446     {
1447       MVertex *v = gVertex->mesh_vertices[i];
1448       if ( v->getIndex() >= 0)
1449       {
1450         outfile << "n" << v->getNum() << " = mesh.AddNode("
1451                 << v->x() << ", " << v->y() << ", " << v->z()<< ")"
1452                 << " ## tag = " << gVertex->tag() << endl;
1453       }
1454     }
1455   }
1456
1457   for(GModel::eiter it = _gModel->firstEdge(); it != _gModel->lastEdge(); ++it)
1458   {
1459     GEdge *gEdge = *it;
1460     outfile << "## GEdge " << gEdge->tag() << endl;
1461
1462 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
1463     if(gEdge->haveParametrization())
1464 #else
1465       if ( gEdge->geomType() != GEntity::CompoundCurve )
1466 #endif
1467         for ( size_t i = 0; i < gEdge->mesh_vertices.size(); i++ )
1468         {
1469           MVertex *v = gEdge->mesh_vertices[i];
1470           if ( v->getIndex() >= 0 )
1471           {
1472             outfile << "n" << v->getNum() << " = mesh.AddNode("
1473                     << v->x() << ", " << v->y() << ", " << v->z()<< ")"
1474                     << " ## tag = " << gEdge->tag() << endl;
1475           }
1476         }
1477   }
1478
1479   for ( GModel::fiter it = _gModel->firstFace(); it != _gModel->lastFace(); ++it)
1480   {
1481     GFace *gFace = *it;
1482     if ( _compounds.size() && gFace->geomType() == GEntity::DiscreteSurface )
1483       continue;
1484     outfile << "## GFace " << gFace->tag() << endl;
1485
1486     for ( size_t i = 0; i < gFace->mesh_vertices.size(); i++ )
1487     {
1488       MVertex *v = gFace->mesh_vertices[i];
1489       if ( v->getIndex() >= 0 )
1490       {
1491         outfile << "n" << v->getNum() << " = mesh.AddNode("
1492                 << v->x() << ", " << v->y() << ", " << v->z()<< ")"
1493                 << " ## tag = " << gFace->tag() << endl;
1494       }
1495     }
1496   }
1497
1498   std::vector<MVertex*> verts(3);
1499   for(GModel::eiter it = _gModel->firstEdge(); it != _gModel->lastEdge(); ++it)
1500   {
1501     GEdge *gEdge = *it;
1502     outfile << "## GEdge " << gEdge->tag() << endl;
1503
1504 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
1505     if(gEdge->haveParametrization())
1506 #else
1507       if ( gEdge->geomType() != GEntity::CompoundCurve )
1508 #endif
1509     for ( size_t i = 0; i < gEdge->getNumMeshElements(); i++ )
1510     {
1511       MElement *e = gEdge->getMeshElement(i);
1512       verts.clear();
1513       e->getVertices(verts);
1514
1515       outfile << "e" << e->getNum() << " = mesh.AddEdge(["
1516               << "n" << verts[0]->getNum() << ","
1517               << "n" << verts[1]->getNum();
1518       if ( verts.size() == 3 )
1519         outfile << "n" << verts[2]->getNum();
1520       outfile << "])"<< endl;
1521     }
1522   }
1523
1524   for ( GModel::fiter it = _gModel->firstFace(); it != _gModel->lastFace(); ++it)
1525   {
1526     GFace *gFace = *it;
1527     if ( _compounds.size() && gFace->geomType() == GEntity::DiscreteSurface )
1528       continue;
1529     outfile << "## GFace " << gFace->tag() << endl;
1530
1531     for ( size_t i = 0; i < gFace->getNumMeshElements(); i++ )
1532     {
1533       MElement *e = gFace->getMeshElement(i);
1534       verts.clear();
1535       e->getVertices(verts);
1536
1537       outfile << "f" << e->getNum() << " = mesh.AddFace([";
1538       for ( size_t j = 0; j < verts.size(); j++)
1539       {
1540         outfile << "n" << verts[j]->getNum();
1541         if ( j < verts.size()-1 )
1542           outfile << ", ";
1543       }
1544       outfile << "])" << endl;
1545     }
1546   }
1547   std::cout << "Write " << pyFile << std::endl;
1548 }
1549 */