1 // Copyright (C) 2012-2015 ALNEOS
2 // Copyright (C) 2016-2022 EDF R&D
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.
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.
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
18 // See http://www.alneos.com/ or email : contact@alneos.fr
19 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 #include "GMSHPlugin_Mesher.hxx"
22 #include "GMSHPlugin_Hypothesis_2D.hxx"
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>
39 #include <TopExp_Explorer.hxx>
43 #include <MTriangle.h>
44 #include <MQuadrangle.h>
45 #if GMSH_MAJOR_VERSION >=4
46 #include <GmshGlobal.h>
47 #include <gmsh/Context.h>
50 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
60 SBoundingBox3d _bounds;
64 //================================================================================
66 * \brief Retrieve ShapeBounds from a compound GEdge
68 //================================================================================
70 bool getBoundsOfShapes( GEdge* gEdge,
71 std::vector< ShapeBounds > & topoEdges )
74 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
75 for ( size_t i = 0; i < gEdge->compound.size(); ++i )
77 GEdge* gE = static_cast< GEdge* >( gEdge->compound[ i ]);
78 topoEdges.push_back( ShapeBounds{ gE->bounds(), *((TopoDS_Edge*)gE->getNativePtr()) });
81 for ( size_t i = 0; i < gEdge->_compound.size(); ++i )
83 GEdge* gE = static_cast< GEdge* >( gEdge->_compound[ i ]);
84 topoEdges.push_back( ShapeBounds{ gE->bounds(), *((TopoDS_Edge*)gE->getNativePtr()) });
87 return topoEdges.size();
90 //================================================================================
92 * \brief Retrieve ShapeBounds from a compound GFace
94 //================================================================================
96 bool getBoundsOfShapes( GFace* gFace,
97 std::vector< ShapeBounds > & topoFaces )
100 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
101 for ( size_t i = 0; i < gFace->compound.size(); ++i )
103 GFace* gF = static_cast< GFace* >( gFace->compound[ i ]);
104 topoFaces.push_back( ShapeBounds{ gF->bounds(), *((TopoDS_Face*)gF->getNativePtr()) });
107 for ( size_t i = 0; i < gFace->_compound.size(); ++i )
109 GFace* gF = static_cast< GFace* >( gFace->_compound[ i ]);
110 topoFaces.push_back( ShapeBounds{ gF->bounds(), *((TopoDS_Face*)gF->getNativePtr()) });
113 return topoFaces.size();
115 //================================================================================
117 * \brief Find a shape whose bounding box includes a given point
119 //================================================================================
121 TopoDS_Shape getShapeAtPoint( const SPoint3& point, const std::vector< ShapeBounds > & shapes )
124 float distmin = std::numeric_limits<float>::max();
125 for ( size_t i = 0; i < shapes.size(); ++i )
127 float dist = GMSHPlugin_Mesher::DistBoundingBox( shapes[i]._bounds, point );
130 shape = shapes[i]._shape;
139 double segmentSize( const UVPtStructVec& nodeParam, size_t i )
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 );
147 //=============================================================================
151 //=============================================================================
153 GMSHPlugin_Mesher::GMSHPlugin_Mesher (SMESH_Mesh* mesh,
154 const TopoDS_Shape& aShape,
160 // il faudra peut être mettre un truc par defaut si l'utilisateur ne rentre rien en para
161 //defaultParameters();
164 //void GMSHPlugin_Mesher::defaultParameters(){}
166 void GMSHPlugin_Mesher::SetParameters(const GMSHPlugin_Hypothesis* hyp)
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();
190 _recombineAll = false;
198 _secondOrder = false;
199 _useIncomplElem = true;
205 //================================================================================
207 * \brief Set maximum number of threads to be used by Gmsh
209 //================================================================================
211 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
212 void GMSHPlugin_Mesher::SetMaxThreadsGmsh()
214 MESSAGE("GMSHPlugin_Mesher::SetMaxThreadsGmsh");
215 if (_compounds.size() > 0)
218 _maxThreads = omp_get_max_threads();
222 //================================================================================
224 * \brief Set Gmsh Options
226 //================================================================================
228 void GMSHPlugin_Mesher::SetGmshOptions()
230 MESSAGE("GMSHPlugin_Mesher::SetGmshOptions");
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);
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
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
264 ok = GmshSetOption("Mesh", "Algorithm" , mapAlgo2d[_algo2d]) ;
268 ok = GmshSetOption("Mesh", "Algorithm3D" , mapAlgo3d[_algo3d]) ;
271 ok = GmshSetOption("Mesh", "RecombinationAlgorithm" , (double)_recomb2DAlgo) ;
273 ok = GmshSetOption("Mesh", "RecombineAll" , (_recombineAll)?1.:0.) ;
275 ok = GmshSetOption("Mesh", "SubdivisionAlgorithm" , (double)_subdivAlgo) ;
277 ok = GmshSetOption("Mesh", "RemeshAlgorithm" , (double)_remeshAlgo) ;
279 ok = GmshSetOption("Mesh", "RemeshParametrization" , (double)_remeshPara) ;
281 ok = GmshSetOption("Mesh", "Smoothing" , (double)_smouthSteps) ;
283 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
284 ok = GmshSetOption("Mesh", "MeshSizeFactor" , _sizeFactor) ;
286 ok = GmshSetOption("Mesh", "MeshSizeMin" , _minSize) ;
288 ok = GmshSetOption("Mesh", "MeshSizeMax" , _maxSize) ;
291 ok = GmshSetOption("Mesh", "CharacteristicLengthFactor" , _sizeFactor) ;
293 ok = GmshSetOption("Mesh", "CharacteristicLengthMin" , _minSize) ;
295 ok = GmshSetOption("Mesh", "CharacteristicLengthMax" , _maxSize) ;
298 ok = GmshSetOption("Mesh", "ElementOrder" , (_secondOrder)?2.:1.) ;
302 ok = GmshSetOption("Mesh", "SecondOrderIncomplete" ,(_useIncomplElem)?1.:0.);
306 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
307 /*ok = GmshSetOption("Mesh", "MaxNumThreads1D" , 0. ) ; // Coarse-grain algo threads
309 ok = GmshSetOption("Mesh", "MaxNumThreads2D" , 0. ) ; // Coarse-grain algo threads
311 ok = GmshSetOption("Mesh", "MaxNumThreads3D" , 0. ) ; // Fine-grain algo threads HXT
314 ok = GmshSetOption("General", "NumThreads" , _maxThreads ) ; // system default i.e. OMP_NUM_THREADS
319 //================================================================================
321 * \brief Create and add Compounds into GModel _gModel.
323 //================================================================================
325 void GMSHPlugin_Mesher::CreateGmshCompounds()
327 MESSAGE("GMSHPlugin_Mesher::CreateGmshCompounds");
329 SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
331 OCC_Internals* occgeo = _gModel->getOCCInternals();
332 bool toSynchronize = false;
334 for(std::set<std::string>::const_iterator its = _compounds.begin();its != _compounds.end(); ++its )
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"))
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);
347 geomShape = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
348 if ( geomShape.IsNull() )
351 TopAbs_ShapeEnum geomType = geomShape.ShapeType();
352 if ( geomType == TopAbs_COMPOUND)// voir s'il ne faut pas mettre une erreur dans le cas contraire
354 MESSAGE("shapeType == TopAbs_COMPOUND");
355 TopoDS_Iterator it(geomShape);
358 TopAbs_ShapeEnum shapeType = it.Value().ShapeType();
359 std::vector< std::pair< int, int > > dimTags;
360 for ( ; it.More(); it.Next())
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 );
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");
375 std::vector<int> tags;
376 int dim = ( shapeType == TopAbs_EDGE ) ? 1 : 2;
377 for ( size_t i = 0; i < dimTags.size(); ++i )
379 if ( dimTags[i].first == dim )
380 tags.push_back( dimTags[i].second );
384 _gModel->getGEOInternals()->setCompoundMesh( dim, tags );
385 toSynchronize = true;
388 _gModel->getGEOInternals()->synchronize(_gModel);
393 //================================================================================
395 * \brief For a compound mesh set the mesh components to be transmitted to SMESH
397 //================================================================================
399 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
400 void GMSHPlugin_Mesher::SetCompoundMeshVisibility()
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.
410 for ( GModel::fiter itF = _gModel->firstFace(); itF != _gModel->lastFace(); ++itF )
412 std::vector< GEdge *> faceEdges = (*itF)->edges();
414 for ( auto itE = faceEdges.begin(); itE != faceEdges.end(); ++itE )
416 if ( ((*itF)->compound.size()) )
417 (*itE)->setVisibility(0);
419 (*itE)->setVisibility(1);
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.
431 for ( GModel::eiter itE = _gModel->firstEdge(); itE != _gModel->lastEdge(); ++itE )
433 std::vector<GVertex *> bndVerticies = (*itE)->vertices();
435 for( auto itV = bndVerticies.begin(); itV != bndVerticies.end(); ++itV )
437 if(((*itE)->compound.size()))
438 (*itV)->setVisibility(0);
440 (*itV)->setVisibility(1);
447 //================================================================================
449 * \brief Get a node by a GMSH mesh vertex
451 //================================================================================
453 const SMDS_MeshNode* GMSHPlugin_Mesher::Node( const MVertex* v )
455 std::map< const MVertex *, const SMDS_MeshNode* >::iterator v2n = _nodeMap.find( v );
456 if ( v2n != _nodeMap.end() )
462 //================================================================================
464 * \brief Return a corresponding sub-mesh if a shape is meshed
466 //================================================================================
468 SMESHDS_SubMesh* GMSHPlugin_Mesher::HasSubMesh( const TopoDS_Shape& s )
470 if ( SMESHDS_SubMesh* sm = _mesh->GetMeshDS()->MeshElements( s ))
472 if ( s.ShapeType() == TopAbs_VERTEX )
473 return ( sm->NbNodes() > 0 ) ? sm : nullptr;
475 return ( sm->NbElements() > 0 ) ? sm : nullptr;
480 //================================================================================
482 * \brief Write mesh from GModel instance to SMESH instance
484 //================================================================================
486 void GMSHPlugin_Mesher::FillSMesh()
488 SMESHDS_Mesh* meshDS = _mesh->GetMeshDS();
491 for ( GModel::viter it = _gModel->firstVertex(); it != _gModel->lastVertex(); ++it)
493 GVertex *gVertex = *it;
495 // GET topoVertex CORRESPONDING TO gVertex
496 TopoDS_Vertex topoVertex = *((TopoDS_Vertex*)gVertex->getNativePtr());
498 if (gVertex->getVisibility() == 0) // belongs to a compound
500 SMESH_subMesh* sm = _mesh->GetSubMesh(topoVertex);
501 sm->SetIsAlwaysComputed(true); // prevent from displaying errors
505 // FILL SMESH FOR topoVertex
507 for( size_t i = 0; i < gVertex->mesh_vertices.size(); i++)
509 MVertex *v = gVertex->mesh_vertices[i];
510 if(v->getIndex() >= 0)
512 if ( SMESHDS_SubMesh* sm = HasSubMesh( topoVertex ))
514 const SMDS_MeshNode *node = sm->GetNodes()->next();
515 _nodeMap.insert({ v, node });
519 SMDS_MeshNode *node = meshDS->AddNode( v->x(),v->y(),v->z() );
520 meshDS->SetNodeOnVertex( node, topoVertex );
521 _nodeMap.insert({ v, node });
525 // WE DON'T ADD 0D ELEMENTS because it does not follow the salome meshers philosophy
527 // for(unsigned int i = 0; i < gVertex->getNumMeshElements(); i++)
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);
540 for(GModel::eiter it = _gModel->firstEdge(); it != _gModel->lastEdge(); ++it)
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())
550 if ( gEdge->geomType() != GEntity::CompoundCurve )
553 topoEdge = *((TopoDS_Edge*)gEdge->getNativePtr());
554 if (gEdge->getVisibility() == 0) // belongs to a compound
556 SMESH_subMesh* sm = _mesh->GetSubMesh(topoEdge);
557 sm->SetIsAlwaysComputed(true); // prevent from displaying errors
560 if ( HasSubMesh( topoEdge ))
561 continue; // a meshed sub-mesh
563 bool isCompound = getBoundsOfShapes( gEdge, topoEdges );
565 // FILL SMESH FOR topoEdge
567 for ( size_t i = 0; i < gEdge->mesh_vertices.size(); i++ )
569 MVertex *v = gEdge->mesh_vertices[i];
570 if ( v->getIndex() >= 0 )
572 SMDS_MeshNode *node = meshDS->AddNode( v->x(),v->y(),v->z() );
575 topoEdge = TopoDS::Edge( getShapeAtPoint( v->point(), topoEdges ));
577 meshDS->SetNodeOnEdge( node, topoEdge );
578 _nodeMap.insert({ v, node });
583 for ( GModel::eiter it = _gModel->firstEdge(); it != _gModel->lastEdge(); ++it )
586 if ( gEdge->getVisibility() == 0) // belongs to a compound
589 TopoDS_Edge topoEdge;
590 std::vector< ShapeBounds > topoEdges;
591 bool isCompound = getBoundsOfShapes( gEdge, topoEdges );
593 topoEdge = *((TopoDS_Edge*)gEdge->getNativePtr());
595 if ( HasSubMesh( topoEdge ))
596 continue; // a meshed sub-mesh
599 std::vector<MVertex*> verts(3);
600 for ( size_t i = 0; i < gEdge->getNumMeshElements(); i++ )
602 MElement *e = gEdge->getMeshElement(i);
604 e->getVertices(verts);
606 // if a node wasn't set, it is assigned here
607 for ( size_t j = 0; j < verts.size(); j++ )
609 if ( verts[j]->onWhat()->getVisibility() == 0 )
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 });
618 SMDS_MeshEdge* edge = 0;
619 switch (verts.size())
622 edge = meshDS->AddEdge(Node( verts[0]),
626 edge = meshDS->AddEdge(Node( verts[0]),
635 topoEdge = TopoDS::Edge( getShapeAtPoint( e->barycenter(), topoEdges ));
637 meshDS->SetMeshElementOnShape( edge, topoEdge );
642 for ( GModel::fiter it = _gModel->firstFace(); it != _gModel->lastFace(); ++it)
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 )
656 // GET topoFace CORRESPONDING TO gFace
657 TopoDS_Face topoFace;
658 std::vector< ShapeBounds > topoFaces;
660 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
661 if(gFace->haveParametrization())
663 if ( gFace->geomType() != GEntity::CompoundSurface )
666 topoFace = *((TopoDS_Face*)gFace->getNativePtr());
667 if (gFace->getVisibility() == 0) // belongs to a compound
669 SMESH_subMesh* sm = _mesh->GetSubMesh(topoFace);
670 sm->SetIsAlwaysComputed(true); // prevent from displaying errors
673 if ( HasSubMesh( topoFace ))
674 continue; // a meshed sub-mesh
676 bool isCompound = getBoundsOfShapes( gFace, topoFaces );
678 // FILL SMESH FOR topoFace
680 for ( size_t i = 0; i < gFace->mesh_vertices.size(); i++ )
682 MVertex *v = gFace->mesh_vertices[i];
683 if ( v->getIndex() >= 0 )
685 SMDS_MeshNode *node = meshDS->AddNode( v->x(),v->y(),v->z() );
688 topoFace = TopoDS::Face( getShapeAtPoint( v->point(), topoFaces ));
690 meshDS->SetNodeOnFace( node, topoFace );
691 _nodeMap.insert({ v, node });
696 for ( GModel::fiter it = _gModel->firstFace(); it != _gModel->lastFace(); ++it)
700 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
701 if ( _compounds.size() && gFace->geomType() == GEntity::DiscreteSurface )
704 bool isCompound = (!gFace->haveParametrization());
706 bool isCompound = ( gFace->geomType() == GEntity::CompoundSurface );
709 if ( !isCompound && gFace->getVisibility() == 0 )
710 continue; // belongs to a compound
712 TopoDS_Face topoFace;
713 std::vector< ShapeBounds > topoFaces;
715 getBoundsOfShapes( gFace, topoFaces );
717 topoFace = *((TopoDS_Face*)gFace->getNativePtr());
719 if ( HasSubMesh( topoFace ))
720 continue; // a meshed sub-mesh
723 std::vector<MVertex*> verts;
724 for ( size_t i = 0; i < gFace->getNumMeshElements(); i++ )
726 MElement *e = gFace->getMeshElement(i);
728 e->getVertices(verts);
729 SMDS_MeshFace* face = 0;
731 // if a node wasn't set, it is assigned here
732 for ( size_t j = 0; j < verts.size(); j++)
734 if(verts[j]->onWhat()->getVisibility() == 0)
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);
742 switch (verts.size())
745 face = meshDS->AddFace(Node( verts[0]),
750 face = meshDS->AddFace(Node( verts[0]),
756 face = meshDS->AddFace(Node( verts[0]),
764 face = meshDS->AddFace(Node( verts[0]),
774 face = meshDS->AddFace(Node( verts[0]),
790 topoFace = TopoDS::Face( getShapeAtPoint( e->barycenter(), topoFaces ));
792 meshDS->SetMeshElementOnShape(face, topoFace);
797 for ( GModel::riter it = _gModel->firstRegion(); it != _gModel->lastRegion(); ++it)
799 GRegion *gRegion = *it;
800 if (gRegion->getVisibility() == 0)
803 // GET topoSolid CORRESPONDING TO gRegion
804 TopoDS_Solid topoSolid = *((TopoDS_Solid*)gRegion->getNativePtr());
806 // FILL SMESH FOR topoSolid
809 for( size_t i = 0; i < gRegion->mesh_vertices.size(); i++)
811 MVertex *v = gRegion->mesh_vertices[i];
812 if(v->getIndex() >= 0)
814 SMDS_MeshNode *node = meshDS->AddNode( v->x(),v->y(),v->z() );
815 meshDS->SetNodeInVolume( node, topoSolid );
816 _nodeMap.insert({ v, node });
821 std::vector<MVertex*> verts;
822 for( size_t i = 0; i < gRegion->getNumMeshElements(); i++)
824 MElement *e = gRegion->getMeshElement(i);
826 e->getVertices(verts);
827 SMDS_MeshVolume* volume = 0;
828 switch (verts.size()){
830 volume = meshDS->AddVolume(Node( verts[0]),
836 volume = meshDS->AddVolume(Node( verts[0]),
843 volume = meshDS->AddVolume(Node( verts[0]),
851 volume = meshDS->AddVolume(Node( verts[0]),
861 volume = meshDS->AddVolume(Node( verts[0]),
873 volume = meshDS->AddVolume(Node( verts[0] ),
887 case 14: // same as case 13, because no pyra14 in smesh
888 volume = meshDS->AddVolume(Node( verts[0] ),
903 volume = meshDS->AddVolume(Node( verts[0] ),
919 case 18: // same as case 15, because no penta18 in smesh
920 volume = meshDS->AddVolume(Node( verts[0] ),
937 volume = meshDS->AddVolume(Node( verts[0] ),
959 volume = meshDS->AddVolume(Node( verts[0] ),
991 meshDS->SetMeshElementOnShape(volume, topoSolid);
998 //================================================================================
1000 * \brief Find if SPoint point is in SBoundingBox3d bounds
1002 //================================================================================
1004 float GMSHPlugin_Mesher::DistBoundingBox(const SBoundingBox3d& bounds, const SPoint3& point)
1006 SPoint3 min = bounds.min();
1007 SPoint3 max = bounds.max();
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();
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();
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();
1034 //================================================================================
1036 * \brief Reimplemented GmshMessage call. Actions done if errors occurs
1037 * during gmsh meshing. We define here what to display and what to do.
1039 //================================================================================
1040 void GMSHPlugin_Mesher::mymsg::operator()(std::string level, std::string msg)
1042 //MESSAGE("level="<< level.c_str() << ", msg=" << msg.c_str()<< "\n");
1043 printf("level=%s msg=%s\n", level.c_str(), msg.c_str());
1045 if(level == "Fatal" || level == "Error")
1047 std::ostringstream oss;
1048 if (level == "Fatal")
1049 oss << "Fatal error during Generation of Gmsh Mesh\n";
1051 oss << "Error during Generation of Gmsh Mesh\n";
1052 oss << " " << msg.c_str() << "\n";
1053 GEntity *e = _gModel->getCurrentMeshEntity();
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)
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 ));
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
1076 if (level == "Fatal")
1078 CTX::instance()->lock = 0;
1082 printf("%s\n", oss.str().c_str());
1086 //=============================================================================
1088 * Here we are going to use the GMSH mesher
1090 //=============================================================================
1092 bool GMSHPlugin_Mesher::Compute()
1094 MESSAGE("GMSHPlugin_Mesher::Compute");
1098 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
1099 SetMaxThreadsGmsh();
1103 _gModel = new GModel();
1105 GmshSetMessageHandler(&msg);
1106 _gModel->importOCCShape((void*)&_shape);
1107 if (_compounds.size() > 0) CreateGmshCompounds();
1110 //Msg::SetVerbosity(100);
1111 //CTX::instance()->mesh.maxNumThreads1D=1;
1113 HideComputedEntities( _gModel );
1115 _gModel->mesh( /*dim=*/ 1 );
1117 Set1DSubMeshes( _gModel );
1119 //_gModel->writeUNV("/tmp/1D.unv", 1,0,0);
1120 //CTX::instance()->mesh.maxNumThreads2D=1;
1122 _gModel->mesh( /*dim=*/ 2 );
1126 Set2DSubMeshes( _gModel );
1128 //CTX::instance()->mesh.maxNumThreads3D=1;
1130 _gModel->mesh( /*dim=*/ 3 );
1132 RestoreVisibility( _gModel );
1134 #ifdef WITH_SMESH_CANCEL_COMPUTE
1138 catch (std::string& str)
1141 std::cerr << "GMSH: exception caught: " << str << std::endl;
1147 std::cerr << "GMSH: Unknown exception caught: " << std::endl;
1148 MESSAGE("Unrecoverable error during Generation of Gmsh Mesh");
1153 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
1154 if (_compounds.size() > 0)
1155 SetCompoundMeshVisibility();
1159 GmshSetMessageHandler(nullptr);
1162 MESSAGE("GMSHPlugin_Mesher::Compute:End");
1166 //================================================================================
1168 * \brief Set 1D sub-meshes to GModel. GMSH 1D mesh is made by now.
1169 * \param [inout] _gModel - GMSH model
1171 //================================================================================
1173 void GMSHPlugin_Mesher::Set1DSubMeshes( GModel* gModel )
1175 SMESHDS_Mesh* meshDS = _mesh->GetMeshDS();
1177 for(GModel::eiter it = gModel->firstEdge(); it != gModel->lastEdge(); ++it)
1181 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
1182 if ( !gEdge->haveParametrization())
1184 if ( gEdge->geomType() == GEntity::CompoundCurve )
1188 TopoDS_Edge topoEdge = *((TopoDS_Edge*)gEdge->getNativePtr());
1189 if ( !HasSubMesh( topoEdge ))
1190 continue; // empty sub-mesh
1192 gEdge->deleteMesh();
1194 // get node parameters on topoEdge
1195 StdMeshers_FaceSide side( TopoDS_Face(), topoEdge, _mesh, /*fwd=*/true, /*skpMedium=*/true);
1196 const UVPtStructVec& nodeParam = side.GetUVPtStruct();
1197 if ( nodeParam.empty() )
1198 throw std::string("Pb with StdMeshers_FaceSide::GetUVPtStruct()");
1200 // get GMSH mesh vertices on VERTEX'es
1201 std::vector<MVertex *> mVertices( nodeParam.size(), nullptr );
1202 GVertex * gV0 = gEdge->getBeginVertex(), *gV1 = gEdge->getEndVertex();
1203 mVertices[0] = gV0->mesh_vertices[ 0 ];
1204 mVertices.back() = gV1->mesh_vertices[ 0 ];
1205 TopoDS_Vertex v01 = *((TopoDS_Vertex*) gV0->getNativePtr());
1206 TopoDS_Shape v02 = SMESH_MesherHelper::GetSubShapeByNode( nodeParam[0].node, meshDS );
1207 bool reverse = !v01.IsSame( v02 );
1208 if ( mVertices[0] == mVertices.back() )
1209 reverse = ( nodeParam[0].param > nodeParam.back().param );
1210 const SMDS_MeshNode* n0 = reverse ? nodeParam.back().node : nodeParam[0].node;
1211 const SMDS_MeshNode* n1 = reverse ? nodeParam[0].node : nodeParam.back().node;
1212 _nodeMap.insert({ mVertices[ 0 ], n0 });
1213 _nodeMap.insert({ mVertices.back(), n1 });
1215 // create GMSH mesh vertices on gEdge
1216 for ( size_t i = 1; i < nodeParam.size() - 1; ++i )
1218 size_t iN = reverse ? ( nodeParam.size() - 1 - i ) : i;
1219 SMESH_NodeXYZ xyz = nodeParam[ iN ].node;
1220 double lc = segmentSize( nodeParam, iN );
1221 // SVector3 der = gEdge->firstDer(nodeParam[ iN ].param);
1222 // double lc = norm(der) / segmentSize( nodeParam, i );
1224 mVertices[ i ] = new MEdgeVertex( xyz.X(), xyz.Y(), xyz.Z(),
1225 gEdge, nodeParam[ iN ].param, 0, lc);
1226 gEdge->mesh_vertices.push_back( mVertices[ i ]);
1227 _nodeMap.insert({ mVertices[ i ], nodeParam[ iN ].node });
1229 // create GMSH mesh edges
1230 for ( size_t i = 1; i < mVertices.size(); ++i )
1232 gEdge->lines.push_back( new MLine( mVertices[ i - 1 ],
1236 cout << endl << "EDGE " << gEdge->tag() <<
1237 ( topoEdge.Orientation() == TopAbs_FORWARD ? " F" : " R") << endl;
1238 MVertex* mv = gV0->mesh_vertices[ 0 ];
1239 cout << "V0: " << mv->x() << ", " << mv->y() << ", " << mv->z() << ", "<<endl;
1240 for ( size_t i = 0; i < gEdge->mesh_vertices.size(); ++i )
1242 MEdgeVertex* mv = (MEdgeVertex*) gEdge->mesh_vertices[i];
1243 cout << i << ": " << mv->x() << ", " << mv->y() << ", " << mv->z() << ", ";
1245 mv->getParameter(0, t );
1246 cout << ":\t t = "<< t << " lc = " << mv->getLc() << endl;
1248 mv = gV1->mesh_vertices[ 0 ];
1249 cout << "V1: " << mv->x() << ", " << mv->y() << ", " << mv->z() << ", "<<endl;
1255 //================================================================================
1257 * \brief Set 2D sub-meshes to GModel. GMSH 2D mesh is made by now.
1258 * \param [inout] _gModel - GMSH model
1260 //================================================================================
1262 void GMSHPlugin_Mesher::Set2DSubMeshes( GModel* gModel )
1264 if ( _nodeMap.empty() )
1265 return; // no sub-meshes
1267 SMESH_MesherHelper helper( *_mesh );
1269 std::map< const SMDS_MeshNode* , const MVertex * > nodes2mvertMap;
1270 for ( auto & v2n : _nodeMap )
1271 nodes2mvertMap.insert({ v2n.second, v2n.first });
1273 std::vector<MVertex *> mVertices;
1275 for(GModel::fiter it = gModel->firstFace(); it != gModel->lastFace(); ++it)
1279 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
1280 if ( !gFace->haveParametrization())
1282 if ( gFace->geomType() == GEntity::CompoundSurface )
1286 TopoDS_Face topoFace = *((TopoDS_Face*)gFace->getNativePtr());
1287 SMESHDS_SubMesh* sm = HasSubMesh( topoFace );
1290 //_gModel->writeUNV("/tmp/befDEl.unv", 1,0,0);
1292 gFace->deleteMesh();
1294 bool reverse = false;
1295 if ( gFace->getRegion(0) )
1297 //GRegion * gRegion = gFace->getRegion(0);
1298 TopoDS_Shape topoSolid = *((TopoDS_Shape*)gFace->getNativePtr());
1299 TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( topoSolid, topoFace );
1300 if ( faceOriInSolid >= 0 )
1302 helper.IsReversedSubMesh( TopoDS::Face( topoFace.Oriented( faceOriInSolid )));
1305 for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
1307 const SMDS_MeshElement* f = fIt->next();
1309 int nbN = f->NbCornerNodes();
1311 throw std::string("Polygon sub-meshes not supported");
1313 mVertices.resize( nbN );
1314 for ( int i = 0; i < nbN; ++i )
1316 const SMDS_MeshNode* n = f->GetNode( i );
1317 MVertex * mv = nullptr;
1318 auto n2v = nodes2mvertMap.find( n );
1319 if ( n2v != nodes2mvertMap.end() )
1321 mv = const_cast< MVertex*>( n2v->second );
1325 if ( n->GetPosition()->GetDim() < 2 )
1326 throw std::string("Wrong mapping of edge nodes to GMSH nodes");
1327 SMESH_NodeXYZ xyz = n;
1329 gp_XY uv = helper.GetNodeUV( topoFace, n, nullptr, &ok );
1330 mv = new MFaceVertex( xyz.X(), xyz.Y(), xyz.Z(), gFace, uv.X(), uv.Y() );
1331 gFace->mesh_vertices.push_back( mv );
1332 nodes2mvertMap.insert({ n, mv });
1333 _nodeMap.insert ({ mv, n });
1335 mVertices[ i ] = mv;
1337 // create GMSH mesh faces
1341 gFace->triangles.push_back (new MTriangle(mVertices[0], mVertices[2], mVertices[1]));
1343 gFace->triangles.push_back (new MTriangle(mVertices[0], mVertices[1], mVertices[2]));
1347 gFace->quadrangles.push_back (new MQuadrangle(mVertices[0], mVertices[3],
1348 mVertices[2], mVertices[1]));
1350 gFace->quadrangles.push_back (new MQuadrangle(mVertices[0], mVertices[1],
1351 mVertices[2], mVertices[3]));
1356 } // loop on GMSH faces
1361 //================================================================================
1363 * \brief Set visibility 0 to already computed geom entities
1364 * to prevent their meshing
1366 //================================================================================
1368 void GMSHPlugin_Mesher::HideComputedEntities( GModel* gModel )
1370 CTX::instance()->mesh.meshOnlyVisible = true;
1372 for(GModel::eiter it = gModel->firstEdge(); it != gModel->lastEdge(); ++it)
1376 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
1377 if ( !gEdge->haveParametrization())
1379 if ( gEdge->geomType() == GEntity::CompoundCurve )
1383 TopoDS_Edge topoEdge = *((TopoDS_Edge*)gEdge->getNativePtr());
1384 if ( HasSubMesh( topoEdge ))
1385 gEdge->setVisibility(0);
1389 for(GModel::fiter it = gModel->firstFace(); it != gModel->lastFace(); ++it)
1393 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
1394 if ( !gFace->haveParametrization())
1396 if ( gFace->geomType() == GEntity::CompoundSurface )
1400 TopoDS_Face topoFace = *((TopoDS_Face*)gFace->getNativePtr());
1401 if ( HasSubMesh( topoFace ))
1402 gFace->setVisibility(0);
1406 //================================================================================
1408 * \brief Restore visibility of all geom entities
1410 //================================================================================
1412 void GMSHPlugin_Mesher::RestoreVisibility( GModel* gModel )
1414 for(GModel::eiter it = gModel->firstEdge(); it != gModel->lastEdge(); ++it)
1417 gEdge->setVisibility(1);
1419 for(GModel::fiter it = gModel->firstFace(); it != gModel->lastFace(); ++it)
1422 gFace->setVisibility(1);
1427 void GMSHPlugin_Mesher::toPython( GModel* )
1429 const char* pyFile = "/tmp/gMesh.py";
1430 ofstream outfile( pyFile, ios::out );
1431 if ( !outfile ) return;
1433 outfile << "import salome, SMESH" << std::endl
1434 << "from salome.smesh import smeshBuilder" << std::endl
1435 << "smesh = smeshBuilder.New()" << std::endl
1436 << "mesh = smesh.Mesh()" << std::endl << std::endl;
1438 outfile << "## VERTICES" << endl;
1439 for ( GModel::viter it = _gModel->firstVertex(); it != _gModel->lastVertex(); ++it)
1441 GVertex *gVertex = *it;
1443 for(unsigned int i = 0; i < gVertex->mesh_vertices.size(); i++)
1445 MVertex *v = gVertex->mesh_vertices[i];
1446 if ( v->getIndex() >= 0)
1448 outfile << "n" << v->getNum() << " = mesh.AddNode("
1449 << v->x() << ", " << v->y() << ", " << v->z()<< ")"
1450 << " ## tag = " << gVertex->tag() << endl;
1455 for(GModel::eiter it = _gModel->firstEdge(); it != _gModel->lastEdge(); ++it)
1458 outfile << "## GEdge " << gEdge->tag() << endl;
1460 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
1461 if(gEdge->haveParametrization())
1463 if ( gEdge->geomType() != GEntity::CompoundCurve )
1465 for ( size_t i = 0; i < gEdge->mesh_vertices.size(); i++ )
1467 MVertex *v = gEdge->mesh_vertices[i];
1468 if ( v->getIndex() >= 0 )
1470 outfile << "n" << v->getNum() << " = mesh.AddNode("
1471 << v->x() << ", " << v->y() << ", " << v->z()<< ")"
1472 << " ## tag = " << gEdge->tag() << endl;
1477 for ( GModel::fiter it = _gModel->firstFace(); it != _gModel->lastFace(); ++it)
1480 if ( _compounds.size() && gFace->geomType() == GEntity::DiscreteSurface )
1482 outfile << "## GFace " << gFace->tag() << endl;
1484 for ( size_t i = 0; i < gFace->mesh_vertices.size(); i++ )
1486 MVertex *v = gFace->mesh_vertices[i];
1487 if ( v->getIndex() >= 0 )
1489 outfile << "n" << v->getNum() << " = mesh.AddNode("
1490 << v->x() << ", " << v->y() << ", " << v->z()<< ")"
1491 << " ## tag = " << gFace->tag() << endl;
1496 std::vector<MVertex*> verts(3);
1497 for(GModel::eiter it = _gModel->firstEdge(); it != _gModel->lastEdge(); ++it)
1500 outfile << "## GEdge " << gEdge->tag() << endl;
1502 #if GMSH_MAJOR_VERSION >=4 && GMSH_MINOR_VERSION >=8
1503 if(gEdge->haveParametrization())
1505 if ( gEdge->geomType() != GEntity::CompoundCurve )
1507 for ( size_t i = 0; i < gEdge->getNumMeshElements(); i++ )
1509 MElement *e = gEdge->getMeshElement(i);
1511 e->getVertices(verts);
1513 outfile << "e" << e->getNum() << " = mesh.AddEdge(["
1514 << "n" << verts[0]->getNum() << ","
1515 << "n" << verts[1]->getNum();
1516 if ( verts.size() == 3 )
1517 outfile << "n" << verts[2]->getNum();
1518 outfile << "])"<< endl;
1522 for ( GModel::fiter it = _gModel->firstFace(); it != _gModel->lastFace(); ++it)
1525 if ( _compounds.size() && gFace->geomType() == GEntity::DiscreteSurface )
1527 outfile << "## GFace " << gFace->tag() << endl;
1529 for ( size_t i = 0; i < gFace->getNumMeshElements(); i++ )
1531 MElement *e = gFace->getMeshElement(i);
1533 e->getVertices(verts);
1535 outfile << "f" << e->getNum() << " = mesh.AddFace([";
1536 for ( size_t j = 0; j < verts.size(); j++)
1538 outfile << "n" << verts[j]->getNum();
1539 if ( j < verts.size()-1 )
1542 outfile << "])" << endl;
1545 std::cout << "Write " << pyFile << std::endl;