1 // Copyright (C) 2007-2022 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 #include <Basics_OCCTVersion.hxx>
80 // Netgen include files
84 #include <occgeom.hpp>
85 #include <meshing.hpp>
86 //#include <ngexception.hpp>
89 NETGENPLUGIN_DLL_HEADER
90 extern MeshingParameters mparam;
92 NETGENPLUGIN_DLL_HEADER
93 extern volatile multithreadt multithread;
95 NETGENPLUGIN_DLL_HEADER
96 extern bool merge_solids;
98 // values used for occgeo.facemeshstatus
99 enum EFaceMeshStatus { FACE_NOT_TREATED = 0,
111 using namespace nglib;
115 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec.at((index)))
117 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec[index])
120 #define NGPOINT_COORDS(p) p(0),p(1),p(2)
123 // dump elements added to ng mesh
124 //#define DUMP_SEGMENTS
125 //#define DUMP_TRIANGLES
126 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids()
129 TopTools_IndexedMapOfShape ShapesWithLocalSize;
130 std::map<int,double> VertexId2LocalSize;
131 std::map<int,double> EdgeId2LocalSize;
132 std::map<int,double> FaceId2LocalSize;
133 std::map<int,double> SolidId2LocalSize;
135 std::vector<SMESHUtils::ControlPnt> ControlPoints;
136 std::set<int> ShapesWithControlPoints; // <-- allows calling SetLocalSize() several times w/o recomputing ControlPoints
140 inline void NOOP_Deleter(void *) { ; }
142 //=============================================================================
144 * Link - a pair of integer numbers
146 //=============================================================================
150 Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
151 Link() : n1(0), n2(0) {}
152 bool Contains( int n ) const { return n == n1 || n == n2; }
153 bool IsConnected( const Link& other ) const
155 return (( Contains( other.n1 ) || Contains( other.n2 )) && ( this != &other ));
157 static int HashCode(const Link& aLink, int aLimit)
159 return ::HashCode(aLink.n1 + aLink.n2, aLimit);
162 static Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
164 return (( aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ) ||
165 ( aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1 ));
169 typedef NCollection_Map<Link,Link> TLinkMap;
171 //================================================================================
173 * \brief return id of netgen point corresponding to SMDS node
175 //================================================================================
176 typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
178 int ngNodeId( const SMDS_MeshNode* node,
179 netgen::Mesh& ngMesh,
180 TNode2IdMap& nodeNgIdMap)
182 int newNgId = ngMesh.GetNP() + 1;
184 TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
186 if ( node_id->second == newNgId)
188 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
189 cout << "Ng " << newNgId << " - " << node;
191 netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
192 ngMesh.AddPoint( p );
194 return node_id->second;
197 //================================================================================
199 * \brief Return computed EDGEs connected to the given one
201 //================================================================================
203 list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge& edge,
204 const TopoDS_Face& face,
205 const set< SMESH_subMesh* > & /*computedSM*/,
206 const SMESH_MesherHelper& helper,
207 map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
210 list< TopoDS_Edge > edges;
211 list< int > nbEdgesInWire;
212 /*int nbWires =*/ SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire);
214 // find <edge> within <edges>
215 list< TopoDS_Edge >::iterator eItFwd = edges.begin();
216 for ( ; eItFwd != edges.end(); ++eItFwd )
217 if ( edge.IsSame( *eItFwd ))
219 if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
221 if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
223 // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
224 // so treat each INTERNAL edge separately
225 TopoDS_Edge e = *eItFwd;
227 edges.push_back( e );
231 // get all computed EDGEs connected to <edge>
233 list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
234 TopoDS_Vertex vCommon;
235 TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
238 // put edges before <edge> to <edges> back
239 while ( edges.begin() != eItFwd )
240 edges.splice( edges.end(), edges, edges.begin() );
244 while ( ++eItFwd != edges.end() )
246 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
248 bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
249 bool computed = !sm->IsEmpty();
250 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
251 bool doubled = !eAdded.Add( *eItFwd );
252 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
253 ( eItFwd->Orientation() < TopAbs_INTERNAL ) );
254 if ( !connected || !computed || !orientOK || added || doubled )
256 // stop advancement; move edges from tail to head
257 while ( edges.back() != *ePrev )
258 edges.splice( edges.begin(), edges, --edges.end() );
264 while ( eItBack != edges.begin() )
268 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
270 bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
271 bool computed = !sm->IsEmpty();
272 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
273 bool doubled = !eAdded.Add( *eItBack );
274 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
275 ( eItBack->Orientation() < TopAbs_INTERNAL ) );
276 if ( !connected || !computed || !orientOK || added || doubled)
279 edges.erase( edges.begin(), ePrev );
283 if ( edges.front() != edges.back() )
285 // assure that the 1st vertex is meshed
286 TopoDS_Edge eLast = edges.back();
287 while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
289 edges.front() != eLast )
290 edges.splice( edges.end(), edges, edges.begin() );
295 //================================================================================
297 * \brief Make triangulation of a shape precise enough
299 //================================================================================
301 void updateTriangulation( const TopoDS_Shape& shape )
303 // static set< Poly_Triangulation* > updated;
305 // TopLoc_Location loc;
306 // TopExp_Explorer fExp( shape, TopAbs_FACE );
307 // for ( ; fExp.More(); fExp.Next() )
309 // Handle(Poly_Triangulation) triangulation =
310 // BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
311 // if ( triangulation.IsNull() ||
312 // updated.insert( triangulation.operator->() ).second )
314 // BRepTools::Clean (shape);
317 BRepMesh_IncrementalMesh e(shape, 0.01, true);
319 catch (Standard_Failure&)
322 // updated.erase( triangulation.operator->() );
323 // triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
324 // updated.insert( triangulation.operator->() );
328 //================================================================================
330 * \brief Returns a medium node either existing in SMESH of created by NETGEN
331 * \param [in] corner1 - corner node 1
332 * \param [in] corner2 - corner node 2
333 * \param [in] defaultMedium - the node created by NETGEN
334 * \param [in] helper - holder of medium nodes existing in SMESH
335 * \return const SMDS_MeshNode* - the result node
337 //================================================================================
339 const SMDS_MeshNode* mediumNode( const SMDS_MeshNode* corner1,
340 const SMDS_MeshNode* corner2,
341 const SMDS_MeshNode* defaultMedium,
342 const SMESH_MesherHelper* helper)
346 TLinkNodeMap::const_iterator l2n =
347 helper->GetTLinkNodeMap().find( SMESH_TLink( corner1, corner2 ));
348 if ( l2n != helper->GetTLinkNodeMap().end() )
349 defaultMedium = l2n->second;
351 return defaultMedium;
354 //================================================================================
356 * \brief Assure that mesh on given shapes is quadratic
358 //================================================================================
360 // void makeQuadratic( const TopTools_IndexedMapOfShape& shapes,
361 // SMESH_Mesh* mesh )
363 // for ( int i = 1; i <= shapes.Extent(); ++i )
365 // SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) );
366 // if ( !smDS ) continue;
367 // SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
368 // if ( !elemIt->more() ) continue;
369 // const SMDS_MeshElement* e = elemIt->next();
370 // if ( !e || e->IsQuadratic() )
373 // TIDSortedElemSet elems;
374 // elems.insert( e );
375 // while ( elemIt->more() )
376 // elems.insert( elems.end(), elemIt->next() );
378 // SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false );
382 //================================================================================
384 * \brief Restrict size of elements on the given edge
386 //================================================================================
388 void setLocalSize(const TopoDS_Edge& edge,
391 const bool overrideMinH = true)
393 if ( size <= std::numeric_limits<double>::min() )
395 Standard_Real u1, u2;
396 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
397 if ( curve.IsNull() )
399 TopoDS_Iterator vIt( edge );
400 if ( !vIt.More() ) return;
401 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
402 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH );
406 const int nb = (int)( 1.5 * SMESH_Algo::EdgeLength( edge ) / size );
407 Standard_Real delta = (u2-u1)/nb;
408 for(int i=0; i<nb; i++)
410 Standard_Real u = u1 + delta*i;
411 gp_Pnt p = curve->Value(u);
412 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH );
413 netgen::Point3d pi(p.X(), p.Y(), p.Z());
414 double resultSize = mesh.GetH(pi);
415 if ( resultSize - size > 0.1*size )
416 // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
417 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201, overrideMinH );
422 //================================================================================
424 * \brief Return triangle size for a given chordalError and radius of curvature
426 //================================================================================
428 double elemSizeForChordalError( double chordalError, double radius )
430 if ( 2 * radius < chordalError )
432 return Sqrt( 3 ) * Sqrt( chordalError * ( 2 * radius - chordalError ));
435 //=============================================================================
439 //=============================================================================
441 void setLocalSize(const TopoDS_Shape& GeomShape, double LocalSize)
443 if ( GeomShape.IsNull() ) return;
444 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
445 if (GeomType == TopAbs_COMPOUND) {
446 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
447 setLocalSize(it.Value(), LocalSize);
452 if (! ShapesWithLocalSize.Contains(GeomShape))
453 key = ShapesWithLocalSize.Add(GeomShape);
455 key = ShapesWithLocalSize.FindIndex(GeomShape);
456 if (GeomType == TopAbs_VERTEX) {
457 VertexId2LocalSize[key] = LocalSize;
458 } else if (GeomType == TopAbs_EDGE) {
459 EdgeId2LocalSize[key] = LocalSize;
460 } else if (GeomType == TopAbs_FACE) {
461 FaceId2LocalSize[key] = LocalSize;
462 } else if (GeomType == TopAbs_SOLID) {
463 SolidId2LocalSize[key] = LocalSize;
468 //================================================================================
470 * \brief Return faceNgID or faceNgID-1 depending on side the given proxy face lies
471 * \param [in] f - proxy face
472 * \param [in] solidSMDSIDs - IDs of SOLIDs sharing the FACE on which face lies
473 * \param [in] faceNgID - NETGEN ID of the FACE
474 * \return int - NETGEN ID of the FACE
476 //================================================================================
478 int getFaceNgID( const SMDS_MeshElement* face,
479 const int * solidSMDSIDs,
482 for ( int i = 0; i < 3; ++i )
484 const SMDS_MeshNode* n = face->GetNode( i );
485 const int shapeID = n->GetShapeID();
486 if ( shapeID == solidSMDSIDs[0] )
488 if ( shapeID == solidSMDSIDs[1] )
491 std::vector<const SMDS_MeshNode*> fNodes( face->begin_nodes(), face->end_nodes() );
492 std::vector<const SMDS_MeshElement*> vols;
493 if ( SMDS_Mesh::GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ))
494 for ( size_t i = 0; i < vols.size(); ++i )
496 const int shapeID = vols[i]->GetShapeID();
497 if ( shapeID == solidSMDSIDs[0] )
499 if ( shapeID == solidSMDSIDs[1] )
509 //=============================================================================
513 //=============================================================================
515 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh,
516 const TopoDS_Shape& aShape,
522 _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
523 _isViscousLayers2D(false),
524 _chordalError(-1), // means disabled
531 _viscousLayersHyp(NULL),
534 SetDefaultParameters();
535 ShapesWithLocalSize.Clear();
536 VertexId2LocalSize.clear();
537 EdgeId2LocalSize.clear();
538 FaceId2LocalSize.clear();
539 SolidId2LocalSize.clear();
540 ControlPoints.clear();
541 ShapesWithControlPoints.clear();
544 //================================================================================
548 //================================================================================
550 NETGENPlugin_Mesher::~NETGENPlugin_Mesher()
558 //================================================================================
560 * Set pointer to NETGENPlugin_Mesher* field of the holder, that will be
561 * nullified at destruction of this
563 //================================================================================
565 void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr )
576 //================================================================================
578 * \brief Initialize global NETGEN parameters with default values
580 //================================================================================
582 void NETGENPlugin_Mesher::SetDefaultParameters()
584 netgen::MeshingParameters& mparams = netgen::mparam;
585 mparams = netgen::MeshingParameters();
586 // maximal mesh edge size
587 mparams.maxh = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
589 // minimal number of segments per edge
590 mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
591 // rate of growth of size between elements
592 mparams.grading = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
593 // safety factor for curvatures (elements per radius)
594 mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
595 // create elements of second order
596 mparams.secondorder = NETGENPlugin_Hypothesis::GetDefaultSecondOrder();
597 // quad-dominated surface meshing
601 mparams.quad = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed();
602 _fineness = NETGENPlugin_Hypothesis::GetDefaultFineness();
603 mparams.uselocalh = NETGENPlugin_Hypothesis::GetDefaultSurfaceCurvature();
604 netgen::merge_solids = NETGENPlugin_Hypothesis::GetDefaultFuseEdges();
605 // Unused argument but set 0 to initialise it
606 mparams.elementorder = 0;
610 mparams.nthreads = NETGENPlugin_Hypothesis::GetDefaultNbThreads();
612 if ( getenv( "SALOME_NETGEN_DISABLE_MULTITHREADING" ))
614 mparams.nthreads = 1;
615 mparams.parallel_meshing = false;
621 //=============================================================================
623 * Pass parameters to NETGEN
625 //=============================================================================
626 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
630 netgen::MeshingParameters& mparams = netgen::mparam;
631 // Initialize global NETGEN parameters:
632 // maximal mesh segment size
633 mparams.maxh = hyp->GetMaxSize();
634 // maximal mesh element linear size
635 mparams.minh = hyp->GetMinSize();
636 // minimal number of segments per edge
637 mparams.segmentsperedge = hyp->GetNbSegPerEdge();
638 // rate of growth of size between elements
639 mparams.grading = hyp->GetGrowthRate();
640 // safety factor for curvatures (elements per radius)
641 mparams.curvaturesafety = hyp->GetNbSegPerRadius();
642 // create elements of second order
643 mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
644 // quad-dominated surface meshing
645 mparams.quad = hyp->GetQuadAllowed() ? 1 : 0;
646 _optimize = hyp->GetOptimize();
647 _fineness = hyp->GetFineness();
648 mparams.uselocalh = hyp->GetSurfaceCurvature();
649 netgen::merge_solids = hyp->GetFuseEdges();
650 _chordalError = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
651 mparams.optsteps2d = _optimize ? hyp->GetNbSurfOptSteps() : 0;
652 mparams.optsteps3d = _optimize ? hyp->GetNbVolOptSteps() : 0;
653 mparams.elsizeweight = hyp->GetElemSizeWeight();
654 mparams.opterrpow = hyp->GetWorstElemMeasure();
655 mparams.delaunay = hyp->GetUseDelauney();
656 mparams.checkoverlap = hyp->GetCheckOverlapping();
657 mparams.checkchartboundary = hyp->GetCheckChartBoundary();
662 mparams.meshsizefilename = hyp->GetMeshSizeFile();
663 mparams.nthreads = hyp->GetNbThreads();
666 mparams.meshsizefilename= hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
668 const NETGENPlugin_Hypothesis::TLocalSize& localSizes = hyp->GetLocalSizesAndEntries();
669 if ( !localSizes.empty() )
671 SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
672 NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
673 for ( ; it != localSizes.end() ; it++)
675 std::string entry = (*it).first;
676 double val = (*it).second;
678 GEOM::GEOM_Object_var aGeomObj;
679 SALOMEDS::SObject_var aSObj = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( entry.c_str() );
680 if ( !aSObj->_is_nil() ) {
681 CORBA::Object_var obj = aSObj->GetObject();
682 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
685 TopoDS_Shape S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
686 setLocalSize(S, val);
693 netgen::mparam.closeedgefac = 2;
698 //=============================================================================
700 * Pass simple parameters to NETGEN
702 //=============================================================================
704 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
708 SetDefaultParameters();
711 //================================================================================
713 * \brief Store a Viscous Layers hypothesis
715 //================================================================================
717 void NETGENPlugin_Mesher::SetParameters(const StdMeshers_ViscousLayers* hyp )
719 _viscousLayersHyp = hyp;
722 //================================================================================
724 * \brief Set local size on shapes defined by SetParameters()
726 //================================================================================
728 void NETGENPlugin_Mesher::SetLocalSize( netgen::OCCGeometry& occgeo,
729 netgen::Mesh& ngMesh)
732 std::map<int,double>::const_iterator it;
733 for( it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
735 int key = (*it).first;
736 double hi = (*it).second;
737 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
738 setLocalSize( TopoDS::Edge(shape), hi, ngMesh );
741 for(it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
743 int key = (*it).first;
744 double hi = (*it).second;
745 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
746 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex(shape) );
747 NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, p.XYZ(), hi );
750 for(it=FaceId2LocalSize.begin(); it!=FaceId2LocalSize.end(); it++)
752 int key = (*it).first;
753 double val = (*it).second;
754 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
755 int faceNgID = occgeo.fmap.FindIndex(shape);
759 occgeo.SetFaceMaxH(faceNgID-1, val, netgen::mparam);
761 occgeo.SetFaceMaxH(faceNgID, val);
763 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
764 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, ngMesh );
766 else if ( !ShapesWithControlPoints.count( key ))
768 SMESHUtils::createPointsSampleFromFace( TopoDS::Face( shape ), val, ControlPoints );
769 ShapesWithControlPoints.insert( key );
773 for(it=SolidId2LocalSize.begin(); it!=SolidId2LocalSize.end(); it++)
775 int key = (*it).first;
776 double val = (*it).second;
777 if ( !ShapesWithControlPoints.count( key ))
779 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
780 SMESHUtils::createPointsSampleFromSolid( TopoDS::Solid( shape ), val, ControlPoints );
781 ShapesWithControlPoints.insert( key );
785 if ( !ControlPoints.empty() )
787 for ( size_t i = 0; i < ControlPoints.size(); ++i )
788 NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, ControlPoints[i].XYZ(), ControlPoints[i].Size() );
793 //================================================================================
795 * \brief Restrict local size to achieve a required _chordalError
797 //================================================================================
799 void NETGENPlugin_Mesher::SetLocalSizeForChordalError( netgen::OCCGeometry& occgeo,
800 netgen::Mesh& ngMesh)
802 if ( _chordalError <= 0. )
806 BRepLProp_SLProps surfProp( 2, 1e-6 );
807 const double sizeCoef = 0.95;
809 // find non-planar FACEs with non-constant curvature
810 std::vector<int> fInd;
811 for ( int i = 1; i <= occgeo.fmap.Extent(); ++i )
813 const TopoDS_Face& face = TopoDS::Face( occgeo.fmap( i ));
814 BRepAdaptor_Surface surfAd( face, false );
815 switch ( surfAd.GetType() )
819 case GeomAbs_Cylinder:
821 case GeomAbs_Torus: // constant curvature
823 surfProp.SetSurface( surfAd );
824 surfProp.SetParameters( 0, 0 );
825 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
826 double size = elemSizeForChordalError( _chordalError, 1 / maxCurv );
828 occgeo.SetFaceMaxH( i-1, size * sizeCoef, netgen::mparam );
830 occgeo.SetFaceMaxH( i, size * sizeCoef );
832 // limit size one edges
833 TopTools_MapOfShape edgeMap;
834 for ( TopExp_Explorer eExp( face, TopAbs_EDGE ); eExp.More(); eExp.Next() )
835 if ( edgeMap.Add( eExp.Current() ))
836 setLocalSize( TopoDS::Edge( eExp.Current() ), size, ngMesh, /*overrideMinH=*/false );
840 Handle(Geom_Surface) surf = BRep_Tool::Surface( face, loc );
841 if ( GeomLib_IsPlanarSurface( surf ).IsPlanar() )
850 TopoDS_Compound allFacesComp;
851 b.MakeCompound( allFacesComp );
852 for ( size_t i = 0; i < fInd.size(); ++i )
853 b.Add( allFacesComp, occgeo.fmap( fInd[i] ));
855 // copy the shape to avoid spoiling its triangulation
856 TopoDS_Shape allFacesCompCopy = BRepBuilderAPI_Copy( allFacesComp );
858 // create triangulation with desired chordal error
859 BRepMesh_IncrementalMesh( allFacesCompCopy,
861 /*isRelative = */Standard_False,
862 /*theAngDeflection = */ 0.5,
863 /*isInParallel = */Standard_True);
866 for ( TopExp_Explorer fExp( allFacesCompCopy, TopAbs_FACE ); fExp.More(); fExp.Next() )
868 const TopoDS_Face& face = TopoDS::Face( fExp.Current() );
869 Handle(Poly_Triangulation) triangulation = BRep_Tool::Triangulation ( face, loc );
870 if ( triangulation.IsNull() ) continue;
872 BRepAdaptor_Surface surf( face, false );
873 surfProp.SetSurface( surf );
878 for ( int i = 1; i <= triangulation->NbTriangles(); ++i )
880 Standard_Integer n1,n2,n3;
881 triangulation->Triangles()(i).Get( n1,n2,n3 );
882 #if OCC_VERSION_LARGE < 0x07060000
883 p [0] = triangulation->Nodes()(n1).Transformed(loc).XYZ();
884 p [1] = triangulation->Nodes()(n2).Transformed(loc).XYZ();
885 p [2] = triangulation->Nodes()(n3).Transformed(loc).XYZ();
886 uv[0] = triangulation->UVNodes()(n1).XY();
887 uv[1] = triangulation->UVNodes()(n2).XY();
888 uv[2] = triangulation->UVNodes()(n3).XY();
890 p[0] = triangulation->Node(n1).Transformed(loc).XYZ();
891 p[1] = triangulation->Node(n2).Transformed(loc).XYZ();
892 p[2] = triangulation->Node(n3).Transformed(loc).XYZ();
893 uv[0] = triangulation->UVNode(n1).XY();
894 uv[1] = triangulation->UVNode(n2).XY();
895 uv[2] = triangulation->UVNode(n3).XY();
897 surfProp.SetParameters( uv[0].X(), uv[0].Y() );
898 if ( !surfProp.IsCurvatureDefined() )
901 for ( int n = 0; n < 3; ++n ) // get size at triangle nodes
903 surfProp.SetParameters( uv[n].X(), uv[n].Y() );
904 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
905 size[n] = elemSizeForChordalError( _chordalError, 1 / maxCurv );
907 for ( int n1 = 0; n1 < 3; ++n1 ) // limit size along each triangle edge
909 int n2 = ( n1 + 1 ) % 3;
910 double minSize = size[n1], maxSize = size[n2];
911 if ( size[n1] > size[n2] )
912 minSize = size[n2], maxSize = size[n1];
914 if ( maxSize / minSize < 1.2 ) // netgen ignores size difference < 1.2
916 ngMesh.RestrictLocalHLine ( netgen::Point3d( p[n1].X(), p[n1].Y(), p[n1].Z() ),
917 netgen::Point3d( p[n2].X(), p[n2].Y(), p[n2].Z() ),
918 sizeCoef * minSize );
922 gp_XY uvVec( uv[n2] - uv[n1] );
923 double len = ( p[n1] - p[n2] ).Modulus();
924 int nb = int( len / minSize ) + 1;
925 for ( int j = 0; j <= nb; ++j )
927 double r = double( j ) / nb;
928 gp_XY uvj = uv[n1] + r * uvVec;
930 surfProp.SetParameters( uvj.X(), uvj.Y() );
931 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
932 double h = elemSizeForChordalError( _chordalError, 1 / maxCurv );
934 const gp_Pnt& pj = surfProp.Value();
935 netgen::Point3d ngP( pj.X(), pj.Y(), pj.Z());
936 ngMesh.RestrictLocalH( ngP, h * sizeCoef );
945 //================================================================================
947 * \brief Initialize netgen::OCCGeometry with OCCT shape
949 //================================================================================
951 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo,
952 const TopoDS_Shape& shape,
954 list< SMESH_subMesh* > * meshedSM,
955 NETGENPlugin_Internals* intern)
957 updateTriangulation( shape );
960 BRepBndLib::Add (shape, bb);
961 double x1,y1,z1,x2,y2,z2;
962 bb.Get (x1,y1,z1,x2,y2,z2);
963 netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
964 netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
965 occgeo.boundingbox = netgen::Box<3> (p1,p2);
967 occgeo.shape = shape;
970 // fill maps of shapes of occgeo with not yet meshed subshapes
972 // get root submeshes
973 list< SMESH_subMesh* > rootSM;
974 const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
975 if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
976 rootSM.push_back( mesh.GetSubMesh( shape ));
979 for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
980 rootSM.push_back( mesh.GetSubMesh( it.Value() ));
985 // add subshapes of empty submeshes
986 list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
987 for ( ; rootIt != rootEnd; ++rootIt ) {
988 SMESH_subMesh * root = *rootIt;
989 SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
990 /*complexShapeFirst=*/true);
991 // to find a right orientation of subshapes (PAL20462)
992 TopTools_IndexedMapOfShape subShapes;
993 TopExp::MapShapes(root->GetSubShape(), subShapes);
994 while ( smIt->more() )
996 SMESH_subMesh* sm = smIt->next();
997 TopoDS_Shape shape = sm->GetSubShape();
998 totNbFaces += ( shape.ShapeType() == TopAbs_FACE );
999 if ( intern && intern->isShapeToPrecompute( shape ))
1001 if ( !meshedSM || sm->IsEmpty() )
1003 if ( shape.ShapeType() != TopAbs_VERTEX )
1004 shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
1005 if ( shape.Orientation() >= TopAbs_INTERNAL )
1006 shape.Orientation( TopAbs_FORWARD ); // issue 0020676
1007 switch ( shape.ShapeType() ) {
1008 case TopAbs_FACE : occgeo.fmap.Add( shape ); break;
1009 case TopAbs_EDGE : occgeo.emap.Add( shape ); break;
1010 case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
1011 case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
1015 // collect submeshes of meshed shapes
1018 const int dim = SMESH_Gen::GetShapeDim( shape );
1019 meshedSM[ dim ].push_back( sm );
1023 occgeo.facemeshstatus.SetSize (totNbFaces);
1024 occgeo.facemeshstatus = 0;
1025 occgeo.face_maxh_modified.SetSize(totNbFaces);
1026 occgeo.face_maxh_modified = 0;
1027 occgeo.face_maxh.SetSize(totNbFaces);
1028 occgeo.face_maxh = netgen::mparam.maxh;
1031 //================================================================================
1033 * \brief Return a default min size value suitable for the given geometry.
1035 //================================================================================
1037 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
1038 const double maxSize)
1040 updateTriangulation( geom );
1042 TopLoc_Location loc;
1044 const int* pi[4] = { &i1, &i2, &i3, &i1 };
1045 double minh = 1e100;
1047 TopExp_Explorer fExp( geom, TopAbs_FACE );
1048 for ( ; fExp.More(); fExp.Next() )
1050 Handle(Poly_Triangulation) triangulation =
1051 BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
1052 if ( triangulation.IsNull() ) continue;
1053 const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
1054 #if OCC_VERSION_HEX < 0x070600
1055 const TColgp_Array1OfPnt& points = triangulation->Nodes();
1057 auto points = [&triangulation](Standard_Integer index) {
1058 return triangulation->Node(index);
1062 const Poly_Array1OfTriangle& trias = triangulation->Triangles();
1063 for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
1065 trias(iT).Get( i1, i2, i3 );
1066 for ( int j = 0; j < 3; ++j )
1068 double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
1069 if ( dist2 < minh && fTol*fTol < dist2 )
1071 bb.Add( points(*pi[j]));
1075 if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
1077 minh = 1e-3 * sqrt( bb.SquareExtent());
1078 //cout << "BND BOX minh = " <<minh << endl;
1082 minh = sqrt( minh ); // triangulation for visualization is rather fine
1083 //cout << "TRIANGULATION minh = " <<minh << endl;
1085 if ( minh > 0.5 * maxSize )
1086 minh = maxSize / 3.;
1091 //================================================================================
1093 * \brief Restrict size of elements at a given point
1095 //================================================================================
1097 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh,
1100 const bool overrideMinH)
1102 if ( size <= std::numeric_limits<double>::min() )
1104 if ( netgen::mparam.minh > size )
1108 ngMesh.SetMinimalH( size );
1109 netgen::mparam.minh = size;
1113 size = netgen::mparam.minh;
1116 netgen::Point3d pi(p.X(), p.Y(), p.Z());
1117 ngMesh.RestrictLocalH( pi, size );
1120 //================================================================================
1122 * \brief fill ngMesh with nodes and elements of computed submeshes
1124 //================================================================================
1126 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom,
1127 netgen::Mesh& ngMesh,
1128 vector<const SMDS_MeshNode*>& nodeVec,
1129 const list< SMESH_subMesh* > & meshedSM,
1130 SMESH_MesherHelper* quadHelper,
1131 SMESH_ProxyMesh::Ptr proxyMesh)
1133 TNode2IdMap nodeNgIdMap;
1134 for ( size_t i = 1; i < nodeVec.size(); ++i )
1135 nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
1137 TopTools_MapOfShape visitedShapes;
1138 map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
1139 set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
1141 SMESH_MesherHelper helper (*_mesh);
1142 SMESHDS_Mesh* meshDS = _mesh->GetMeshDS();
1144 int faceNgID = ngMesh.GetNFD();
1146 list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
1147 for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
1149 SMESH_subMesh* sm = *smIt;
1150 if ( !visitedShapes.Add( sm->GetSubShape() ))
1153 const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
1154 if ( !smDS ) continue;
1156 switch ( sm->GetSubShape().ShapeType() )
1158 case TopAbs_EDGE: { // EDGE
1159 // ----------------------
1160 TopoDS_Edge geomEdge = TopoDS::Edge( sm->GetSubShape() );
1161 if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
1162 geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
1164 // Add ng segments for each not meshed FACE the EDGE bounds
1165 PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
1166 while ( const TopoDS_Shape * anc = fIt->next() )
1168 faceNgID = occgeom.fmap.FindIndex( *anc );
1170 continue; // meshed face
1172 int faceSMDSId = meshDS->ShapeToIndex( *anc );
1173 if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
1174 continue; // already treated EDGE
1176 TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
1177 if ( face.Orientation() >= TopAbs_INTERNAL )
1178 face.Orientation( TopAbs_FORWARD ); // issue 0020676
1180 // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
1181 helper.SetSubShape( face );
1182 list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
1183 visitedEdgeSM2Faces );
1184 if ( edges.empty() )
1185 continue; // wrong ancestor?
1187 // find out orientation of <edges> within <face>
1188 TopoDS_Edge eNotSeam = edges.front();
1189 if ( helper.HasSeam() )
1191 list< TopoDS_Edge >::iterator eIt = edges.begin();
1192 while ( helper.IsRealSeam( *eIt )) ++eIt;
1193 if ( eIt != edges.end() )
1196 TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
1197 bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
1199 // get all nodes from connected <edges>
1200 const bool skipMedium = netgen::mparam.secondorder;//smDS->IsQuadratic();
1201 StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, skipMedium, &helper );
1202 const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
1203 if ( points.empty() )
1204 return false; // invalid node params?
1205 smIdType i, nbSeg = fSide.NbSegments();
1207 // remember EDGEs of fSide to treat only once
1208 for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
1209 visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
1211 double otherSeamParam = 0;
1212 bool isSeam = false;
1216 int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
1218 for ( i = 0; i < nbSeg; ++i )
1220 const UVPtStruct& p1 = points[ i ];
1221 const UVPtStruct& p2 = points[ i+1 ];
1223 if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
1226 if ( helper.IsRealSeam( p1.node->GetShapeID() ))
1228 TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
1229 isSeam = helper.IsRealSeam( e );
1232 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
1236 netgen::Segment seg;
1239 seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
1240 // node param on curve
1241 seg.epgeominfo[ 0 ].dist = p1.param;
1242 seg.epgeominfo[ 1 ].dist = p2.param;
1244 seg.epgeominfo[ 0 ].u = p1.u;
1245 seg.epgeominfo[ 0 ].v = p1.v;
1246 seg.epgeominfo[ 1 ].u = p2.u;
1247 seg.epgeominfo[ 1 ].v = p2.v;
1249 //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
1250 //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
1252 //seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
1253 seg.si = faceNgID; // = geom.fmap.FindIndex (face);
1254 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1255 ngMesh.AddSegment (seg);
1257 SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
1258 RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
1260 #ifdef DUMP_SEGMENTS
1261 cout << "Segment: " << seg.edgenr << " on SMESH face " << meshDS->ShapeToIndex( face ) << endl
1262 << "\tface index: " << seg.si << endl
1263 << "\tp1: " << seg[0] << endl
1264 << "\tp2: " << seg[1] << endl
1265 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1266 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1267 //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1268 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1269 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
1270 //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1274 if ( helper.GetPeriodicIndex() && 1 ) {
1275 seg.epgeominfo[ 0 ].u = otherSeamParam;
1276 seg.epgeominfo[ 1 ].u = otherSeamParam;
1277 swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
1279 seg.epgeominfo[ 0 ].v = otherSeamParam;
1280 seg.epgeominfo[ 1 ].v = otherSeamParam;
1281 swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
1283 swap( seg[0], seg[1] );
1284 swap( seg.epgeominfo[0].dist, seg.epgeominfo[1].dist );
1285 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1286 ngMesh.AddSegment( seg );
1287 #ifdef DUMP_SEGMENTS
1288 cout << "Segment: " << seg.edgenr << endl
1289 << "\t is SEAM (reverse) of the previous. "
1290 << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
1291 << " = " << otherSeamParam << endl;
1294 else if ( fOri == TopAbs_INTERNAL )
1296 swap( seg[0], seg[1] );
1297 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1298 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1299 ngMesh.AddSegment( seg );
1300 #ifdef DUMP_SEGMENTS
1301 cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
1305 } // loop on geomEdge ancestors
1307 if ( quadHelper ) // remember medium nodes of sub-meshes
1309 SMDS_ElemIteratorPtr edges = smDS->GetElements();
1310 while ( edges->more() )
1312 const SMDS_MeshElement* e = edges->next();
1313 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshEdge*>( e )))
1319 } // case TopAbs_EDGE
1321 case TopAbs_FACE: { // FACE
1322 // ----------------------
1323 const TopoDS_Face& geomFace = TopoDS::Face( sm->GetSubShape() );
1324 helper.SetSubShape( geomFace );
1325 bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
1327 // Find solids the geomFace bounds
1328 int solidID1 = 0, solidID2 = 0; // ng IDs
1329 int solidSMDSIDs[2] = { 0,0 }; // smds IDs
1331 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
1332 while ( const TopoDS_Shape * solid = solidIt->next() )
1334 int id = occgeom.somap.FindIndex ( *solid );
1335 if ( solidID1 && id != solidID1 ) solidID2 = id;
1337 if ( id ) solidSMDSIDs[ bool( solidSMDSIDs[0] )] = meshDS->ShapeToIndex( *solid );
1340 bool isShrunk = true;
1341 if ( proxyMesh && proxyMesh->GetProxySubMesh( geomFace ))
1343 // if a proxy sub-mesh contains temporary faces, then these faces
1344 // should be used to mesh only one SOLID
1345 smDS = proxyMesh->GetSubMesh( geomFace );
1346 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1347 while ( faces->more() )
1349 const SMDS_MeshElement* f = faces->next();
1350 if ( proxyMesh->IsTemporary( f ))
1353 if ( solidSMDSIDs[1] && proxyMesh->HasPrismsOnTwoSides( meshDS->MeshElements( geomFace )))
1356 solidSMDSIDs[1] = 0;
1357 std::vector<const SMDS_MeshNode*> fNodes( f->begin_nodes(), f->end_nodes() );
1358 std::vector<const SMDS_MeshElement*> vols;
1359 if ( meshDS->GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ) == 1 )
1361 int geomID = vols[0]->GetShapeID();
1362 const TopoDS_Shape& solid = meshDS->IndexToShape( geomID );
1363 if ( !solid.IsNull() )
1364 solidID1 = occgeom.somap.FindIndex ( solid );
1370 const int fID = occgeom.fmap.FindIndex( geomFace );
1371 if ( isShrunk ) // shrunk mesh
1373 // move netgen points according to moved nodes
1374 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
1375 while ( smIt->more() )
1377 SMESH_subMesh* sub = smIt->next();
1378 if ( !sub->GetSubMeshDS() ) continue;
1379 SMDS_NodeIteratorPtr nodeIt = sub->GetSubMeshDS()->GetNodes();
1380 while ( nodeIt->more() )
1382 const SMDS_MeshNode* n = nodeIt->next();
1383 int ngID = ngNodeId( n, ngMesh, nodeNgIdMap );
1384 netgen::MeshPoint& ngPoint = ngMesh.Point( ngID );
1385 ngPoint(0) = n->X();
1386 ngPoint(1) = n->Y();
1387 ngPoint(2) = n->Z();
1390 // remove faces near boundary to avoid their overlapping
1391 // with shrunk faces
1392 for ( int i = 1; i <= ngMesh.GetNSE(); ++i )
1394 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1395 if ( elem.GetIndex() == fID )
1397 for ( int iN = 0; iN < elem.GetNP(); ++iN )
1398 if ( ngMesh[ elem[ iN ]].Type() != netgen::SURFACEPOINT )
1400 ngMesh.DeleteSurfaceElement( i );
1406 // exclude faces generated by NETGEN from computation of 3D mesh
1410 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID,/*solid1=*/0,/*solid2=*/0,0 ));
1411 for (int i = 1; i <= ngMesh.GetNSE(); ++i )
1413 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1414 if ( elem.GetIndex() == fID )
1415 const_cast< netgen::Element2d& >( elem ).SetIndex( faceNgID );
1421 solidSMDSIDs[1] = 0;
1423 const bool hasVLOn2Sides = ( solidSMDSIDs[1] > 0 && !isShrunk );
1425 // Add ng face descriptors of meshed faces
1427 if ( hasVLOn2Sides )
1429 // viscous layers are on two sides of the FACE
1430 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, 0, 0 ));
1432 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, 0, solidID2, 0 ));
1436 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, solidID2, 0 ));
1438 // if second oreder is required, even already meshed faces must be passed to NETGEN
1439 int fID = occgeom.fmap.Add( geomFace );
1440 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1441 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1442 while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
1444 fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
1445 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1446 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1448 // Problem with the second order in a quadrangular mesh remains.
1449 // 1) All quadrangles generated by NETGEN are moved to an inexistent face
1450 // by FillSMesh() (find "AddFaceDescriptor")
1451 // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
1452 // are on faces where quadrangles were.
1453 // Due to these 2 points, wrong geom faces are used while conversion to quadratic
1454 // of the mentioned above quadrangles and triangles
1456 // Orient the face correctly in solidID1 (issue 0020206)
1457 bool reverse = false;
1459 TopoDS_Shape solid = occgeom.somap( solidID1 );
1460 TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
1461 if ( faceOriInSolid >= 0 )
1463 helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
1466 // Add surface elements
1468 netgen::Element2d tri(3);
1469 tri.SetIndex( faceNgID );
1470 SMESH_TNodeXYZ xyz[3];
1472 #ifdef DUMP_TRIANGLES
1473 cout << "SMESH face " << meshDS->ShapeToIndex( geomFace )
1474 << " internal="<<isInternalFace << endl;
1477 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1478 while ( faces->more() )
1480 const SMDS_MeshElement* f = faces->next();
1481 if ( f->NbNodes() % 3 != 0 ) // not triangle
1483 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace,*sm->GetFather(),TopAbs_SOLID);
1484 if ( const TopoDS_Shape * solid = solidIt->next() )
1485 sm = _mesh->GetSubMesh( *solid );
1486 SMESH_BadInputElements* badElems =
1487 new SMESH_BadInputElements( meshDS, COMPERR_BAD_INPUT_MESH, "Not triangle sub-mesh");
1489 sm->GetComputeError().reset( badElems );
1493 if ( hasVLOn2Sides )
1494 tri.SetIndex( getFaceNgID( f, solidSMDSIDs, faceNgID ));
1496 for ( int i = 0; i < 3; ++i )
1498 const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
1501 // get node UV on face
1502 int shapeID = node->GetShapeID();
1503 if ( helper.IsSeamShape( shapeID ))
1505 if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->GetShapeID() ))
1506 inFaceNode = f->GetNodeWrap( i-1 );
1508 inFaceNode = f->GetNodeWrap( i+1 );
1510 gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
1512 int ind = reverse ? 3-i : i+1;
1513 tri.GeomInfoPi(ind).u = uv.X();
1514 tri.GeomInfoPi(ind).v = uv.Y();
1515 tri.PNum (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
1518 // pass a triangle size to NG size-map
1519 double size = ( ( xyz[0] - xyz[1] ).Modulus() +
1520 ( xyz[1] - xyz[2] ).Modulus() +
1521 ( xyz[2] - xyz[0] ).Modulus() ) / 3;
1522 gp_XYZ gc = ( xyz[0] + xyz[1] + xyz[2] ) / 3;
1523 RestrictLocalSize( ngMesh, gc, size, /*overrideMinH=*/false );
1525 ngMesh.AddSurfaceElement (tri);
1526 #ifdef DUMP_TRIANGLES
1527 cout << tri << endl;
1530 if ( isInternalFace )
1532 swap( tri[1], tri[2] );
1533 ngMesh.AddSurfaceElement (tri);
1534 #ifdef DUMP_TRIANGLES
1535 cout << tri << endl;
1538 } // loop on sub-mesh faces
1540 if ( quadHelper ) // remember medium nodes of sub-meshes
1542 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1543 while ( faces->more() )
1545 const SMDS_MeshElement* f = faces->next();
1546 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshFace*>( f )))
1552 } // case TopAbs_FACE
1554 case TopAbs_VERTEX: { // VERTEX
1555 // --------------------------
1556 // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
1557 // else netgen removes a free node and nodeVector becomes invalid
1558 PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
1562 while ( const TopoDS_Shape* e = ansIt->next() )
1564 SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
1565 if (( toAdd = ( eSub->IsEmpty() && !SMESH_Algo::isDegenerated( TopoDS::Edge( *e )))))
1570 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
1571 if ( nodeIt->more() )
1572 ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
1578 } // loop on submeshes
1581 nodeVec.resize( ngMesh.GetNP() + 1 );
1582 TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
1583 for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
1584 nodeVec[ node_NgId->second ] = node_NgId->first;
1589 //================================================================================
1591 * \brief Duplicate mesh faces on internal geom faces
1593 //================================================================================
1595 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
1596 netgen::Mesh& ngMesh,
1597 NETGENPlugin_Internals& internalShapes)
1599 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1601 // find ng indices of internal faces
1603 for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
1605 int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
1606 if ( internalShapes.isInternalShape( smeshID ))
1607 ngFaceIds.insert( ngFaceID );
1609 if ( !ngFaceIds.empty() )
1612 int i, nbFaces = ngMesh.GetNSE();
1613 for ( i = 1; i <= nbFaces; ++i)
1615 netgen::Element2d elem = ngMesh.SurfaceElement(i);
1616 if ( ngFaceIds.count( elem.GetIndex() ))
1618 swap( elem[1], elem[2] );
1619 ngMesh.AddSurfaceElement (elem);
1625 //================================================================================
1627 * \brief Tries to heal the mesh on a FACE. The FACE is supposed to be partially
1628 * meshed due to NETGEN failure
1629 * \param [in] occgeom - geometry
1630 * \param [in,out] ngMesh - the mesh to fix
1631 * \param [inout] faceID - ID of the FACE to fix the mesh on
1632 * \return bool - is mesh is or becomes OK
1634 //================================================================================
1636 bool NETGENPlugin_Mesher::FixFaceMesh(const netgen::OCCGeometry& occgeom,
1637 netgen::Mesh& ngMesh,
1640 // we address a case where the FACE is almost fully meshed except small holes
1641 // of usually triangular shape at FACE boundary (IPAL52861)
1643 // The case appeared to be not simple: holes only look triangular but
1644 // indeed are a self intersecting polygon. A reason of the bug was in coincident
1645 // NG points on a seam edge. But the code below is very nice, leave it for
1650 if ( occgeom.fmap.Extent() < faceID )
1652 //const TopoDS_Face& face = TopoDS::Face( occgeom.fmap( faceID ));
1654 // find free links on the FACE
1656 for ( int iF = 1; iF <= ngMesh.GetNSE(); ++iF )
1658 const netgen::Element2d& elem = ngMesh.SurfaceElement(iF);
1659 if ( faceID != elem.GetIndex() )
1661 int n0 = elem[ elem.GetNP() - 1 ];
1662 for ( int i = 0; i < elem.GetNP(); ++i )
1665 Link link( n0, n1 );
1666 if ( !linkMap.Add( link ))
1667 linkMap.Remove( link );
1671 // add/remove boundary links
1672 for ( int iSeg = 1; iSeg <= ngMesh.GetNSeg(); ++iSeg )
1674 const netgen::Segment& seg = ngMesh.LineSegment( iSeg );
1675 if ( seg.si != faceID ) // !edgeIDs.Contains( seg.edgenr ))
1677 Link link( seg[1], seg[0] ); // reverse!!!
1678 if ( !linkMap.Add( link ))
1679 linkMap.Remove( link );
1681 if ( linkMap.IsEmpty() )
1683 if ( linkMap.Extent() < 3 )
1686 // make triangles of the links
1688 netgen::Element2d tri(3);
1689 tri.SetIndex ( faceID );
1691 TLinkMap::Iterator linkIt( linkMap );
1692 Link link1 = linkIt.Value();
1693 // look for a link connected to link1
1694 TLinkMap::Iterator linkIt2 = linkIt;
1695 for ( linkIt2.Next(); linkIt2.More(); linkIt2.Next() )
1697 const Link& link2 = linkIt2.Value();
1698 if ( link2.IsConnected( link1 ))
1700 // look for a link connected to both link1 and link2
1701 TLinkMap::Iterator linkIt3 = linkIt2;
1702 for ( linkIt3.Next(); linkIt3.More(); linkIt3.Next() )
1704 const Link& link3 = linkIt3.Value();
1705 if ( link3.IsConnected( link1 ) &&
1706 link3.IsConnected( link2 ) )
1711 tri[2] = ( link2.Contains( link1.n1 ) ? link2.n1 : link3.n1 );
1712 if ( tri[0] == tri[2] || tri[1] == tri[2] )
1714 ngMesh.AddSurfaceElement( tri );
1716 // prepare for the next tria search
1717 if ( linkMap.Extent() == 3 )
1719 linkMap.Remove( link3 );
1720 linkMap.Remove( link2 );
1722 linkMap.Remove( link1 );
1723 link1 = linkIt.Value();
1736 //================================================================================
1737 // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
1738 gp_XY_FunPtr(Subtracted);
1739 //gp_XY_FunPtr(Added);
1741 //================================================================================
1743 * \brief Evaluate distance between two 2d points along the surface
1745 //================================================================================
1747 double evalDist( const gp_XY& uv1,
1749 const Handle(Geom_Surface)& surf,
1750 const int stopHandler=-1)
1752 if ( stopHandler > 0 ) // continue recursion
1754 gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
1755 return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
1757 double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1758 if ( stopHandler == 0 ) // stop recursion
1761 // start recursion if necessary
1762 double dist2D = SMESH_MesherHelper::ApplyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1763 if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1764 return dist3D; // equal parametrization of a planar surface
1766 return evalDist( uv1, uv2, surf, 3 ); // start recursion
1769 //================================================================================
1771 * \brief Data of vertex internal in geom face
1773 //================================================================================
1777 gp_XY uv; //!< UV in face parametric space
1778 int ngId; //!< ng id of corresponding node
1779 gp_XY uvClose; //!< UV of closest boundary node
1780 int ngIdClose; //!< ng id of closest boundary node
1783 //================================================================================
1785 * \brief Data of vertex internal in solid
1787 //================================================================================
1791 int ngId; //!< ng id of corresponding node
1792 int ngIdClose; //!< ng id of closest 2d mesh element
1793 int ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1796 inline double dist2( const netgen::MeshPoint& p1, const netgen::MeshPoint& p2 )
1798 return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1801 // inline double dist2(const netgen::MeshPoint& p, const SMDS_MeshNode* n )
1803 // return gp_Pnt( NGPOINT_COORDS(p)).SquareDistance( SMESH_NodeXYZ(n));
1807 //================================================================================
1809 * \brief Make netgen take internal vertices in faces into account by adding
1810 * segments including internal vertices
1812 * This function works in supposition that 1D mesh is already computed in ngMesh
1814 //================================================================================
1816 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& occgeom,
1817 netgen::Mesh& ngMesh,
1818 vector<const SMDS_MeshNode*>& nodeVec,
1819 NETGENPlugin_Internals& internalShapes)
1821 if ((int) nodeVec.size() < ngMesh.GetNP() )
1822 nodeVec.resize( ngMesh.GetNP(), 0 );
1824 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1825 SMESH_MesherHelper helper( internalShapes.getMesh() );
1827 const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1828 map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1829 for ( ; f2v != face2Vert.end(); ++f2v )
1831 const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1832 if ( face.IsNull() ) continue;
1833 int faceNgID = occgeom.fmap.FindIndex (face);
1834 if ( faceNgID < 0 ) continue;
1836 TopLoc_Location loc;
1837 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1839 helper.SetSubShape( face );
1840 helper.SetElementsOnShape( true );
1842 // Get data of internal vertices and add them to ngMesh
1844 multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1846 int i, nbSegInit = ngMesh.GetNSeg();
1848 // boundary characteristics
1849 double totSegLen2D = 0;
1852 const list<int>& iVertices = f2v->second;
1853 list<int>::const_iterator iv = iVertices.begin();
1854 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1857 // get node on vertex
1858 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1859 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1862 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1863 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1864 nV = SMESH_Algo::VertexNode( V, meshDS );
1865 if ( !nV ) continue;
1868 netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1869 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1870 vData.ngId = ngMesh.GetNP();
1871 nodeVec.push_back( nV );
1875 vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1876 if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1878 // loop on all segments of the face to find the node closest to vertex and to count
1879 // average segment 2d length
1880 double closeDist2 = numeric_limits<double>::max(), dist2;
1882 for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1884 netgen::Segment & seg = ngMesh.LineSegment(i);
1885 if ( seg.si != faceNgID ) continue;
1887 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1889 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1890 if ( ngIdLast == seg[ iEnd ] ) continue;
1891 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1892 if ( dist2 < closeDist2 )
1893 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1894 ngIdLast = seg[ iEnd ];
1898 totSegLen2D += helper.ApplyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1902 dist2VData.insert( make_pair( closeDist2, vData ));
1905 if ( totNbSeg == 0 ) break;
1906 double avgSegLen2d = totSegLen2D / totNbSeg;
1908 // Loop on vertices to add segments
1910 multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1911 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1913 double closeDist2 = dist_vData->first, dist2;
1914 TIntVData & vData = dist_vData->second;
1916 // try to find more close node among segments added for internal vertices
1917 for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1919 netgen::Segment & seg = ngMesh.LineSegment(i);
1920 if ( seg.si != faceNgID ) continue;
1922 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1924 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1925 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1926 if ( dist2 < closeDist2 )
1927 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1930 // decide whether to use the closest node as the second end of segment or to
1931 // create a new point
1932 int segEnd1 = vData.ngId;
1933 int segEnd2 = vData.ngIdClose; // to use closest node
1934 gp_XY uvV = vData.uv, uvP = vData.uvClose;
1935 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1936 double nodeDist2D = sqrt( closeDist2 );
1937 double nodeDist3D = evalDist( vData.uv, vData.uvClose, surf );
1938 bool avgLenOK = ( avgSegLen2d < 0.75 * nodeDist2D );
1939 bool hintLenOK = ( segLenHint < 0.75 * nodeDist3D );
1940 //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1941 if ( hintLenOK || avgLenOK )
1943 // create a point between the closest node and V
1946 double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1947 // direction from V to closet node in 2D
1948 gp_Dir2d v2n( helper.ApplyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1950 uvP = vData.uv + r * nodeDist2D * v2n.XY();
1951 gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1953 netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1954 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1955 segEnd2 = ngMesh.GetNP();
1956 //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1957 SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1958 nodeVec.push_back( nP );
1960 //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1963 netgen::Segment seg;
1965 if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1966 seg[0] = segEnd1; // ng node id
1967 seg[1] = segEnd2; // ng node id
1968 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1971 seg.epgeominfo[ 0 ].dist = 0; // param on curve
1972 seg.epgeominfo[ 0 ].u = uvV.X();
1973 seg.epgeominfo[ 0 ].v = uvV.Y();
1974 seg.epgeominfo[ 1 ].dist = 1; // param on curve
1975 seg.epgeominfo[ 1 ].u = uvP.X();
1976 seg.epgeominfo[ 1 ].v = uvP.Y();
1978 // seg.epgeominfo[ 0 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1979 // seg.epgeominfo[ 1 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1981 ngMesh.AddSegment (seg);
1983 // add reverse segment
1984 swap( seg[0], seg[1] );
1985 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1986 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1987 ngMesh.AddSegment (seg);
1991 ngMesh.CalcSurfacesOfNode();
1994 //================================================================================
1996 * \brief Make netgen take internal vertices in solids into account by adding
1997 * faces including internal vertices
1999 * This function works in supposition that 2D mesh is already computed in ngMesh
2001 //================================================================================
2003 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry& occgeom,
2004 netgen::Mesh& ngMesh,
2005 vector<const SMDS_MeshNode*>& nodeVec,
2006 NETGENPlugin_Internals& internalShapes)
2008 #ifdef DUMP_TRIANGLES_SCRIPT
2009 // create a python script making a mesh containing triangles added for internal vertices
2010 ofstream py(DUMP_TRIANGLES_SCRIPT);
2011 py << "import SMESH"<< endl
2012 << "from salome.smesh import smeshBuilder"<<endl
2013 << "smesh = smeshBuilder.New()"<<endl
2014 << "m = smesh.Mesh(name='triangles')" << endl;
2016 if ((int) nodeVec.size() < ngMesh.GetNP() )
2017 nodeVec.resize( ngMesh.GetNP(), 0 );
2019 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
2020 SMESH_MesherHelper helper( internalShapes.getMesh() );
2022 const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
2023 map<int,list<int> >::const_iterator s2v = so2Vert.begin();
2024 for ( ; s2v != so2Vert.end(); ++s2v )
2026 const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
2027 if ( solid.IsNull() ) continue;
2028 int solidNgID = occgeom.somap.FindIndex (solid);
2029 if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
2031 helper.SetSubShape( solid );
2032 helper.SetElementsOnShape( true );
2034 // find ng indices of faces within the solid
2036 for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
2037 ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
2038 if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
2039 ngFaceIds.insert( 1 );
2041 // Get data of internal vertices and add them to ngMesh
2043 multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
2045 int i, nbFaceInit = ngMesh.GetNSE();
2047 // boundary characteristics
2048 double totSegLen = 0;
2051 const list<int>& iVertices = s2v->second;
2052 list<int>::const_iterator iv = iVertices.begin();
2053 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
2056 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
2058 // get node on vertex
2059 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
2062 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
2063 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2064 nV = SMESH_Algo::VertexNode( V, meshDS );
2065 if ( !nV ) continue;
2068 netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
2069 ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
2070 vData.ngId = ngMesh.GetNP();
2071 nodeVec.push_back( nV );
2073 // loop on all 2d elements to find the one closest to vertex and to count
2074 // average segment length
2075 double closeDist2 = numeric_limits<double>::max(), avgDist2;
2076 for (i = 1; i <= ngMesh.GetNSE(); ++i)
2078 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2079 if ( !ngFaceIds.count( elem.GetIndex() )) continue;
2081 multimap< double, int> dist2nID; // sort nodes of element by distance from V
2082 for ( int j = 0; j < elem.GetNP(); ++j)
2084 netgen::MeshPoint mp = ngMesh.Point( elem[j] );
2085 double d2 = dist2( mpV, mp );
2086 dist2nID.insert( make_pair( d2, elem[j] ));
2087 avgDist2 += d2 / elem.GetNP();
2089 totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
2091 double dist = dist2nID.begin()->first; //avgDist2;
2092 if ( dist < closeDist2 )
2093 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
2095 dist2VData.insert( make_pair( closeDist2, vData ));
2098 if ( totNbSeg == 0 ) break;
2099 double avgSegLen = totSegLen / totNbSeg;
2101 // Loop on vertices to add triangles
2103 multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
2104 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
2106 double closeDist2 = dist_vData->first;
2107 TIntVSoData & vData = dist_vData->second;
2109 const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
2111 // try to find more close face among ones added for internal vertices
2112 for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
2114 double avgDist2 = 0;
2115 multimap< double, int> dist2nID;
2116 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2117 for ( int j = 0; j < elem.GetNP(); ++j)
2119 double d = dist2( mpV, ngMesh.Point( elem[j] ));
2120 dist2nID.insert( make_pair( d, elem[j] ));
2121 avgDist2 += d / elem.GetNP();
2122 if ( avgDist2 < closeDist2 )
2123 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
2126 // sort nodes of the closest face by angle with vector from V to the closest node
2127 const double tol = numeric_limits<double>::min();
2128 map< double, int > angle2ID;
2129 const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
2130 netgen::MeshPoint mp[2];
2131 mp[0] = ngMesh.Point( vData.ngIdCloseN );
2132 gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
2133 gp_XYZ pV( NGPOINT_COORDS( mpV ));
2134 gp_Vec v2p1( pV, p1 );
2135 double distN1 = v2p1.Magnitude();
2136 if ( distN1 <= tol ) continue;
2138 for ( int j = 0; j < closeFace.GetNP(); ++j)
2140 mp[1] = ngMesh.Point( closeFace[j] );
2141 gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
2142 angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
2144 // get node with angle of 60 degrees or greater
2145 map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
2146 if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
2147 const double minAngle = 30. * M_PI / 180.;
2148 const double angle = angle_id->first;
2149 bool angleOK = ( angle > minAngle );
2151 // find points to create a triangle
2152 netgen::Element2d tri(3);
2154 tri[0] = vData.ngId;
2155 tri[1] = vData.ngIdCloseN; // to use the closest nodes
2156 tri[2] = angle_id->second; // to use the node with best angle
2158 // decide whether to use the closest node and the node with best angle or to create new ones
2159 for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
2161 bool createNew = !angleOK; //, distOK = true;
2163 int triInd = isBestAngleN ? 2 : 1;
2164 mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
2169 double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
2170 createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
2172 else if ( angle < tol )
2174 v2p1.SetX( v2p1.X() + 1e-3 );
2180 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
2181 bool avgLenOK = ( avgSegLen < 0.75 * distN1 );
2182 bool hintLenOK = ( segLenHint < 0.75 * distN1 );
2183 createNew = (createNew || avgLenOK || hintLenOK );
2184 // we create a new node not closer than 0.5 to the closest face
2185 // in order not to clash with other close face
2186 double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
2187 distFromV = r * distN1;
2191 // create a new point, between the node and the vertex if angleOK
2192 gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
2193 gp_Vec v2p( pV, p ); v2p.Normalize();
2194 if ( isBestAngleN && !angleOK )
2195 p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
2197 p = pV + v2p.XYZ() * distFromV;
2199 if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
2201 mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
2202 ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
2203 tri[triInd] = ngMesh.GetNP();
2204 nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
2207 ngMesh.AddSurfaceElement (tri);
2208 swap( tri[1], tri[2] );
2209 ngMesh.AddSurfaceElement (tri);
2211 #ifdef DUMP_TRIANGLES_SCRIPT
2212 py << "n1 = m.AddNode( "<< mpV(0)<<", "<< mpV(1)<<", "<< mpV(2)<<") "<< endl
2213 << "n2 = m.AddNode( "<< mp[0](0)<<", "<< mp[0](1)<<", "<< mp[0](2)<<") "<< endl
2214 << "n3 = m.AddNode( "<< mp[1](0)<<", "<< mp[1](1)<<", "<< mp[1](2)<<" )" << endl
2215 << "m.AddFace([n1,n2,n3])" << endl;
2217 } // loop on internal vertices of a solid
2219 } // loop on solids with internal vertices
2222 //================================================================================
2224 * \brief Fill netgen mesh with segments of a FACE
2225 * \param ngMesh - netgen mesh
2226 * \param geom - container of OCCT geometry to mesh
2227 * \param wires - data of nodes on FACE boundary
2228 * \param helper - mesher helper holding the FACE
2229 * \param nodeVec - vector of nodes in which node index == netgen ID
2230 * \retval SMESH_ComputeErrorPtr - error description
2232 //================================================================================
2234 SMESH_ComputeErrorPtr
2235 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh,
2236 netgen::OCCGeometry& geom,
2237 const TSideVector& wires,
2238 SMESH_MesherHelper& helper,
2239 vector< const SMDS_MeshNode* > & nodeVec,
2240 const bool overrideMinH)
2242 // ----------------------------
2243 // Check wires and count nodes
2244 // ----------------------------
2245 smIdType nbNodes = 0;
2246 for ( size_t iW = 0; iW < wires.size(); ++iW )
2248 StdMeshers_FaceSidePtr wire = wires[ iW ];
2249 if ( wire->MissVertexNode() )
2251 // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
2252 // It seems that there is no reason for this limitation
2254 // (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
2256 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2257 if ((int) uvPtVec.size() != wire->NbPoints() )
2258 return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
2259 SMESH_Comment("Unexpected nb of points on wire ") << iW
2260 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
2261 nbNodes += wire->NbPoints();
2263 nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
2264 if ( nodeVec.empty() )
2265 nodeVec.push_back( 0 );
2267 // -----------------
2269 // -----------------
2271 const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
2272 NETGENPlugin_NETGEN_2D_ONLY */
2274 // map for nodes on vertices since they can be shared between wires
2275 // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
2276 map<const SMDS_MeshNode*, int > node2ngID;
2277 if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
2279 set< int > subIDs; // ids of sub-shapes of the FACE
2280 for ( size_t iW = 0; iW < wires.size(); ++iW )
2282 StdMeshers_FaceSidePtr wire = wires[ iW ];
2283 for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
2285 subIDs.insert( wire->EdgeID( iE ));
2286 subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
2289 for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
2290 if ( subIDs.count( nodeVec[ngID]->GetShapeID() ))
2291 node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
2294 const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
2295 if ( ngMesh.GetNFD() < 1 )
2296 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceID, solidID, solidID, 0 ));
2298 for ( size_t iW = 0; iW < wires.size(); ++iW )
2300 StdMeshers_FaceSidePtr wire = wires[ iW ];
2301 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2302 const smIdType nbSegments = wire->NbPoints() - 1;
2304 // assure the 1st node to be in node2ngID, which is needed to correctly
2305 // "close chain of segments" (see below) in case if the 1st node is not
2306 // onVertex because it is on a Viscous layer
2307 node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
2309 // compute length of every segment
2310 vector<double> segLen( nbSegments );
2311 for ( int i = 0; i < nbSegments; ++i )
2312 segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
2314 int edgeID = 1, posID = -2;
2315 bool isInternalWire = false;
2316 double vertexNormPar = 0;
2317 const int prevNbNGSeg = ngMesh.GetNSeg();
2318 for ( int i = 0; i < nbSegments; ++i ) // loop on segments
2320 // Add the first point of a segment
2322 const SMDS_MeshNode * n = uvPtVec[ i ].node;
2323 const int posShapeID = n->GetShapeID();
2324 bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
2325 bool onEdge = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE );
2327 // skip nodes on degenerated edges
2328 if ( helper.IsDegenShape( posShapeID ) &&
2329 helper.IsDegenShape( uvPtVec[ i+1 ].node->GetShapeID() ))
2332 int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
2333 if ( onVertex || ( !wasNgMeshEmpty && onEdge ) || helper.IsRealSeam( posShapeID ))
2334 ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
2335 if ( ngID1 > ngMesh.GetNP() )
2337 netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
2338 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2339 nodeVec.push_back( n );
2341 else // n is in ngMesh already, and ngID2 in prev segment is wrong
2343 ngID2 = ngMesh.GetNP() + 1;
2344 if ( i > 0 ) // prev segment belongs to same wire
2346 netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2353 netgen::Segment seg;
2355 seg[0] = ngID1; // ng node id
2356 seg[1] = ngID2; // ng node id
2357 seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
2358 seg.si = faceID; // = geom.fmap.FindIndex (face);
2360 for ( int iEnd = 0; iEnd < 2; ++iEnd)
2362 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
2364 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
2365 seg.epgeominfo[ iEnd ].u = pnt.u;
2366 seg.epgeominfo[ iEnd ].v = pnt.v;
2368 // find out edge id and node parameter on edge
2369 onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
2370 if ( onVertex || posShapeID != posID )
2373 double normParam = pnt.normParam;
2375 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
2376 int edgeIndexInWire = wire->EdgeIndex( normParam );
2377 vertexNormPar = wire->LastParameter( edgeIndexInWire );
2378 const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
2379 edgeID = geom.emap.FindIndex( edge );
2381 isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
2382 // if ( onVertex ) // param on curve is different on each of two edges
2383 // seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
2385 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
2388 ngMesh.AddSegment (seg);
2390 // restrict size of elements near the segment
2391 SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
2392 // get an average size of adjacent segments to avoid sharp change of
2393 // element size (regression on issue 0020452, note 0010898)
2394 int iPrev = SMESH_MesherHelper::WrapIndex( i-1, (int) nbSegments );
2395 int iNext = SMESH_MesherHelper::WrapIndex( i+1, (int) nbSegments );
2396 double sumH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
2397 int nbSeg = ( int( segLen[ iPrev ] > sumH / 100.) +
2398 int( segLen[ i ] > sumH / 100.) +
2399 int( segLen[ iNext ] > sumH / 100.));
2401 RestrictLocalSize( ngMesh, 0.5*(np1+np2), sumH / nbSeg, overrideMinH );
2403 if ( isInternalWire )
2405 swap (seg[0], seg[1]);
2406 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
2407 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
2408 ngMesh.AddSegment (seg);
2410 } // loop on segments on a wire
2412 // close chain of segments
2413 if ( nbSegments > 0 )
2415 netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire ));
2416 const SMDS_MeshNode * lastNode = uvPtVec.back().node;
2417 lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
2418 if ( lastSeg[1] > ngMesh.GetNP() )
2420 netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
2421 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2422 nodeVec.push_back( lastNode );
2424 if ( isInternalWire )
2426 netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2427 realLastSeg[0] = lastSeg[1];
2431 #ifdef DUMP_SEGMENTS
2432 cout << "BEGIN WIRE " << iW << endl;
2433 for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
2435 netgen::Segment& seg = ngMesh.LineSegment( i );
2437 netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
2438 if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
2440 cout << "Segment: " << seg.edgenr << endl << "\tis REVERSE of the previous one" << endl;
2444 cout << "Segment: " << seg.edgenr << endl
2445 << "\tp1: " << seg[0] << " n" << nodeVec[ seg[0]]->GetID() << endl
2446 << "\tp2: " << seg[1] << " n" << nodeVec[ seg[1]]->GetID() << endl
2447 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
2448 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
2449 << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
2450 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
2451 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
2452 << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
2454 cout << "--END WIRE " << iW << endl;
2456 SMESH_Comment __not_unused_variable( prevNbNGSeg );
2459 } // loop on WIREs of a FACE
2461 // add a segment instead of an internal vertex
2462 if ( wasNgMeshEmpty )
2464 NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
2465 AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
2467 ngMesh.CalcSurfacesOfNode();
2472 //================================================================================
2474 * \brief Fill SMESH mesh according to contents of netgen mesh
2475 * \param occgeo - container of OCCT geometry to mesh
2476 * \param ngMesh - netgen mesh
2477 * \param initState - bn of entities in netgen mesh before computing
2478 * \param sMesh - SMESH mesh to fill in
2479 * \param nodeVec - vector of nodes in which node index == netgen ID
2480 * \param comment - returns problem description
2481 * \param quadHelper - holder of medium nodes of sub-meshes
2482 * \retval int - error
2484 //================================================================================
2486 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo,
2487 netgen::Mesh& ngMesh,
2488 const NETGENPlugin_ngMeshInfo& initState,
2490 std::vector<const SMDS_MeshNode*>& nodeVec,
2491 SMESH_Comment& comment,
2492 SMESH_MesherHelper* quadHelper)
2494 int nbNod = ngMesh.GetNP();
2495 int nbSeg = ngMesh.GetNSeg();
2496 int nbFac = ngMesh.GetNSE();
2497 int nbVol = ngMesh.GetNE();
2499 SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
2501 // quadHelper is used for either
2502 // 1) making quadratic elements when a lower dimension mesh is loaded
2503 // to SMESH before conversion to quadratic by NETGEN
2504 // 2) sewing of quadratic elements with quadratic elements of sub-meshes
2505 if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() )
2508 int ngID, nbInitNod = initState._nbNodes;
2509 if ( initState._elementsRemoved )
2511 // PAL23427. Update nodeVec to track removal of netgen free points as a result
2512 // of removal of faces in FillNgMesh() in the case of a shrunk sub-mesh
2513 size_t i, nodeVecSize = nodeVec.size();
2514 const double eps = std::numeric_limits<double>::min();
2515 for ( i = ngID = 1; i < nodeVecSize; ++ngID, ++i )
2517 gp_Pnt ngPnt( NGPOINT_COORDS( ngMesh.Point( ngID )));
2518 gp_Pnt node ( SMESH_NodeXYZ (nodeVec_ACCESS(i) ));
2519 if ( ngPnt.SquareDistance( node ) < eps )
2521 nodeVec[ ngID ] = nodeVec[ i ];
2528 nodeVec.resize( ngID );
2529 nbInitNod = ngID - 1;
2531 // -------------------------------------
2532 // Create and insert nodes into nodeVec
2533 // -------------------------------------
2535 if ( nbNod > nbInitNod )
2536 nodeVec.resize( nbNod + 1 );
2537 for ( int i = nbInitNod+1; i <= nbNod; ++i )
2539 const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
2540 SMDS_MeshNode* node = NULL;
2541 TopoDS_Vertex aVert;
2542 // First, netgen creates nodes on vertices in occgeo.vmap,
2543 // so node index corresponds to vertex index
2544 // but (issue 0020776) netgen does not create nodes with equal coordinates
2545 if ( i-nbInitNod <= occgeo.vmap.Extent() )
2547 gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
2548 for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
2550 aVert = TopoDS::Vertex( occgeo.vmap( iV ));
2551 gp_Pnt pV = BRep_Tool::Pnt( aVert );
2552 if ( p.SquareDistance( pV ) > 1e-20 )
2555 node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
2558 if (!node) // node not found on vertex
2560 node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
2561 if (!aVert.IsNull())
2562 meshDS->SetNodeOnVertex(node, aVert);
2567 // -------------------------------------------
2568 // Create mesh segments along geometric edges
2569 // -------------------------------------------
2571 int nbInitSeg = initState._nbSegments;
2572 for ( int i = nbInitSeg+1; i <= nbSeg; ++i )
2574 const netgen::Segment& seg = ngMesh.LineSegment(i);
2576 int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
2579 for (int j=0; j < 3; ++j)
2581 int pind = pinds[j];
2582 if (pind <= 0 || !nodeVec_ACCESS(pind))
2590 int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
2591 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2592 aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
2594 param = seg.epgeominfo[j].dist;
2597 else // middle point
2599 param = param2 * 0.5;
2601 if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->GetShapeID() < 1)
2603 meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
2608 SMDS_MeshEdge* edge = 0;
2609 if (nbp == 2) // second order ?
2611 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
2613 if ( quadHelper ) // final mesh must be quadratic
2614 edge = quadHelper->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2616 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2620 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2621 nodeVec_ACCESS(pinds[2])))
2623 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2624 nodeVec_ACCESS(pinds[2]));
2628 if ( comment.empty() ) comment << "Cannot create a mesh edge";
2629 MESSAGE("Cannot create a mesh edge");
2630 nbSeg = nbFac = nbVol = 0;
2633 if ( !aEdge.IsNull() && edge->GetShapeID() < 1 )
2634 meshDS->SetMeshElementOnShape(edge, aEdge);
2636 else if ( comment.empty() )
2638 comment << "Invalid netgen segment #" << i;
2642 // ----------------------------------------
2643 // Create mesh faces along geometric faces
2644 // ----------------------------------------
2646 int nbInitFac = initState._nbFaces;
2647 int quadFaceID = ngMesh.GetNFD() + 1;
2648 if ( nbInitFac < nbFac )
2649 // add a faces descriptor to exclude qudrangle elements generated by NETGEN
2650 // from computation of 3D mesh
2651 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
2653 vector<const SMDS_MeshNode*> nodes;
2654 for ( int i = nbInitFac+1; i <= nbFac; ++i )
2656 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2657 const int aGeomFaceInd = elem.GetIndex();
2659 if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
2660 aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
2662 for ( int j = 1; j <= elem.GetNP(); ++j )
2664 int pind = elem.PNum(j);
2665 if ( pind < 1 || pind >= (int) nodeVec.size() )
2667 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
2669 nodes.push_back( node );
2670 if (!aFace.IsNull() && node->GetShapeID() < 1)
2672 const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
2673 meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
2677 if ((int) nodes.size() != elem.GetNP() )
2679 if ( comment.empty() )
2680 comment << "Invalid netgen 2d element #" << i;
2681 continue; // bad node ids
2683 SMDS_MeshFace* face = NULL;
2684 switch (elem.GetType())
2687 if ( quadHelper ) // final mesh must be quadratic
2688 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2]);
2690 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
2693 if ( quadHelper ) // final mesh must be quadratic
2694 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2696 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2697 // exclude qudrangle elements from computation of 3D mesh
2698 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2701 nodes[5] = mediumNode( nodes[0],nodes[1],nodes[5], quadHelper );
2702 nodes[3] = mediumNode( nodes[1],nodes[2],nodes[3], quadHelper );
2703 nodes[4] = mediumNode( nodes[2],nodes[0],nodes[4], quadHelper );
2704 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
2707 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2708 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2709 nodes[5] = mediumNode( nodes[2],nodes[3],nodes[5], quadHelper );
2710 nodes[6] = mediumNode( nodes[3],nodes[0],nodes[6], quadHelper );
2711 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
2712 nodes[4],nodes[7],nodes[5],nodes[6]);
2713 // exclude qudrangle elements from computation of 3D mesh
2714 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2717 MESSAGE("NETGEN created a face of unexpected type, ignoring");
2722 if ( comment.empty() ) comment << "Cannot create a mesh face";
2723 MESSAGE("Cannot create a mesh face");
2724 nbSeg = nbFac = nbVol = 0;
2727 if ( !aFace.IsNull() )
2728 meshDS->SetMeshElementOnShape( face, aFace );
2731 // ------------------
2732 // Create tetrahedra
2733 // ------------------
2735 for ( int i = 1; i <= nbVol; ++i )
2737 const netgen::Element& elem = ngMesh.VolumeElement(i);
2738 int aSolidInd = elem.GetIndex();
2739 TopoDS_Solid aSolid;
2740 if ( aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent() )
2741 aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
2743 for ( int j = 1; j <= elem.GetNP(); ++j )
2745 int pind = elem.PNum(j);
2746 if ( pind < 1 || pind >= (int)nodeVec.size() )
2748 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
2750 nodes.push_back(node);
2751 if ( !aSolid.IsNull() && node->GetShapeID() < 1 )
2752 meshDS->SetNodeInVolume(node, aSolid);
2755 if ((int) nodes.size() != elem.GetNP() )
2757 if ( comment.empty() )
2758 comment << "Invalid netgen 3d element #" << i;
2761 SMDS_MeshVolume* vol = NULL;
2762 switch ( elem.GetType() )
2765 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
2768 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2769 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2770 nodes[5] = mediumNode( nodes[2],nodes[0],nodes[5], quadHelper );
2771 nodes[6] = mediumNode( nodes[0],nodes[3],nodes[6], quadHelper );
2772 nodes[8] = mediumNode( nodes[1],nodes[3],nodes[8], quadHelper );
2773 nodes[9] = mediumNode( nodes[2],nodes[3],nodes[9], quadHelper );
2774 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
2775 nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
2778 MESSAGE("NETGEN created a volume of unexpected type, ignoring");
2783 if ( comment.empty() ) comment << "Cannot create a mesh volume";
2784 MESSAGE("Cannot create a mesh volume");
2785 nbSeg = nbFac = nbVol = 0;
2788 if (!aSolid.IsNull())
2789 meshDS->SetMeshElementOnShape(vol, aSolid);
2791 return comment.empty() ? 0 : 1;
2796 //================================================================================
2798 * \brief Convert error into text
2800 //================================================================================
2802 std::string text(int err)
2807 SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2810 //================================================================================
2812 * \brief Convert exception into text
2814 //================================================================================
2816 std::string text(Standard_Failure& ex)
2818 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2819 str << " at " << netgen::multithread.task
2820 << ": " << ex.DynamicType()->Name();
2821 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2822 str << ": " << ex.GetMessageString();
2825 //================================================================================
2827 * \brief Convert exception into text
2829 //================================================================================
2831 std::string text(netgen::NgException& ex)
2833 SMESH_Comment str("NgException");
2834 if ( strlen( netgen::multithread.task ) > 0 )
2835 str << " at " << netgen::multithread.task;
2836 str << ": " << ex.What();
2840 //================================================================================
2842 * \brief Looks for triangles lying on a SOLID
2844 //================================================================================
2846 bool hasBadElemOnSolid( const list<const SMDS_MeshElement*>& elems,
2847 SMESH_subMesh* solidSM )
2849 TopTools_IndexedMapOfShape solidSubs;
2850 TopExp::MapShapes( solidSM->GetSubShape(), solidSubs );
2851 SMESHDS_Mesh* mesh = solidSM->GetFather()->GetMeshDS();
2853 list<const SMDS_MeshElement*>::const_iterator e = elems.begin();
2854 for ( ; e != elems.end(); ++e )
2856 const SMDS_MeshElement* elem = *e;
2857 // if ( elem->GetType() != SMDSAbs_Face ) -- 23047
2859 int nbNodesOnSolid = 0, nbNodes = elem->NbNodes();
2860 SMDS_NodeIteratorPtr nIt = elem->nodeIterator();
2861 while ( nIt->more() )
2863 const SMDS_MeshNode* n = nIt->next();
2864 const TopoDS_Shape& s = mesh->IndexToShape( n->GetShapeID() );
2865 nbNodesOnSolid += ( !s.IsNull() && solidSubs.Contains( s ));
2866 if ( nbNodesOnSolid > 2 ||
2867 nbNodesOnSolid == nbNodes)
2874 const double edgeMeshingTime = 0.001;
2875 const double faceMeshingTime = 0.019;
2876 const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
2877 const double faceOptimizTime = 0.06;
2878 const double voluMeshingTime = 0.15;
2879 const double volOptimizeTime = 0.77;
2882 //=============================================================================
2884 * Here we are going to use the NETGEN mesher
2886 //=============================================================================
2888 bool NETGENPlugin_Mesher::Compute()
2890 NETGENPlugin_NetgenLibWrapper ngLib;
2892 netgen::MeshingParameters& mparams = netgen::mparam;
2894 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2895 SMESH_MesherHelper quadHelper( *_mesh );
2896 quadHelper.SetIsQuadratic( mparams.secondorder );
2898 // -------------------------
2899 // Prepare OCC geometry
2900 // -------------------------
2902 netgen::OCCGeometry occgeo;
2903 list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2904 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2905 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2908 _totalTime = edgeFaceMeshingTime;
2910 _totalTime += faceOptimizTime;
2912 _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
2913 double doneTime = 0;
2916 _curShapeIndex = -1;
2918 // -------------------------
2919 // Generate the mesh
2920 // -------------------------
2923 NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2925 SMESH_Comment comment;
2928 // vector of nodes in which node index == netgen ID
2929 vector< const SMDS_MeshNode* > nodeVec;
2937 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2938 mparams.uselocalh = false;
2939 mparams.grading = 0.8; // not limitited size growth
2941 if ( _simpleHyp->GetNumberOfSegments() )
2943 mparams.maxh = occgeo.boundingbox.Diam();
2946 mparams.maxh = _simpleHyp->GetLocalLength();
2949 if ( mparams.maxh == 0.0 )
2950 mparams.maxh = occgeo.boundingbox.Diam();
2951 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2952 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2954 // Local size on faces
2955 occgeo.face_maxh = mparams.maxh;
2957 // Let netgen create _ngMesh and calculate element size on not meshed shapes
2958 int startWith = netgen::MESHCONST_ANALYSE;
2959 int endWith = netgen::MESHCONST_ANALYSE;
2964 err = ngLib.GenerateMesh(occgeo, startWith, endWith, _ngMesh);
2966 if(netgen::multithread.terminate)
2969 comment << text(err);
2971 catch (Standard_Failure& ex)
2973 comment << text(ex);
2975 catch (netgen::NgException & ex)
2977 comment << text(ex);
2979 bool hasSizeFile = !mparams.meshsizefilename.empty();
2981 bool hasSizeFile = mparams.meshsizefilename;
2984 throw SMESH_ComputeError(COMPERR_BAD_PARMETERS, comment );
2986 err = 0; //- MESHCONST_ANALYSE isn't so important step
2989 ngLib.setMesh(( Ng_Mesh*) _ngMesh );
2991 _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2993 if ( !mparams.uselocalh ) // mparams.grading is not taken into account yet
2994 _ngMesh->LocalHFunction().SetGrading( mparams.grading );
2998 // Pass 1D simple parameters to NETGEN
2999 // --------------------------------
3000 double nbSeg = (double) _simpleHyp->GetNumberOfSegments();
3001 double segSize = _simpleHyp->GetLocalLength();
3002 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
3004 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
3006 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
3007 setLocalSize( e, segSize, *_ngMesh );
3010 else // if ( ! _simpleHyp )
3012 // Local size on shapes
3013 SetLocalSize( occgeo, *_ngMesh );
3014 SetLocalSizeForChordalError( occgeo, *_ngMesh );
3017 // Precompute internal edges (issue 0020676) in order to
3018 // add mesh on them correctly (twice) to netgen mesh
3019 if ( !err && internals.hasInternalEdges() )
3021 // load internal shapes into OCCGeometry
3022 netgen::OCCGeometry intOccgeo;
3023 internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
3024 intOccgeo.boundingbox = occgeo.boundingbox;
3025 intOccgeo.shape = occgeo.shape;
3026 intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
3027 intOccgeo.face_maxh = netgen::mparam.maxh;
3028 netgen::Mesh *tmpNgMesh = NULL;
3032 // compute local H on internal shapes in the main mesh
3033 //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
3035 // let netgen create a temporary mesh
3036 ngLib.GenerateMesh(intOccgeo, startWith, endWith, tmpNgMesh);
3038 if ( netgen::multithread.terminate )
3041 // copy LocalH from the main to temporary mesh
3042 initState.transferLocalH( _ngMesh, tmpNgMesh );
3044 // compute mesh on internal edges
3045 startWith = endWith = netgen::MESHCONST_MESHEDGES;
3046 err = ngLib.GenerateMesh(intOccgeo, startWith, endWith, tmpNgMesh);
3048 comment << text(err);
3050 catch (Standard_Failure& ex)
3052 comment << text(ex);
3055 initState.restoreLocalH( tmpNgMesh );
3057 // fill SMESH by netgen mesh
3058 vector< const SMDS_MeshNode* > tmpNodeVec;
3059 FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
3060 err = ( err || !comment.empty() );
3062 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
3065 // Fill _ngMesh with nodes and segments of computed submeshes
3068 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
3069 FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ], &quadHelper));
3071 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3076 startWith = endWith = netgen::MESHCONST_MESHEDGES;
3081 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3083 if ( netgen::multithread.terminate )
3086 comment << text(err);
3088 catch (Standard_Failure& ex)
3090 comment << text(ex);
3095 _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
3097 mparams.uselocalh = true; // restore as it is used at surface optimization
3099 // ---------------------
3100 // compute surface mesh
3101 // ---------------------
3104 // Pass 2D simple parameters to NETGEN
3106 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3108 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3109 mparams.grading = 0.4; // moderate size growth
3112 // length from edges
3113 if ( _ngMesh->GetNSeg() ) {
3114 double edgeLength = 0;
3115 TopTools_MapOfShape visitedEdges;
3116 for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
3117 if( visitedEdges.Add(exp.Current()) )
3118 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
3119 // we have to multiply length by 2 since for each TopoDS_Edge there
3120 // are double set of NETGEN edges, in other words, we have to
3121 // divide _ngMesh->GetNSeg() by 2.
3122 mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
3125 mparams.maxh = 1000;
3127 mparams.grading = 0.2; // slow size growth
3129 mparams.quad = _simpleHyp->GetAllowQuadrangles();
3130 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3131 _ngMesh->SetGlobalH (mparams.maxh);
3132 netgen::Box<3> bb = occgeo.GetBoundingBox();
3133 bb.Increase (bb.Diam()/20);
3134 _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
3137 // Care of vertices internal in faces (issue 0020676)
3138 if ( internals.hasInternalVertexInFace() )
3140 // store computed segments in SMESH in order not to create SMESH
3141 // edges for ng segments added by AddIntVerticesInFaces()
3142 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
3143 // add segments to faces with internal vertices
3144 AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
3145 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3148 // Build viscous layers
3149 if (( _isViscousLayers2D ) ||
3150 ( !occgeo.fmap.IsEmpty() &&
3151 StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( occgeo.fmap(1) ), *_mesh )))
3153 if ( !internals.hasInternalVertexInFace() ) {
3154 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
3155 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3157 SMESH_ProxyMesh::Ptr viscousMesh;
3158 SMESH_MesherHelper helper( *_mesh );
3159 for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
3161 const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
3162 viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
3165 if ( viscousMesh->NbProxySubMeshes() == 0 )
3167 // exclude from computation ng segments built on EDGEs of F
3168 for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
3170 netgen::Segment & seg = _ngMesh->LineSegment(i);
3171 if (seg.si == faceID)
3174 // add new segments to _ngMesh instead of excluded ones
3175 helper.SetSubShape( F );
3177 StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
3178 error, &helper, viscousMesh );
3179 error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
3181 if ( !error ) error = SMESH_ComputeError::New();
3183 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3186 // Let netgen compute 2D mesh
3187 startWith = netgen::MESHCONST_MESHSURFACE;
3188 endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
3193 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3195 if ( netgen::multithread.terminate )
3198 comment << text (err);
3200 catch (Standard_Failure& ex)
3202 comment << text(ex);
3203 //err = 1; -- try to make volumes anyway
3205 catch (netgen::NgException& exc)
3207 comment << text(exc);
3208 //err = 1; -- try to make volumes anyway
3213 doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
3214 _ticTime = doneTime / _totalTime / _progressTic;
3216 // ---------------------
3217 // generate volume mesh
3218 // ---------------------
3219 // Fill _ngMesh with nodes and faces of computed 2D submeshes
3220 if ( !err && _isVolume &&
3221 ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad || _viscousLayersHyp ))
3223 // load SMESH with computed segments and faces
3224 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3226 // compute prismatic boundary volumes
3227 smIdType nbQuad = _mesh->NbQuadrangles();
3228 SMESH_ProxyMesh::Ptr viscousMesh;
3229 if ( _viscousLayersHyp )
3231 viscousMesh = _viscousLayersHyp->Compute( *_mesh, _shape );
3235 // compute pyramids on quadrangles
3236 vector<SMESH_ProxyMesh::Ptr> pyramidMeshes( occgeo.somap.Extent() );
3238 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
3240 StdMeshers_QuadToTriaAdaptor* adaptor = new StdMeshers_QuadToTriaAdaptor;
3241 pyramidMeshes[ iS-1 ].reset( adaptor );
3242 bool ok = adaptor->Compute( *_mesh, occgeo.somap(iS), viscousMesh.get() );
3246 // add proxy faces to NG mesh
3247 list< SMESH_subMesh* > viscousSM;
3248 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
3250 list< SMESH_subMesh* > quadFaceSM;
3251 for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
3252 if ( pyramidMeshes[iS-1] && pyramidMeshes[iS-1]->GetProxySubMesh( face.Current() ))
3254 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
3255 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
3257 else if ( viscousMesh && viscousMesh->GetProxySubMesh( face.Current() ))
3259 viscousSM.push_back( _mesh->GetSubMesh( face.Current() ));
3260 meshedSM[ MeshDim_2D ].remove( viscousSM.back() );
3262 if ( !quadFaceSM.empty() )
3263 FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, pyramidMeshes[iS-1]);
3265 if ( !viscousSM.empty() )
3266 FillNgMesh(occgeo, *_ngMesh, nodeVec, viscousSM, &quadHelper, viscousMesh );
3268 // fill _ngMesh with faces of sub-meshes
3269 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper));
3270 initState = NETGENPlugin_ngMeshInfo(_ngMesh, /*checkRemovedElems=*/true);
3271 // toPython( _ngMesh )
3273 if (!err && _isVolume)
3275 // Pass 3D simple parameters to NETGEN
3276 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3277 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3279 _ngMesh->Compress();
3280 if ( double vol = simple3d->GetMaxElementVolume() ) {
3282 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3283 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3286 // length from faces
3287 mparams.maxh = _ngMesh->AverageH();
3289 _ngMesh->SetGlobalH (mparams.maxh);
3290 mparams.grading = 0.4;
3291 ngLib.CalcLocalH( ngLib._ngMesh );
3293 // Care of vertices internal in solids and internal faces (issue 0020676)
3294 if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
3296 // store computed faces in SMESH in order not to create SMESH
3297 // faces for ng faces added here
3298 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3299 // add ng faces to solids with internal vertices
3300 AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
3301 // duplicate mesh faces on internal faces
3302 FixIntFaces( occgeo, *_ngMesh, internals );
3303 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3305 // Let netgen compute 3D mesh
3306 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
3311 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3313 if ( netgen::multithread.terminate )
3316 if ( comment.empty() ) // do not overwrite a previous error
3317 comment << text(err);
3319 catch (Standard_Failure& ex)
3321 if ( comment.empty() ) // do not overwrite a previous error
3322 comment << text(ex);
3325 catch (netgen::NgException& exc)
3327 if ( comment.empty() ) // do not overwrite a previous error
3328 comment << text(exc);
3331 _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
3333 // Let netgen optimize 3D mesh
3334 if ( !err && _optimize )
3336 startWith = endWith = netgen::MESHCONST_OPTVOLUME;
3341 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3343 if ( netgen::multithread.terminate )
3346 if ( comment.empty() ) // do not overwrite a previous error
3347 comment << text(err);
3349 catch (Standard_Failure& ex)
3351 if ( comment.empty() ) // do not overwrite a previous error
3352 comment << text(ex);
3354 catch (netgen::NgException& exc)
3356 if ( comment.empty() ) // do not overwrite a previous error
3357 comment << text(exc);
3361 if (!err && mparams.secondorder > 0)
3366 if ( !meshedSM[ MeshDim_1D ].empty() )
3368 // remove segments not attached to geometry (IPAL0052479)
3369 for (int i = 1; i <= _ngMesh->GetNSeg(); ++i)
3371 const netgen::Segment & seg = _ngMesh->LineSegment (i);
3372 if ( seg.epgeominfo[ 0 ].edgenr == 0 )
3374 _ngMesh->DeleteSegment( i );
3375 initState._nbSegments--;
3378 _ngMesh->Compress();
3380 // convert to quadratic
3382 occgeo.GetRefinement().MakeSecondOrder(*_ngMesh);
3384 netgen::OCCRefinementSurfaces(occgeo).MakeSecondOrder(*_ngMesh);
3387 // care of elements already loaded to SMESH
3388 // if ( initState._nbSegments > 0 )
3389 // makeQuadratic( occgeo.emap, _mesh );
3390 // if ( initState._nbFaces > 0 )
3391 // makeQuadratic( occgeo.fmap, _mesh );
3393 catch (Standard_Failure& ex)
3395 if ( comment.empty() ) // do not overwrite a previous error
3396 comment << "Exception in netgen at passing to 2nd order ";
3398 catch (netgen::NgException& exc)
3400 if ( comment.empty() ) // do not overwrite a previous error
3401 comment << exc.What();
3406 _ticTime = 0.98 / _progressTic;
3408 //int nbNod = _ngMesh->GetNP();
3409 //int nbSeg = _ngMesh->GetNSeg();
3410 int nbFac = _ngMesh->GetNSE();
3411 int nbVol = _ngMesh->GetNE();
3412 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
3414 // Feed back the SMESHDS with the generated Nodes and Elements
3415 if ( true /*isOK*/ ) // get whatever built
3417 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3419 if ( quadHelper.GetIsQuadratic() ) // remove free nodes
3421 for ( size_t i = 0; i < nodeVec.size(); ++i )
3422 if ( nodeVec[i] && nodeVec[i]->NbInverseElements() == 0 )
3424 _mesh->GetMeshDS()->RemoveFreeNode( nodeVec[i], 0, /*fromGroups=*/false );
3427 for ( size_t i = nodeVec.size()-1; i > 0; --i ) // remove trailing removed nodes
3429 nodeVec.resize( i );
3434 SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
3435 if ( readErr && readErr->HasBadElems() )
3438 if ( !comment.empty() && !readErr->myComment.empty() ) comment += "\n";
3439 comment += readErr->myComment;
3441 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
3442 error->myName = COMPERR_ALGO_FAILED;
3443 if ( !comment.empty() )
3444 error->myComment = comment;
3446 // SetIsAlwaysComputed( true ) to empty sub-meshes, which
3447 // appear if the geometry contains coincident sub-shape due
3448 // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
3449 const int nbMaps = 2;
3450 const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
3451 { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
3452 for ( int iMap = 0; iMap < nbMaps; ++iMap )
3453 for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
3454 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
3455 if ( !sm->IsMeshComputed() )
3456 sm->SetIsAlwaysComputed( true );
3458 // set bad compute error to subshapes of all failed sub-shapes
3459 if ( !error->IsOK() )
3461 bool pb2D = false, pb3D = false;
3462 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
3463 int status = occgeo.facemeshstatus[i-1];
3464 if (status == netgen::FACE_MESHED_OK ) continue;
3465 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
3466 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3467 if ( !smError || smError->IsOK() ) {
3468 if ( status == netgen::FACE_FAILED )
3469 smError.reset( new SMESH_ComputeError( *error ));
3471 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
3472 if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3473 smError->myName = COMPERR_WARNING;
3475 pb2D = pb2D || smError->IsKO();
3478 if ( !pb2D ) // all faces are OK
3479 for (int i = 1; i <= occgeo.somap.Extent(); i++)
3480 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
3482 bool smComputed = nbVol && !sm->IsEmpty();
3483 if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
3485 size_t nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
3486 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3487 smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > (smIdType) nbIntV );
3489 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3490 if ( !smComputed && ( !smError || smError->IsOK() ))
3493 if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3495 smError->myName = COMPERR_WARNING;
3497 else if ( smError->HasBadElems() ) // bad surface mesh
3499 if ( !hasBadElemOnSolid
3500 ( static_cast<SMESH_BadInputElements*>( smError.get() )->myBadElements, sm ))
3504 pb3D = pb3D || ( smError && smError->IsKO() );
3506 if ( !pb2D && !pb3D )
3507 err = 0; // no fatal errors, only warnings
3510 ngLib._isComputeOk = !err;
3515 //=============================================================================
3519 //=============================================================================
3520 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
3522 netgen::MeshingParameters& mparams = netgen::mparam;
3525 // -------------------------
3526 // Prepare OCC geometry
3527 // -------------------------
3528 netgen::OCCGeometry occgeo;
3529 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
3530 PrepareOCCgeometry( occgeo, _shape, *_mesh, 0, &internals );
3532 bool tooManyElems = false;
3533 const int hugeNb = std::numeric_limits<int>::max() / 100;
3538 // pass 1D simple parameters to NETGEN
3541 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
3542 mparams.uselocalh = false;
3543 mparams.grading = 0.8; // not limitited size growth
3545 if ( _simpleHyp->GetNumberOfSegments() )
3547 mparams.maxh = occgeo.boundingbox.Diam();
3550 mparams.maxh = _simpleHyp->GetLocalLength();
3553 if ( mparams.maxh == 0.0 )
3554 mparams.maxh = occgeo.boundingbox.Diam();
3555 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
3556 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
3558 // let netgen create _ngMesh and calculate element size on not meshed shapes
3559 NETGENPlugin_NetgenLibWrapper ngLib;
3560 netgen::Mesh *ngMesh = NULL;
3561 int startWith = netgen::MESHCONST_ANALYSE;
3562 int endWith = netgen::MESHCONST_MESHEDGES;
3563 int err = ngLib.GenerateMesh(occgeo, startWith, endWith, ngMesh);
3565 if(netgen::multithread.terminate)
3568 ngLib.setMesh(( Ng_Mesh*) ngMesh );
3570 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
3571 sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
3574 // if ( _simpleHyp )
3576 // // Pass 1D simple parameters to NETGEN
3577 // // --------------------------------
3578 // int nbSeg = _simpleHyp->GetNumberOfSegments();
3579 // double segSize = _simpleHyp->GetLocalLength();
3580 // for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
3582 // const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
3584 // segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
3585 // setLocalSize( e, segSize, *ngMesh );
3588 // else // if ( ! _simpleHyp )
3590 // // Local size on shapes
3591 // SetLocalSize( occgeo, *ngMesh );
3593 // calculate total nb of segments and length of edges
3594 double fullLen = 0.0;
3595 smIdType fullNbSeg = 0;
3596 int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
3597 TopTools_DataMapOfShapeInteger Edge2NbSeg;
3598 for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
3600 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3601 if( !Edge2NbSeg.Bind(E,0) )
3604 double aLen = SMESH_Algo::EdgeLength(E);
3607 vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(E)];
3609 aVec.resize( SMDSEntity_Last, 0);
3611 fullNbSeg += aVec[ entity ];
3614 // store nb of segments computed by Netgen
3616 for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
3618 const netgen::Segment& seg = ngMesh->LineSegment(i);
3619 Link link(seg[0], seg[1]);
3620 if ( !linkMap.Add( link )) continue;
3621 int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
3622 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
3624 vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
3628 // store nb of nodes on edges computed by Netgen
3629 TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
3630 for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
3632 vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
3633 if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
3634 aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
3636 fullNbSeg += aVec[ entity ];
3637 Edge2NbSeg( Edge2NbSegIt.Key() ) = (int) aVec[ entity ];
3639 if ( fullNbSeg == 0 )
3646 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3648 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3649 mparams.grading = 0.4; // moderate size growth
3652 // length from edges
3653 mparams.maxh = fullLen / double( fullNbSeg );
3654 mparams.grading = 0.2; // slow size growth
3657 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3658 mparams.maxh = min( mparams.maxh, fullLen / double( fullNbSeg ) * (1. + mparams.grading));
3660 for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
3662 TopoDS_Face F = TopoDS::Face( exp.Current() );
3663 SMESH_subMesh *sm = _mesh->GetSubMesh(F);
3665 BRepGProp::SurfaceProperties(F,G);
3666 double anArea = G.Mass();
3667 tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
3669 if ( !tooManyElems )
3671 TopTools_MapOfShape edges;
3672 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
3673 if ( edges.Add( exp1.Current() ))
3674 nb1d += Edge2NbSeg.Find(exp1.Current());
3676 int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
3677 int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
3679 vector<smIdType> aVec(SMDSEntity_Last, 0);
3680 if( mparams.secondorder > 0 ) {
3681 int nb1d_in = (nbFaces*3 - nb1d) / 2;
3682 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3683 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
3686 aVec[SMDSEntity_Node] = Max ( nbNodes, 0 );
3687 aVec[SMDSEntity_Triangle] = nbFaces;
3689 aResMap[sm].swap(aVec);
3696 // pass 3D simple parameters to NETGEN
3697 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3698 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3700 if ( double vol = simple3d->GetMaxElementVolume() ) {
3702 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3703 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3706 // using previous length from faces
3708 mparams.grading = 0.4;
3709 mparams.maxh = min( mparams.maxh, fullLen / double( fullNbSeg ) * (1. + mparams.grading));
3712 BRepGProp::VolumeProperties(_shape,G);
3713 double aVolume = G.Mass();
3714 double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
3715 tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
3716 int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
3717 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3718 vector<smIdType> aVec(SMDSEntity_Last, 0 );
3719 if ( tooManyElems ) // avoid FPE
3721 aVec[SMDSEntity_Node] = hugeNb;
3722 aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
3726 if( mparams.secondorder > 0 ) {
3727 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3728 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3731 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3732 aVec[SMDSEntity_Tetra] = nbVols;
3735 SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
3736 aResMap[sm].swap(aVec);
3742 double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* /*holder*/,
3743 const int * algoProgressTic,
3744 const double * algoProgress) const
3746 ((int&) _progressTic ) = *algoProgressTic + 1;
3748 if ( !_occgeom ) return 0;
3750 double progress = -1;
3753 if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
3755 ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
3757 else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
3759 int doneShapeIndex = -1;
3760 while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
3761 _occgeom->facemeshstatus[ doneShapeIndex+1 ])
3763 if ( doneShapeIndex+1 != _curShapeIndex )
3765 ((int&) _curShapeIndex) = doneShapeIndex+1;
3766 double doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
3767 double doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
3768 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3769 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3770 // << " " << doneTime / _totalTime / _progressTic << endl;
3774 else if ( !_optimize && _occgeom->somap.Extent() > 1 )
3776 int curShapeIndex = _curShapeIndex;
3777 if ( _ngMesh->GetNE() > 0 )
3779 netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
3780 curShapeIndex = el.GetIndex();
3782 if ( curShapeIndex != _curShapeIndex )
3784 ((int&) _curShapeIndex) = curShapeIndex;
3785 double doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
3786 double doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
3787 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3788 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3789 // << " " << doneTime / _totalTime / _progressTic << endl;
3794 progress = Max( *algoProgressTic * _ticTime, *algoProgress );
3799 netgen::multithread.task[0] == 'D'/*elaunay meshing*/ &&
3800 progress > voluMeshingTime )
3802 progress = voluMeshingTime;
3803 ((double&) _ticTime) = voluMeshingTime / _totalTime / _progressTic;
3805 ((int&) *algoProgressTic )++;
3806 ((double&) *algoProgress) = progress;
3808 //cout << progress << " " << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
3810 return Min( progress, 0.99 );
3813 //================================================================================
3815 * \brief Read mesh entities preventing successful computation from "test.out" file
3817 //================================================================================
3819 SMESH_ComputeErrorPtr
3820 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
3822 if ( nodeVec.size() < 2 ) return SMESH_ComputeErrorPtr();
3823 SMESH_BadInputElements* err =
3824 new SMESH_BadInputElements( nodeVec.back()->GetMesh(), COMPERR_BAD_INPUT_MESH,
3825 "Some edges multiple times in surface mesh");
3826 SMESH_File file("test.out");
3828 vector<int> three1(3), three2(3);
3829 const char* badEdgeStr = " multiple times in surface mesh";
3830 const int badEdgeStrLen = (int) strlen( badEdgeStr );
3831 const int nbNodes = (int) nodeVec.size();
3833 while( !file.eof() )
3835 if ( strncmp( file, "Edge ", 5 ) == 0 &&
3836 file.getInts( two ) &&
3837 strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
3838 two[0] < nbNodes && two[1] < nbNodes )
3840 err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
3841 file += (int) badEdgeStrLen;
3843 else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
3846 // openelement 18 with open element 126
3850 const char* pos = file;
3851 bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
3852 ok = ok && file.getInts( two );
3853 ok = ok && file.getInts( three1 );
3854 ok = ok && file.getInts( three2 );
3855 for ( int i = 0; ok && i < 3; ++i )
3856 ok = ( three1[i] < nbNodes && nodeVec[ three1[i]]);
3857 for ( int i = 0; ok && i < 3; ++i )
3858 ok = ( three2[i] < nbNodes && nodeVec[ three2[i]]);
3861 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
3862 nodeVec[ three1[1]],
3863 nodeVec[ three1[2]]));
3864 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
3865 nodeVec[ three2[1]],
3866 nodeVec[ three2[2]]));
3867 err->myComment = "Intersecting triangles";
3881 size_t nbBadElems = err->myBadElements.size();
3882 if ( nbBadElems ) nbBadElems++; // avoid warning: variable set but not used
3885 return SMESH_ComputeErrorPtr( err );
3888 //================================================================================
3890 * \brief Write a python script creating an equivalent SALOME mesh.
3891 * This is useful to see what mesh is passed as input for the next step of mesh
3892 * generation (of mesh of higher dimension)
3894 //================================================================================
3896 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh )
3898 const char* pyFile = "/tmp/ngMesh.py";
3899 ofstream outfile( pyFile, ios::out );
3900 if ( !outfile ) return;
3902 outfile << "import salome, SMESH" << std::endl
3903 << "from salome.smesh import smeshBuilder" << std::endl
3904 << "smesh = smeshBuilder.New()" << std::endl
3905 << "mesh = smesh.Mesh()" << std::endl << std::endl;
3907 using namespace netgen;
3911 for ( int i = 1; i <= ngMesh->GetNP(); i++)
3913 const Point3d & p = ngMesh->Point(i);
3914 outfile << "mesh.AddNode( ";
3915 outfile << p.X() << ", ";
3916 outfile << p.Y() << ", ";
3917 outfile << p.Z() << ") ## "<< i << std::endl;
3920 int nbDom = ngMesh->GetNDomains();
3921 for ( int i = 0; i < nbDom; ++i )
3922 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< std::endl;
3925 for (int i = 1; i <= ngMesh->GetNSE(); i++)
3927 outfile << "mesh.AddFace([ ";
3928 Element2d sel = ngMesh->SurfaceElement(i);
3929 for (int j = 1; j <= sel.GetNP(); j++)
3930 outfile << sel.PNum(j) << ( j < sel.GetNP() ? ", " : " ])");
3931 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3932 outfile << std::endl;
3933 nbDel += sel.IsDeleted();
3937 if ( int dom1 = ngMesh->GetFaceDescriptor(sel.GetIndex ()).DomainIn())
3938 outfile << "grp"<< dom1 <<".Add([ " << i - nbDel << " ])" << std::endl;
3939 if ( int dom2 = ngMesh->GetFaceDescriptor(sel.GetIndex ()).DomainOut())
3940 outfile << "grp"<< dom2 <<".Add([ " << i - nbDel << " ])" << std::endl;
3944 for (int i = 1; i <= ngMesh->GetNE(); i++)
3946 Element el = ngMesh->VolumeElement(i);
3947 outfile << "mesh.AddVolume([ ";
3948 for (int j = 1; j <= el.GetNP(); j++)
3949 outfile << el.PNum(j) << ( j < el.GetNP() ? ", " : " ])");
3950 outfile << std::endl;
3953 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3955 const Segment & seg = ngMesh->LineSegment (i);
3956 outfile << "mesh.AddEdge([ "
3958 << seg[1]+1 << " ])" << std::endl;
3964 for (pi = PointIndex::BASE;
3965 pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3967 outfile << "mesh.AddNode( ";
3968 outfile << (*ngMesh)[pi](0) << ", ";
3969 outfile << (*ngMesh)[pi](1) << ", ";
3970 outfile << (*ngMesh)[pi](2) << ") ## "<< pi << std::endl;
3973 int nbDom = ngMesh->GetNDomains();
3974 for ( int i = 0; i < nbDom; ++i )
3975 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< std::endl;
3978 SurfaceElementIndex sei;
3979 for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3981 outfile << "mesh.AddFace([ ";
3982 Element2d sel = (*ngMesh)[sei];
3983 for (int j = 0; j < sel.GetNP(); j++)
3984 outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3985 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3986 outfile << std::endl;
3987 nbDel += sel.IsDeleted();
3989 if ((*ngMesh)[sei].GetIndex())
3991 if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3992 outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 - nbDel << " ])" << std::endl;
3993 if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3994 outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 - nbDel << " ])" << std::endl;
3998 for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
4000 Element el = (*ngMesh)[ei];
4001 outfile << "mesh.AddVolume([ ";
4002 for (int j = 0; j < el.GetNP(); j++)
4003 outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
4004 outfile << std::endl;
4007 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
4009 const Segment & seg = ngMesh->LineSegment (i);
4010 outfile << "mesh.AddEdge([ "
4012 << seg[1] << " ])" << std::endl;
4017 std::cout << "Write " << pyFile << std::endl;
4020 //================================================================================
4022 * \brief Constructor of NETGENPlugin_ngMeshInfo
4024 //================================================================================
4026 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh,
4027 bool checkRemovedElems):
4028 _elementsRemoved( false ), _copyOfLocalH(0)
4032 _nbNodes = ngMesh->GetNP();
4033 _nbSegments = ngMesh->GetNSeg();
4034 _nbFaces = ngMesh->GetNSE();
4035 _nbVolumes = ngMesh->GetNE();
4037 if ( checkRemovedElems )
4038 for ( int i = 1; i <= ngMesh->GetNSE() && !_elementsRemoved; ++i )
4039 _elementsRemoved = ngMesh->SurfaceElement(i).IsDeleted();
4043 _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
4047 //================================================================================
4049 * \brief Copy LocalH member from one netgen mesh to another
4051 //================================================================================
4053 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
4054 netgen::Mesh* toMesh )
4056 if ( !fromMesh->LocalHFunctionGenerated() ) return;
4057 if ( !toMesh->LocalHFunctionGenerated() )
4058 NETGENPlugin_NetgenLibWrapper::CalcLocalH( toMesh );
4060 const size_t size = sizeof( netgen::LocalH );
4061 _copyOfLocalH = new char[ size ];
4062 memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
4063 memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
4066 //================================================================================
4068 * \brief Restore LocalH member of a netgen mesh
4070 //================================================================================
4072 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
4074 if ( _copyOfLocalH )
4076 const size_t size = sizeof( netgen::LocalH );
4077 memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
4078 delete [] _copyOfLocalH;
4083 //================================================================================
4085 * \brief Find "internal" sub-shapes
4087 //================================================================================
4089 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh,
4090 const TopoDS_Shape& shape,
4092 : _mesh( mesh ), _is3D( is3D )
4094 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
4096 TopExp_Explorer f,e;
4097 for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
4099 int faceID = meshDS->ShapeToIndex( f.Current() );
4101 // find not computed internal edges
4103 for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
4104 if ( e.Current().Orientation() == TopAbs_INTERNAL )
4106 SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
4107 if ( eSM->IsEmpty() )
4109 _e2face.insert( make_pair( eSM->GetId(), faceID ));
4110 for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
4111 _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
4115 // find internal vertices in a face
4116 set<int> intVV; // issue 0020850 where same vertex is twice in a face
4117 for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
4118 if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
4120 int vID = meshDS->ShapeToIndex( fSub.Value() );
4121 if ( intVV.insert( vID ).second )
4122 _f2v[ faceID ].push_back( vID );
4127 // find internal faces and their subshapes where nodes are to be doubled
4128 // to make a crack with non-sewed borders
4130 if ( f.Current().Orientation() == TopAbs_INTERNAL )
4132 _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
4135 list< TopoDS_Shape > edges;
4136 for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
4137 if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
4139 _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
4140 edges.push_back( e.Current() );
4141 // find border faces
4142 PShapeIteratorPtr fIt =
4143 SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
4144 while ( const TopoDS_Shape* pFace = fIt->next() )
4145 if ( !pFace->IsSame( f.Current() ))
4146 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
4149 // we consider vertex internal if it is shared by more than one internal edge
4150 list< TopoDS_Shape >::iterator edge = edges.begin();
4151 for ( ; edge != edges.end(); ++edge )
4152 for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
4154 set<int> internalEdges;
4155 PShapeIteratorPtr eIt =
4156 SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
4157 while ( const TopoDS_Shape* pEdge = eIt->next() )
4159 int edgeID = meshDS->ShapeToIndex( *pEdge );
4160 if ( isInternalShape( edgeID ))
4161 internalEdges.insert( edgeID );
4163 if ( internalEdges.size() > 1 )
4164 _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
4168 } // loop on geom faces
4170 // find vertices internal in solids
4173 for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
4175 int soID = meshDS->ShapeToIndex( so.Current() );
4176 for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
4177 if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
4178 _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
4183 //================================================================================
4185 * \brief Find mesh faces on non-internal geom faces sharing internal edge
4186 * some nodes of which are to be doubled to make the second border of the "crack"
4188 //================================================================================
4190 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
4192 if ( _intShapes.empty() ) return;
4194 SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
4195 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
4197 // loop on internal geom edges
4198 set<int>::const_iterator intShapeId = _intShapes.begin();
4199 for ( ; intShapeId != _intShapes.end(); ++intShapeId )
4201 const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
4202 if ( s.ShapeType() != TopAbs_EDGE ) continue;
4204 // get internal and non-internal geom faces sharing the internal edge <s>
4206 set<int>::iterator bordFace = _borderFaces.end();
4207 PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
4208 while ( const TopoDS_Shape* pFace = faces->next() )
4210 int faceID = meshDS->ShapeToIndex( *pFace );
4211 if ( isInternalShape( faceID ))
4214 bordFace = _borderFaces.insert( faceID ).first;
4216 if ( bordFace == _borderFaces.end() || !intFace ) continue;
4218 // get all links of mesh faces on internal geom face sharing nodes on edge <s>
4219 set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
4220 list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
4221 int nbSuspectFaces = 0;
4222 SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
4223 if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
4224 SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
4225 while ( smIt->more() )
4227 SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
4228 if ( !sm ) continue;
4229 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4230 while ( nIt->more() )
4232 const SMDS_MeshNode* nOnEdge = nIt->next();
4233 SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
4234 while ( fIt->more() )
4236 const SMDS_MeshElement* f = fIt->next();
4237 const int nbNodes = f->NbCornerNodes();
4238 if ( intFaceSM->Contains( f ))
4240 for ( int i = 0; i < nbNodes; ++i )
4241 links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
4246 for ( int i = 0; i < nbNodes; ++i )
4247 nbDblNodes += isInternalShape( f->GetNode(i)->GetShapeID() );
4249 suspectFaces[ nbDblNodes < 2 ].push_back( f );
4255 // suspectFaces[0] having link with same orientation as mesh faces on
4256 // the internal geom face are <borderElems>. suspectFaces[1] have
4257 // only one node on edge <s>, we decide on them later (at the 2nd loop)
4258 // by links of <borderElems> found at the 1st and 2nd loops
4259 set< SMESH_OrientedLink > borderLinks;
4260 for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
4262 list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
4263 for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
4265 const SMDS_MeshElement* f = *fIt;
4266 bool isBorder = false, linkFound = false, borderLinkFound = false;
4267 list< SMESH_OrientedLink > faceLinks;
4268 int nbNodes = f->NbCornerNodes();
4269 for ( int i = 0; i < nbNodes; ++i )
4271 SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
4272 faceLinks.push_back( link );
4275 set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
4276 if ( foundLink != links.end() )
4279 isBorder = ( foundLink->_reversed == link._reversed );
4280 if ( !isBorder && !isPostponed ) break;
4281 faceLinks.pop_back();
4283 else if ( isPostponed && !borderLinkFound )
4285 foundLink = borderLinks.find( link );
4286 if ( foundLink != borderLinks.end() )
4288 borderLinkFound = true;
4289 isBorder = ( foundLink->_reversed != link._reversed );
4296 borderElems.insert( f );
4297 borderLinks.insert( faceLinks.begin(), faceLinks.end() );
4299 else if ( !linkFound && !borderLinkFound )
4301 suspectFaces[1].push_back( f );
4302 if ( nbF > 2 * nbSuspectFaces )
4303 break; // dead loop protection
4310 //================================================================================
4312 * \brief put internal shapes in maps and fill in submeshes to precompute
4314 //================================================================================
4316 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
4317 TopTools_IndexedMapOfShape& emap,
4318 TopTools_IndexedMapOfShape& vmap,
4319 list< SMESH_subMesh* > smToPrecompute[])
4321 if ( !hasInternalEdges() ) return;
4322 map<int,int>::const_iterator ev_face = _e2face.begin();
4323 for ( ; ev_face != _e2face.end(); ++ev_face )
4325 const TopoDS_Shape& ev = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
4326 const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
4328 ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
4330 //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
4332 smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
4336 //================================================================================
4338 * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
4340 //================================================================================
4342 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
4343 TopTools_IndexedMapOfShape& emap,
4344 list< SMESH_subMesh* >& intFaceSM,
4345 list< SMESH_subMesh* >& boundarySM)
4347 if ( !hasInternalFaces() ) return;
4349 // <fmap> and <emap> are for not yet meshed shapes
4350 // <intFaceSM> is for submeshes of faces
4351 // <boundarySM> is for meshed edges and vertices
4356 set<int> shapeIDs ( _intShapes );
4357 if ( !_borderFaces.empty() )
4358 shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
4360 set<int>::const_iterator intS = shapeIDs.begin();
4361 for ( ; intS != shapeIDs.end(); ++intS )
4363 SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
4365 if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
4367 intFaceSM.push_back( sm );
4369 // add submeshes of not computed internal faces
4370 if ( !sm->IsEmpty() ) continue;
4372 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
4373 while ( smIt->more() )
4376 const TopoDS_Shape& s = sm->GetSubShape();
4378 if ( sm->IsEmpty() )
4381 switch ( s.ShapeType() ) {
4382 case TopAbs_FACE: fmap.Add ( s ); break;
4383 case TopAbs_EDGE: emap.Add ( s ); break;
4389 if ( s.ShapeType() != TopAbs_FACE )
4390 boundarySM.push_back( sm );
4396 //================================================================================
4398 * \brief Return true if given shape is to be precomputed in order to be correctly
4399 * added to netgen mesh
4401 //================================================================================
4403 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
4405 int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
4406 switch ( s.ShapeType() ) {
4407 case TopAbs_FACE : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
4408 case TopAbs_EDGE : return isInternalEdge( shapeID );
4409 case TopAbs_VERTEX: break;
4415 //================================================================================
4417 * \brief Return SMESH
4419 //================================================================================
4421 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
4423 return const_cast<SMESH_Mesh&>( _mesh );
4426 //================================================================================
4428 * \brief Access to a counter of NETGENPlugin_NetgenLibWrapper instances
4430 //================================================================================
4432 int& NETGENPlugin_NetgenLibWrapper::instanceCounter()
4434 static int theCouner = 0;
4438 //================================================================================
4440 * \brief Initialize netgen library
4442 //================================================================================
4444 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper():
4445 _ngMesh(0),_tmpDir(SALOMEDS_Tool::GetTmpDir())
4447 if ( instanceCounter() == 0 )
4450 if ( !netgen::testout )
4451 netgen::testout = new ofstream( "test.out" );
4454 ++instanceCounter();
4456 _isComputeOk = false;
4460 if ( !getenv( "KEEP_NETGEN_OUTPUT" ))
4462 setOutputFile(getOutputFileName());
4465 setMesh( Ng_NewMesh() );
4468 //================================================================================
4470 * \brief Finish using netgen library
4472 //================================================================================
4474 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
4476 --instanceCounter();
4478 Ng_DeleteMesh( ngMesh() );
4482 std::cout.rdbuf( _coutBuffer );
4489 //================================================================================
4491 * \brief Set netgen mesh to delete at destruction
4493 //================================================================================
4495 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
4498 Ng_DeleteMesh( ngMesh() );
4499 _ngMesh = (netgen::Mesh*) mesh;
4502 //================================================================================
4504 * \brief Perform a step of mesh generation
4505 * \param [inout] occgeo - geometry to mesh
4506 * \param [inout] startWith - start step
4507 * \param [inout] endWith - end step
4508 * \param [inout] ngMesh - netgen mesh
4509 * \return int - is error
4511 //================================================================================
4513 int NETGENPlugin_NetgenLibWrapper::GenerateMesh( netgen::OCCGeometry& occgeo,
4514 int startWith, int endWith,
4515 netgen::Mesh* & ngMesh )
4519 ngMesh = new netgen::Mesh;
4522 // netgen::mparam.Print(std::cerr);
4526 ngMesh->SetGeometry( shared_ptr<netgen::NetgenGeometry>( &occgeo, &NOOP_Deleter ));
4528 netgen::mparam.perfstepsstart = startWith;
4529 netgen::mparam.perfstepsend = endWith;
4530 std::shared_ptr<netgen::Mesh> meshPtr( ngMesh, &NOOP_Deleter );
4531 err = occgeo.GenerateMesh( meshPtr, netgen::mparam );
4536 err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
4541 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
4548 //================================================================================
4550 * \brief Create a mesh size tree
4552 //================================================================================
4554 void NETGENPlugin_NetgenLibWrapper::CalcLocalH( netgen::Mesh * ngMesh )
4556 #if defined( NETGEN_V5 ) || defined( NETGEN_V6 )
4557 ngMesh->CalcLocalH(netgen::mparam.grading);
4559 ngMesh->CalcLocalH();
4563 //================================================================================
4565 * \brief Return a unique file name
4567 //================================================================================
4569 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
4571 std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
4573 TCollection_AsciiString aGenericName = aTmpDir.c_str();
4574 aGenericName += "NETGEN_";
4576 aGenericName += getpid();
4578 aGenericName += _getpid();
4580 aGenericName += "_";
4581 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
4582 aGenericName += ".out";
4584 return aGenericName.ToCString();
4586 //================================================================================
4588 * \brief Set output file name for netgen log
4590 //================================================================================
4592 void NETGENPlugin_NetgenLibWrapper::setOutputFile(std::string outputfile)
4594 // redirect all netgen output (mycout,myerr,cout) to _outputFileName
4595 _outputFileName = outputfile;
4596 _ngcout = netgen::mycout;
4597 _ngcerr = netgen::myerr;
4598 netgen::mycout = new ofstream ( _outputFileName.c_str() );
4599 netgen::myerr = netgen::mycout;
4600 _coutBuffer = std::cout.rdbuf();
4602 std::cout << "NOTE: netgen output is redirected to file " << _outputFileName << std::endl;
4604 std::cout.rdbuf( netgen::mycout->rdbuf() );
4608 //================================================================================
4610 * \brief Remove "test.out" and "problemfaces" files in current directory
4612 //================================================================================
4614 void NETGENPlugin_NetgenLibWrapper::RemoveTmpFiles()
4616 bool rm = SMESH_File("test.out").remove() ;
4618 if ( rm && netgen::testout && instanceCounter() == 0 )
4620 delete netgen::testout;
4621 netgen::testout = 0;
4624 SMESH_File("problemfaces").remove();
4625 SMESH_File("occmesh.rep").remove();
4628 //================================================================================
4630 * \brief Remove file with netgen output
4632 //================================================================================
4634 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
4636 if ( !_outputFileName.empty() )
4640 delete netgen::mycout;
4641 netgen::mycout = _ngcout;
4642 netgen::myerr = _ngcerr;
4645 string tmpDir = SALOMEDS_Tool::GetDirFromPath ( _outputFileName );
4646 string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
4647 SALOMEDS_Tool::ListOfFiles aFiles;
4649 aFiles.push_back(aFileName.c_str());
4651 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles, true );