1 // Copyright (C) 2007-2019 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // NETGENPlugin : C++ implementation
24 // File : NETGENPlugin_Mesher.cxx
25 // Author : Michael Sazonov (OCN)
28 //=============================================================================
30 #include "NETGENPlugin_Mesher.hxx"
31 #include "NETGENPlugin_Hypothesis_2D.hxx"
32 #include "NETGENPlugin_SimpleHypothesis_3D.hxx"
34 #include <SMDS_FaceOfNodes.hxx>
35 #include <SMDS_LinearEdge.hxx>
36 #include <SMDS_MeshElement.hxx>
37 #include <SMDS_MeshNode.hxx>
38 #include <SMESHDS_Mesh.hxx>
39 #include <SMESH_Block.hxx>
40 #include <SMESH_Comment.hxx>
41 #include <SMESH_ComputeError.hxx>
42 #include <SMESH_ControlPnt.hxx>
43 #include <SMESH_File.hxx>
44 #include <SMESH_Gen_i.hxx>
45 #include <SMESH_Mesh.hxx>
46 #include <SMESH_MesherHelper.hxx>
47 #include <SMESH_subMesh.hxx>
48 #include <StdMeshers_QuadToTriaAdaptor.hxx>
49 #include <StdMeshers_ViscousLayers2D.hxx>
51 #include <SALOMEDS_Tool.hxx>
53 #include <utilities.h>
55 #include <BRepAdaptor_Surface.hxx>
56 #include <BRepBuilderAPI_Copy.hxx>
57 #include <BRepLProp_SLProps.hxx>
58 #include <BRepMesh_IncrementalMesh.hxx>
59 #include <BRep_Builder.hxx>
60 #include <BRep_Tool.hxx>
61 #include <Bnd_B3d.hxx>
62 #include <GeomLib_IsPlanarSurface.hxx>
63 #include <NCollection_Map.hxx>
64 #include <Poly_Triangulation.hxx>
65 #include <Standard_ErrorHandler.hxx>
66 #include <Standard_ProgramError.hxx>
67 #include <TColStd_MapOfInteger.hxx>
69 #include <TopExp_Explorer.hxx>
70 #include <TopLoc_Location.hxx>
71 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
72 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
73 #include <TopTools_DataMapOfShapeInteger.hxx>
74 #include <TopTools_DataMapOfShapeShape.hxx>
75 #include <TopTools_MapOfShape.hxx>
77 #include <TopoDS_Compound.hxx>
79 // Netgen include files
83 #include <occgeom.hpp>
84 #include <meshing.hpp>
85 //#include <ngexception.hpp>
88 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, MeshingParameters&, int, int);
90 extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*);
92 //extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh);
94 NETGENPLUGIN_DLL_HEADER
95 extern MeshingParameters mparam;
97 NETGENPLUGIN_DLL_HEADER
98 extern volatile multithreadt multithread;
100 NETGENPLUGIN_DLL_HEADER
101 extern bool merge_solids;
103 // values used for occgeo.facemeshstatus
104 enum EFaceMeshStatus { FACE_NOT_TREATED = 0,
116 using namespace nglib;
120 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec.at((index)))
122 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec[index])
125 #define NGPOINT_COORDS(p) p(0),p(1),p(2)
128 // dump elements added to ng mesh
129 //#define DUMP_SEGMENTS
130 //#define DUMP_TRIANGLES
131 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids()
134 TopTools_IndexedMapOfShape ShapesWithLocalSize;
135 std::map<int,double> VertexId2LocalSize;
136 std::map<int,double> EdgeId2LocalSize;
137 std::map<int,double> FaceId2LocalSize;
138 std::map<int,double> SolidId2LocalSize;
140 std::vector<SMESHUtils::ControlPnt> ControlPoints;
141 std::set<int> ShapesWithControlPoints; // <-- allows calling SetLocalSize() several times w/o recomputing ControlPoints
145 //=============================================================================
147 * Link - a pair of integer numbers
149 //=============================================================================
153 Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
154 Link() : n1(0), n2(0) {}
155 bool Contains( int n ) const { return n == n1 || n == n2; }
156 bool IsConnected( const Link& other ) const
158 return (( Contains( other.n1 ) || Contains( other.n2 )) && ( this != &other ));
160 static int HashCode(const Link& aLink, int aLimit)
162 return ::HashCode(aLink.n1 + aLink.n2, aLimit);
165 static Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
167 return (( aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ) ||
168 ( aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1 ));
172 typedef NCollection_Map<Link,Link> TLinkMap;
174 //================================================================================
176 * \brief return id of netgen point corresponding to SMDS node
178 //================================================================================
179 typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
181 int ngNodeId( const SMDS_MeshNode* node,
182 netgen::Mesh& ngMesh,
183 TNode2IdMap& nodeNgIdMap)
185 int newNgId = ngMesh.GetNP() + 1;
187 TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
189 if ( node_id->second == newNgId)
191 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
192 cout << "Ng " << newNgId << " - " << node;
194 netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
195 ngMesh.AddPoint( p );
197 return node_id->second;
200 //================================================================================
202 * \brief Return computed EDGEs connected to the given one
204 //================================================================================
206 list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge& edge,
207 const TopoDS_Face& face,
208 const set< SMESH_subMesh* > & computedSM,
209 const SMESH_MesherHelper& helper,
210 map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
213 list< TopoDS_Edge > edges;
214 list< int > nbEdgesInWire;
215 /*int nbWires =*/ SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire);
217 // find <edge> within <edges>
218 list< TopoDS_Edge >::iterator eItFwd = edges.begin();
219 for ( ; eItFwd != edges.end(); ++eItFwd )
220 if ( edge.IsSame( *eItFwd ))
222 if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
224 if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
226 // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
227 // so treat each INTERNAL edge separately
228 TopoDS_Edge e = *eItFwd;
230 edges.push_back( e );
234 // get all computed EDGEs connected to <edge>
236 list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
237 TopoDS_Vertex vCommon;
238 TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
241 // put edges before <edge> to <edges> back
242 while ( edges.begin() != eItFwd )
243 edges.splice( edges.end(), edges, edges.begin() );
247 while ( ++eItFwd != edges.end() )
249 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
251 bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
252 bool computed = sm->IsMeshComputed();
253 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
254 bool doubled = !eAdded.Add( *eItFwd );
255 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
256 ( eItFwd->Orientation() < TopAbs_INTERNAL ) );
257 if ( !connected || !computed || !orientOK || added || doubled )
259 // stop advancement; move edges from tail to head
260 while ( edges.back() != *ePrev )
261 edges.splice( edges.begin(), edges, --edges.end() );
267 while ( eItBack != edges.begin() )
271 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
273 bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
274 bool computed = sm->IsMeshComputed();
275 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
276 bool doubled = !eAdded.Add( *eItBack );
277 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
278 ( eItBack->Orientation() < TopAbs_INTERNAL ) );
279 if ( !connected || !computed || !orientOK || added || doubled)
282 edges.erase( edges.begin(), ePrev );
286 if ( edges.front() != edges.back() )
288 // assure that the 1st vertex is meshed
289 TopoDS_Edge eLast = edges.back();
290 while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
292 edges.front() != eLast )
293 edges.splice( edges.end(), edges, edges.begin() );
298 //================================================================================
300 * \brief Make triangulation of a shape precise enough
302 //================================================================================
304 void updateTriangulation( const TopoDS_Shape& shape )
306 // static set< Poly_Triangulation* > updated;
308 // TopLoc_Location loc;
309 // TopExp_Explorer fExp( shape, TopAbs_FACE );
310 // for ( ; fExp.More(); fExp.Next() )
312 // Handle(Poly_Triangulation) triangulation =
313 // BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
314 // if ( triangulation.IsNull() ||
315 // updated.insert( triangulation.operator->() ).second )
317 // BRepTools::Clean (shape);
320 BRepMesh_IncrementalMesh e(shape, 0.01, true);
322 catch (Standard_Failure)
325 // updated.erase( triangulation.operator->() );
326 // triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
327 // updated.insert( triangulation.operator->() );
331 //================================================================================
333 * \brief Returns a medium node either existing in SMESH of created by NETGEN
334 * \param [in] corner1 - corner node 1
335 * \param [in] corner2 - corner node 2
336 * \param [in] defaultMedium - the node created by NETGEN
337 * \param [in] helper - holder of medium nodes existing in SMESH
338 * \return const SMDS_MeshNode* - the result node
340 //================================================================================
342 const SMDS_MeshNode* mediumNode( const SMDS_MeshNode* corner1,
343 const SMDS_MeshNode* corner2,
344 const SMDS_MeshNode* defaultMedium,
345 const SMESH_MesherHelper* helper)
349 TLinkNodeMap::const_iterator l2n =
350 helper->GetTLinkNodeMap().find( SMESH_TLink( corner1, corner2 ));
351 if ( l2n != helper->GetTLinkNodeMap().end() )
352 defaultMedium = l2n->second;
354 return defaultMedium;
357 //================================================================================
359 * \brief Assure that mesh on given shapes is quadratic
361 //================================================================================
363 // void makeQuadratic( const TopTools_IndexedMapOfShape& shapes,
364 // SMESH_Mesh* mesh )
366 // for ( int i = 1; i <= shapes.Extent(); ++i )
368 // SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) );
369 // if ( !smDS ) continue;
370 // SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
371 // if ( !elemIt->more() ) continue;
372 // const SMDS_MeshElement* e = elemIt->next();
373 // if ( !e || e->IsQuadratic() )
376 // TIDSortedElemSet elems;
377 // elems.insert( e );
378 // while ( elemIt->more() )
379 // elems.insert( elems.end(), elemIt->next() );
381 // SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false );
385 //================================================================================
387 * \brief Restrict size of elements on the given edge
389 //================================================================================
391 void setLocalSize(const TopoDS_Edge& edge,
394 const bool overrideMinH = true)
396 if ( size <= std::numeric_limits<double>::min() )
398 Standard_Real u1, u2;
399 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
400 if ( curve.IsNull() )
402 TopoDS_Iterator vIt( edge );
403 if ( !vIt.More() ) return;
404 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
405 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH );
409 const int nb = (int)( 1.5 * SMESH_Algo::EdgeLength( edge ) / size );
410 Standard_Real delta = (u2-u1)/nb;
411 for(int i=0; i<nb; i++)
413 Standard_Real u = u1 + delta*i;
414 gp_Pnt p = curve->Value(u);
415 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH );
416 netgen::Point3d pi(p.X(), p.Y(), p.Z());
417 double resultSize = mesh.GetH(pi);
418 if ( resultSize - size > 0.1*size )
419 // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
420 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201, overrideMinH );
425 //================================================================================
427 * \brief Return triangle size for a given chordalError and radius of curvature
429 //================================================================================
431 double elemSizeForChordalError( double chordalError, double radius )
433 if ( 2 * radius < chordalError )
435 return Sqrt( 3 ) * Sqrt( chordalError * ( 2 * radius - chordalError ));
438 //=============================================================================
442 //=============================================================================
444 void setLocalSize(const TopoDS_Shape& GeomShape, double LocalSize)
446 if ( GeomShape.IsNull() ) return;
447 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
448 if (GeomType == TopAbs_COMPOUND) {
449 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
450 setLocalSize(it.Value(), LocalSize);
455 if (! ShapesWithLocalSize.Contains(GeomShape))
456 key = ShapesWithLocalSize.Add(GeomShape);
458 key = ShapesWithLocalSize.FindIndex(GeomShape);
459 if (GeomType == TopAbs_VERTEX) {
460 VertexId2LocalSize[key] = LocalSize;
461 } else if (GeomType == TopAbs_EDGE) {
462 EdgeId2LocalSize[key] = LocalSize;
463 } else if (GeomType == TopAbs_FACE) {
464 FaceId2LocalSize[key] = LocalSize;
465 } else if (GeomType == TopAbs_SOLID) {
466 SolidId2LocalSize[key] = LocalSize;
471 //================================================================================
473 * \brief Return faceNgID or faceNgID-1 depending on side the given proxy face lies
474 * \param [in] f - proxy face
475 * \param [in] solidSMDSIDs - IDs of SOLIDs sharing the FACE on which face lies
476 * \param [in] faceNgID - NETGEN ID of the FACE
477 * \return int - NETGEN ID of the FACE
479 //================================================================================
481 int getFaceNgID( const SMDS_MeshElement* face,
482 const int * solidSMDSIDs,
485 for ( int i = 0; i < 3; ++i )
487 const SMDS_MeshNode* n = face->GetNode( i );
488 const int shapeID = n->GetShapeID();
489 if ( shapeID == solidSMDSIDs[0] )
491 if ( shapeID == solidSMDSIDs[1] )
494 std::vector<const SMDS_MeshNode*> fNodes( face->begin_nodes(), face->end_nodes() );
495 std::vector<const SMDS_MeshElement*> vols;
496 if ( SMDS_Mesh::GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ))
497 for ( size_t i = 0; i < vols.size(); ++i )
499 const int shapeID = vols[i]->GetShapeID();
500 if ( shapeID == solidSMDSIDs[0] )
502 if ( shapeID == solidSMDSIDs[1] )
510 //=============================================================================
514 //=============================================================================
516 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh,
517 const TopoDS_Shape& aShape,
523 _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
524 _isViscousLayers2D(false),
525 _chordalError(-1), // means disabled
532 _viscousLayersHyp(NULL),
535 SetDefaultParameters();
536 ShapesWithLocalSize.Clear();
537 VertexId2LocalSize.clear();
538 EdgeId2LocalSize.clear();
539 FaceId2LocalSize.clear();
540 SolidId2LocalSize.clear();
541 ControlPoints.clear();
542 ShapesWithControlPoints.clear();
545 //================================================================================
549 //================================================================================
551 NETGENPlugin_Mesher::~NETGENPlugin_Mesher()
559 //================================================================================
561 * Set pointer to NETGENPlugin_Mesher* field of the holder, that will be
562 * nullified at destruction of this
564 //================================================================================
566 void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr )
577 //================================================================================
579 * \brief Initialize global NETGEN parameters with default values
581 //================================================================================
583 void NETGENPlugin_Mesher::SetDefaultParameters()
585 netgen::MeshingParameters& mparams = netgen::mparam;
586 mparams = netgen::MeshingParameters();
587 // maximal mesh edge size
588 mparams.maxh = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
590 // minimal number of segments per edge
591 mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
592 // rate of growth of size between elements
593 mparams.grading = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
594 // safety factor for curvatures (elements per radius)
595 mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
596 // create elements of second order
597 mparams.secondorder = NETGENPlugin_Hypothesis::GetDefaultSecondOrder();
598 // quad-dominated surface meshing
602 mparams.quad = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed();
603 _fineness = NETGENPlugin_Hypothesis::GetDefaultFineness();
604 mparams.uselocalh = NETGENPlugin_Hypothesis::GetDefaultSurfaceCurvature();
605 netgen::merge_solids = NETGENPlugin_Hypothesis::GetDefaultFuseEdges();
608 //=============================================================================
610 * Pass parameters to NETGEN
612 //=============================================================================
613 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
617 netgen::MeshingParameters& mparams = netgen::mparam;
618 // Initialize global NETGEN parameters:
619 // maximal mesh segment size
620 mparams.maxh = hyp->GetMaxSize();
621 // maximal mesh element linear size
622 mparams.minh = hyp->GetMinSize();
623 // minimal number of segments per edge
624 mparams.segmentsperedge = hyp->GetNbSegPerEdge();
625 // rate of growth of size between elements
626 mparams.grading = hyp->GetGrowthRate();
627 // safety factor for curvatures (elements per radius)
628 mparams.curvaturesafety = hyp->GetNbSegPerRadius();
629 // create elements of second order
630 mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
631 // quad-dominated surface meshing
632 mparams.quad = hyp->GetQuadAllowed() ? 1 : 0;
633 _optimize = hyp->GetOptimize();
634 _fineness = hyp->GetFineness();
635 mparams.uselocalh = hyp->GetSurfaceCurvature();
636 netgen::merge_solids = hyp->GetFuseEdges();
637 _chordalError = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
638 mparams.optsteps2d = _optimize ? hyp->GetNbSurfOptSteps() : 0;
639 mparams.optsteps3d = _optimize ? hyp->GetNbVolOptSteps() : 0;
640 mparams.elsizeweight = hyp->GetElemSizeWeight();
641 mparams.opterrpow = hyp->GetWorstElemMeasure();
642 mparams.delaunay = hyp->GetUseDelauney();
643 mparams.checkoverlap = hyp->GetCheckOverlapping();
644 mparams.checkchartboundary = hyp->GetCheckChartBoundary();
647 mparams.meshsizefilename= hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
649 const NETGENPlugin_Hypothesis::TLocalSize& localSizes = hyp->GetLocalSizesAndEntries();
650 if ( !localSizes.empty() )
652 SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
653 NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
654 for ( ; it != localSizes.end() ; it++)
656 std::string entry = (*it).first;
657 double val = (*it).second;
659 GEOM::GEOM_Object_var aGeomObj;
660 SALOMEDS::SObject_var aSObj = SMESH_Gen_i::getStudyServant()->FindObjectID( entry.c_str() );
661 if ( !aSObj->_is_nil() ) {
662 CORBA::Object_var obj = aSObj->GetObject();
663 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
666 TopoDS_Shape S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
667 setLocalSize(S, val);
673 //=============================================================================
675 * Pass simple parameters to NETGEN
677 //=============================================================================
679 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
683 SetDefaultParameters();
686 //================================================================================
688 * \brief Store a Viscous Layers hypothesis
690 //================================================================================
692 void NETGENPlugin_Mesher::SetParameters(const StdMeshers_ViscousLayers* hyp )
694 _viscousLayersHyp = hyp;
697 //================================================================================
699 * \brief Set local size on shapes defined by SetParameters()
701 //================================================================================
703 void NETGENPlugin_Mesher::SetLocalSize( netgen::OCCGeometry& occgeo,
704 netgen::Mesh& ngMesh)
707 std::map<int,double>::const_iterator it;
708 for( it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
710 int key = (*it).first;
711 double hi = (*it).second;
712 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
713 setLocalSize( TopoDS::Edge(shape), hi, ngMesh );
716 for(it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
718 int key = (*it).first;
719 double hi = (*it).second;
720 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
721 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex(shape) );
722 NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, p.XYZ(), hi );
725 for(it=FaceId2LocalSize.begin(); it!=FaceId2LocalSize.end(); it++)
727 int key = (*it).first;
728 double val = (*it).second;
729 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
730 int faceNgID = occgeo.fmap.FindIndex(shape);
733 occgeo.SetFaceMaxH(faceNgID, val);
734 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
735 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, ngMesh );
737 else if ( !ShapesWithControlPoints.count( key ))
739 SMESHUtils::createPointsSampleFromFace( TopoDS::Face( shape ), val, ControlPoints );
740 ShapesWithControlPoints.insert( key );
744 for(it=SolidId2LocalSize.begin(); it!=SolidId2LocalSize.end(); it++)
746 int key = (*it).first;
747 double val = (*it).second;
748 if ( !ShapesWithControlPoints.count( key ))
750 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
751 SMESHUtils::createPointsSampleFromSolid( TopoDS::Solid( shape ), val, ControlPoints );
752 ShapesWithControlPoints.insert( key );
756 if ( !ControlPoints.empty() )
758 for ( size_t i = 0; i < ControlPoints.size(); ++i )
759 NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, ControlPoints[i].XYZ(), ControlPoints[i].Size() );
764 //================================================================================
766 * \brief Restrict local size to achieve a required _chordalError
768 //================================================================================
770 void NETGENPlugin_Mesher::SetLocalSizeForChordalError( netgen::OCCGeometry& occgeo,
771 netgen::Mesh& ngMesh)
773 if ( _chordalError <= 0. )
777 BRepLProp_SLProps surfProp( 2, 1e-6 );
778 const double sizeCoef = 0.95;
780 // find non-planar FACEs with non-constant curvature
781 std::vector<int> fInd;
782 for ( int i = 1; i <= occgeo.fmap.Extent(); ++i )
784 const TopoDS_Face& face = TopoDS::Face( occgeo.fmap( i ));
785 BRepAdaptor_Surface surfAd( face, false );
786 switch ( surfAd.GetType() )
790 case GeomAbs_Cylinder:
792 case GeomAbs_Torus: // constant curvature
794 surfProp.SetSurface( surfAd );
795 surfProp.SetParameters( 0, 0 );
796 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
797 double size = elemSizeForChordalError( _chordalError, 1 / maxCurv );
798 occgeo.SetFaceMaxH( i, size * sizeCoef );
799 // limit size one edges
800 TopTools_MapOfShape edgeMap;
801 for ( TopExp_Explorer eExp( face, TopAbs_EDGE ); eExp.More(); eExp.Next() )
802 if ( edgeMap.Add( eExp.Current() ))
803 setLocalSize( TopoDS::Edge( eExp.Current() ), size, ngMesh, /*overrideMinH=*/false );
807 Handle(Geom_Surface) surf = BRep_Tool::Surface( face, loc );
808 if ( GeomLib_IsPlanarSurface( surf ).IsPlanar() )
817 TopoDS_Compound allFacesComp;
818 b.MakeCompound( allFacesComp );
819 for ( size_t i = 0; i < fInd.size(); ++i )
820 b.Add( allFacesComp, occgeo.fmap( fInd[i] ));
822 // copy the shape to avoid spoiling its triangulation
823 TopoDS_Shape allFacesCompCopy = BRepBuilderAPI_Copy( allFacesComp );
825 // create triangulation with desired chordal error
826 BRepMesh_IncrementalMesh( allFacesCompCopy,
828 /*isRelative = */Standard_False,
829 /*theAngDeflection = */ 0.5,
830 /*isInParallel = */Standard_True);
833 for ( TopExp_Explorer fExp( allFacesCompCopy, TopAbs_FACE ); fExp.More(); fExp.Next() )
835 const TopoDS_Face& face = TopoDS::Face( fExp.Current() );
836 Handle(Poly_Triangulation) triangulation = BRep_Tool::Triangulation ( face, loc );
837 if ( triangulation.IsNull() ) continue;
839 BRepAdaptor_Surface surf( face, false );
840 surfProp.SetSurface( surf );
845 for ( int i = 1; i <= triangulation->NbTriangles(); ++i )
847 Standard_Integer n1,n2,n3;
848 triangulation->Triangles()(i).Get( n1,n2,n3 );
849 p [0] = triangulation->Nodes()(n1).Transformed(loc).XYZ();
850 p [1] = triangulation->Nodes()(n2).Transformed(loc).XYZ();
851 p [2] = triangulation->Nodes()(n3).Transformed(loc).XYZ();
852 uv[0] = triangulation->UVNodes()(n1).XY();
853 uv[1] = triangulation->UVNodes()(n2).XY();
854 uv[2] = triangulation->UVNodes()(n3).XY();
855 surfProp.SetParameters( uv[0].X(), uv[0].Y() );
856 if ( !surfProp.IsCurvatureDefined() )
859 for ( int n = 0; n < 3; ++n ) // get size at triangle nodes
861 surfProp.SetParameters( uv[n].X(), uv[n].Y() );
862 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
863 size[n] = elemSizeForChordalError( _chordalError, 1 / maxCurv );
865 for ( int n1 = 0; n1 < 3; ++n1 ) // limit size along each triangle edge
867 int n2 = ( n1 + 1 ) % 3;
868 double minSize = size[n1], maxSize = size[n2];
869 if ( size[n1] > size[n2] )
870 minSize = size[n2], maxSize = size[n1];
872 if ( maxSize / minSize < 1.2 ) // netgen ignores size difference < 1.2
874 ngMesh.RestrictLocalHLine ( netgen::Point3d( p[n1].X(), p[n1].Y(), p[n1].Z() ),
875 netgen::Point3d( p[n2].X(), p[n2].Y(), p[n2].Z() ),
876 sizeCoef * minSize );
880 gp_XY uvVec( uv[n2] - uv[n1] );
881 double len = ( p[n1] - p[n2] ).Modulus();
882 int nb = int( len / minSize ) + 1;
883 for ( int j = 0; j <= nb; ++j )
885 double r = double( j ) / nb;
886 gp_XY uvj = uv[n1] + r * uvVec;
888 surfProp.SetParameters( uvj.X(), uvj.Y() );
889 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
890 double h = elemSizeForChordalError( _chordalError, 1 / maxCurv );
892 const gp_Pnt& pj = surfProp.Value();
893 netgen::Point3d ngP( pj.X(), pj.Y(), pj.Z());
894 ngMesh.RestrictLocalH( ngP, h * sizeCoef );
903 //================================================================================
905 * \brief Initialize netgen::OCCGeometry with OCCT shape
907 //================================================================================
909 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo,
910 const TopoDS_Shape& shape,
912 list< SMESH_subMesh* > * meshedSM,
913 NETGENPlugin_Internals* intern)
915 updateTriangulation( shape );
918 BRepBndLib::Add (shape, bb);
919 double x1,y1,z1,x2,y2,z2;
920 bb.Get (x1,y1,z1,x2,y2,z2);
921 netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
922 netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
923 occgeo.boundingbox = netgen::Box<3> (p1,p2);
925 occgeo.shape = shape;
928 // fill maps of shapes of occgeo with not yet meshed subshapes
930 // get root submeshes
931 list< SMESH_subMesh* > rootSM;
932 const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
933 if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
934 rootSM.push_back( mesh.GetSubMesh( shape ));
937 for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
938 rootSM.push_back( mesh.GetSubMesh( it.Value() ));
943 // add subshapes of empty submeshes
944 list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
945 for ( ; rootIt != rootEnd; ++rootIt ) {
946 SMESH_subMesh * root = *rootIt;
947 SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
948 /*complexShapeFirst=*/true);
949 // to find a right orientation of subshapes (PAL20462)
950 TopTools_IndexedMapOfShape subShapes;
951 TopExp::MapShapes(root->GetSubShape(), subShapes);
952 while ( smIt->more() )
954 SMESH_subMesh* sm = smIt->next();
955 TopoDS_Shape shape = sm->GetSubShape();
956 totNbFaces += ( shape.ShapeType() == TopAbs_FACE );
957 if ( intern && intern->isShapeToPrecompute( shape ))
959 if ( !meshedSM || sm->IsEmpty() )
961 if ( shape.ShapeType() != TopAbs_VERTEX )
962 shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
963 if ( shape.Orientation() >= TopAbs_INTERNAL )
964 shape.Orientation( TopAbs_FORWARD ); // issue 0020676
965 switch ( shape.ShapeType() ) {
966 case TopAbs_FACE : occgeo.fmap.Add( shape ); break;
967 case TopAbs_EDGE : occgeo.emap.Add( shape ); break;
968 case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
969 case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
973 // collect submeshes of meshed shapes
976 const int dim = SMESH_Gen::GetShapeDim( shape );
977 meshedSM[ dim ].push_back( sm );
981 occgeo.facemeshstatus.SetSize (totNbFaces);
982 occgeo.facemeshstatus = 0;
983 occgeo.face_maxh_modified.SetSize(totNbFaces);
984 occgeo.face_maxh_modified = 0;
985 occgeo.face_maxh.SetSize(totNbFaces);
986 occgeo.face_maxh = netgen::mparam.maxh;
989 //================================================================================
991 * \brief Return a default min size value suitable for the given geometry.
993 //================================================================================
995 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
996 const double maxSize)
998 updateTriangulation( geom );
1000 TopLoc_Location loc;
1002 const int* pi[4] = { &i1, &i2, &i3, &i1 };
1003 double minh = 1e100;
1005 TopExp_Explorer fExp( geom, TopAbs_FACE );
1006 for ( ; fExp.More(); fExp.Next() )
1008 Handle(Poly_Triangulation) triangulation =
1009 BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
1010 if ( triangulation.IsNull() ) continue;
1011 const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
1012 const TColgp_Array1OfPnt& points = triangulation->Nodes();
1013 const Poly_Array1OfTriangle& trias = triangulation->Triangles();
1014 for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
1016 trias(iT).Get( i1, i2, i3 );
1017 for ( int j = 0; j < 3; ++j )
1019 double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
1020 if ( dist2 < minh && fTol*fTol < dist2 )
1022 bb.Add( points(*pi[j]));
1026 if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
1028 minh = 1e-3 * sqrt( bb.SquareExtent());
1029 //cout << "BND BOX minh = " <<minh << endl;
1033 minh = sqrt( minh ); // triangulation for visualization is rather fine
1034 //cout << "TRIANGULATION minh = " <<minh << endl;
1036 if ( minh > 0.5 * maxSize )
1037 minh = maxSize / 3.;
1042 //================================================================================
1044 * \brief Restrict size of elements at a given point
1046 //================================================================================
1048 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh,
1051 const bool overrideMinH)
1053 if ( size <= std::numeric_limits<double>::min() )
1055 if ( netgen::mparam.minh > size )
1059 ngMesh.SetMinimalH( size );
1060 netgen::mparam.minh = size;
1064 size = netgen::mparam.minh;
1067 netgen::Point3d pi(p.X(), p.Y(), p.Z());
1068 ngMesh.RestrictLocalH( pi, size );
1071 //================================================================================
1073 * \brief fill ngMesh with nodes and elements of computed submeshes
1075 //================================================================================
1077 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom,
1078 netgen::Mesh& ngMesh,
1079 vector<const SMDS_MeshNode*>& nodeVec,
1080 const list< SMESH_subMesh* > & meshedSM,
1081 SMESH_MesherHelper* quadHelper,
1082 SMESH_ProxyMesh::Ptr proxyMesh)
1084 TNode2IdMap nodeNgIdMap;
1085 for ( size_t i = 1; i < nodeVec.size(); ++i )
1086 nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
1088 TopTools_MapOfShape visitedShapes;
1089 map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
1090 set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
1092 SMESH_MesherHelper helper (*_mesh);
1093 SMESHDS_Mesh* meshDS = _mesh->GetMeshDS();
1095 int faceNgID = ngMesh.GetNFD();
1097 list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
1098 for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
1100 SMESH_subMesh* sm = *smIt;
1101 if ( !visitedShapes.Add( sm->GetSubShape() ))
1104 const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
1105 if ( !smDS ) continue;
1107 switch ( sm->GetSubShape().ShapeType() )
1109 case TopAbs_EDGE: { // EDGE
1110 // ----------------------
1111 TopoDS_Edge geomEdge = TopoDS::Edge( sm->GetSubShape() );
1112 if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
1113 geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
1115 // Add ng segments for each not meshed FACE the EDGE bounds
1116 PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
1117 while ( const TopoDS_Shape * anc = fIt->next() )
1119 faceNgID = occgeom.fmap.FindIndex( *anc );
1121 continue; // meshed face
1123 int faceSMDSId = meshDS->ShapeToIndex( *anc );
1124 if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
1125 continue; // already treated EDGE
1127 TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
1128 if ( face.Orientation() >= TopAbs_INTERNAL )
1129 face.Orientation( TopAbs_FORWARD ); // issue 0020676
1131 // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
1132 helper.SetSubShape( face );
1133 list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
1134 visitedEdgeSM2Faces );
1135 if ( edges.empty() )
1136 continue; // wrong ancestor?
1138 // find out orientation of <edges> within <face>
1139 TopoDS_Edge eNotSeam = edges.front();
1140 if ( helper.HasSeam() )
1142 list< TopoDS_Edge >::iterator eIt = edges.begin();
1143 while ( helper.IsRealSeam( *eIt )) ++eIt;
1144 if ( eIt != edges.end() )
1147 TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
1148 bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
1150 // get all nodes from connected <edges>
1151 const bool skipMedium = netgen::mparam.secondorder;//smDS->IsQuadratic();
1152 StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, skipMedium, &helper );
1153 const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
1154 if ( points.empty() )
1155 return false; // invalid node params?
1156 int i, nbSeg = fSide.NbSegments();
1158 // remember EDGEs of fSide to treat only once
1159 for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
1160 visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
1162 double otherSeamParam = 0;
1163 bool isSeam = false;
1167 int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
1169 for ( i = 0; i < nbSeg; ++i )
1171 const UVPtStruct& p1 = points[ i ];
1172 const UVPtStruct& p2 = points[ i+1 ];
1174 if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
1177 if ( helper.IsRealSeam( p1.node->GetShapeID() ))
1179 TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
1180 isSeam = helper.IsRealSeam( e );
1183 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
1187 netgen::Segment seg;
1190 seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
1191 // node param on curve
1192 seg.epgeominfo[ 0 ].dist = p1.param;
1193 seg.epgeominfo[ 1 ].dist = p2.param;
1195 seg.epgeominfo[ 0 ].u = p1.u;
1196 seg.epgeominfo[ 0 ].v = p1.v;
1197 seg.epgeominfo[ 1 ].u = p2.u;
1198 seg.epgeominfo[ 1 ].v = p2.v;
1200 //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
1201 //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
1203 //seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
1204 seg.si = faceNgID; // = geom.fmap.FindIndex (face);
1205 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1206 ngMesh.AddSegment (seg);
1208 SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
1209 RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
1211 #ifdef DUMP_SEGMENTS
1212 cout << "Segment: " << seg.edgenr << " on SMESH face " << meshDS->ShapeToIndex( face ) << endl
1213 << "\tface index: " << seg.si << endl
1214 << "\tp1: " << seg[0] << endl
1215 << "\tp2: " << seg[1] << endl
1216 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1217 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1218 //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1219 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1220 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
1221 //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1225 if ( helper.GetPeriodicIndex() && 1 ) {
1226 seg.epgeominfo[ 0 ].u = otherSeamParam;
1227 seg.epgeominfo[ 1 ].u = otherSeamParam;
1228 swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
1230 seg.epgeominfo[ 0 ].v = otherSeamParam;
1231 seg.epgeominfo[ 1 ].v = otherSeamParam;
1232 swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
1234 swap( seg[0], seg[1] );
1235 swap( seg.epgeominfo[0].dist, seg.epgeominfo[1].dist );
1236 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1237 ngMesh.AddSegment( seg );
1238 #ifdef DUMP_SEGMENTS
1239 cout << "Segment: " << seg.edgenr << endl
1240 << "\t is SEAM (reverse) of the previous. "
1241 << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
1242 << " = " << otherSeamParam << endl;
1245 else if ( fOri == TopAbs_INTERNAL )
1247 swap( seg[0], seg[1] );
1248 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1249 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1250 ngMesh.AddSegment( seg );
1251 #ifdef DUMP_SEGMENTS
1252 cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
1256 } // loop on geomEdge ancestors
1258 if ( quadHelper ) // remember medium nodes of sub-meshes
1260 SMDS_ElemIteratorPtr edges = smDS->GetElements();
1261 while ( edges->more() )
1263 const SMDS_MeshElement* e = edges->next();
1264 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshEdge*>( e )))
1270 } // case TopAbs_EDGE
1272 case TopAbs_FACE: { // FACE
1273 // ----------------------
1274 const TopoDS_Face& geomFace = TopoDS::Face( sm->GetSubShape() );
1275 helper.SetSubShape( geomFace );
1276 bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
1278 // Find solids the geomFace bounds
1279 int solidID1 = 0, solidID2 = 0; // ng IDs
1280 int solidSMDSIDs[2] = { 0,0 }; // smds IDs
1282 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
1283 while ( const TopoDS_Shape * solid = solidIt->next() )
1285 int id = occgeom.somap.FindIndex ( *solid );
1286 if ( solidID1 && id != solidID1 ) solidID2 = id;
1288 if ( id ) solidSMDSIDs[ bool( solidSMDSIDs[0] )] = meshDS->ShapeToIndex( *solid );
1291 if ( proxyMesh && proxyMesh->GetProxySubMesh( geomFace ))
1293 // if a proxy sub-mesh contains temporary faces, then these faces
1294 // should be used to mesh only one SOLID
1295 bool hasTmp = false;
1296 smDS = proxyMesh->GetSubMesh( geomFace );
1297 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1298 while ( faces->more() )
1300 const SMDS_MeshElement* f = faces->next();
1301 if ( proxyMesh->IsTemporary( f ))
1304 if ( solidSMDSIDs[1] && proxyMesh->HasPrismsOnTwoSides( meshDS->MeshElements( geomFace )))
1307 solidSMDSIDs[1] = 0;
1308 std::vector<const SMDS_MeshNode*> fNodes( f->begin_nodes(), f->end_nodes() );
1309 std::vector<const SMDS_MeshElement*> vols;
1310 if ( meshDS->GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ) == 1 )
1312 int geomID = vols[0]->GetShapeID();
1313 const TopoDS_Shape& solid = meshDS->IndexToShape( geomID );
1314 if ( !solid.IsNull() )
1315 solidID1 = occgeom.somap.FindIndex ( solid );
1321 const int fID = occgeom.fmap.FindIndex( geomFace );
1322 if ( !hasTmp ) // shrunk mesh
1324 // move netgen points according to moved nodes
1325 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
1326 while ( smIt->more() )
1328 SMESH_subMesh* sub = smIt->next();
1329 if ( !sub->GetSubMeshDS() ) continue;
1330 SMDS_NodeIteratorPtr nodeIt = sub->GetSubMeshDS()->GetNodes();
1331 while ( nodeIt->more() )
1333 const SMDS_MeshNode* n = nodeIt->next();
1334 int ngID = ngNodeId( n, ngMesh, nodeNgIdMap );
1335 netgen::MeshPoint& ngPoint = ngMesh.Point( ngID );
1336 ngPoint(0) = n->X();
1337 ngPoint(1) = n->Y();
1338 ngPoint(2) = n->Z();
1341 // remove faces near boundary to avoid their overlapping
1342 // with shrunk faces
1343 for ( int i = 1; i <= ngMesh.GetNSE(); ++i )
1345 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1346 if ( elem.GetIndex() == fID )
1348 for ( int iN = 0; iN < elem.GetNP(); ++iN )
1349 if ( ngMesh[ elem[ iN ]].Type() != netgen::SURFACEPOINT )
1351 ngMesh.DeleteSurfaceElement( i );
1357 // exclude faces generated by NETGEN from computation of 3D mesh
1361 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID,/*solid1=*/0,/*solid2=*/0,0 ));
1362 for (int i = 1; i <= ngMesh.GetNSE(); ++i )
1364 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1365 if ( elem.GetIndex() == fID )
1366 const_cast< netgen::Element2d& >( elem ).SetIndex( faceNgID );
1372 solidSMDSIDs[1] = 0;
1374 const bool hasVLOn2Sides = ( solidSMDSIDs[1] > 0 );
1376 // Add ng face descriptors of meshed faces
1378 if ( hasVLOn2Sides )
1380 // viscous layers are on two sides of the FACE
1381 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, 0, 0 ));
1383 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, 0, solidID2, 0 ));
1387 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, solidID2, 0 ));
1389 // if second oreder is required, even already meshed faces must be passed to NETGEN
1390 int fID = occgeom.fmap.Add( geomFace );
1391 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1392 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1393 while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
1395 fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
1396 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1397 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1399 // Problem with the second order in a quadrangular mesh remains.
1400 // 1) All quadrangles generated by NETGEN are moved to an inexistent face
1401 // by FillSMesh() (find "AddFaceDescriptor")
1402 // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
1403 // are on faces where quadrangles were.
1404 // Due to these 2 points, wrong geom faces are used while conversion to quadratic
1405 // of the mentioned above quadrangles and triangles
1407 // Orient the face correctly in solidID1 (issue 0020206)
1408 bool reverse = false;
1410 TopoDS_Shape solid = occgeom.somap( solidID1 );
1411 TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
1412 if ( faceOriInSolid >= 0 )
1414 helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
1417 // Add surface elements
1419 netgen::Element2d tri(3);
1420 tri.SetIndex( faceNgID );
1421 SMESH_TNodeXYZ xyz[3];
1423 #ifdef DUMP_TRIANGLES
1424 cout << "SMESH face " << meshDS->ShapeToIndex( geomFace )
1425 << " internal="<<isInternalFace << endl;
1428 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1429 while ( faces->more() )
1431 const SMDS_MeshElement* f = faces->next();
1432 if ( f->NbNodes() % 3 != 0 ) // not triangle
1434 PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID);
1435 if ( const TopoDS_Shape * solid = solidIt->next() )
1436 sm = _mesh->GetSubMesh( *solid );
1437 SMESH_BadInputElements* badElems =
1438 new SMESH_BadInputElements( meshDS, COMPERR_BAD_INPUT_MESH, "Not triangle sub-mesh");
1440 sm->GetComputeError().reset( badElems );
1444 if ( hasVLOn2Sides )
1445 tri.SetIndex( getFaceNgID( f, solidSMDSIDs, faceNgID ));
1447 for ( int i = 0; i < 3; ++i )
1449 const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
1452 // get node UV on face
1453 int shapeID = node->GetShapeID();
1454 if ( helper.IsSeamShape( shapeID ))
1456 if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->GetShapeID() ))
1457 inFaceNode = f->GetNodeWrap( i-1 );
1459 inFaceNode = f->GetNodeWrap( i+1 );
1461 gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
1463 int ind = reverse ? 3-i : i+1;
1464 tri.GeomInfoPi(ind).u = uv.X();
1465 tri.GeomInfoPi(ind).v = uv.Y();
1466 tri.PNum (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
1469 // pass a triangle size to NG size-map
1470 double size = ( ( xyz[0] - xyz[1] ).Modulus() +
1471 ( xyz[1] - xyz[2] ).Modulus() +
1472 ( xyz[2] - xyz[0] ).Modulus() ) / 3;
1473 gp_XYZ gc = ( xyz[0] + xyz[1] + xyz[2] ) / 3;
1474 RestrictLocalSize( ngMesh, gc, size, /*overrideMinH=*/false );
1476 ngMesh.AddSurfaceElement (tri);
1477 #ifdef DUMP_TRIANGLES
1478 cout << tri << endl;
1481 if ( isInternalFace )
1483 swap( tri[1], tri[2] );
1484 ngMesh.AddSurfaceElement (tri);
1485 #ifdef DUMP_TRIANGLES
1486 cout << tri << endl;
1489 } // loop on sub-mesh faces
1491 if ( quadHelper ) // remember medium nodes of sub-meshes
1493 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1494 while ( faces->more() )
1496 const SMDS_MeshElement* f = faces->next();
1497 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshFace*>( f )))
1503 } // case TopAbs_FACE
1505 case TopAbs_VERTEX: { // VERTEX
1506 // --------------------------
1507 // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
1508 // else netgen removes a free node and nodeVector becomes invalid
1509 PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
1513 while ( const TopoDS_Shape* e = ansIt->next() )
1515 SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
1516 if (( toAdd = ( eSub->IsEmpty() && !SMESH_Algo::isDegenerated( TopoDS::Edge( *e )))))
1521 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
1522 if ( nodeIt->more() )
1523 ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
1529 } // loop on submeshes
1532 nodeVec.resize( ngMesh.GetNP() + 1 );
1533 TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
1534 for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
1535 nodeVec[ node_NgId->second ] = node_NgId->first;
1540 //================================================================================
1542 * \brief Duplicate mesh faces on internal geom faces
1544 //================================================================================
1546 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
1547 netgen::Mesh& ngMesh,
1548 NETGENPlugin_Internals& internalShapes)
1550 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1552 // find ng indices of internal faces
1554 for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
1556 int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
1557 if ( internalShapes.isInternalShape( smeshID ))
1558 ngFaceIds.insert( ngFaceID );
1560 if ( !ngFaceIds.empty() )
1563 int i, nbFaces = ngMesh.GetNSE();
1564 for ( i = 1; i <= nbFaces; ++i)
1566 netgen::Element2d elem = ngMesh.SurfaceElement(i);
1567 if ( ngFaceIds.count( elem.GetIndex() ))
1569 swap( elem[1], elem[2] );
1570 ngMesh.AddSurfaceElement (elem);
1576 //================================================================================
1578 * \brief Tries to heal the mesh on a FACE. The FACE is supposed to be partially
1579 * meshed due to NETGEN failure
1580 * \param [in] occgeom - geometry
1581 * \param [in,out] ngMesh - the mesh to fix
1582 * \param [inout] faceID - ID of the FACE to fix the mesh on
1583 * \return bool - is mesh is or becomes OK
1585 //================================================================================
1587 bool NETGENPlugin_Mesher::FixFaceMesh(const netgen::OCCGeometry& occgeom,
1588 netgen::Mesh& ngMesh,
1591 // we address a case where the FACE is almost fully meshed except small holes
1592 // of usually triangular shape at FACE boundary (IPAL52861)
1594 // The case appeared to be not simple: holes only look triangular but
1595 // indeed are a self intersecting polygon. A reason of the bug was in coincident
1596 // NG points on a seam edge. But the code below is very nice, leave it for
1601 if ( occgeom.fmap.Extent() < faceID )
1603 //const TopoDS_Face& face = TopoDS::Face( occgeom.fmap( faceID ));
1605 // find free links on the FACE
1607 for ( int iF = 1; iF <= ngMesh.GetNSE(); ++iF )
1609 const netgen::Element2d& elem = ngMesh.SurfaceElement(iF);
1610 if ( faceID != elem.GetIndex() )
1612 int n0 = elem[ elem.GetNP() - 1 ];
1613 for ( int i = 0; i < elem.GetNP(); ++i )
1616 Link link( n0, n1 );
1617 if ( !linkMap.Add( link ))
1618 linkMap.Remove( link );
1622 // add/remove boundary links
1623 for ( int iSeg = 1; iSeg <= ngMesh.GetNSeg(); ++iSeg )
1625 const netgen::Segment& seg = ngMesh.LineSegment( iSeg );
1626 if ( seg.si != faceID ) // !edgeIDs.Contains( seg.edgenr ))
1628 Link link( seg[1], seg[0] ); // reverse!!!
1629 if ( !linkMap.Add( link ))
1630 linkMap.Remove( link );
1632 if ( linkMap.IsEmpty() )
1634 if ( linkMap.Extent() < 3 )
1637 // make triangles of the links
1639 netgen::Element2d tri(3);
1640 tri.SetIndex ( faceID );
1642 TLinkMap::Iterator linkIt( linkMap );
1643 Link link1 = linkIt.Value();
1644 // look for a link connected to link1
1645 TLinkMap::Iterator linkIt2 = linkIt;
1646 for ( linkIt2.Next(); linkIt2.More(); linkIt2.Next() )
1648 const Link& link2 = linkIt2.Value();
1649 if ( link2.IsConnected( link1 ))
1651 // look for a link connected to both link1 and link2
1652 TLinkMap::Iterator linkIt3 = linkIt2;
1653 for ( linkIt3.Next(); linkIt3.More(); linkIt3.Next() )
1655 const Link& link3 = linkIt3.Value();
1656 if ( link3.IsConnected( link1 ) &&
1657 link3.IsConnected( link2 ) )
1662 tri[2] = ( link2.Contains( link1.n1 ) ? link2.n1 : link3.n1 );
1663 if ( tri[0] == tri[2] || tri[1] == tri[2] )
1665 ngMesh.AddSurfaceElement( tri );
1667 // prepare for the next tria search
1668 if ( linkMap.Extent() == 3 )
1670 linkMap.Remove( link3 );
1671 linkMap.Remove( link2 );
1673 linkMap.Remove( link1 );
1674 link1 = linkIt.Value();
1687 //================================================================================
1688 // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
1689 gp_XY_FunPtr(Subtracted);
1690 //gp_XY_FunPtr(Added);
1692 //================================================================================
1694 * \brief Evaluate distance between two 2d points along the surface
1696 //================================================================================
1698 double evalDist( const gp_XY& uv1,
1700 const Handle(Geom_Surface)& surf,
1701 const int stopHandler=-1)
1703 if ( stopHandler > 0 ) // continue recursion
1705 gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
1706 return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
1708 double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1709 if ( stopHandler == 0 ) // stop recursion
1712 // start recursion if necessary
1713 double dist2D = SMESH_MesherHelper::ApplyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1714 if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1715 return dist3D; // equal parametrization of a planar surface
1717 return evalDist( uv1, uv2, surf, 3 ); // start recursion
1720 //================================================================================
1722 * \brief Data of vertex internal in geom face
1724 //================================================================================
1728 gp_XY uv; //!< UV in face parametric space
1729 int ngId; //!< ng id of corresponding node
1730 gp_XY uvClose; //!< UV of closest boundary node
1731 int ngIdClose; //!< ng id of closest boundary node
1734 //================================================================================
1736 * \brief Data of vertex internal in solid
1738 //================================================================================
1742 int ngId; //!< ng id of corresponding node
1743 int ngIdClose; //!< ng id of closest 2d mesh element
1744 int ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1747 inline double dist2( const netgen::MeshPoint& p1, const netgen::MeshPoint& p2 )
1749 return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1752 // inline double dist2(const netgen::MeshPoint& p, const SMDS_MeshNode* n )
1754 // return gp_Pnt( NGPOINT_COORDS(p)).SquareDistance( SMESH_NodeXYZ(n));
1758 //================================================================================
1760 * \brief Make netgen take internal vertices in faces into account by adding
1761 * segments including internal vertices
1763 * This function works in supposition that 1D mesh is already computed in ngMesh
1765 //================================================================================
1767 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& occgeom,
1768 netgen::Mesh& ngMesh,
1769 vector<const SMDS_MeshNode*>& nodeVec,
1770 NETGENPlugin_Internals& internalShapes)
1772 if ((int) nodeVec.size() < ngMesh.GetNP() )
1773 nodeVec.resize( ngMesh.GetNP(), 0 );
1775 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1776 SMESH_MesherHelper helper( internalShapes.getMesh() );
1778 const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1779 map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1780 for ( ; f2v != face2Vert.end(); ++f2v )
1782 const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1783 if ( face.IsNull() ) continue;
1784 int faceNgID = occgeom.fmap.FindIndex (face);
1785 if ( faceNgID < 0 ) continue;
1787 TopLoc_Location loc;
1788 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1790 helper.SetSubShape( face );
1791 helper.SetElementsOnShape( true );
1793 // Get data of internal vertices and add them to ngMesh
1795 multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1797 int i, nbSegInit = ngMesh.GetNSeg();
1799 // boundary characteristics
1800 double totSegLen2D = 0;
1803 const list<int>& iVertices = f2v->second;
1804 list<int>::const_iterator iv = iVertices.begin();
1805 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1808 // get node on vertex
1809 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1810 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1813 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1814 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1815 nV = SMESH_Algo::VertexNode( V, meshDS );
1816 if ( !nV ) continue;
1819 netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1820 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1821 vData.ngId = ngMesh.GetNP();
1822 nodeVec.push_back( nV );
1826 vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1827 if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1829 // loop on all segments of the face to find the node closest to vertex and to count
1830 // average segment 2d length
1831 double closeDist2 = numeric_limits<double>::max(), dist2;
1833 for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1835 netgen::Segment & seg = ngMesh.LineSegment(i);
1836 if ( seg.si != faceNgID ) continue;
1838 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1840 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1841 if ( ngIdLast == seg[ iEnd ] ) continue;
1842 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1843 if ( dist2 < closeDist2 )
1844 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1845 ngIdLast = seg[ iEnd ];
1849 totSegLen2D += helper.ApplyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1853 dist2VData.insert( make_pair( closeDist2, vData ));
1856 if ( totNbSeg == 0 ) break;
1857 double avgSegLen2d = totSegLen2D / totNbSeg;
1859 // Loop on vertices to add segments
1861 multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1862 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1864 double closeDist2 = dist_vData->first, dist2;
1865 TIntVData & vData = dist_vData->second;
1867 // try to find more close node among segments added for internal vertices
1868 for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1870 netgen::Segment & seg = ngMesh.LineSegment(i);
1871 if ( seg.si != faceNgID ) continue;
1873 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1875 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1876 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1877 if ( dist2 < closeDist2 )
1878 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1881 // decide whether to use the closest node as the second end of segment or to
1882 // create a new point
1883 int segEnd1 = vData.ngId;
1884 int segEnd2 = vData.ngIdClose; // to use closest node
1885 gp_XY uvV = vData.uv, uvP = vData.uvClose;
1886 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1887 double nodeDist2D = sqrt( closeDist2 );
1888 double nodeDist3D = evalDist( vData.uv, vData.uvClose, surf );
1889 bool avgLenOK = ( avgSegLen2d < 0.75 * nodeDist2D );
1890 bool hintLenOK = ( segLenHint < 0.75 * nodeDist3D );
1891 //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1892 if ( hintLenOK || avgLenOK )
1894 // create a point between the closest node and V
1897 double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1898 // direction from V to closet node in 2D
1899 gp_Dir2d v2n( helper.ApplyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1901 uvP = vData.uv + r * nodeDist2D * v2n.XY();
1902 gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1904 netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1905 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1906 segEnd2 = ngMesh.GetNP();
1907 //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1908 SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1909 nodeVec.push_back( nP );
1911 //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1914 netgen::Segment seg;
1916 if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1917 seg[0] = segEnd1; // ng node id
1918 seg[1] = segEnd2; // ng node id
1919 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1922 seg.epgeominfo[ 0 ].dist = 0; // param on curve
1923 seg.epgeominfo[ 0 ].u = uvV.X();
1924 seg.epgeominfo[ 0 ].v = uvV.Y();
1925 seg.epgeominfo[ 1 ].dist = 1; // param on curve
1926 seg.epgeominfo[ 1 ].u = uvP.X();
1927 seg.epgeominfo[ 1 ].v = uvP.Y();
1929 // seg.epgeominfo[ 0 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1930 // seg.epgeominfo[ 1 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1932 ngMesh.AddSegment (seg);
1934 // add reverse segment
1935 swap( seg[0], seg[1] );
1936 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1937 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1938 ngMesh.AddSegment (seg);
1942 ngMesh.CalcSurfacesOfNode();
1945 //================================================================================
1947 * \brief Make netgen take internal vertices in solids into account by adding
1948 * faces including internal vertices
1950 * This function works in supposition that 2D mesh is already computed in ngMesh
1952 //================================================================================
1954 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry& occgeom,
1955 netgen::Mesh& ngMesh,
1956 vector<const SMDS_MeshNode*>& nodeVec,
1957 NETGENPlugin_Internals& internalShapes)
1959 #ifdef DUMP_TRIANGLES_SCRIPT
1960 // create a python script making a mesh containing triangles added for internal vertices
1961 ofstream py(DUMP_TRIANGLES_SCRIPT);
1962 py << "import SMESH"<< endl
1963 << "from salome.smesh import smeshBuilder"<<endl
1964 << "smesh = smeshBuilder.New()"<<endl
1965 << "m = smesh.Mesh(name='triangles')" << endl;
1967 if ((int) nodeVec.size() < ngMesh.GetNP() )
1968 nodeVec.resize( ngMesh.GetNP(), 0 );
1970 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1971 SMESH_MesherHelper helper( internalShapes.getMesh() );
1973 const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
1974 map<int,list<int> >::const_iterator s2v = so2Vert.begin();
1975 for ( ; s2v != so2Vert.end(); ++s2v )
1977 const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
1978 if ( solid.IsNull() ) continue;
1979 int solidNgID = occgeom.somap.FindIndex (solid);
1980 if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
1982 helper.SetSubShape( solid );
1983 helper.SetElementsOnShape( true );
1985 // find ng indices of faces within the solid
1987 for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
1988 ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
1989 if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
1990 ngFaceIds.insert( 1 );
1992 // Get data of internal vertices and add them to ngMesh
1994 multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
1996 int i, nbFaceInit = ngMesh.GetNSE();
1998 // boundary characteristics
1999 double totSegLen = 0;
2002 const list<int>& iVertices = s2v->second;
2003 list<int>::const_iterator iv = iVertices.begin();
2004 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
2007 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
2009 // get node on vertex
2010 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
2013 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
2014 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2015 nV = SMESH_Algo::VertexNode( V, meshDS );
2016 if ( !nV ) continue;
2019 netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
2020 ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
2021 vData.ngId = ngMesh.GetNP();
2022 nodeVec.push_back( nV );
2024 // loop on all 2d elements to find the one closest to vertex and to count
2025 // average segment length
2026 double closeDist2 = numeric_limits<double>::max(), avgDist2;
2027 for (i = 1; i <= ngMesh.GetNSE(); ++i)
2029 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2030 if ( !ngFaceIds.count( elem.GetIndex() )) continue;
2032 multimap< double, int> dist2nID; // sort nodes of element by distance from V
2033 for ( int j = 0; j < elem.GetNP(); ++j)
2035 netgen::MeshPoint mp = ngMesh.Point( elem[j] );
2036 double d2 = dist2( mpV, mp );
2037 dist2nID.insert( make_pair( d2, elem[j] ));
2038 avgDist2 += d2 / elem.GetNP();
2040 totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
2042 double dist = dist2nID.begin()->first; //avgDist2;
2043 if ( dist < closeDist2 )
2044 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
2046 dist2VData.insert( make_pair( closeDist2, vData ));
2049 if ( totNbSeg == 0 ) break;
2050 double avgSegLen = totSegLen / totNbSeg;
2052 // Loop on vertices to add triangles
2054 multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
2055 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
2057 double closeDist2 = dist_vData->first;
2058 TIntVSoData & vData = dist_vData->second;
2060 const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
2062 // try to find more close face among ones added for internal vertices
2063 for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
2065 double avgDist2 = 0;
2066 multimap< double, int> dist2nID;
2067 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2068 for ( int j = 0; j < elem.GetNP(); ++j)
2070 double d = dist2( mpV, ngMesh.Point( elem[j] ));
2071 dist2nID.insert( make_pair( d, elem[j] ));
2072 avgDist2 += d / elem.GetNP();
2073 if ( avgDist2 < closeDist2 )
2074 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
2077 // sort nodes of the closest face by angle with vector from V to the closest node
2078 const double tol = numeric_limits<double>::min();
2079 map< double, int > angle2ID;
2080 const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
2081 netgen::MeshPoint mp[2];
2082 mp[0] = ngMesh.Point( vData.ngIdCloseN );
2083 gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
2084 gp_XYZ pV( NGPOINT_COORDS( mpV ));
2085 gp_Vec v2p1( pV, p1 );
2086 double distN1 = v2p1.Magnitude();
2087 if ( distN1 <= tol ) continue;
2089 for ( int j = 0; j < closeFace.GetNP(); ++j)
2091 mp[1] = ngMesh.Point( closeFace[j] );
2092 gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
2093 angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
2095 // get node with angle of 60 degrees or greater
2096 map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
2097 if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
2098 const double minAngle = 30. * M_PI / 180.;
2099 const double angle = angle_id->first;
2100 bool angleOK = ( angle > minAngle );
2102 // find points to create a triangle
2103 netgen::Element2d tri(3);
2105 tri[0] = vData.ngId;
2106 tri[1] = vData.ngIdCloseN; // to use the closest nodes
2107 tri[2] = angle_id->second; // to use the node with best angle
2109 // decide whether to use the closest node and the node with best angle or to create new ones
2110 for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
2112 bool createNew = !angleOK; //, distOK = true;
2114 int triInd = isBestAngleN ? 2 : 1;
2115 mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
2120 double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
2121 createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
2123 else if ( angle < tol )
2125 v2p1.SetX( v2p1.X() + 1e-3 );
2131 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
2132 bool avgLenOK = ( avgSegLen < 0.75 * distN1 );
2133 bool hintLenOK = ( segLenHint < 0.75 * distN1 );
2134 createNew = (createNew || avgLenOK || hintLenOK );
2135 // we create a new node not closer than 0.5 to the closest face
2136 // in order not to clash with other close face
2137 double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
2138 distFromV = r * distN1;
2142 // create a new point, between the node and the vertex if angleOK
2143 gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
2144 gp_Vec v2p( pV, p ); v2p.Normalize();
2145 if ( isBestAngleN && !angleOK )
2146 p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
2148 p = pV + v2p.XYZ() * distFromV;
2150 if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
2152 mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
2153 ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
2154 tri[triInd] = ngMesh.GetNP();
2155 nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
2158 ngMesh.AddSurfaceElement (tri);
2159 swap( tri[1], tri[2] );
2160 ngMesh.AddSurfaceElement (tri);
2162 #ifdef DUMP_TRIANGLES_SCRIPT
2163 py << "n1 = m.AddNode( "<< mpV(0)<<", "<< mpV(1)<<", "<< mpV(2)<<") "<< endl
2164 << "n2 = m.AddNode( "<< mp[0](0)<<", "<< mp[0](1)<<", "<< mp[0](2)<<") "<< endl
2165 << "n3 = m.AddNode( "<< mp[1](0)<<", "<< mp[1](1)<<", "<< mp[1](2)<<" )" << endl
2166 << "m.AddFace([n1,n2,n3])" << endl;
2168 } // loop on internal vertices of a solid
2170 } // loop on solids with internal vertices
2173 //================================================================================
2175 * \brief Fill netgen mesh with segments of a FACE
2176 * \param ngMesh - netgen mesh
2177 * \param geom - container of OCCT geometry to mesh
2178 * \param wires - data of nodes on FACE boundary
2179 * \param helper - mesher helper holding the FACE
2180 * \param nodeVec - vector of nodes in which node index == netgen ID
2181 * \retval SMESH_ComputeErrorPtr - error description
2183 //================================================================================
2185 SMESH_ComputeErrorPtr
2186 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh,
2187 netgen::OCCGeometry& geom,
2188 const TSideVector& wires,
2189 SMESH_MesherHelper& helper,
2190 vector< const SMDS_MeshNode* > & nodeVec,
2191 const bool overrideMinH)
2193 // ----------------------------
2194 // Check wires and count nodes
2195 // ----------------------------
2197 for ( size_t iW = 0; iW < wires.size(); ++iW )
2199 StdMeshers_FaceSidePtr wire = wires[ iW ];
2200 if ( wire->MissVertexNode() )
2202 // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
2203 // It seems that there is no reason for this limitation
2205 // (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
2207 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2208 if ((int) uvPtVec.size() != wire->NbPoints() )
2209 return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
2210 SMESH_Comment("Unexpected nb of points on wire ") << iW
2211 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
2212 nbNodes += wire->NbPoints();
2214 nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
2215 if ( nodeVec.empty() )
2216 nodeVec.push_back( 0 );
2218 // -----------------
2220 // -----------------
2222 const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
2223 NETGENPlugin_NETGEN_2D_ONLY */
2225 // map for nodes on vertices since they can be shared between wires
2226 // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
2227 map<const SMDS_MeshNode*, int > node2ngID;
2228 if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
2230 set< int > subIDs; // ids of sub-shapes of the FACE
2231 for ( size_t iW = 0; iW < wires.size(); ++iW )
2233 StdMeshers_FaceSidePtr wire = wires[ iW ];
2234 for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
2236 subIDs.insert( wire->EdgeID( iE ));
2237 subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
2240 for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
2241 if ( subIDs.count( nodeVec[ngID]->GetShapeID() ))
2242 node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
2245 const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
2246 if ( ngMesh.GetNFD() < 1 )
2247 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceID, solidID, solidID, 0 ));
2249 for ( size_t iW = 0; iW < wires.size(); ++iW )
2251 StdMeshers_FaceSidePtr wire = wires[ iW ];
2252 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2253 const int nbSegments = wire->NbPoints() - 1;
2255 // assure the 1st node to be in node2ngID, which is needed to correctly
2256 // "close chain of segments" (see below) in case if the 1st node is not
2257 // onVertex because it is on a Viscous layer
2258 node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
2260 // compute length of every segment
2261 vector<double> segLen( nbSegments );
2262 for ( int i = 0; i < nbSegments; ++i )
2263 segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
2265 int edgeID = 1, posID = -2;
2266 bool isInternalWire = false;
2267 double vertexNormPar = 0;
2268 const int prevNbNGSeg = ngMesh.GetNSeg();
2269 for ( int i = 0; i < nbSegments; ++i ) // loop on segments
2271 // Add the first point of a segment
2273 const SMDS_MeshNode * n = uvPtVec[ i ].node;
2274 const int posShapeID = n->GetShapeID();
2275 bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
2276 bool onEdge = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE );
2278 // skip nodes on degenerated edges
2279 if ( helper.IsDegenShape( posShapeID ) &&
2280 helper.IsDegenShape( uvPtVec[ i+1 ].node->GetShapeID() ))
2283 int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
2284 if ( onVertex || ( !wasNgMeshEmpty && onEdge ) || helper.IsRealSeam( posShapeID ))
2285 ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
2286 if ( ngID1 > ngMesh.GetNP() )
2288 netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
2289 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2290 nodeVec.push_back( n );
2292 else // n is in ngMesh already, and ngID2 in prev segment is wrong
2294 ngID2 = ngMesh.GetNP() + 1;
2295 if ( i > 0 ) // prev segment belongs to same wire
2297 netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2304 netgen::Segment seg;
2306 seg[0] = ngID1; // ng node id
2307 seg[1] = ngID2; // ng node id
2308 seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
2309 seg.si = faceID; // = geom.fmap.FindIndex (face);
2311 for ( int iEnd = 0; iEnd < 2; ++iEnd)
2313 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
2315 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
2316 seg.epgeominfo[ iEnd ].u = pnt.u;
2317 seg.epgeominfo[ iEnd ].v = pnt.v;
2319 // find out edge id and node parameter on edge
2320 onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
2321 if ( onVertex || posShapeID != posID )
2324 double normParam = pnt.normParam;
2326 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
2327 int edgeIndexInWire = wire->EdgeIndex( normParam );
2328 vertexNormPar = wire->LastParameter( edgeIndexInWire );
2329 const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
2330 edgeID = geom.emap.FindIndex( edge );
2332 isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
2333 // if ( onVertex ) // param on curve is different on each of two edges
2334 // seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
2336 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
2339 ngMesh.AddSegment (seg);
2341 // restrict size of elements near the segment
2342 SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
2343 // get an average size of adjacent segments to avoid sharp change of
2344 // element size (regression on issue 0020452, note 0010898)
2345 int iPrev = SMESH_MesherHelper::WrapIndex( i-1, nbSegments );
2346 int iNext = SMESH_MesherHelper::WrapIndex( i+1, nbSegments );
2347 double sumH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
2348 int nbSeg = ( int( segLen[ iPrev ] > sumH / 100.) +
2349 int( segLen[ i ] > sumH / 100.) +
2350 int( segLen[ iNext ] > sumH / 100.));
2352 RestrictLocalSize( ngMesh, 0.5*(np1+np2), sumH / nbSeg, overrideMinH );
2354 if ( isInternalWire )
2356 swap (seg[0], seg[1]);
2357 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
2358 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
2359 ngMesh.AddSegment (seg);
2361 } // loop on segments on a wire
2363 // close chain of segments
2364 if ( nbSegments > 0 )
2366 netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire ));
2367 const SMDS_MeshNode * lastNode = uvPtVec.back().node;
2368 lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
2369 if ( lastSeg[1] > ngMesh.GetNP() )
2371 netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
2372 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2373 nodeVec.push_back( lastNode );
2375 if ( isInternalWire )
2377 netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2378 realLastSeg[0] = lastSeg[1];
2382 #ifdef DUMP_SEGMENTS
2383 cout << "BEGIN WIRE " << iW << endl;
2384 for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
2386 netgen::Segment& seg = ngMesh.LineSegment( i );
2388 netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
2389 if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
2391 cout << "Segment: " << seg.edgenr << endl << "\tis REVERSE of the previous one" << endl;
2395 cout << "Segment: " << seg.edgenr << endl
2396 << "\tp1: " << seg[0] << " n" << nodeVec[ seg[0]]->GetID() << endl
2397 << "\tp2: " << seg[1] << " n" << nodeVec[ seg[1]]->GetID() << endl
2398 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
2399 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
2400 << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
2401 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
2402 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
2403 << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
2405 cout << "--END WIRE " << iW << endl;
2407 SMESH_Comment __not_unused_variable( prevNbNGSeg );
2410 } // loop on WIREs of a FACE
2412 // add a segment instead of an internal vertex
2413 if ( wasNgMeshEmpty )
2415 NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
2416 AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
2418 ngMesh.CalcSurfacesOfNode();
2423 //================================================================================
2425 * \brief Fill SMESH mesh according to contents of netgen mesh
2426 * \param occgeo - container of OCCT geometry to mesh
2427 * \param ngMesh - netgen mesh
2428 * \param initState - bn of entities in netgen mesh before computing
2429 * \param sMesh - SMESH mesh to fill in
2430 * \param nodeVec - vector of nodes in which node index == netgen ID
2431 * \param comment - returns problem description
2432 * \param quadHelper - holder of medium nodes of sub-meshes
2433 * \retval int - error
2435 //================================================================================
2437 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo,
2438 netgen::Mesh& ngMesh,
2439 const NETGENPlugin_ngMeshInfo& initState,
2441 std::vector<const SMDS_MeshNode*>& nodeVec,
2442 SMESH_Comment& comment,
2443 SMESH_MesherHelper* quadHelper)
2445 int nbNod = ngMesh.GetNP();
2446 int nbSeg = ngMesh.GetNSeg();
2447 int nbFac = ngMesh.GetNSE();
2448 int nbVol = ngMesh.GetNE();
2450 SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
2452 // quadHelper is used for either
2453 // 1) making quadratic elements when a lower dimension mesh is loaded
2454 // to SMESH before conversion to quadratic by NETGEN
2455 // 2) sewing of quadratic elements with quadratic elements of sub-meshes
2456 if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() )
2459 int i, nbInitNod = initState._nbNodes;
2460 if ( initState._elementsRemoved )
2462 // PAL23427. Update nodeVec to track removal of netgen free points as a result
2463 // of removal of faces in FillNgMesh() in the case of a shrunk sub-mesh
2464 int ngID, nodeVecSize = nodeVec.size();
2465 const double eps = std::numeric_limits<double>::min();
2466 for ( ngID = i = 1; i < nodeVecSize; ++ngID, ++i )
2468 gp_Pnt ngPnt( NGPOINT_COORDS( ngMesh.Point( ngID )));
2469 gp_Pnt node ( SMESH_NodeXYZ (nodeVec_ACCESS(i) ));
2470 if ( ngPnt.SquareDistance( node ) < eps )
2472 nodeVec[ ngID ] = nodeVec[ i ];
2479 nodeVec.resize( ngID );
2480 nbInitNod = ngID - 1;
2482 // -------------------------------------
2483 // Create and insert nodes into nodeVec
2484 // -------------------------------------
2486 nodeVec.resize( nbNod + 1 );
2487 for ( i = nbInitNod+1; i <= nbNod; ++i )
2489 const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
2490 SMDS_MeshNode* node = NULL;
2491 TopoDS_Vertex aVert;
2492 // First, netgen creates nodes on vertices in occgeo.vmap,
2493 // so node index corresponds to vertex index
2494 // but (issue 0020776) netgen does not create nodes with equal coordinates
2495 if ( i-nbInitNod <= occgeo.vmap.Extent() )
2497 gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
2498 for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
2500 aVert = TopoDS::Vertex( occgeo.vmap( iV ));
2501 gp_Pnt pV = BRep_Tool::Pnt( aVert );
2502 if ( p.SquareDistance( pV ) > 1e-20 )
2505 node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
2508 if (!node) // node not found on vertex
2510 node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
2511 if (!aVert.IsNull())
2512 meshDS->SetNodeOnVertex(node, aVert);
2517 // -------------------------------------------
2518 // Create mesh segments along geometric edges
2519 // -------------------------------------------
2521 int nbInitSeg = initState._nbSegments;
2522 for (i = nbInitSeg+1; i <= nbSeg; ++i )
2524 const netgen::Segment& seg = ngMesh.LineSegment(i);
2526 int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
2529 for (int j=0; j < 3; ++j)
2531 int pind = pinds[j];
2532 if (pind <= 0 || !nodeVec_ACCESS(pind))
2540 int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
2541 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2542 aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
2544 param = seg.epgeominfo[j].dist;
2547 else // middle point
2549 param = param2 * 0.5;
2551 if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->GetShapeID() < 1)
2553 meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
2558 SMDS_MeshEdge* edge = 0;
2559 if (nbp == 2) // second order ?
2561 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
2563 if ( quadHelper ) // final mesh must be quadratic
2564 edge = quadHelper->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2566 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2570 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2571 nodeVec_ACCESS(pinds[2])))
2573 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2574 nodeVec_ACCESS(pinds[2]));
2578 if ( comment.empty() ) comment << "Cannot create a mesh edge";
2579 MESSAGE("Cannot create a mesh edge");
2580 nbSeg = nbFac = nbVol = 0;
2583 if ( !aEdge.IsNull() && edge->GetShapeID() < 1 )
2584 meshDS->SetMeshElementOnShape(edge, aEdge);
2586 else if ( comment.empty() )
2588 comment << "Invalid netgen segment #" << i;
2592 // ----------------------------------------
2593 // Create mesh faces along geometric faces
2594 // ----------------------------------------
2596 int nbInitFac = initState._nbFaces;
2597 int quadFaceID = ngMesh.GetNFD() + 1;
2598 if ( nbInitFac < nbFac )
2599 // add a faces descriptor to exclude qudrangle elements generated by NETGEN
2600 // from computation of 3D mesh
2601 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
2603 vector<const SMDS_MeshNode*> nodes;
2604 for (i = nbInitFac+1; i <= nbFac; ++i )
2606 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2607 const int aGeomFaceInd = elem.GetIndex();
2609 if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
2610 aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
2612 for ( int j = 1; j <= elem.GetNP(); ++j )
2614 int pind = elem.PNum(j);
2615 if ( pind < 1 || pind >= (int) nodeVec.size() )
2617 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
2619 nodes.push_back( node );
2620 if (!aFace.IsNull() && node->GetShapeID() < 1)
2622 const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
2623 meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
2627 if ((int) nodes.size() != elem.GetNP() )
2629 if ( comment.empty() )
2630 comment << "Invalid netgen 2d element #" << i;
2631 continue; // bad node ids
2633 SMDS_MeshFace* face = NULL;
2634 switch (elem.GetType())
2637 if ( quadHelper ) // final mesh must be quadratic
2638 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2]);
2640 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
2643 if ( quadHelper ) // final mesh must be quadratic
2644 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2646 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2647 // exclude qudrangle elements from computation of 3D mesh
2648 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2651 nodes[5] = mediumNode( nodes[0],nodes[1],nodes[5], quadHelper );
2652 nodes[3] = mediumNode( nodes[1],nodes[2],nodes[3], quadHelper );
2653 nodes[4] = mediumNode( nodes[2],nodes[0],nodes[4], quadHelper );
2654 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
2657 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2658 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2659 nodes[5] = mediumNode( nodes[2],nodes[3],nodes[5], quadHelper );
2660 nodes[6] = mediumNode( nodes[3],nodes[0],nodes[6], quadHelper );
2661 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
2662 nodes[4],nodes[7],nodes[5],nodes[6]);
2663 // exclude qudrangle elements from computation of 3D mesh
2664 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2667 MESSAGE("NETGEN created a face of unexpected type, ignoring");
2672 if ( comment.empty() ) comment << "Cannot create a mesh face";
2673 MESSAGE("Cannot create a mesh face");
2674 nbSeg = nbFac = nbVol = 0;
2677 if ( !aFace.IsNull() )
2678 meshDS->SetMeshElementOnShape( face, aFace );
2681 // ------------------
2682 // Create tetrahedra
2683 // ------------------
2685 for ( i = 1; i <= nbVol; ++i )
2687 const netgen::Element& elem = ngMesh.VolumeElement(i);
2688 int aSolidInd = elem.GetIndex();
2689 TopoDS_Solid aSolid;
2690 if ( aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent() )
2691 aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
2693 for ( int j = 1; j <= elem.GetNP(); ++j )
2695 int pind = elem.PNum(j);
2696 if ( pind < 1 || pind >= (int)nodeVec.size() )
2698 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
2700 nodes.push_back(node);
2701 if ( !aSolid.IsNull() && node->GetShapeID() < 1 )
2702 meshDS->SetNodeInVolume(node, aSolid);
2705 if ((int) nodes.size() != elem.GetNP() )
2707 if ( comment.empty() )
2708 comment << "Invalid netgen 3d element #" << i;
2711 SMDS_MeshVolume* vol = NULL;
2712 switch ( elem.GetType() )
2715 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
2718 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2719 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2720 nodes[5] = mediumNode( nodes[2],nodes[0],nodes[5], quadHelper );
2721 nodes[6] = mediumNode( nodes[0],nodes[3],nodes[6], quadHelper );
2722 nodes[8] = mediumNode( nodes[1],nodes[3],nodes[8], quadHelper );
2723 nodes[9] = mediumNode( nodes[2],nodes[3],nodes[9], quadHelper );
2724 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
2725 nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
2728 MESSAGE("NETGEN created a volume of unexpected type, ignoring");
2733 if ( comment.empty() ) comment << "Cannot create a mesh volume";
2734 MESSAGE("Cannot create a mesh volume");
2735 nbSeg = nbFac = nbVol = 0;
2738 if (!aSolid.IsNull())
2739 meshDS->SetMeshElementOnShape(vol, aSolid);
2741 return comment.empty() ? 0 : 1;
2746 //================================================================================
2748 * \brief Convert error into text
2750 //================================================================================
2752 std::string text(int err)
2757 SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2760 //================================================================================
2762 * \brief Convert exception into text
2764 //================================================================================
2766 std::string text(Standard_Failure& ex)
2768 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2769 str << " at " << netgen::multithread.task
2770 << ": " << ex.DynamicType()->Name();
2771 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2772 str << ": " << ex.GetMessageString();
2775 //================================================================================
2777 * \brief Convert exception into text
2779 //================================================================================
2781 std::string text(netgen::NgException& ex)
2783 SMESH_Comment str("NgException");
2784 if ( strlen( netgen::multithread.task ) > 0 )
2785 str << " at " << netgen::multithread.task;
2786 str << ": " << ex.What();
2790 //================================================================================
2792 * \brief Looks for triangles lying on a SOLID
2794 //================================================================================
2796 bool hasBadElemOnSolid( const list<const SMDS_MeshElement*>& elems,
2797 SMESH_subMesh* solidSM )
2799 TopTools_IndexedMapOfShape solidSubs;
2800 TopExp::MapShapes( solidSM->GetSubShape(), solidSubs );
2801 SMESHDS_Mesh* mesh = solidSM->GetFather()->GetMeshDS();
2803 list<const SMDS_MeshElement*>::const_iterator e = elems.begin();
2804 for ( ; e != elems.end(); ++e )
2806 const SMDS_MeshElement* elem = *e;
2807 // if ( elem->GetType() != SMDSAbs_Face ) -- 23047
2809 int nbNodesOnSolid = 0, nbNodes = elem->NbNodes();
2810 SMDS_NodeIteratorPtr nIt = elem->nodeIterator();
2811 while ( nIt->more() )
2813 const SMDS_MeshNode* n = nIt->next();
2814 const TopoDS_Shape& s = mesh->IndexToShape( n->GetShapeID() );
2815 nbNodesOnSolid += ( !s.IsNull() && solidSubs.Contains( s ));
2816 if ( nbNodesOnSolid > 2 ||
2817 nbNodesOnSolid == nbNodes)
2824 const double edgeMeshingTime = 0.001;
2825 const double faceMeshingTime = 0.019;
2826 const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
2827 const double faceOptimizTime = 0.06;
2828 const double voluMeshingTime = 0.15;
2829 const double volOptimizeTime = 0.77;
2832 //=============================================================================
2834 * Here we are going to use the NETGEN mesher
2836 //=============================================================================
2838 bool NETGENPlugin_Mesher::Compute()
2840 NETGENPlugin_NetgenLibWrapper ngLib;
2842 netgen::MeshingParameters& mparams = netgen::mparam;
2844 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2845 SMESH_MesherHelper quadHelper( *_mesh );
2846 quadHelper.SetIsQuadratic( mparams.secondorder );
2848 // -------------------------
2849 // Prepare OCC geometry
2850 // -------------------------
2852 netgen::OCCGeometry occgeo;
2853 list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2854 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2855 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2858 _totalTime = edgeFaceMeshingTime;
2860 _totalTime += faceOptimizTime;
2862 _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
2863 double doneTime = 0;
2866 _curShapeIndex = -1;
2868 // -------------------------
2869 // Generate the mesh
2870 // -------------------------
2873 NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2875 SMESH_Comment comment;
2878 // vector of nodes in which node index == netgen ID
2879 vector< const SMDS_MeshNode* > nodeVec;
2887 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2888 mparams.uselocalh = false;
2889 mparams.grading = 0.8; // not limitited size growth
2891 if ( _simpleHyp->GetNumberOfSegments() )
2893 mparams.maxh = occgeo.boundingbox.Diam();
2896 mparams.maxh = _simpleHyp->GetLocalLength();
2899 if ( mparams.maxh == 0.0 )
2900 mparams.maxh = occgeo.boundingbox.Diam();
2901 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2902 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2904 // Local size on faces
2905 occgeo.face_maxh = mparams.maxh;
2907 // Let netgen create _ngMesh and calculate element size on not meshed shapes
2911 int startWith = netgen::MESHCONST_ANALYSE;
2912 int endWith = netgen::MESHCONST_ANALYSE;
2917 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
2919 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
2921 if(netgen::multithread.terminate)
2924 comment << text(err);
2926 catch (Standard_Failure& ex)
2928 comment << text(ex);
2930 catch (netgen::NgException & ex)
2932 comment << text(ex);
2933 if ( mparams.meshsizefilename )
2934 throw SMESH_ComputeError(COMPERR_BAD_PARMETERS, comment );
2936 err = 0; //- MESHCONST_ANALYSE isn't so important step
2939 ngLib.setMesh(( Ng_Mesh*) _ngMesh );
2941 _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2943 if ( !mparams.uselocalh ) // mparams.grading is not taken into account yet
2944 _ngMesh->LocalHFunction().SetGrading( mparams.grading );
2948 // Pass 1D simple parameters to NETGEN
2949 // --------------------------------
2950 int nbSeg = _simpleHyp->GetNumberOfSegments();
2951 double segSize = _simpleHyp->GetLocalLength();
2952 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2954 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2956 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2957 setLocalSize( e, segSize, *_ngMesh );
2960 else // if ( ! _simpleHyp )
2962 // Local size on shapes
2963 SetLocalSize( occgeo, *_ngMesh );
2964 SetLocalSizeForChordalError( occgeo, *_ngMesh );
2967 // Precompute internal edges (issue 0020676) in order to
2968 // add mesh on them correctly (twice) to netgen mesh
2969 if ( !err && internals.hasInternalEdges() )
2971 // load internal shapes into OCCGeometry
2972 netgen::OCCGeometry intOccgeo;
2973 internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
2974 intOccgeo.boundingbox = occgeo.boundingbox;
2975 intOccgeo.shape = occgeo.shape;
2976 intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
2977 intOccgeo.face_maxh = netgen::mparam.maxh;
2978 netgen::Mesh *tmpNgMesh = NULL;
2982 // compute local H on internal shapes in the main mesh
2983 //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
2985 // let netgen create a temporary mesh
2987 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
2989 netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
2991 if(netgen::multithread.terminate)
2994 // copy LocalH from the main to temporary mesh
2995 initState.transferLocalH( _ngMesh, tmpNgMesh );
2997 // compute mesh on internal edges
2998 startWith = endWith = netgen::MESHCONST_MESHEDGES;
3000 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith);
3002 err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr);
3004 comment << text(err);
3006 catch (Standard_Failure& ex)
3008 comment << text(ex);
3011 initState.restoreLocalH( tmpNgMesh );
3013 // fill SMESH by netgen mesh
3014 vector< const SMDS_MeshNode* > tmpNodeVec;
3015 FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
3016 err = ( err || !comment.empty() );
3018 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
3021 // Fill _ngMesh with nodes and segments of computed submeshes
3024 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
3025 FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ], &quadHelper));
3027 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3032 startWith = endWith = netgen::MESHCONST_MESHEDGES;
3037 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
3039 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
3041 if(netgen::multithread.terminate)
3044 comment << text(err);
3046 catch (Standard_Failure& ex)
3048 comment << text(ex);
3053 _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
3055 mparams.uselocalh = true; // restore as it is used at surface optimization
3057 // ---------------------
3058 // compute surface mesh
3059 // ---------------------
3062 // Pass 2D simple parameters to NETGEN
3064 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3066 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3067 mparams.grading = 0.4; // moderate size growth
3070 // length from edges
3071 if ( _ngMesh->GetNSeg() ) {
3072 double edgeLength = 0;
3073 TopTools_MapOfShape visitedEdges;
3074 for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
3075 if( visitedEdges.Add(exp.Current()) )
3076 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
3077 // we have to multiply length by 2 since for each TopoDS_Edge there
3078 // are double set of NETGEN edges, in other words, we have to
3079 // divide _ngMesh->GetNSeg() by 2.
3080 mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
3083 mparams.maxh = 1000;
3085 mparams.grading = 0.2; // slow size growth
3087 mparams.quad = _simpleHyp->GetAllowQuadrangles();
3088 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3089 _ngMesh->SetGlobalH (mparams.maxh);
3090 netgen::Box<3> bb = occgeo.GetBoundingBox();
3091 bb.Increase (bb.Diam()/20);
3092 _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
3095 // Care of vertices internal in faces (issue 0020676)
3096 if ( internals.hasInternalVertexInFace() )
3098 // store computed segments in SMESH in order not to create SMESH
3099 // edges for ng segments added by AddIntVerticesInFaces()
3100 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
3101 // add segments to faces with internal vertices
3102 AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
3103 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3106 // Build viscous layers
3107 if (( _isViscousLayers2D ) ||
3108 ( !occgeo.fmap.IsEmpty() &&
3109 StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( occgeo.fmap(1) ), *_mesh )))
3111 if ( !internals.hasInternalVertexInFace() ) {
3112 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
3113 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3115 SMESH_ProxyMesh::Ptr viscousMesh;
3116 SMESH_MesherHelper helper( *_mesh );
3117 for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
3119 const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
3120 viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
3123 if ( viscousMesh->NbProxySubMeshes() == 0 )
3125 // exclude from computation ng segments built on EDGEs of F
3126 for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
3128 netgen::Segment & seg = _ngMesh->LineSegment(i);
3129 if (seg.si == faceID)
3132 // add new segments to _ngMesh instead of excluded ones
3133 helper.SetSubShape( F );
3135 StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
3136 error, &helper, viscousMesh );
3137 error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
3139 if ( !error ) error = SMESH_ComputeError::New();
3141 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3144 // Let netgen compute 2D mesh
3145 startWith = netgen::MESHCONST_MESHSURFACE;
3146 endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
3151 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
3153 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
3155 if(netgen::multithread.terminate)
3158 comment << text (err);
3160 catch (Standard_Failure& ex)
3162 comment << text(ex);
3163 //err = 1; -- try to make volumes anyway
3165 catch (netgen::NgException exc)
3167 comment << text(exc);
3168 //err = 1; -- try to make volumes anyway
3173 doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
3174 _ticTime = doneTime / _totalTime / _progressTic;
3176 // ---------------------
3177 // generate volume mesh
3178 // ---------------------
3179 // Fill _ngMesh with nodes and faces of computed 2D submeshes
3180 if ( !err && _isVolume &&
3181 ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad || _viscousLayersHyp ))
3183 // load SMESH with computed segments and faces
3184 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3186 // compute prismatic boundary volumes
3187 int nbQuad = _mesh->NbQuadrangles();
3188 SMESH_ProxyMesh::Ptr viscousMesh;
3189 if ( _viscousLayersHyp )
3191 viscousMesh = _viscousLayersHyp->Compute( *_mesh, _shape );
3195 // compute pyramids on quadrangles
3196 vector<SMESH_ProxyMesh::Ptr> pyramidMeshes( occgeo.somap.Extent() );
3198 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
3200 StdMeshers_QuadToTriaAdaptor* adaptor = new StdMeshers_QuadToTriaAdaptor;
3201 pyramidMeshes[ iS-1 ].reset( adaptor );
3202 bool ok = adaptor->Compute( *_mesh, occgeo.somap(iS), viscousMesh.get() );
3206 // add proxy faces to NG mesh
3207 list< SMESH_subMesh* > viscousSM;
3208 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
3210 list< SMESH_subMesh* > quadFaceSM;
3211 for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
3212 if ( pyramidMeshes[iS-1] && pyramidMeshes[iS-1]->GetProxySubMesh( face.Current() ))
3214 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
3215 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
3217 else if ( viscousMesh && viscousMesh->GetProxySubMesh( face.Current() ))
3219 viscousSM.push_back( _mesh->GetSubMesh( face.Current() ));
3220 meshedSM[ MeshDim_2D ].remove( viscousSM.back() );
3222 if ( !quadFaceSM.empty() )
3223 FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, pyramidMeshes[iS-1]);
3225 if ( !viscousSM.empty() )
3226 FillNgMesh(occgeo, *_ngMesh, nodeVec, viscousSM, &quadHelper, viscousMesh );
3228 // fill _ngMesh with faces of sub-meshes
3229 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper));
3230 initState = NETGENPlugin_ngMeshInfo(_ngMesh, /*checkRemovedElems=*/true);
3231 // toPython( _ngMesh );
3233 if (!err && _isVolume)
3235 // Pass 3D simple parameters to NETGEN
3236 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3237 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3239 _ngMesh->Compress();
3240 if ( double vol = simple3d->GetMaxElementVolume() ) {
3242 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3243 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3246 // length from faces
3247 mparams.maxh = _ngMesh->AverageH();
3249 _ngMesh->SetGlobalH (mparams.maxh);
3250 mparams.grading = 0.4;
3252 _ngMesh->CalcLocalH(mparams.grading);
3254 _ngMesh->CalcLocalH();
3257 // Care of vertices internal in solids and internal faces (issue 0020676)
3258 if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
3260 // store computed faces in SMESH in order not to create SMESH
3261 // faces for ng faces added here
3262 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3263 // add ng faces to solids with internal vertices
3264 AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
3265 // duplicate mesh faces on internal faces
3266 FixIntFaces( occgeo, *_ngMesh, internals );
3267 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3269 // Let netgen compute 3D mesh
3270 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
3275 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
3277 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
3279 if(netgen::multithread.terminate)
3282 if ( comment.empty() ) // do not overwrite a previous error
3283 comment << text(err);
3285 catch (Standard_Failure& ex)
3287 if ( comment.empty() ) // do not overwrite a previous error
3288 comment << text(ex);
3291 catch (netgen::NgException exc)
3293 if ( comment.empty() ) // do not overwrite a previous error
3294 comment << text(exc);
3297 _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
3299 // Let netgen optimize 3D mesh
3300 if ( !err && _optimize )
3302 startWith = endWith = netgen::MESHCONST_OPTVOLUME;
3307 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith);
3309 err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr);
3311 if(netgen::multithread.terminate)
3314 if ( comment.empty() ) // do not overwrite a previous error
3315 comment << text(err);
3317 catch (Standard_Failure& ex)
3319 if ( comment.empty() ) // do not overwrite a previous error
3320 comment << text(ex);
3322 catch (netgen::NgException exc)
3324 if ( comment.empty() ) // do not overwrite a previous error
3325 comment << text(exc);
3329 if (!err && mparams.secondorder > 0)
3334 if ( !meshedSM[ MeshDim_1D ].empty() )
3336 // remove segments not attached to geometry (IPAL0052479)
3337 for (int i = 1; i <= _ngMesh->GetNSeg(); ++i)
3339 const netgen::Segment & seg = _ngMesh->LineSegment (i);
3340 if ( seg.epgeominfo[ 0 ].edgenr == 0 )
3342 _ngMesh->DeleteSegment( i );
3343 initState._nbSegments--;
3346 _ngMesh->Compress();
3348 // convert to quadratic
3349 netgen::OCCRefinementSurfaces ref (occgeo);
3350 ref.MakeSecondOrder (*_ngMesh);
3352 // care of elements already loaded to SMESH
3353 // if ( initState._nbSegments > 0 )
3354 // makeQuadratic( occgeo.emap, _mesh );
3355 // if ( initState._nbFaces > 0 )
3356 // makeQuadratic( occgeo.fmap, _mesh );
3358 catch (Standard_Failure& ex)
3360 if ( comment.empty() ) // do not overwrite a previous error
3361 comment << "Exception in netgen at passing to 2nd order ";
3363 catch (netgen::NgException exc)
3365 if ( comment.empty() ) // do not overwrite a previous error
3366 comment << exc.What();
3371 _ticTime = 0.98 / _progressTic;
3373 //int nbNod = _ngMesh->GetNP();
3374 //int nbSeg = _ngMesh->GetNSeg();
3375 int nbFac = _ngMesh->GetNSE();
3376 int nbVol = _ngMesh->GetNE();
3377 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
3379 // Feed back the SMESHDS with the generated Nodes and Elements
3380 if ( true /*isOK*/ ) // get whatever built
3382 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3384 if ( quadHelper.GetIsQuadratic() ) // remove free nodes
3386 for ( size_t i = 0; i < nodeVec.size(); ++i )
3387 if ( nodeVec[i] && nodeVec[i]->NbInverseElements() == 0 )
3389 _mesh->GetMeshDS()->RemoveFreeNode( nodeVec[i], 0, /*fromGroups=*/false );
3392 for ( size_t i = nodeVec.size()-1; i > 0; --i ) // remove trailing removed nodes
3394 nodeVec.resize( i );
3399 SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
3400 if ( readErr && readErr->HasBadElems() )
3403 if ( !comment.empty() && !readErr->myComment.empty() ) comment += "\n";
3404 comment += readErr->myComment;
3406 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
3407 error->myName = COMPERR_ALGO_FAILED;
3408 if ( !comment.empty() )
3409 error->myComment = comment;
3411 // SetIsAlwaysComputed( true ) to empty sub-meshes, which
3412 // appear if the geometry contains coincident sub-shape due
3413 // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
3414 const int nbMaps = 2;
3415 const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
3416 { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
3417 for ( int iMap = 0; iMap < nbMaps; ++iMap )
3418 for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
3419 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
3420 if ( !sm->IsMeshComputed() )
3421 sm->SetIsAlwaysComputed( true );
3423 // set bad compute error to subshapes of all failed sub-shapes
3424 if ( !error->IsOK() )
3426 bool pb2D = false, pb3D = false;
3427 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
3428 int status = occgeo.facemeshstatus[i-1];
3429 if (status == netgen::FACE_MESHED_OK ) continue;
3430 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
3431 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3432 if ( !smError || smError->IsOK() ) {
3433 if ( status == netgen::FACE_FAILED )
3434 smError.reset( new SMESH_ComputeError( *error ));
3436 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
3437 if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3438 smError->myName = COMPERR_WARNING;
3440 pb2D = pb2D || smError->IsKO();
3443 if ( !pb2D ) // all faces are OK
3444 for (int i = 1; i <= occgeo.somap.Extent(); i++)
3445 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
3447 bool smComputed = nbVol && !sm->IsEmpty();
3448 if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
3450 int nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
3451 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3452 smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > nbIntV );
3454 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3455 if ( !smComputed && ( !smError || smError->IsOK() ))
3458 if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3460 smError->myName = COMPERR_WARNING;
3462 else if ( smError->HasBadElems() ) // bad surface mesh
3464 if ( !hasBadElemOnSolid
3465 ( static_cast<SMESH_BadInputElements*>( smError.get() )->myBadElements, sm ))
3469 pb3D = pb3D || ( smError && smError->IsKO() );
3471 if ( !pb2D && !pb3D )
3472 err = 0; // no fatal errors, only warnings
3475 ngLib._isComputeOk = !err;
3480 //=============================================================================
3484 //=============================================================================
3485 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
3487 netgen::MeshingParameters& mparams = netgen::mparam;
3490 // -------------------------
3491 // Prepare OCC geometry
3492 // -------------------------
3493 netgen::OCCGeometry occgeo;
3494 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
3495 PrepareOCCgeometry( occgeo, _shape, *_mesh, 0, &internals );
3497 bool tooManyElems = false;
3498 const int hugeNb = std::numeric_limits<int>::max() / 100;
3503 // pass 1D simple parameters to NETGEN
3506 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
3507 mparams.uselocalh = false;
3508 mparams.grading = 0.8; // not limitited size growth
3510 if ( _simpleHyp->GetNumberOfSegments() )
3512 mparams.maxh = occgeo.boundingbox.Diam();
3515 mparams.maxh = _simpleHyp->GetLocalLength();
3518 if ( mparams.maxh == 0.0 )
3519 mparams.maxh = occgeo.boundingbox.Diam();
3520 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
3521 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
3523 // let netgen create _ngMesh and calculate element size on not meshed shapes
3524 NETGENPlugin_NetgenLibWrapper ngLib;
3525 netgen::Mesh *ngMesh = NULL;
3529 int startWith = netgen::MESHCONST_ANALYSE;
3530 int endWith = netgen::MESHCONST_MESHEDGES;
3532 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith);
3534 int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
3537 if(netgen::multithread.terminate)
3540 ngLib.setMesh(( Ng_Mesh*) ngMesh );
3542 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
3543 sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
3546 // if ( _simpleHyp )
3548 // // Pass 1D simple parameters to NETGEN
3549 // // --------------------------------
3550 // int nbSeg = _simpleHyp->GetNumberOfSegments();
3551 // double segSize = _simpleHyp->GetLocalLength();
3552 // for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
3554 // const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
3556 // segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
3557 // setLocalSize( e, segSize, *ngMesh );
3560 // else // if ( ! _simpleHyp )
3562 // // Local size on shapes
3563 // SetLocalSize( occgeo, *ngMesh );
3565 // calculate total nb of segments and length of edges
3566 double fullLen = 0.0;
3568 int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
3569 TopTools_DataMapOfShapeInteger Edge2NbSeg;
3570 for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
3572 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3573 if( !Edge2NbSeg.Bind(E,0) )
3576 double aLen = SMESH_Algo::EdgeLength(E);
3579 vector<int>& aVec = aResMap[_mesh->GetSubMesh(E)];
3581 aVec.resize( SMDSEntity_Last, 0);
3583 fullNbSeg += aVec[ entity ];
3586 // store nb of segments computed by Netgen
3588 for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
3590 const netgen::Segment& seg = ngMesh->LineSegment(i);
3591 Link link(seg[0], seg[1]);
3592 if ( !linkMap.Add( link )) continue;
3593 int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
3594 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
3596 vector<int>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
3600 // store nb of nodes on edges computed by Netgen
3601 TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
3602 for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
3604 vector<int>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
3605 if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
3606 aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
3608 fullNbSeg += aVec[ entity ];
3609 Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ];
3611 if ( fullNbSeg == 0 )
3618 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3620 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3621 mparams.grading = 0.4; // moderate size growth
3624 // length from edges
3625 mparams.maxh = fullLen/fullNbSeg;
3626 mparams.grading = 0.2; // slow size growth
3629 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3630 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
3632 for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
3634 TopoDS_Face F = TopoDS::Face( exp.Current() );
3635 SMESH_subMesh *sm = _mesh->GetSubMesh(F);
3637 BRepGProp::SurfaceProperties(F,G);
3638 double anArea = G.Mass();
3639 tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
3641 if ( !tooManyElems )
3643 TopTools_MapOfShape edges;
3644 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
3645 if ( edges.Add( exp1.Current() ))
3646 nb1d += Edge2NbSeg.Find(exp1.Current());
3648 int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
3649 int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
3651 vector<int> aVec(SMDSEntity_Last, 0);
3652 if( mparams.secondorder > 0 ) {
3653 int nb1d_in = (nbFaces*3 - nb1d) / 2;
3654 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3655 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
3658 aVec[SMDSEntity_Node] = Max ( nbNodes, 0 );
3659 aVec[SMDSEntity_Triangle] = nbFaces;
3661 aResMap[sm].swap(aVec);
3668 // pass 3D simple parameters to NETGEN
3669 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3670 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3672 if ( double vol = simple3d->GetMaxElementVolume() ) {
3674 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3675 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3678 // using previous length from faces
3680 mparams.grading = 0.4;
3681 mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading));
3684 BRepGProp::VolumeProperties(_shape,G);
3685 double aVolume = G.Mass();
3686 double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
3687 tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
3688 int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
3689 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3690 vector<int> aVec(SMDSEntity_Last, 0 );
3691 if ( tooManyElems ) // avoid FPE
3693 aVec[SMDSEntity_Node] = hugeNb;
3694 aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
3698 if( mparams.secondorder > 0 ) {
3699 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3700 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3703 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3704 aVec[SMDSEntity_Tetra] = nbVols;
3707 SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
3708 aResMap[sm].swap(aVec);
3714 double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder,
3715 const int * algoProgressTic,
3716 const double * algoProgress) const
3718 ((int&) _progressTic ) = *algoProgressTic + 1;
3720 if ( !_occgeom ) return 0;
3722 double progress = -1;
3725 if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
3727 ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
3729 else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
3731 int doneShapeIndex = -1;
3732 while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
3733 _occgeom->facemeshstatus[ doneShapeIndex+1 ])
3735 if ( doneShapeIndex+1 != _curShapeIndex )
3737 ((int&) _curShapeIndex) = doneShapeIndex+1;
3738 double doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
3739 double doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
3740 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3741 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3742 // << " " << doneTime / _totalTime / _progressTic << endl;
3746 else if ( !_optimize && _occgeom->somap.Extent() > 1 )
3748 int curShapeIndex = _curShapeIndex;
3749 if ( _ngMesh->GetNE() > 0 )
3751 netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
3752 curShapeIndex = el.GetIndex();
3754 if ( curShapeIndex != _curShapeIndex )
3756 ((int&) _curShapeIndex) = curShapeIndex;
3757 double doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
3758 double doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
3759 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3760 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3761 // << " " << doneTime / _totalTime / _progressTic << endl;
3766 progress = Max( *algoProgressTic * _ticTime, *algoProgress );
3771 netgen::multithread.task[0] == 'D'/*elaunay meshing*/ &&
3772 progress > voluMeshingTime )
3774 progress = voluMeshingTime;
3775 ((double&) _ticTime) = voluMeshingTime / _totalTime / _progressTic;
3777 ((int&) *algoProgressTic )++;
3778 ((double&) *algoProgress) = progress;
3780 //cout << progress << " " << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
3782 return Min( progress, 0.99 );
3785 //================================================================================
3787 * \brief Read mesh entities preventing successful computation from "test.out" file
3789 //================================================================================
3791 SMESH_ComputeErrorPtr
3792 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
3794 if ( nodeVec.size() < 2 ) return SMESH_ComputeErrorPtr();
3795 SMESH_BadInputElements* err =
3796 new SMESH_BadInputElements( nodeVec.back()->GetMesh(), COMPERR_BAD_INPUT_MESH,
3797 "Some edges multiple times in surface mesh");
3798 SMESH_File file("test.out");
3800 vector<int> three1(3), three2(3);
3801 const char* badEdgeStr = " multiple times in surface mesh";
3802 const int badEdgeStrLen = strlen( badEdgeStr );
3803 const int nbNodes = nodeVec.size();
3805 while( !file.eof() )
3807 if ( strncmp( file, "Edge ", 5 ) == 0 &&
3808 file.getInts( two ) &&
3809 strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
3810 two[0] < nbNodes && two[1] < nbNodes )
3812 err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
3813 file += badEdgeStrLen;
3815 else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
3818 // openelement 18 with open element 126
3822 const char* pos = file;
3823 bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
3824 ok = ok && file.getInts( two );
3825 ok = ok && file.getInts( three1 );
3826 ok = ok && file.getInts( three2 );
3827 for ( int i = 0; ok && i < 3; ++i )
3828 ok = ( three1[i] < nbNodes && nodeVec[ three1[i]]);
3829 for ( int i = 0; ok && i < 3; ++i )
3830 ok = ( three2[i] < nbNodes && nodeVec[ three2[i]]);
3833 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
3834 nodeVec[ three1[1]],
3835 nodeVec[ three1[2]]));
3836 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
3837 nodeVec[ three2[1]],
3838 nodeVec[ three2[2]]));
3839 err->myComment = "Intersecting triangles";
3853 size_t nbBadElems = err->myBadElements.size();
3854 if ( nbBadElems ) nbBadElems++; // avoid warning: variable set but not used
3857 return SMESH_ComputeErrorPtr( err );
3860 //================================================================================
3862 * \brief Write a python script creating an equivalent SALOME mesh.
3863 * This is useful to see what mesh is passed as input for the next step of mesh
3864 * generation (of mesh of higher dimension)
3866 //================================================================================
3868 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh )
3870 const char* pyFile = "/tmp/ngMesh.py";
3871 ofstream outfile( pyFile, ios::out );
3872 if ( !outfile ) return;
3874 outfile << "import salome, SMESH" << std::endl
3875 << "from salome.smesh import smeshBuilder" << std::endl
3876 << "smesh = smeshBuilder.New()" << std::endl
3877 << "mesh = smesh.Mesh()" << std::endl << std::endl;
3879 using namespace netgen;
3881 for (pi = PointIndex::BASE;
3882 pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3884 outfile << "mesh.AddNode( ";
3885 outfile << (*ngMesh)[pi](0) << ", ";
3886 outfile << (*ngMesh)[pi](1) << ", ";
3887 outfile << (*ngMesh)[pi](2) << ") ## "<< pi << std::endl;
3890 int nbDom = ngMesh->GetNDomains();
3891 for ( int i = 0; i < nbDom; ++i )
3892 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< std::endl;
3894 SurfaceElementIndex sei;
3895 for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3897 outfile << "mesh.AddFace([ ";
3898 Element2d sel = (*ngMesh)[sei];
3899 for (int j = 0; j < sel.GetNP(); j++)
3900 outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3901 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3902 outfile << std::endl;
3904 if ((*ngMesh)[sei].GetIndex())
3906 if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3907 outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << std::endl;
3908 if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3909 outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << std::endl;
3913 for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3915 Element el = (*ngMesh)[ei];
3916 outfile << "mesh.AddVolume([ ";
3917 for (int j = 0; j < el.GetNP(); j++)
3918 outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3919 outfile << std::endl;
3922 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3924 const Segment & seg = ngMesh->LineSegment (i);
3925 outfile << "mesh.AddEdge([ "
3927 << seg[1] << " ])" << std::endl;
3929 std::cout << "Write " << pyFile << std::endl;
3932 //================================================================================
3934 * \brief Constructor of NETGENPlugin_ngMeshInfo
3936 //================================================================================
3938 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh,
3939 bool checkRemovedElems):
3940 _elementsRemoved( false ), _copyOfLocalH(0)
3944 _nbNodes = ngMesh->GetNP();
3945 _nbSegments = ngMesh->GetNSeg();
3946 _nbFaces = ngMesh->GetNSE();
3947 _nbVolumes = ngMesh->GetNE();
3949 if ( checkRemovedElems )
3950 for ( int i = 1; i <= ngMesh->GetNSE() && !_elementsRemoved; ++i )
3951 _elementsRemoved = ngMesh->SurfaceElement(i).IsDeleted();
3955 _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
3959 //================================================================================
3961 * \brief Copy LocalH member from one netgen mesh to another
3963 //================================================================================
3965 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
3966 netgen::Mesh* toMesh )
3968 if ( !fromMesh->LocalHFunctionGenerated() ) return;
3969 if ( !toMesh->LocalHFunctionGenerated() )
3971 toMesh->CalcLocalH(netgen::mparam.grading);
3973 toMesh->CalcLocalH();
3976 const size_t size = sizeof( netgen::LocalH );
3977 _copyOfLocalH = new char[ size ];
3978 memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
3979 memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
3982 //================================================================================
3984 * \brief Restore LocalH member of a netgen mesh
3986 //================================================================================
3988 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
3990 if ( _copyOfLocalH )
3992 const size_t size = sizeof( netgen::LocalH );
3993 memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
3994 delete [] _copyOfLocalH;
3999 //================================================================================
4001 * \brief Find "internal" sub-shapes
4003 //================================================================================
4005 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh,
4006 const TopoDS_Shape& shape,
4008 : _mesh( mesh ), _is3D( is3D )
4010 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
4012 TopExp_Explorer f,e;
4013 for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
4015 int faceID = meshDS->ShapeToIndex( f.Current() );
4017 // find not computed internal edges
4019 for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
4020 if ( e.Current().Orientation() == TopAbs_INTERNAL )
4022 SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
4023 if ( eSM->IsEmpty() )
4025 _e2face.insert( make_pair( eSM->GetId(), faceID ));
4026 for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
4027 _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
4031 // find internal vertices in a face
4032 set<int> intVV; // issue 0020850 where same vertex is twice in a face
4033 for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
4034 if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
4036 int vID = meshDS->ShapeToIndex( fSub.Value() );
4037 if ( intVV.insert( vID ).second )
4038 _f2v[ faceID ].push_back( vID );
4043 // find internal faces and their subshapes where nodes are to be doubled
4044 // to make a crack with non-sewed borders
4046 if ( f.Current().Orientation() == TopAbs_INTERNAL )
4048 _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
4051 list< TopoDS_Shape > edges;
4052 for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
4053 if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
4055 _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
4056 edges.push_back( e.Current() );
4057 // find border faces
4058 PShapeIteratorPtr fIt =
4059 SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
4060 while ( const TopoDS_Shape* pFace = fIt->next() )
4061 if ( !pFace->IsSame( f.Current() ))
4062 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
4065 // we consider vertex internal if it is shared by more than one internal edge
4066 list< TopoDS_Shape >::iterator edge = edges.begin();
4067 for ( ; edge != edges.end(); ++edge )
4068 for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
4070 set<int> internalEdges;
4071 PShapeIteratorPtr eIt =
4072 SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
4073 while ( const TopoDS_Shape* pEdge = eIt->next() )
4075 int edgeID = meshDS->ShapeToIndex( *pEdge );
4076 if ( isInternalShape( edgeID ))
4077 internalEdges.insert( edgeID );
4079 if ( internalEdges.size() > 1 )
4080 _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
4084 } // loop on geom faces
4086 // find vertices internal in solids
4089 for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
4091 int soID = meshDS->ShapeToIndex( so.Current() );
4092 for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
4093 if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
4094 _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
4099 //================================================================================
4101 * \brief Find mesh faces on non-internal geom faces sharing internal edge
4102 * some nodes of which are to be doubled to make the second border of the "crack"
4104 //================================================================================
4106 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
4108 if ( _intShapes.empty() ) return;
4110 SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
4111 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
4113 // loop on internal geom edges
4114 set<int>::const_iterator intShapeId = _intShapes.begin();
4115 for ( ; intShapeId != _intShapes.end(); ++intShapeId )
4117 const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
4118 if ( s.ShapeType() != TopAbs_EDGE ) continue;
4120 // get internal and non-internal geom faces sharing the internal edge <s>
4122 set<int>::iterator bordFace = _borderFaces.end();
4123 PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
4124 while ( const TopoDS_Shape* pFace = faces->next() )
4126 int faceID = meshDS->ShapeToIndex( *pFace );
4127 if ( isInternalShape( faceID ))
4130 bordFace = _borderFaces.insert( faceID ).first;
4132 if ( bordFace == _borderFaces.end() || !intFace ) continue;
4134 // get all links of mesh faces on internal geom face sharing nodes on edge <s>
4135 set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
4136 list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
4137 int nbSuspectFaces = 0;
4138 SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
4139 if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
4140 SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
4141 while ( smIt->more() )
4143 SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
4144 if ( !sm ) continue;
4145 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4146 while ( nIt->more() )
4148 const SMDS_MeshNode* nOnEdge = nIt->next();
4149 SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
4150 while ( fIt->more() )
4152 const SMDS_MeshElement* f = fIt->next();
4153 const int nbNodes = f->NbCornerNodes();
4154 if ( intFaceSM->Contains( f ))
4156 for ( int i = 0; i < nbNodes; ++i )
4157 links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
4162 for ( int i = 0; i < nbNodes; ++i )
4163 nbDblNodes += isInternalShape( f->GetNode(i)->GetShapeID() );
4165 suspectFaces[ nbDblNodes < 2 ].push_back( f );
4171 // suspectFaces[0] having link with same orientation as mesh faces on
4172 // the internal geom face are <borderElems>. suspectFaces[1] have
4173 // only one node on edge <s>, we decide on them later (at the 2nd loop)
4174 // by links of <borderElems> found at the 1st and 2nd loops
4175 set< SMESH_OrientedLink > borderLinks;
4176 for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
4178 list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
4179 for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
4181 const SMDS_MeshElement* f = *fIt;
4182 bool isBorder = false, linkFound = false, borderLinkFound = false;
4183 list< SMESH_OrientedLink > faceLinks;
4184 int nbNodes = f->NbCornerNodes();
4185 for ( int i = 0; i < nbNodes; ++i )
4187 SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
4188 faceLinks.push_back( link );
4191 set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
4192 if ( foundLink != links.end() )
4195 isBorder = ( foundLink->_reversed == link._reversed );
4196 if ( !isBorder && !isPostponed ) break;
4197 faceLinks.pop_back();
4199 else if ( isPostponed && !borderLinkFound )
4201 foundLink = borderLinks.find( link );
4202 if ( foundLink != borderLinks.end() )
4204 borderLinkFound = true;
4205 isBorder = ( foundLink->_reversed != link._reversed );
4212 borderElems.insert( f );
4213 borderLinks.insert( faceLinks.begin(), faceLinks.end() );
4215 else if ( !linkFound && !borderLinkFound )
4217 suspectFaces[1].push_back( f );
4218 if ( nbF > 2 * nbSuspectFaces )
4219 break; // dead loop protection
4226 //================================================================================
4228 * \brief put internal shapes in maps and fill in submeshes to precompute
4230 //================================================================================
4232 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
4233 TopTools_IndexedMapOfShape& emap,
4234 TopTools_IndexedMapOfShape& vmap,
4235 list< SMESH_subMesh* > smToPrecompute[])
4237 if ( !hasInternalEdges() ) return;
4238 map<int,int>::const_iterator ev_face = _e2face.begin();
4239 for ( ; ev_face != _e2face.end(); ++ev_face )
4241 const TopoDS_Shape& ev = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
4242 const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
4244 ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
4246 //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
4248 smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
4252 //================================================================================
4254 * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
4256 //================================================================================
4258 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
4259 TopTools_IndexedMapOfShape& emap,
4260 list< SMESH_subMesh* >& intFaceSM,
4261 list< SMESH_subMesh* >& boundarySM)
4263 if ( !hasInternalFaces() ) return;
4265 // <fmap> and <emap> are for not yet meshed shapes
4266 // <intFaceSM> is for submeshes of faces
4267 // <boundarySM> is for meshed edges and vertices
4272 set<int> shapeIDs ( _intShapes );
4273 if ( !_borderFaces.empty() )
4274 shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
4276 set<int>::const_iterator intS = shapeIDs.begin();
4277 for ( ; intS != shapeIDs.end(); ++intS )
4279 SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
4281 if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
4283 intFaceSM.push_back( sm );
4285 // add submeshes of not computed internal faces
4286 if ( !sm->IsEmpty() ) continue;
4288 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
4289 while ( smIt->more() )
4292 const TopoDS_Shape& s = sm->GetSubShape();
4294 if ( sm->IsEmpty() )
4297 switch ( s.ShapeType() ) {
4298 case TopAbs_FACE: fmap.Add ( s ); break;
4299 case TopAbs_EDGE: emap.Add ( s ); break;
4305 if ( s.ShapeType() != TopAbs_FACE )
4306 boundarySM.push_back( sm );
4312 //================================================================================
4314 * \brief Return true if given shape is to be precomputed in order to be correctly
4315 * added to netgen mesh
4317 //================================================================================
4319 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
4321 int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
4322 switch ( s.ShapeType() ) {
4323 case TopAbs_FACE : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
4324 case TopAbs_EDGE : return isInternalEdge( shapeID );
4325 case TopAbs_VERTEX: break;
4331 //================================================================================
4333 * \brief Return SMESH
4335 //================================================================================
4337 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
4339 return const_cast<SMESH_Mesh&>( _mesh );
4342 //================================================================================
4344 * \brief Access to a counter of NETGENPlugin_NetgenLibWrapper instances
4346 //================================================================================
4348 int& NETGENPlugin_NetgenLibWrapper::instanceCounter()
4350 static int theCouner = 0;
4354 //================================================================================
4356 * \brief Initialize netgen library
4358 //================================================================================
4360 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper()
4362 if ( instanceCounter() == 0 )
4365 ++instanceCounter();
4367 _isComputeOk = false;
4371 if ( !getenv( "KEEP_NETGEN_OUTPUT" ))
4373 // redirect all netgen output (mycout,myerr,cout) to _outputFileName
4374 _outputFileName = getOutputFileName();
4375 _ngcout = netgen::mycout;
4376 _ngcerr = netgen::myerr;
4377 netgen::mycout = new ofstream ( _outputFileName.c_str() );
4378 netgen::myerr = netgen::mycout;
4379 _coutBuffer = std::cout.rdbuf();
4381 std::cout << "NOTE: netgen output is redirected to file " << _outputFileName << std::endl;
4383 std::cout.rdbuf( netgen::mycout->rdbuf() );
4387 _ngMesh = Ng_NewMesh();
4390 //================================================================================
4392 * \brief Finish using netgen library
4394 //================================================================================
4396 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
4398 --instanceCounter();
4400 Ng_DeleteMesh( _ngMesh );
4404 std::cout.rdbuf( _coutBuffer );
4411 //================================================================================
4413 * \brief Set netgen mesh to delete at destruction
4415 //================================================================================
4417 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
4420 Ng_DeleteMesh( _ngMesh );
4424 //================================================================================
4426 * \brief Return a unique file name
4428 //================================================================================
4430 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
4432 std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
4434 TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str();
4435 aGenericName += "NETGEN_";
4437 aGenericName += getpid();
4439 aGenericName += _getpid();
4441 aGenericName += "_";
4442 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
4443 aGenericName += ".out";
4445 return aGenericName.ToCString();
4448 //================================================================================
4450 * \brief Remove "test.out" and "problemfaces" files in current directory
4452 //================================================================================
4454 void NETGENPlugin_NetgenLibWrapper::RemoveTmpFiles()
4456 bool rm = SMESH_File("test.out").remove() ;
4458 if ( rm && netgen::testout && instanceCounter() == 0 )
4460 delete netgen::testout;
4461 netgen::testout = 0;
4464 SMESH_File("problemfaces").remove();
4465 SMESH_File("occmesh.rep").remove();
4468 //================================================================================
4470 * \brief Remove file with netgen output
4472 //================================================================================
4474 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
4476 if ( !_outputFileName.empty() )
4480 delete netgen::mycout;
4481 netgen::mycout = _ngcout;
4482 netgen::myerr = _ngcerr;
4485 string tmpDir = SALOMEDS_Tool::GetDirFromPath ( _outputFileName );
4486 string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
4487 SALOMEDS_Tool::ListOfFiles aFiles;
4489 aFiles.push_back(aFileName.c_str());
4491 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles, true );