1 // Copyright (C) 2007-2021 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 // NETGENPlugin : C++ implementation
24 // File : NETGENPlugin_Mesher.cxx
25 // Author : Michael Sazonov (OCN)
28 //=============================================================================
30 #include "NETGENPlugin_Mesher.hxx"
31 #include "NETGENPlugin_Hypothesis_2D.hxx"
32 #include "NETGENPlugin_SimpleHypothesis_3D.hxx"
34 #include <SMDS_FaceOfNodes.hxx>
35 #include <SMDS_LinearEdge.hxx>
36 #include <SMDS_MeshElement.hxx>
37 #include <SMDS_MeshNode.hxx>
38 #include <SMESHDS_Mesh.hxx>
39 #include <SMESH_Block.hxx>
40 #include <SMESH_Comment.hxx>
41 #include <SMESH_ComputeError.hxx>
42 #include <SMESH_ControlPnt.hxx>
43 #include <SMESH_File.hxx>
44 #include <SMESH_Gen_i.hxx>
45 #include <SMESH_Mesh.hxx>
46 #include <SMESH_MesherHelper.hxx>
47 #include <SMESH_subMesh.hxx>
48 #include <StdMeshers_QuadToTriaAdaptor.hxx>
49 #include <StdMeshers_ViscousLayers2D.hxx>
51 #include <SALOMEDS_Tool.hxx>
53 #include <utilities.h>
55 #include <BRepAdaptor_Surface.hxx>
56 #include <BRepBuilderAPI_Copy.hxx>
57 #include <BRepLProp_SLProps.hxx>
58 #include <BRepMesh_IncrementalMesh.hxx>
59 #include <BRep_Builder.hxx>
60 #include <BRep_Tool.hxx>
61 #include <Bnd_B3d.hxx>
62 #include <GeomLib_IsPlanarSurface.hxx>
63 #include <NCollection_Map.hxx>
64 #include <Poly_Triangulation.hxx>
65 #include <Standard_ErrorHandler.hxx>
66 #include <Standard_ProgramError.hxx>
67 #include <TColStd_MapOfInteger.hxx>
69 #include <TopExp_Explorer.hxx>
70 #include <TopLoc_Location.hxx>
71 #include <TopTools_DataMapIteratorOfDataMapOfShapeInteger.hxx>
72 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
73 #include <TopTools_DataMapOfShapeInteger.hxx>
74 #include <TopTools_DataMapOfShapeShape.hxx>
75 #include <TopTools_MapOfShape.hxx>
77 #include <TopoDS_Compound.hxx>
79 // Netgen include files
83 #include <occgeom.hpp>
84 #include <meshing.hpp>
85 //#include <ngexception.hpp>
88 NETGENPLUGIN_DLL_HEADER
89 extern MeshingParameters mparam;
91 NETGENPLUGIN_DLL_HEADER
92 extern volatile multithreadt multithread;
94 NETGENPLUGIN_DLL_HEADER
95 extern bool merge_solids;
97 // values used for occgeo.facemeshstatus
98 enum EFaceMeshStatus { FACE_NOT_TREATED = 0,
110 using namespace nglib;
114 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec.at((index)))
116 #define nodeVec_ACCESS(index) ((SMDS_MeshNode*) nodeVec[index])
119 #define NGPOINT_COORDS(p) p(0),p(1),p(2)
122 // dump elements added to ng mesh
123 //#define DUMP_SEGMENTS
124 //#define DUMP_TRIANGLES
125 //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids()
128 TopTools_IndexedMapOfShape ShapesWithLocalSize;
129 std::map<int,double> VertexId2LocalSize;
130 std::map<int,double> EdgeId2LocalSize;
131 std::map<int,double> FaceId2LocalSize;
132 std::map<int,double> SolidId2LocalSize;
134 std::vector<SMESHUtils::ControlPnt> ControlPoints;
135 std::set<int> ShapesWithControlPoints; // <-- allows calling SetLocalSize() several times w/o recomputing ControlPoints
139 inline void NOOP_Deleter(void *) { ; }
141 //=============================================================================
143 * Link - a pair of integer numbers
145 //=============================================================================
149 Link(int _n1, int _n2) : n1(_n1), n2(_n2) {}
150 Link() : n1(0), n2(0) {}
151 bool Contains( int n ) const { return n == n1 || n == n2; }
152 bool IsConnected( const Link& other ) const
154 return (( Contains( other.n1 ) || Contains( other.n2 )) && ( this != &other ));
156 static int HashCode(const Link& aLink, int aLimit)
158 return ::HashCode(aLink.n1 + aLink.n2, aLimit);
161 static Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2)
163 return (( aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ) ||
164 ( aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1 ));
168 typedef NCollection_Map<Link,Link> TLinkMap;
170 //================================================================================
172 * \brief return id of netgen point corresponding to SMDS node
174 //================================================================================
175 typedef map< const SMDS_MeshNode*, int > TNode2IdMap;
177 int ngNodeId( const SMDS_MeshNode* node,
178 netgen::Mesh& ngMesh,
179 TNode2IdMap& nodeNgIdMap)
181 int newNgId = ngMesh.GetNP() + 1;
183 TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first;
185 if ( node_id->second == newNgId)
187 #if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES)
188 cout << "Ng " << newNgId << " - " << node;
190 netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) );
191 ngMesh.AddPoint( p );
193 return node_id->second;
196 //================================================================================
198 * \brief Return computed EDGEs connected to the given one
200 //================================================================================
202 list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge& edge,
203 const TopoDS_Face& face,
204 const set< SMESH_subMesh* > & /*computedSM*/,
205 const SMESH_MesherHelper& helper,
206 map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces)
209 list< TopoDS_Edge > edges;
210 list< int > nbEdgesInWire;
211 /*int nbWires =*/ SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire);
213 // find <edge> within <edges>
214 list< TopoDS_Edge >::iterator eItFwd = edges.begin();
215 for ( ; eItFwd != edges.end(); ++eItFwd )
216 if ( edge.IsSame( *eItFwd ))
218 if ( eItFwd == edges.end()) return list< TopoDS_Edge>();
220 if ( eItFwd->Orientation() >= TopAbs_INTERNAL )
222 // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented
223 // so treat each INTERNAL edge separately
224 TopoDS_Edge e = *eItFwd;
226 edges.push_back( e );
230 // get all computed EDGEs connected to <edge>
232 list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev;
233 TopoDS_Vertex vCommon;
234 TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to <edges>
237 // put edges before <edge> to <edges> back
238 while ( edges.begin() != eItFwd )
239 edges.splice( edges.end(), edges, edges.begin() );
243 while ( ++eItFwd != edges.end() )
245 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd );
247 bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon );
248 bool computed = !sm->IsEmpty();
249 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
250 bool doubled = !eAdded.Add( *eItFwd );
251 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
252 ( eItFwd->Orientation() < TopAbs_INTERNAL ) );
253 if ( !connected || !computed || !orientOK || added || doubled )
255 // stop advancement; move edges from tail to head
256 while ( edges.back() != *ePrev )
257 edges.splice( edges.begin(), edges, --edges.end() );
263 while ( eItBack != edges.begin() )
267 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack );
269 bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon );
270 bool computed = !sm->IsEmpty();
271 bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() );
272 bool doubled = !eAdded.Add( *eItBack );
273 bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) ==
274 ( eItBack->Orientation() < TopAbs_INTERNAL ) );
275 if ( !connected || !computed || !orientOK || added || doubled)
278 edges.erase( edges.begin(), ePrev );
282 if ( edges.front() != edges.back() )
284 // assure that the 1st vertex is meshed
285 TopoDS_Edge eLast = edges.back();
286 while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS())
288 edges.front() != eLast )
289 edges.splice( edges.end(), edges, edges.begin() );
294 //================================================================================
296 * \brief Make triangulation of a shape precise enough
298 //================================================================================
300 void updateTriangulation( const TopoDS_Shape& shape )
302 // static set< Poly_Triangulation* > updated;
304 // TopLoc_Location loc;
305 // TopExp_Explorer fExp( shape, TopAbs_FACE );
306 // for ( ; fExp.More(); fExp.Next() )
308 // Handle(Poly_Triangulation) triangulation =
309 // BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
310 // if ( triangulation.IsNull() ||
311 // updated.insert( triangulation.operator->() ).second )
313 // BRepTools::Clean (shape);
316 BRepMesh_IncrementalMesh e(shape, 0.01, true);
318 catch (Standard_Failure&)
321 // updated.erase( triangulation.operator->() );
322 // triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
323 // updated.insert( triangulation.operator->() );
327 //================================================================================
329 * \brief Returns a medium node either existing in SMESH of created by NETGEN
330 * \param [in] corner1 - corner node 1
331 * \param [in] corner2 - corner node 2
332 * \param [in] defaultMedium - the node created by NETGEN
333 * \param [in] helper - holder of medium nodes existing in SMESH
334 * \return const SMDS_MeshNode* - the result node
336 //================================================================================
338 const SMDS_MeshNode* mediumNode( const SMDS_MeshNode* corner1,
339 const SMDS_MeshNode* corner2,
340 const SMDS_MeshNode* defaultMedium,
341 const SMESH_MesherHelper* helper)
345 TLinkNodeMap::const_iterator l2n =
346 helper->GetTLinkNodeMap().find( SMESH_TLink( corner1, corner2 ));
347 if ( l2n != helper->GetTLinkNodeMap().end() )
348 defaultMedium = l2n->second;
350 return defaultMedium;
353 //================================================================================
355 * \brief Assure that mesh on given shapes is quadratic
357 //================================================================================
359 // void makeQuadratic( const TopTools_IndexedMapOfShape& shapes,
360 // SMESH_Mesh* mesh )
362 // for ( int i = 1; i <= shapes.Extent(); ++i )
364 // SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) );
365 // if ( !smDS ) continue;
366 // SMDS_ElemIteratorPtr elemIt = smDS->GetElements();
367 // if ( !elemIt->more() ) continue;
368 // const SMDS_MeshElement* e = elemIt->next();
369 // if ( !e || e->IsQuadratic() )
372 // TIDSortedElemSet elems;
373 // elems.insert( e );
374 // while ( elemIt->more() )
375 // elems.insert( elems.end(), elemIt->next() );
377 // SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false );
381 //================================================================================
383 * \brief Restrict size of elements on the given edge
385 //================================================================================
387 void setLocalSize(const TopoDS_Edge& edge,
390 const bool overrideMinH = true)
392 if ( size <= std::numeric_limits<double>::min() )
394 Standard_Real u1, u2;
395 Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2);
396 if ( curve.IsNull() )
398 TopoDS_Iterator vIt( edge );
399 if ( !vIt.More() ) return;
400 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() ));
401 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH );
405 const int nb = (int)( 1.5 * SMESH_Algo::EdgeLength( edge ) / size );
406 Standard_Real delta = (u2-u1)/nb;
407 for(int i=0; i<nb; i++)
409 Standard_Real u = u1 + delta*i;
410 gp_Pnt p = curve->Value(u);
411 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH );
412 netgen::Point3d pi(p.X(), p.Y(), p.Z());
413 double resultSize = mesh.GetH(pi);
414 if ( resultSize - size > 0.1*size )
415 // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136)
416 NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201, overrideMinH );
421 //================================================================================
423 * \brief Return triangle size for a given chordalError and radius of curvature
425 //================================================================================
427 double elemSizeForChordalError( double chordalError, double radius )
429 if ( 2 * radius < chordalError )
431 return Sqrt( 3 ) * Sqrt( chordalError * ( 2 * radius - chordalError ));
434 //=============================================================================
438 //=============================================================================
440 void setLocalSize(const TopoDS_Shape& GeomShape, double LocalSize)
442 if ( GeomShape.IsNull() ) return;
443 TopAbs_ShapeEnum GeomType = GeomShape.ShapeType();
444 if (GeomType == TopAbs_COMPOUND) {
445 for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) {
446 setLocalSize(it.Value(), LocalSize);
451 if (! ShapesWithLocalSize.Contains(GeomShape))
452 key = ShapesWithLocalSize.Add(GeomShape);
454 key = ShapesWithLocalSize.FindIndex(GeomShape);
455 if (GeomType == TopAbs_VERTEX) {
456 VertexId2LocalSize[key] = LocalSize;
457 } else if (GeomType == TopAbs_EDGE) {
458 EdgeId2LocalSize[key] = LocalSize;
459 } else if (GeomType == TopAbs_FACE) {
460 FaceId2LocalSize[key] = LocalSize;
461 } else if (GeomType == TopAbs_SOLID) {
462 SolidId2LocalSize[key] = LocalSize;
467 //================================================================================
469 * \brief Return faceNgID or faceNgID-1 depending on side the given proxy face lies
470 * \param [in] f - proxy face
471 * \param [in] solidSMDSIDs - IDs of SOLIDs sharing the FACE on which face lies
472 * \param [in] faceNgID - NETGEN ID of the FACE
473 * \return int - NETGEN ID of the FACE
475 //================================================================================
477 int getFaceNgID( const SMDS_MeshElement* face,
478 const int * solidSMDSIDs,
481 for ( int i = 0; i < 3; ++i )
483 const SMDS_MeshNode* n = face->GetNode( i );
484 const int shapeID = n->GetShapeID();
485 if ( shapeID == solidSMDSIDs[0] )
487 if ( shapeID == solidSMDSIDs[1] )
490 std::vector<const SMDS_MeshNode*> fNodes( face->begin_nodes(), face->end_nodes() );
491 std::vector<const SMDS_MeshElement*> vols;
492 if ( SMDS_Mesh::GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ))
493 for ( size_t i = 0; i < vols.size(); ++i )
495 const int shapeID = vols[i]->GetShapeID();
496 if ( shapeID == solidSMDSIDs[0] )
498 if ( shapeID == solidSMDSIDs[1] )
506 //=============================================================================
510 //=============================================================================
512 NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh,
513 const TopoDS_Shape& aShape,
519 _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()),
520 _isViscousLayers2D(false),
521 _chordalError(-1), // means disabled
528 _viscousLayersHyp(NULL),
531 SetDefaultParameters();
532 ShapesWithLocalSize.Clear();
533 VertexId2LocalSize.clear();
534 EdgeId2LocalSize.clear();
535 FaceId2LocalSize.clear();
536 SolidId2LocalSize.clear();
537 ControlPoints.clear();
538 ShapesWithControlPoints.clear();
541 //================================================================================
545 //================================================================================
547 NETGENPlugin_Mesher::~NETGENPlugin_Mesher()
555 //================================================================================
557 * Set pointer to NETGENPlugin_Mesher* field of the holder, that will be
558 * nullified at destruction of this
560 //================================================================================
562 void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr )
573 //================================================================================
575 * \brief Initialize global NETGEN parameters with default values
577 //================================================================================
579 void NETGENPlugin_Mesher::SetDefaultParameters()
581 netgen::MeshingParameters& mparams = netgen::mparam;
582 mparams = netgen::MeshingParameters();
583 // maximal mesh edge size
584 mparams.maxh = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize();
586 // minimal number of segments per edge
587 mparams.segmentsperedge = NETGENPlugin_Hypothesis::GetDefaultNbSegPerEdge();
588 // rate of growth of size between elements
589 mparams.grading = NETGENPlugin_Hypothesis::GetDefaultGrowthRate();
590 // safety factor for curvatures (elements per radius)
591 mparams.curvaturesafety = NETGENPlugin_Hypothesis::GetDefaultNbSegPerRadius();
592 // create elements of second order
593 mparams.secondorder = NETGENPlugin_Hypothesis::GetDefaultSecondOrder();
594 // quad-dominated surface meshing
598 mparams.quad = NETGENPlugin_Hypothesis_2D::GetDefaultQuadAllowed();
599 _fineness = NETGENPlugin_Hypothesis::GetDefaultFineness();
600 mparams.uselocalh = NETGENPlugin_Hypothesis::GetDefaultSurfaceCurvature();
601 netgen::merge_solids = NETGENPlugin_Hypothesis::GetDefaultFuseEdges();
605 mparams.nthreads = std::thread::hardware_concurrency();
607 if ( getenv( "SALOME_NETGEN_DISABLE_MULTITHREADING" ))
609 mparams.nthreads = 1;
610 mparams.parallel_meshing = false;
616 //=============================================================================
618 * Pass parameters to NETGEN
620 //=============================================================================
621 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp)
625 netgen::MeshingParameters& mparams = netgen::mparam;
626 // Initialize global NETGEN parameters:
627 // maximal mesh segment size
628 mparams.maxh = hyp->GetMaxSize();
629 // maximal mesh element linear size
630 mparams.minh = hyp->GetMinSize();
631 // minimal number of segments per edge
632 mparams.segmentsperedge = hyp->GetNbSegPerEdge();
633 // rate of growth of size between elements
634 mparams.grading = hyp->GetGrowthRate();
635 // safety factor for curvatures (elements per radius)
636 mparams.curvaturesafety = hyp->GetNbSegPerRadius();
637 // create elements of second order
638 mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0;
639 // quad-dominated surface meshing
640 mparams.quad = hyp->GetQuadAllowed() ? 1 : 0;
641 _optimize = hyp->GetOptimize();
642 _fineness = hyp->GetFineness();
643 mparams.uselocalh = hyp->GetSurfaceCurvature();
644 netgen::merge_solids = hyp->GetFuseEdges();
645 _chordalError = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.;
646 mparams.optsteps2d = _optimize ? hyp->GetNbSurfOptSteps() : 0;
647 mparams.optsteps3d = _optimize ? hyp->GetNbVolOptSteps() : 0;
648 mparams.elsizeweight = hyp->GetElemSizeWeight();
649 mparams.opterrpow = hyp->GetWorstElemMeasure();
650 mparams.delaunay = hyp->GetUseDelauney();
651 mparams.checkoverlap = hyp->GetCheckOverlapping();
652 mparams.checkchartboundary = hyp->GetCheckChartBoundary();
657 mparams.meshsizefilename = hyp->GetMeshSizeFile();
660 mparams.meshsizefilename= hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str();
662 const NETGENPlugin_Hypothesis::TLocalSize& localSizes = hyp->GetLocalSizesAndEntries();
663 if ( !localSizes.empty() )
665 SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen();
666 NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin();
667 for ( ; it != localSizes.end() ; it++)
669 std::string entry = (*it).first;
670 double val = (*it).second;
672 GEOM::GEOM_Object_var aGeomObj;
673 SALOMEDS::SObject_var aSObj = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( entry.c_str() );
674 if ( !aSObj->_is_nil() ) {
675 CORBA::Object_var obj = aSObj->GetObject();
676 aGeomObj = GEOM::GEOM_Object::_narrow(obj);
679 TopoDS_Shape S = smeshGen_i->GeomObjectToShape( aGeomObj.in() );
680 setLocalSize(S, val);
687 netgen::mparam.closeedgefac = 2;
692 //=============================================================================
694 * Pass simple parameters to NETGEN
696 //=============================================================================
698 void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* hyp)
702 SetDefaultParameters();
705 //================================================================================
707 * \brief Store a Viscous Layers hypothesis
709 //================================================================================
711 void NETGENPlugin_Mesher::SetParameters(const StdMeshers_ViscousLayers* hyp )
713 _viscousLayersHyp = hyp;
716 //================================================================================
718 * \brief Set local size on shapes defined by SetParameters()
720 //================================================================================
722 void NETGENPlugin_Mesher::SetLocalSize( netgen::OCCGeometry& occgeo,
723 netgen::Mesh& ngMesh)
726 std::map<int,double>::const_iterator it;
727 for( it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++)
729 int key = (*it).first;
730 double hi = (*it).second;
731 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
732 setLocalSize( TopoDS::Edge(shape), hi, ngMesh );
735 for(it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++)
737 int key = (*it).first;
738 double hi = (*it).second;
739 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
740 gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex(shape) );
741 NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, p.XYZ(), hi );
744 for(it=FaceId2LocalSize.begin(); it!=FaceId2LocalSize.end(); it++)
746 int key = (*it).first;
747 double val = (*it).second;
748 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
749 int faceNgID = occgeo.fmap.FindIndex(shape);
753 occgeo.SetFaceMaxH(faceNgID-1, val, netgen::mparam);
755 occgeo.SetFaceMaxH(faceNgID, val);
757 for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() )
758 setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, ngMesh );
760 else if ( !ShapesWithControlPoints.count( key ))
762 SMESHUtils::createPointsSampleFromFace( TopoDS::Face( shape ), val, ControlPoints );
763 ShapesWithControlPoints.insert( key );
767 for(it=SolidId2LocalSize.begin(); it!=SolidId2LocalSize.end(); it++)
769 int key = (*it).first;
770 double val = (*it).second;
771 if ( !ShapesWithControlPoints.count( key ))
773 const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key);
774 SMESHUtils::createPointsSampleFromSolid( TopoDS::Solid( shape ), val, ControlPoints );
775 ShapesWithControlPoints.insert( key );
779 if ( !ControlPoints.empty() )
781 for ( size_t i = 0; i < ControlPoints.size(); ++i )
782 NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, ControlPoints[i].XYZ(), ControlPoints[i].Size() );
787 //================================================================================
789 * \brief Restrict local size to achieve a required _chordalError
791 //================================================================================
793 void NETGENPlugin_Mesher::SetLocalSizeForChordalError( netgen::OCCGeometry& occgeo,
794 netgen::Mesh& ngMesh)
796 if ( _chordalError <= 0. )
800 BRepLProp_SLProps surfProp( 2, 1e-6 );
801 const double sizeCoef = 0.95;
803 // find non-planar FACEs with non-constant curvature
804 std::vector<int> fInd;
805 for ( int i = 1; i <= occgeo.fmap.Extent(); ++i )
807 const TopoDS_Face& face = TopoDS::Face( occgeo.fmap( i ));
808 BRepAdaptor_Surface surfAd( face, false );
809 switch ( surfAd.GetType() )
813 case GeomAbs_Cylinder:
815 case GeomAbs_Torus: // constant curvature
817 surfProp.SetSurface( surfAd );
818 surfProp.SetParameters( 0, 0 );
819 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
820 double size = elemSizeForChordalError( _chordalError, 1 / maxCurv );
822 occgeo.SetFaceMaxH( i-1, size * sizeCoef, netgen::mparam );
824 occgeo.SetFaceMaxH( i, size * sizeCoef );
826 // limit size one edges
827 TopTools_MapOfShape edgeMap;
828 for ( TopExp_Explorer eExp( face, TopAbs_EDGE ); eExp.More(); eExp.Next() )
829 if ( edgeMap.Add( eExp.Current() ))
830 setLocalSize( TopoDS::Edge( eExp.Current() ), size, ngMesh, /*overrideMinH=*/false );
834 Handle(Geom_Surface) surf = BRep_Tool::Surface( face, loc );
835 if ( GeomLib_IsPlanarSurface( surf ).IsPlanar() )
844 TopoDS_Compound allFacesComp;
845 b.MakeCompound( allFacesComp );
846 for ( size_t i = 0; i < fInd.size(); ++i )
847 b.Add( allFacesComp, occgeo.fmap( fInd[i] ));
849 // copy the shape to avoid spoiling its triangulation
850 TopoDS_Shape allFacesCompCopy = BRepBuilderAPI_Copy( allFacesComp );
852 // create triangulation with desired chordal error
853 BRepMesh_IncrementalMesh( allFacesCompCopy,
855 /*isRelative = */Standard_False,
856 /*theAngDeflection = */ 0.5,
857 /*isInParallel = */Standard_True);
860 for ( TopExp_Explorer fExp( allFacesCompCopy, TopAbs_FACE ); fExp.More(); fExp.Next() )
862 const TopoDS_Face& face = TopoDS::Face( fExp.Current() );
863 Handle(Poly_Triangulation) triangulation = BRep_Tool::Triangulation ( face, loc );
864 if ( triangulation.IsNull() ) continue;
866 BRepAdaptor_Surface surf( face, false );
867 surfProp.SetSurface( surf );
872 for ( int i = 1; i <= triangulation->NbTriangles(); ++i )
874 Standard_Integer n1,n2,n3;
875 triangulation->Triangles()(i).Get( n1,n2,n3 );
876 p [0] = triangulation->Nodes()(n1).Transformed(loc).XYZ();
877 p [1] = triangulation->Nodes()(n2).Transformed(loc).XYZ();
878 p [2] = triangulation->Nodes()(n3).Transformed(loc).XYZ();
879 uv[0] = triangulation->UVNodes()(n1).XY();
880 uv[1] = triangulation->UVNodes()(n2).XY();
881 uv[2] = triangulation->UVNodes()(n3).XY();
882 surfProp.SetParameters( uv[0].X(), uv[0].Y() );
883 if ( !surfProp.IsCurvatureDefined() )
886 for ( int n = 0; n < 3; ++n ) // get size at triangle nodes
888 surfProp.SetParameters( uv[n].X(), uv[n].Y() );
889 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
890 size[n] = elemSizeForChordalError( _chordalError, 1 / maxCurv );
892 for ( int n1 = 0; n1 < 3; ++n1 ) // limit size along each triangle edge
894 int n2 = ( n1 + 1 ) % 3;
895 double minSize = size[n1], maxSize = size[n2];
896 if ( size[n1] > size[n2] )
897 minSize = size[n2], maxSize = size[n1];
899 if ( maxSize / minSize < 1.2 ) // netgen ignores size difference < 1.2
901 ngMesh.RestrictLocalHLine ( netgen::Point3d( p[n1].X(), p[n1].Y(), p[n1].Z() ),
902 netgen::Point3d( p[n2].X(), p[n2].Y(), p[n2].Z() ),
903 sizeCoef * minSize );
907 gp_XY uvVec( uv[n2] - uv[n1] );
908 double len = ( p[n1] - p[n2] ).Modulus();
909 int nb = int( len / minSize ) + 1;
910 for ( int j = 0; j <= nb; ++j )
912 double r = double( j ) / nb;
913 gp_XY uvj = uv[n1] + r * uvVec;
915 surfProp.SetParameters( uvj.X(), uvj.Y() );
916 double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() ));
917 double h = elemSizeForChordalError( _chordalError, 1 / maxCurv );
919 const gp_Pnt& pj = surfProp.Value();
920 netgen::Point3d ngP( pj.X(), pj.Y(), pj.Z());
921 ngMesh.RestrictLocalH( ngP, h * sizeCoef );
930 //================================================================================
932 * \brief Initialize netgen::OCCGeometry with OCCT shape
934 //================================================================================
936 void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo,
937 const TopoDS_Shape& shape,
939 list< SMESH_subMesh* > * meshedSM,
940 NETGENPlugin_Internals* intern)
942 updateTriangulation( shape );
945 BRepBndLib::Add (shape, bb);
946 double x1,y1,z1,x2,y2,z2;
947 bb.Get (x1,y1,z1,x2,y2,z2);
948 netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1);
949 netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2);
950 occgeo.boundingbox = netgen::Box<3> (p1,p2);
952 occgeo.shape = shape;
955 // fill maps of shapes of occgeo with not yet meshed subshapes
957 // get root submeshes
958 list< SMESH_subMesh* > rootSM;
959 const int shapeID = mesh.GetMeshDS()->ShapeToIndex( shape );
960 if ( shapeID > 0 ) { // SMESH_subMesh with ID 0 may exist, don't use it!
961 rootSM.push_back( mesh.GetSubMesh( shape ));
964 for ( TopoDS_Iterator it( shape ); it.More(); it.Next() )
965 rootSM.push_back( mesh.GetSubMesh( it.Value() ));
970 // add subshapes of empty submeshes
971 list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end();
972 for ( ; rootIt != rootEnd; ++rootIt ) {
973 SMESH_subMesh * root = *rootIt;
974 SMESH_subMeshIteratorPtr smIt = root->getDependsOnIterator(/*includeSelf=*/true,
975 /*complexShapeFirst=*/true);
976 // to find a right orientation of subshapes (PAL20462)
977 TopTools_IndexedMapOfShape subShapes;
978 TopExp::MapShapes(root->GetSubShape(), subShapes);
979 while ( smIt->more() )
981 SMESH_subMesh* sm = smIt->next();
982 TopoDS_Shape shape = sm->GetSubShape();
983 totNbFaces += ( shape.ShapeType() == TopAbs_FACE );
984 if ( intern && intern->isShapeToPrecompute( shape ))
986 if ( !meshedSM || sm->IsEmpty() )
988 if ( shape.ShapeType() != TopAbs_VERTEX )
989 shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape
990 if ( shape.Orientation() >= TopAbs_INTERNAL )
991 shape.Orientation( TopAbs_FORWARD ); // issue 0020676
992 switch ( shape.ShapeType() ) {
993 case TopAbs_FACE : occgeo.fmap.Add( shape ); break;
994 case TopAbs_EDGE : occgeo.emap.Add( shape ); break;
995 case TopAbs_VERTEX: occgeo.vmap.Add( shape ); break;
996 case TopAbs_SOLID :occgeo.somap.Add( shape ); break;
1000 // collect submeshes of meshed shapes
1003 const int dim = SMESH_Gen::GetShapeDim( shape );
1004 meshedSM[ dim ].push_back( sm );
1008 occgeo.facemeshstatus.SetSize (totNbFaces);
1009 occgeo.facemeshstatus = 0;
1010 occgeo.face_maxh_modified.SetSize(totNbFaces);
1011 occgeo.face_maxh_modified = 0;
1012 occgeo.face_maxh.SetSize(totNbFaces);
1013 occgeo.face_maxh = netgen::mparam.maxh;
1016 //================================================================================
1018 * \brief Return a default min size value suitable for the given geometry.
1020 //================================================================================
1022 double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom,
1023 const double maxSize)
1025 updateTriangulation( geom );
1027 TopLoc_Location loc;
1029 const int* pi[4] = { &i1, &i2, &i3, &i1 };
1030 double minh = 1e100;
1032 TopExp_Explorer fExp( geom, TopAbs_FACE );
1033 for ( ; fExp.More(); fExp.Next() )
1035 Handle(Poly_Triangulation) triangulation =
1036 BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc);
1037 if ( triangulation.IsNull() ) continue;
1038 const double fTol = BRep_Tool::Tolerance( TopoDS::Face( fExp.Current() ));
1039 const TColgp_Array1OfPnt& points = triangulation->Nodes();
1040 const Poly_Array1OfTriangle& trias = triangulation->Triangles();
1041 for ( int iT = trias.Lower(); iT <= trias.Upper(); ++iT )
1043 trias(iT).Get( i1, i2, i3 );
1044 for ( int j = 0; j < 3; ++j )
1046 double dist2 = points(*pi[j]).SquareDistance( points( *pi[j+1] ));
1047 if ( dist2 < minh && fTol*fTol < dist2 )
1049 bb.Add( points(*pi[j]));
1053 if ( minh > 0.25 * bb.SquareExtent() ) // simple geometry, rough triangulation
1055 minh = 1e-3 * sqrt( bb.SquareExtent());
1056 //cout << "BND BOX minh = " <<minh << endl;
1060 minh = sqrt( minh ); // triangulation for visualization is rather fine
1061 //cout << "TRIANGULATION minh = " <<minh << endl;
1063 if ( minh > 0.5 * maxSize )
1064 minh = maxSize / 3.;
1069 //================================================================================
1071 * \brief Restrict size of elements at a given point
1073 //================================================================================
1075 void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh,
1078 const bool overrideMinH)
1080 if ( size <= std::numeric_limits<double>::min() )
1082 if ( netgen::mparam.minh > size )
1086 ngMesh.SetMinimalH( size );
1087 netgen::mparam.minh = size;
1091 size = netgen::mparam.minh;
1094 netgen::Point3d pi(p.X(), p.Y(), p.Z());
1095 ngMesh.RestrictLocalH( pi, size );
1098 //================================================================================
1100 * \brief fill ngMesh with nodes and elements of computed submeshes
1102 //================================================================================
1104 bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom,
1105 netgen::Mesh& ngMesh,
1106 vector<const SMDS_MeshNode*>& nodeVec,
1107 const list< SMESH_subMesh* > & meshedSM,
1108 SMESH_MesherHelper* quadHelper,
1109 SMESH_ProxyMesh::Ptr proxyMesh)
1111 TNode2IdMap nodeNgIdMap;
1112 for ( size_t i = 1; i < nodeVec.size(); ++i )
1113 nodeNgIdMap.insert( make_pair( nodeVec[i], i ));
1115 TopTools_MapOfShape visitedShapes;
1116 map< SMESH_subMesh*, set< int > > visitedEdgeSM2Faces;
1117 set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() );
1119 SMESH_MesherHelper helper (*_mesh);
1120 SMESHDS_Mesh* meshDS = _mesh->GetMeshDS();
1122 int faceNgID = ngMesh.GetNFD();
1124 list< SMESH_subMesh* >::const_iterator smIt, smEnd = meshedSM.end();
1125 for ( smIt = meshedSM.begin(); smIt != smEnd; ++smIt )
1127 SMESH_subMesh* sm = *smIt;
1128 if ( !visitedShapes.Add( sm->GetSubShape() ))
1131 const SMESHDS_SubMesh * smDS = sm->GetSubMeshDS();
1132 if ( !smDS ) continue;
1134 switch ( sm->GetSubShape().ShapeType() )
1136 case TopAbs_EDGE: { // EDGE
1137 // ----------------------
1138 TopoDS_Edge geomEdge = TopoDS::Edge( sm->GetSubShape() );
1139 if ( geomEdge.Orientation() >= TopAbs_INTERNAL )
1140 geomEdge.Orientation( TopAbs_FORWARD ); // issue 0020676
1142 // Add ng segments for each not meshed FACE the EDGE bounds
1143 PShapeIteratorPtr fIt = helper.GetAncestors( geomEdge, *sm->GetFather(), TopAbs_FACE );
1144 while ( const TopoDS_Shape * anc = fIt->next() )
1146 faceNgID = occgeom.fmap.FindIndex( *anc );
1148 continue; // meshed face
1150 int faceSMDSId = meshDS->ShapeToIndex( *anc );
1151 if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId ))
1152 continue; // already treated EDGE
1154 TopoDS_Face face = TopoDS::Face( occgeom.fmap( faceNgID ));
1155 if ( face.Orientation() >= TopAbs_INTERNAL )
1156 face.Orientation( TopAbs_FORWARD ); // issue 0020676
1158 // get all meshed EDGEs of the FACE connected to geomEdge (issue 0021140)
1159 helper.SetSubShape( face );
1160 list< TopoDS_Edge > edges = getConnectedEdges( geomEdge, face, computedSM, helper,
1161 visitedEdgeSM2Faces );
1162 if ( edges.empty() )
1163 continue; // wrong ancestor?
1165 // find out orientation of <edges> within <face>
1166 TopoDS_Edge eNotSeam = edges.front();
1167 if ( helper.HasSeam() )
1169 list< TopoDS_Edge >::iterator eIt = edges.begin();
1170 while ( helper.IsRealSeam( *eIt )) ++eIt;
1171 if ( eIt != edges.end() )
1174 TopAbs_Orientation fOri = helper.GetSubShapeOri( face, eNotSeam );
1175 bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL );
1177 // get all nodes from connected <edges>
1178 const bool skipMedium = netgen::mparam.secondorder;//smDS->IsQuadratic();
1179 StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, skipMedium, &helper );
1180 const vector<UVPtStruct>& points = fSide.GetUVPtStruct();
1181 if ( points.empty() )
1182 return false; // invalid node params?
1183 smIdType i, nbSeg = fSide.NbSegments();
1185 // remember EDGEs of fSide to treat only once
1186 for ( int iE = 0; iE < fSide.NbEdges(); ++iE )
1187 visitedEdgeSM2Faces[ helper.GetMesh()->GetSubMesh( fSide.Edge(iE )) ].insert(faceSMDSId);
1189 double otherSeamParam = 0;
1190 bool isSeam = false;
1194 int prevNgId = ngNodeId( points[0].node, ngMesh, nodeNgIdMap );
1196 for ( i = 0; i < nbSeg; ++i )
1198 const UVPtStruct& p1 = points[ i ];
1199 const UVPtStruct& p2 = points[ i+1 ];
1201 if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins
1204 if ( helper.IsRealSeam( p1.node->GetShapeID() ))
1206 TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
1207 isSeam = helper.IsRealSeam( e );
1210 otherSeamParam = helper.GetOtherParam( helper.GetPeriodicIndex() & 1 ? p2.u : p2.v );
1214 netgen::Segment seg;
1217 seg[1] = prevNgId = ngNodeId( p2.node, ngMesh, nodeNgIdMap );
1218 // node param on curve
1219 seg.epgeominfo[ 0 ].dist = p1.param;
1220 seg.epgeominfo[ 1 ].dist = p2.param;
1222 seg.epgeominfo[ 0 ].u = p1.u;
1223 seg.epgeominfo[ 0 ].v = p1.v;
1224 seg.epgeominfo[ 1 ].u = p2.u;
1225 seg.epgeominfo[ 1 ].v = p2.v;
1227 //geomEdge = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam )));
1228 //seg.epgeominfo[ 0 ].edgenr = seg.epgeominfo[ 1 ].edgenr = occgeom.emap.FindIndex( geomEdge );
1230 //seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
1231 seg.si = faceNgID; // = geom.fmap.FindIndex (face);
1232 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1233 ngMesh.AddSegment (seg);
1235 SMESH_TNodeXYZ np1( p1.node ), np2( p2.node );
1236 RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() );
1238 #ifdef DUMP_SEGMENTS
1239 cout << "Segment: " << seg.edgenr << " on SMESH face " << meshDS->ShapeToIndex( face ) << endl
1240 << "\tface index: " << seg.si << endl
1241 << "\tp1: " << seg[0] << endl
1242 << "\tp2: " << seg[1] << endl
1243 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
1244 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
1245 //<< "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
1246 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
1247 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl;
1248 //<< "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
1252 if ( helper.GetPeriodicIndex() && 1 ) {
1253 seg.epgeominfo[ 0 ].u = otherSeamParam;
1254 seg.epgeominfo[ 1 ].u = otherSeamParam;
1255 swap (seg.epgeominfo[0].v, seg.epgeominfo[1].v);
1257 seg.epgeominfo[ 0 ].v = otherSeamParam;
1258 seg.epgeominfo[ 1 ].v = otherSeamParam;
1259 swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u);
1261 swap( seg[0], seg[1] );
1262 swap( seg.epgeominfo[0].dist, seg.epgeominfo[1].dist );
1263 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1264 ngMesh.AddSegment( seg );
1265 #ifdef DUMP_SEGMENTS
1266 cout << "Segment: " << seg.edgenr << endl
1267 << "\t is SEAM (reverse) of the previous. "
1268 << " Other " << (helper.GetPeriodicIndex() && 1 ? "U" : "V")
1269 << " = " << otherSeamParam << endl;
1272 else if ( fOri == TopAbs_INTERNAL )
1274 swap( seg[0], seg[1] );
1275 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1276 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1277 ngMesh.AddSegment( seg );
1278 #ifdef DUMP_SEGMENTS
1279 cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl;
1283 } // loop on geomEdge ancestors
1285 if ( quadHelper ) // remember medium nodes of sub-meshes
1287 SMDS_ElemIteratorPtr edges = smDS->GetElements();
1288 while ( edges->more() )
1290 const SMDS_MeshElement* e = edges->next();
1291 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshEdge*>( e )))
1297 } // case TopAbs_EDGE
1299 case TopAbs_FACE: { // FACE
1300 // ----------------------
1301 const TopoDS_Face& geomFace = TopoDS::Face( sm->GetSubShape() );
1302 helper.SetSubShape( geomFace );
1303 bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL );
1305 // Find solids the geomFace bounds
1306 int solidID1 = 0, solidID2 = 0; // ng IDs
1307 int solidSMDSIDs[2] = { 0,0 }; // smds IDs
1309 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID);
1310 while ( const TopoDS_Shape * solid = solidIt->next() )
1312 int id = occgeom.somap.FindIndex ( *solid );
1313 if ( solidID1 && id != solidID1 ) solidID2 = id;
1315 if ( id ) solidSMDSIDs[ bool( solidSMDSIDs[0] )] = meshDS->ShapeToIndex( *solid );
1318 bool isShrunk = true;
1319 if ( proxyMesh && proxyMesh->GetProxySubMesh( geomFace ))
1321 // if a proxy sub-mesh contains temporary faces, then these faces
1322 // should be used to mesh only one SOLID
1323 smDS = proxyMesh->GetSubMesh( geomFace );
1324 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1325 while ( faces->more() )
1327 const SMDS_MeshElement* f = faces->next();
1328 if ( proxyMesh->IsTemporary( f ))
1331 if ( solidSMDSIDs[1] && proxyMesh->HasPrismsOnTwoSides( meshDS->MeshElements( geomFace )))
1334 solidSMDSIDs[1] = 0;
1335 std::vector<const SMDS_MeshNode*> fNodes( f->begin_nodes(), f->end_nodes() );
1336 std::vector<const SMDS_MeshElement*> vols;
1337 if ( meshDS->GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ) == 1 )
1339 int geomID = vols[0]->GetShapeID();
1340 const TopoDS_Shape& solid = meshDS->IndexToShape( geomID );
1341 if ( !solid.IsNull() )
1342 solidID1 = occgeom.somap.FindIndex ( solid );
1348 const int fID = occgeom.fmap.FindIndex( geomFace );
1349 if ( isShrunk ) // shrunk mesh
1351 // move netgen points according to moved nodes
1352 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true);
1353 while ( smIt->more() )
1355 SMESH_subMesh* sub = smIt->next();
1356 if ( !sub->GetSubMeshDS() ) continue;
1357 SMDS_NodeIteratorPtr nodeIt = sub->GetSubMeshDS()->GetNodes();
1358 while ( nodeIt->more() )
1360 const SMDS_MeshNode* n = nodeIt->next();
1361 int ngID = ngNodeId( n, ngMesh, nodeNgIdMap );
1362 netgen::MeshPoint& ngPoint = ngMesh.Point( ngID );
1363 ngPoint(0) = n->X();
1364 ngPoint(1) = n->Y();
1365 ngPoint(2) = n->Z();
1368 // remove faces near boundary to avoid their overlapping
1369 // with shrunk faces
1370 for ( int i = 1; i <= ngMesh.GetNSE(); ++i )
1372 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1373 if ( elem.GetIndex() == fID )
1375 for ( int iN = 0; iN < elem.GetNP(); ++iN )
1376 if ( ngMesh[ elem[ iN ]].Type() != netgen::SURFACEPOINT )
1378 ngMesh.DeleteSurfaceElement( i );
1384 // exclude faces generated by NETGEN from computation of 3D mesh
1388 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID,/*solid1=*/0,/*solid2=*/0,0 ));
1389 for (int i = 1; i <= ngMesh.GetNSE(); ++i )
1391 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
1392 if ( elem.GetIndex() == fID )
1393 const_cast< netgen::Element2d& >( elem ).SetIndex( faceNgID );
1399 solidSMDSIDs[1] = 0;
1401 const bool hasVLOn2Sides = ( solidSMDSIDs[1] > 0 && !isShrunk );
1403 // Add ng face descriptors of meshed faces
1405 if ( hasVLOn2Sides )
1407 // viscous layers are on two sides of the FACE
1408 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, 0, 0 ));
1410 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, 0, solidID2, 0 ));
1414 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, solidID2, 0 ));
1416 // if second oreder is required, even already meshed faces must be passed to NETGEN
1417 int fID = occgeom.fmap.Add( geomFace );
1418 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1419 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1420 while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy
1422 fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false ));
1423 if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID );
1424 occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK;
1426 // Problem with the second order in a quadrangular mesh remains.
1427 // 1) All quadrangles generated by NETGEN are moved to an inexistent face
1428 // by FillSMesh() (find "AddFaceDescriptor")
1429 // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor
1430 // are on faces where quadrangles were.
1431 // Due to these 2 points, wrong geom faces are used while conversion to quadratic
1432 // of the mentioned above quadrangles and triangles
1434 // Orient the face correctly in solidID1 (issue 0020206)
1435 bool reverse = false;
1437 TopoDS_Shape solid = occgeom.somap( solidID1 );
1438 TopAbs_Orientation faceOriInSolid = helper.GetSubShapeOri( solid, geomFace );
1439 if ( faceOriInSolid >= 0 )
1441 helper.IsReversedSubMesh( TopoDS::Face( geomFace.Oriented( faceOriInSolid )));
1444 // Add surface elements
1446 netgen::Element2d tri(3);
1447 tri.SetIndex( faceNgID );
1448 SMESH_TNodeXYZ xyz[3];
1450 #ifdef DUMP_TRIANGLES
1451 cout << "SMESH face " << meshDS->ShapeToIndex( geomFace )
1452 << " internal="<<isInternalFace << endl;
1455 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1456 while ( faces->more() )
1458 const SMDS_MeshElement* f = faces->next();
1459 if ( f->NbNodes() % 3 != 0 ) // not triangle
1461 PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace,*sm->GetFather(),TopAbs_SOLID);
1462 if ( const TopoDS_Shape * solid = solidIt->next() )
1463 sm = _mesh->GetSubMesh( *solid );
1464 SMESH_BadInputElements* badElems =
1465 new SMESH_BadInputElements( meshDS, COMPERR_BAD_INPUT_MESH, "Not triangle sub-mesh");
1467 sm->GetComputeError().reset( badElems );
1471 if ( hasVLOn2Sides )
1472 tri.SetIndex( getFaceNgID( f, solidSMDSIDs, faceNgID ));
1474 for ( int i = 0; i < 3; ++i )
1476 const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0;
1479 // get node UV on face
1480 int shapeID = node->GetShapeID();
1481 if ( helper.IsSeamShape( shapeID ))
1483 if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->GetShapeID() ))
1484 inFaceNode = f->GetNodeWrap( i-1 );
1486 inFaceNode = f->GetNodeWrap( i+1 );
1488 gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode );
1490 int ind = reverse ? 3-i : i+1;
1491 tri.GeomInfoPi(ind).u = uv.X();
1492 tri.GeomInfoPi(ind).v = uv.Y();
1493 tri.PNum (ind) = ngNodeId( node, ngMesh, nodeNgIdMap );
1496 // pass a triangle size to NG size-map
1497 double size = ( ( xyz[0] - xyz[1] ).Modulus() +
1498 ( xyz[1] - xyz[2] ).Modulus() +
1499 ( xyz[2] - xyz[0] ).Modulus() ) / 3;
1500 gp_XYZ gc = ( xyz[0] + xyz[1] + xyz[2] ) / 3;
1501 RestrictLocalSize( ngMesh, gc, size, /*overrideMinH=*/false );
1503 ngMesh.AddSurfaceElement (tri);
1504 #ifdef DUMP_TRIANGLES
1505 cout << tri << endl;
1508 if ( isInternalFace )
1510 swap( tri[1], tri[2] );
1511 ngMesh.AddSurfaceElement (tri);
1512 #ifdef DUMP_TRIANGLES
1513 cout << tri << endl;
1516 } // loop on sub-mesh faces
1518 if ( quadHelper ) // remember medium nodes of sub-meshes
1520 SMDS_ElemIteratorPtr faces = smDS->GetElements();
1521 while ( faces->more() )
1523 const SMDS_MeshElement* f = faces->next();
1524 if ( !quadHelper->AddTLinks( static_cast< const SMDS_MeshFace*>( f )))
1530 } // case TopAbs_FACE
1532 case TopAbs_VERTEX: { // VERTEX
1533 // --------------------------
1534 // issue 0021405. Add node only if a VERTEX is shared by a not meshed EDGE,
1535 // else netgen removes a free node and nodeVector becomes invalid
1536 PShapeIteratorPtr ansIt = helper.GetAncestors( sm->GetSubShape(),
1540 while ( const TopoDS_Shape* e = ansIt->next() )
1542 SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e );
1543 if (( toAdd = ( eSub->IsEmpty() && !SMESH_Algo::isDegenerated( TopoDS::Edge( *e )))))
1548 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
1549 if ( nodeIt->more() )
1550 ngNodeId( nodeIt->next(), ngMesh, nodeNgIdMap );
1556 } // loop on submeshes
1559 nodeVec.resize( ngMesh.GetNP() + 1 );
1560 TNode2IdMap::iterator node_NgId, nodeNgIdEnd = nodeNgIdMap.end();
1561 for ( node_NgId = nodeNgIdMap.begin(); node_NgId != nodeNgIdEnd; ++node_NgId)
1562 nodeVec[ node_NgId->second ] = node_NgId->first;
1567 //================================================================================
1569 * \brief Duplicate mesh faces on internal geom faces
1571 //================================================================================
1573 void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom,
1574 netgen::Mesh& ngMesh,
1575 NETGENPlugin_Internals& internalShapes)
1577 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1579 // find ng indices of internal faces
1581 for ( int ngFaceID = 1; ngFaceID <= occgeom.fmap.Extent(); ++ngFaceID )
1583 int smeshID = meshDS->ShapeToIndex( occgeom.fmap( ngFaceID ));
1584 if ( internalShapes.isInternalShape( smeshID ))
1585 ngFaceIds.insert( ngFaceID );
1587 if ( !ngFaceIds.empty() )
1590 int i, nbFaces = ngMesh.GetNSE();
1591 for ( i = 1; i <= nbFaces; ++i)
1593 netgen::Element2d elem = ngMesh.SurfaceElement(i);
1594 if ( ngFaceIds.count( elem.GetIndex() ))
1596 swap( elem[1], elem[2] );
1597 ngMesh.AddSurfaceElement (elem);
1603 //================================================================================
1605 * \brief Tries to heal the mesh on a FACE. The FACE is supposed to be partially
1606 * meshed due to NETGEN failure
1607 * \param [in] occgeom - geometry
1608 * \param [in,out] ngMesh - the mesh to fix
1609 * \param [inout] faceID - ID of the FACE to fix the mesh on
1610 * \return bool - is mesh is or becomes OK
1612 //================================================================================
1614 bool NETGENPlugin_Mesher::FixFaceMesh(const netgen::OCCGeometry& occgeom,
1615 netgen::Mesh& ngMesh,
1618 // we address a case where the FACE is almost fully meshed except small holes
1619 // of usually triangular shape at FACE boundary (IPAL52861)
1621 // The case appeared to be not simple: holes only look triangular but
1622 // indeed are a self intersecting polygon. A reason of the bug was in coincident
1623 // NG points on a seam edge. But the code below is very nice, leave it for
1628 if ( occgeom.fmap.Extent() < faceID )
1630 //const TopoDS_Face& face = TopoDS::Face( occgeom.fmap( faceID ));
1632 // find free links on the FACE
1634 for ( int iF = 1; iF <= ngMesh.GetNSE(); ++iF )
1636 const netgen::Element2d& elem = ngMesh.SurfaceElement(iF);
1637 if ( faceID != elem.GetIndex() )
1639 int n0 = elem[ elem.GetNP() - 1 ];
1640 for ( int i = 0; i < elem.GetNP(); ++i )
1643 Link link( n0, n1 );
1644 if ( !linkMap.Add( link ))
1645 linkMap.Remove( link );
1649 // add/remove boundary links
1650 for ( int iSeg = 1; iSeg <= ngMesh.GetNSeg(); ++iSeg )
1652 const netgen::Segment& seg = ngMesh.LineSegment( iSeg );
1653 if ( seg.si != faceID ) // !edgeIDs.Contains( seg.edgenr ))
1655 Link link( seg[1], seg[0] ); // reverse!!!
1656 if ( !linkMap.Add( link ))
1657 linkMap.Remove( link );
1659 if ( linkMap.IsEmpty() )
1661 if ( linkMap.Extent() < 3 )
1664 // make triangles of the links
1666 netgen::Element2d tri(3);
1667 tri.SetIndex ( faceID );
1669 TLinkMap::Iterator linkIt( linkMap );
1670 Link link1 = linkIt.Value();
1671 // look for a link connected to link1
1672 TLinkMap::Iterator linkIt2 = linkIt;
1673 for ( linkIt2.Next(); linkIt2.More(); linkIt2.Next() )
1675 const Link& link2 = linkIt2.Value();
1676 if ( link2.IsConnected( link1 ))
1678 // look for a link connected to both link1 and link2
1679 TLinkMap::Iterator linkIt3 = linkIt2;
1680 for ( linkIt3.Next(); linkIt3.More(); linkIt3.Next() )
1682 const Link& link3 = linkIt3.Value();
1683 if ( link3.IsConnected( link1 ) &&
1684 link3.IsConnected( link2 ) )
1689 tri[2] = ( link2.Contains( link1.n1 ) ? link2.n1 : link3.n1 );
1690 if ( tri[0] == tri[2] || tri[1] == tri[2] )
1692 ngMesh.AddSurfaceElement( tri );
1694 // prepare for the next tria search
1695 if ( linkMap.Extent() == 3 )
1697 linkMap.Remove( link3 );
1698 linkMap.Remove( link2 );
1700 linkMap.Remove( link1 );
1701 link1 = linkIt.Value();
1714 //================================================================================
1715 // define gp_XY_Subtracted pointer to function calling gp_XY::Subtracted(gp_XY)
1716 gp_XY_FunPtr(Subtracted);
1717 //gp_XY_FunPtr(Added);
1719 //================================================================================
1721 * \brief Evaluate distance between two 2d points along the surface
1723 //================================================================================
1725 double evalDist( const gp_XY& uv1,
1727 const Handle(Geom_Surface)& surf,
1728 const int stopHandler=-1)
1730 if ( stopHandler > 0 ) // continue recursion
1732 gp_XY mid = SMESH_MesherHelper::GetMiddleUV( surf, uv1, uv2 );
1733 return evalDist( uv1,mid, surf, stopHandler-1 ) + evalDist( mid,uv2, surf, stopHandler-1 );
1735 double dist3D = surf->Value( uv1.X(), uv1.Y() ).Distance( surf->Value( uv2.X(), uv2.Y() ));
1736 if ( stopHandler == 0 ) // stop recursion
1739 // start recursion if necessary
1740 double dist2D = SMESH_MesherHelper::ApplyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus();
1741 if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 )
1742 return dist3D; // equal parametrization of a planar surface
1744 return evalDist( uv1, uv2, surf, 3 ); // start recursion
1747 //================================================================================
1749 * \brief Data of vertex internal in geom face
1751 //================================================================================
1755 gp_XY uv; //!< UV in face parametric space
1756 int ngId; //!< ng id of corresponding node
1757 gp_XY uvClose; //!< UV of closest boundary node
1758 int ngIdClose; //!< ng id of closest boundary node
1761 //================================================================================
1763 * \brief Data of vertex internal in solid
1765 //================================================================================
1769 int ngId; //!< ng id of corresponding node
1770 int ngIdClose; //!< ng id of closest 2d mesh element
1771 int ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element
1774 inline double dist2( const netgen::MeshPoint& p1, const netgen::MeshPoint& p2 )
1776 return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2)));
1779 // inline double dist2(const netgen::MeshPoint& p, const SMDS_MeshNode* n )
1781 // return gp_Pnt( NGPOINT_COORDS(p)).SquareDistance( SMESH_NodeXYZ(n));
1785 //================================================================================
1787 * \brief Make netgen take internal vertices in faces into account by adding
1788 * segments including internal vertices
1790 * This function works in supposition that 1D mesh is already computed in ngMesh
1792 //================================================================================
1794 void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& occgeom,
1795 netgen::Mesh& ngMesh,
1796 vector<const SMDS_MeshNode*>& nodeVec,
1797 NETGENPlugin_Internals& internalShapes)
1799 if ((int) nodeVec.size() < ngMesh.GetNP() )
1800 nodeVec.resize( ngMesh.GetNP(), 0 );
1802 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1803 SMESH_MesherHelper helper( internalShapes.getMesh() );
1805 const map<int,list<int> >& face2Vert = internalShapes.getFacesWithVertices();
1806 map<int,list<int> >::const_iterator f2v = face2Vert.begin();
1807 for ( ; f2v != face2Vert.end(); ++f2v )
1809 const TopoDS_Face& face = TopoDS::Face( meshDS->IndexToShape( f2v->first ));
1810 if ( face.IsNull() ) continue;
1811 int faceNgID = occgeom.fmap.FindIndex (face);
1812 if ( faceNgID < 0 ) continue;
1814 TopLoc_Location loc;
1815 Handle(Geom_Surface) surf = BRep_Tool::Surface(face,loc);
1817 helper.SetSubShape( face );
1818 helper.SetElementsOnShape( true );
1820 // Get data of internal vertices and add them to ngMesh
1822 multimap< double, TIntVData > dist2VData; // sort vertices by distance from boundary nodes
1824 int i, nbSegInit = ngMesh.GetNSeg();
1826 // boundary characteristics
1827 double totSegLen2D = 0;
1830 const list<int>& iVertices = f2v->second;
1831 list<int>::const_iterator iv = iVertices.begin();
1832 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
1835 // get node on vertex
1836 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
1837 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
1840 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
1841 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
1842 nV = SMESH_Algo::VertexNode( V, meshDS );
1843 if ( !nV ) continue;
1846 netgen::MeshPoint mp( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
1847 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1848 vData.ngId = ngMesh.GetNP();
1849 nodeVec.push_back( nV );
1853 vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK );
1854 if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1);
1856 // loop on all segments of the face to find the node closest to vertex and to count
1857 // average segment 2d length
1858 double closeDist2 = numeric_limits<double>::max(), dist2;
1860 for (i = 1; i <= ngMesh.GetNSeg(); ++i)
1862 netgen::Segment & seg = ngMesh.LineSegment(i);
1863 if ( seg.si != faceNgID ) continue;
1865 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1867 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1868 if ( ngIdLast == seg[ iEnd ] ) continue;
1869 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1870 if ( dist2 < closeDist2 )
1871 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1872 ngIdLast = seg[ iEnd ];
1876 totSegLen2D += helper.ApplyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus();
1880 dist2VData.insert( make_pair( closeDist2, vData ));
1883 if ( totNbSeg == 0 ) break;
1884 double avgSegLen2d = totSegLen2D / totNbSeg;
1886 // Loop on vertices to add segments
1888 multimap< double, TIntVData >::iterator dist_vData = dist2VData.begin();
1889 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
1891 double closeDist2 = dist_vData->first, dist2;
1892 TIntVData & vData = dist_vData->second;
1894 // try to find more close node among segments added for internal vertices
1895 for (i = nbSegInit+1; i <= ngMesh.GetNSeg(); ++i)
1897 netgen::Segment & seg = ngMesh.LineSegment(i);
1898 if ( seg.si != faceNgID ) continue;
1900 for ( int iEnd = 0; iEnd < 2; ++iEnd)
1902 uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v );
1903 dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus();
1904 if ( dist2 < closeDist2 )
1905 vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2;
1908 // decide whether to use the closest node as the second end of segment or to
1909 // create a new point
1910 int segEnd1 = vData.ngId;
1911 int segEnd2 = vData.ngIdClose; // to use closest node
1912 gp_XY uvV = vData.uv, uvP = vData.uvClose;
1913 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
1914 double nodeDist2D = sqrt( closeDist2 );
1915 double nodeDist3D = evalDist( vData.uv, vData.uvClose, surf );
1916 bool avgLenOK = ( avgSegLen2d < 0.75 * nodeDist2D );
1917 bool hintLenOK = ( segLenHint < 0.75 * nodeDist3D );
1918 //cout << "uvV " << uvV.X() <<","<<uvV.Y() << " ";
1919 if ( hintLenOK || avgLenOK )
1921 // create a point between the closest node and V
1924 double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D ));
1925 // direction from V to closet node in 2D
1926 gp_Dir2d v2n( helper.ApplyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false ));
1928 uvP = vData.uv + r * nodeDist2D * v2n.XY();
1929 gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc );
1931 netgen::MeshPoint mp( netgen::Point<3> (P.X(), P.Y(), P.Z()));
1932 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
1933 segEnd2 = ngMesh.GetNP();
1934 //cout << "Middle " << r << " uv " << uvP.X() << "," << uvP.Y() << "( " << ngMesh.Point(segEnd2).X()<<","<<ngMesh.Point(segEnd2).Y()<<","<<ngMesh.Point(segEnd2).Z()<<" )"<< endl;
1935 SMDS_MeshNode * nP = helper.AddNode(P.X(), P.Y(), P.Z());
1936 nodeVec.push_back( nP );
1938 //else cout << "at Node " << " uv " << uvP.X() << "," << uvP.Y() << endl;
1941 netgen::Segment seg;
1943 if ( segEnd1 > segEnd2 ) swap( segEnd1, segEnd2 ), swap( uvV, uvP );
1944 seg[0] = segEnd1; // ng node id
1945 seg[1] = segEnd2; // ng node id
1946 seg.edgenr = ngMesh.GetNSeg() + 1;// segment id
1949 seg.epgeominfo[ 0 ].dist = 0; // param on curve
1950 seg.epgeominfo[ 0 ].u = uvV.X();
1951 seg.epgeominfo[ 0 ].v = uvV.Y();
1952 seg.epgeominfo[ 1 ].dist = 1; // param on curve
1953 seg.epgeominfo[ 1 ].u = uvP.X();
1954 seg.epgeominfo[ 1 ].v = uvP.Y();
1956 // seg.epgeominfo[ 0 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1957 // seg.epgeominfo[ 1 ].edgenr = 10; // = geom.emap.FindIndex(edge);
1959 ngMesh.AddSegment (seg);
1961 // add reverse segment
1962 swap( seg[0], seg[1] );
1963 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
1964 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
1965 ngMesh.AddSegment (seg);
1969 ngMesh.CalcSurfacesOfNode();
1972 //================================================================================
1974 * \brief Make netgen take internal vertices in solids into account by adding
1975 * faces including internal vertices
1977 * This function works in supposition that 2D mesh is already computed in ngMesh
1979 //================================================================================
1981 void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry& occgeom,
1982 netgen::Mesh& ngMesh,
1983 vector<const SMDS_MeshNode*>& nodeVec,
1984 NETGENPlugin_Internals& internalShapes)
1986 #ifdef DUMP_TRIANGLES_SCRIPT
1987 // create a python script making a mesh containing triangles added for internal vertices
1988 ofstream py(DUMP_TRIANGLES_SCRIPT);
1989 py << "import SMESH"<< endl
1990 << "from salome.smesh import smeshBuilder"<<endl
1991 << "smesh = smeshBuilder.New()"<<endl
1992 << "m = smesh.Mesh(name='triangles')" << endl;
1994 if ((int) nodeVec.size() < ngMesh.GetNP() )
1995 nodeVec.resize( ngMesh.GetNP(), 0 );
1997 SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS();
1998 SMESH_MesherHelper helper( internalShapes.getMesh() );
2000 const map<int,list<int> >& so2Vert = internalShapes.getSolidsWithVertices();
2001 map<int,list<int> >::const_iterator s2v = so2Vert.begin();
2002 for ( ; s2v != so2Vert.end(); ++s2v )
2004 const TopoDS_Shape& solid = meshDS->IndexToShape( s2v->first );
2005 if ( solid.IsNull() ) continue;
2006 int solidNgID = occgeom.somap.FindIndex (solid);
2007 if ( solidNgID < 0 && !occgeom.somap.IsEmpty() ) continue;
2009 helper.SetSubShape( solid );
2010 helper.SetElementsOnShape( true );
2012 // find ng indices of faces within the solid
2014 for (TopExp_Explorer fExp(solid, TopAbs_FACE); fExp.More(); fExp.Next() )
2015 ngFaceIds.insert( occgeom.fmap.FindIndex( fExp.Current() ));
2016 if ( ngFaceIds.size() == 1 && *ngFaceIds.begin() == 0 )
2017 ngFaceIds.insert( 1 );
2019 // Get data of internal vertices and add them to ngMesh
2021 multimap< double, TIntVSoData > dist2VData; // sort vertices by distance from ng faces
2023 int i, nbFaceInit = ngMesh.GetNSE();
2025 // boundary characteristics
2026 double totSegLen = 0;
2029 const list<int>& iVertices = s2v->second;
2030 list<int>::const_iterator iv = iVertices.begin();
2031 for ( int nbV = 0; iv != iVertices.end(); ++iv, nbV++ )
2034 const TopoDS_Vertex V = TopoDS::Vertex( meshDS->IndexToShape( *iv ));
2036 // get node on vertex
2037 const SMDS_MeshNode * nV = SMESH_Algo::VertexNode( V, meshDS );
2040 SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( V );
2041 sm->ComputeStateEngine( SMESH_subMesh::COMPUTE );
2042 nV = SMESH_Algo::VertexNode( V, meshDS );
2043 if ( !nV ) continue;
2046 netgen::MeshPoint mpV( netgen::Point<3> (nV->X(), nV->Y(), nV->Z()) );
2047 ngMesh.AddPoint ( mpV, 1, netgen::FIXEDPOINT );
2048 vData.ngId = ngMesh.GetNP();
2049 nodeVec.push_back( nV );
2051 // loop on all 2d elements to find the one closest to vertex and to count
2052 // average segment length
2053 double closeDist2 = numeric_limits<double>::max(), avgDist2;
2054 for (i = 1; i <= ngMesh.GetNSE(); ++i)
2056 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2057 if ( !ngFaceIds.count( elem.GetIndex() )) continue;
2059 multimap< double, int> dist2nID; // sort nodes of element by distance from V
2060 for ( int j = 0; j < elem.GetNP(); ++j)
2062 netgen::MeshPoint mp = ngMesh.Point( elem[j] );
2063 double d2 = dist2( mpV, mp );
2064 dist2nID.insert( make_pair( d2, elem[j] ));
2065 avgDist2 += d2 / elem.GetNP();
2067 totNbSeg++, totSegLen+= sqrt( dist2( mp, ngMesh.Point( elem[(j+1)%elem.GetNP()])));
2069 double dist = dist2nID.begin()->first; //avgDist2;
2070 if ( dist < closeDist2 )
2071 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= dist;
2073 dist2VData.insert( make_pair( closeDist2, vData ));
2076 if ( totNbSeg == 0 ) break;
2077 double avgSegLen = totSegLen / totNbSeg;
2079 // Loop on vertices to add triangles
2081 multimap< double, TIntVSoData >::iterator dist_vData = dist2VData.begin();
2082 for ( ; dist_vData != dist2VData.end(); ++dist_vData )
2084 double closeDist2 = dist_vData->first;
2085 TIntVSoData & vData = dist_vData->second;
2087 const netgen::MeshPoint& mpV = ngMesh.Point( vData.ngId );
2089 // try to find more close face among ones added for internal vertices
2090 for (i = nbFaceInit+1; i <= ngMesh.GetNSE(); ++i)
2092 double avgDist2 = 0;
2093 multimap< double, int> dist2nID;
2094 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2095 for ( int j = 0; j < elem.GetNP(); ++j)
2097 double d = dist2( mpV, ngMesh.Point( elem[j] ));
2098 dist2nID.insert( make_pair( d, elem[j] ));
2099 avgDist2 += d / elem.GetNP();
2100 if ( avgDist2 < closeDist2 )
2101 vData.ngIdClose= i, vData.ngIdCloseN= dist2nID.begin()->second, closeDist2= avgDist2;
2104 // sort nodes of the closest face by angle with vector from V to the closest node
2105 const double tol = numeric_limits<double>::min();
2106 map< double, int > angle2ID;
2107 const netgen::Element2d& closeFace = ngMesh.SurfaceElement( vData.ngIdClose );
2108 netgen::MeshPoint mp[2];
2109 mp[0] = ngMesh.Point( vData.ngIdCloseN );
2110 gp_XYZ p1( NGPOINT_COORDS( mp[0] ));
2111 gp_XYZ pV( NGPOINT_COORDS( mpV ));
2112 gp_Vec v2p1( pV, p1 );
2113 double distN1 = v2p1.Magnitude();
2114 if ( distN1 <= tol ) continue;
2116 for ( int j = 0; j < closeFace.GetNP(); ++j)
2118 mp[1] = ngMesh.Point( closeFace[j] );
2119 gp_Vec v2p( pV, gp_Pnt( NGPOINT_COORDS( mp[1] )) );
2120 angle2ID.insert( make_pair( v2p1.Angle( v2p ), closeFace[j]));
2122 // get node with angle of 60 degrees or greater
2123 map< double, int >::iterator angle_id = angle2ID.lower_bound( 60. * M_PI / 180. );
2124 if ( angle_id == angle2ID.end() ) angle_id = --angle2ID.end();
2125 const double minAngle = 30. * M_PI / 180.;
2126 const double angle = angle_id->first;
2127 bool angleOK = ( angle > minAngle );
2129 // find points to create a triangle
2130 netgen::Element2d tri(3);
2132 tri[0] = vData.ngId;
2133 tri[1] = vData.ngIdCloseN; // to use the closest nodes
2134 tri[2] = angle_id->second; // to use the node with best angle
2136 // decide whether to use the closest node and the node with best angle or to create new ones
2137 for ( int isBestAngleN = 0; isBestAngleN < 2; ++isBestAngleN )
2139 bool createNew = !angleOK; //, distOK = true;
2141 int triInd = isBestAngleN ? 2 : 1;
2142 mp[isBestAngleN] = ngMesh.Point( tri[triInd] );
2147 double distN2 = sqrt( dist2( mpV, mp[isBestAngleN]));
2148 createNew = ( fabs( distN2 - distN1 ) > 0.25 * distN1 );
2150 else if ( angle < tol )
2152 v2p1.SetX( v2p1.X() + 1e-3 );
2158 double segLenHint = ngMesh.GetH( ngMesh.Point( vData.ngId ));
2159 bool avgLenOK = ( avgSegLen < 0.75 * distN1 );
2160 bool hintLenOK = ( segLenHint < 0.75 * distN1 );
2161 createNew = (createNew || avgLenOK || hintLenOK );
2162 // we create a new node not closer than 0.5 to the closest face
2163 // in order not to clash with other close face
2164 double r = min( 0.5, ( hintLenOK ? segLenHint : avgSegLen ) / distN1 );
2165 distFromV = r * distN1;
2169 // create a new point, between the node and the vertex if angleOK
2170 gp_XYZ p( NGPOINT_COORDS( mp[isBestAngleN] ));
2171 gp_Vec v2p( pV, p ); v2p.Normalize();
2172 if ( isBestAngleN && !angleOK )
2173 p = p1 + gp_Dir( v2p.XYZ() - v2p1.XYZ()).XYZ() * distN1 * 0.95;
2175 p = pV + v2p.XYZ() * distFromV;
2177 if ( !isBestAngleN ) p1 = p, distN1 = distFromV;
2179 mp[isBestAngleN].SetPoint( netgen::Point<3> (p.X(), p.Y(), p.Z()));
2180 ngMesh.AddPoint ( mp[isBestAngleN], 1, netgen::SURFACEPOINT );
2181 tri[triInd] = ngMesh.GetNP();
2182 nodeVec.push_back( helper.AddNode( p.X(), p.Y(), p.Z()) );
2185 ngMesh.AddSurfaceElement (tri);
2186 swap( tri[1], tri[2] );
2187 ngMesh.AddSurfaceElement (tri);
2189 #ifdef DUMP_TRIANGLES_SCRIPT
2190 py << "n1 = m.AddNode( "<< mpV(0)<<", "<< mpV(1)<<", "<< mpV(2)<<") "<< endl
2191 << "n2 = m.AddNode( "<< mp[0](0)<<", "<< mp[0](1)<<", "<< mp[0](2)<<") "<< endl
2192 << "n3 = m.AddNode( "<< mp[1](0)<<", "<< mp[1](1)<<", "<< mp[1](2)<<" )" << endl
2193 << "m.AddFace([n1,n2,n3])" << endl;
2195 } // loop on internal vertices of a solid
2197 } // loop on solids with internal vertices
2200 //================================================================================
2202 * \brief Fill netgen mesh with segments of a FACE
2203 * \param ngMesh - netgen mesh
2204 * \param geom - container of OCCT geometry to mesh
2205 * \param wires - data of nodes on FACE boundary
2206 * \param helper - mesher helper holding the FACE
2207 * \param nodeVec - vector of nodes in which node index == netgen ID
2208 * \retval SMESH_ComputeErrorPtr - error description
2210 //================================================================================
2212 SMESH_ComputeErrorPtr
2213 NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh,
2214 netgen::OCCGeometry& geom,
2215 const TSideVector& wires,
2216 SMESH_MesherHelper& helper,
2217 vector< const SMDS_MeshNode* > & nodeVec,
2218 const bool overrideMinH)
2220 // ----------------------------
2221 // Check wires and count nodes
2222 // ----------------------------
2223 smIdType nbNodes = 0;
2224 for ( size_t iW = 0; iW < wires.size(); ++iW )
2226 StdMeshers_FaceSidePtr wire = wires[ iW ];
2227 if ( wire->MissVertexNode() )
2229 // Commented for issue 0020960. It worked for the case, let's wait for case where it doesn't.
2230 // It seems that there is no reason for this limitation
2232 // (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices"));
2234 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2235 if ((int) uvPtVec.size() != wire->NbPoints() )
2236 return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH,
2237 SMESH_Comment("Unexpected nb of points on wire ") << iW
2238 << ": " << uvPtVec.size()<<" != "<<wire->NbPoints());
2239 nbNodes += wire->NbPoints();
2241 nodeVec.reserve( nodeVec.size() + nbNodes + 1 );
2242 if ( nodeVec.empty() )
2243 nodeVec.push_back( 0 );
2245 // -----------------
2247 // -----------------
2249 const bool wasNgMeshEmpty = ( ngMesh.GetNP() < 1 ); /* true => this method is called by
2250 NETGENPlugin_NETGEN_2D_ONLY */
2252 // map for nodes on vertices since they can be shared between wires
2253 // ( issue 0020676, face_int_box.brep) and nodes built by NETGEN
2254 map<const SMDS_MeshNode*, int > node2ngID;
2255 if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN
2257 set< int > subIDs; // ids of sub-shapes of the FACE
2258 for ( size_t iW = 0; iW < wires.size(); ++iW )
2260 StdMeshers_FaceSidePtr wire = wires[ iW ];
2261 for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE )
2263 subIDs.insert( wire->EdgeID( iE ));
2264 subIDs.insert( helper.GetMeshDS()->ShapeToIndex( wire->FirstVertex( iE )));
2267 for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID )
2268 if ( subIDs.count( nodeVec[ngID]->GetShapeID() ))
2269 node2ngID.insert( make_pair( nodeVec[ngID], ngID ));
2272 const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() );
2273 if ( ngMesh.GetNFD() < 1 )
2274 ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceID, solidID, solidID, 0 ));
2276 for ( size_t iW = 0; iW < wires.size(); ++iW )
2278 StdMeshers_FaceSidePtr wire = wires[ iW ];
2279 const vector<UVPtStruct>& uvPtVec = wire->GetUVPtStruct();
2280 const smIdType nbSegments = wire->NbPoints() - 1;
2282 // assure the 1st node to be in node2ngID, which is needed to correctly
2283 // "close chain of segments" (see below) in case if the 1st node is not
2284 // onVertex because it is on a Viscous layer
2285 node2ngID.insert( make_pair( uvPtVec[ 0 ].node, ngMesh.GetNP() + 1 ));
2287 // compute length of every segment
2288 vector<double> segLen( nbSegments );
2289 for ( int i = 0; i < nbSegments; ++i )
2290 segLen[i] = SMESH_TNodeXYZ( uvPtVec[ i ].node ).Distance( uvPtVec[ i+1 ].node );
2292 int edgeID = 1, posID = -2;
2293 bool isInternalWire = false;
2294 double vertexNormPar = 0;
2295 const int prevNbNGSeg = ngMesh.GetNSeg();
2296 for ( int i = 0; i < nbSegments; ++i ) // loop on segments
2298 // Add the first point of a segment
2300 const SMDS_MeshNode * n = uvPtVec[ i ].node;
2301 const int posShapeID = n->GetShapeID();
2302 bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX );
2303 bool onEdge = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE );
2305 // skip nodes on degenerated edges
2306 if ( helper.IsDegenShape( posShapeID ) &&
2307 helper.IsDegenShape( uvPtVec[ i+1 ].node->GetShapeID() ))
2310 int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1;
2311 if ( onVertex || ( !wasNgMeshEmpty && onEdge ) || helper.IsRealSeam( posShapeID ))
2312 ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second;
2313 if ( ngID1 > ngMesh.GetNP() )
2315 netgen::MeshPoint mp( netgen::Point<3> (n->X(), n->Y(), n->Z()) );
2316 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2317 nodeVec.push_back( n );
2319 else // n is in ngMesh already, and ngID2 in prev segment is wrong
2321 ngID2 = ngMesh.GetNP() + 1;
2322 if ( i > 0 ) // prev segment belongs to same wire
2324 netgen::Segment& prevSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2331 netgen::Segment seg;
2333 seg[0] = ngID1; // ng node id
2334 seg[1] = ngID2; // ng node id
2335 seg.edgenr = ngMesh.GetNSeg() + 1; // ng segment id
2336 seg.si = faceID; // = geom.fmap.FindIndex (face);
2338 for ( int iEnd = 0; iEnd < 2; ++iEnd)
2340 const UVPtStruct& pnt = uvPtVec[ i + iEnd ];
2342 seg.epgeominfo[ iEnd ].dist = pnt.param; // param on curve
2343 seg.epgeominfo[ iEnd ].u = pnt.u;
2344 seg.epgeominfo[ iEnd ].v = pnt.v;
2346 // find out edge id and node parameter on edge
2347 onVertex = ( pnt.normParam + 1e-10 > vertexNormPar );
2348 if ( onVertex || posShapeID != posID )
2351 double normParam = pnt.normParam;
2353 normParam = 0.5 * ( uvPtVec[ i ].normParam + uvPtVec[ i+1 ].normParam );
2354 int edgeIndexInWire = wire->EdgeIndex( normParam );
2355 vertexNormPar = wire->LastParameter( edgeIndexInWire );
2356 const TopoDS_Edge& edge = wire->Edge( edgeIndexInWire );
2357 edgeID = geom.emap.FindIndex( edge );
2359 isInternalWire = ( edge.Orientation() == TopAbs_INTERNAL );
2360 // if ( onVertex ) // param on curve is different on each of two edges
2361 // seg.epgeominfo[ iEnd ].dist = helper.GetNodeU( edge, pnt.node );
2363 seg.epgeominfo[ iEnd ].edgenr = edgeID; // = geom.emap.FindIndex(edge);
2366 ngMesh.AddSegment (seg);
2368 // restrict size of elements near the segment
2369 SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node );
2370 // get an average size of adjacent segments to avoid sharp change of
2371 // element size (regression on issue 0020452, note 0010898)
2372 int iPrev = SMESH_MesherHelper::WrapIndex( i-1, (int) nbSegments );
2373 int iNext = SMESH_MesherHelper::WrapIndex( i+1, (int) nbSegments );
2374 double sumH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ];
2375 int nbSeg = ( int( segLen[ iPrev ] > sumH / 100.) +
2376 int( segLen[ i ] > sumH / 100.) +
2377 int( segLen[ iNext ] > sumH / 100.));
2379 RestrictLocalSize( ngMesh, 0.5*(np1+np2), sumH / nbSeg, overrideMinH );
2381 if ( isInternalWire )
2383 swap (seg[0], seg[1]);
2384 swap( seg.epgeominfo[0], seg.epgeominfo[1] );
2385 seg.edgenr = ngMesh.GetNSeg() + 1; // segment id
2386 ngMesh.AddSegment (seg);
2388 } // loop on segments on a wire
2390 // close chain of segments
2391 if ( nbSegments > 0 )
2393 netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire ));
2394 const SMDS_MeshNode * lastNode = uvPtVec.back().node;
2395 lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second;
2396 if ( lastSeg[1] > ngMesh.GetNP() )
2398 netgen::MeshPoint mp( netgen::Point<3> (lastNode->X(), lastNode->Y(), lastNode->Z()) );
2399 ngMesh.AddPoint ( mp, 1, netgen::EDGEPOINT );
2400 nodeVec.push_back( lastNode );
2402 if ( isInternalWire )
2404 netgen::Segment& realLastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() );
2405 realLastSeg[0] = lastSeg[1];
2409 #ifdef DUMP_SEGMENTS
2410 cout << "BEGIN WIRE " << iW << endl;
2411 for ( int i = prevNbNGSeg+1; i <= ngMesh.GetNSeg(); ++i )
2413 netgen::Segment& seg = ngMesh.LineSegment( i );
2415 netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 );
2416 if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] )
2418 cout << "Segment: " << seg.edgenr << endl << "\tis REVERSE of the previous one" << endl;
2422 cout << "Segment: " << seg.edgenr << endl
2423 << "\tp1: " << seg[0] << " n" << nodeVec[ seg[0]]->GetID() << endl
2424 << "\tp2: " << seg[1] << " n" << nodeVec[ seg[1]]->GetID() << endl
2425 << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl
2426 << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl
2427 << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl
2428 << "\tp1 param: " << seg.epgeominfo[ 1 ].dist << endl
2429 << "\tp1 uv: " << seg.epgeominfo[ 1 ].u <<", "<< seg.epgeominfo[ 1 ].v << endl
2430 << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl;
2432 cout << "--END WIRE " << iW << endl;
2434 SMESH_Comment __not_unused_variable( prevNbNGSeg );
2437 } // loop on WIREs of a FACE
2439 // add a segment instead of an internal vertex
2440 if ( wasNgMeshEmpty )
2442 NETGENPlugin_Internals intShapes( *helper.GetMesh(), helper.GetSubShape(), /*is3D=*/false );
2443 AddIntVerticesInFaces( geom, ngMesh, nodeVec, intShapes );
2445 ngMesh.CalcSurfacesOfNode();
2450 //================================================================================
2452 * \brief Fill SMESH mesh according to contents of netgen mesh
2453 * \param occgeo - container of OCCT geometry to mesh
2454 * \param ngMesh - netgen mesh
2455 * \param initState - bn of entities in netgen mesh before computing
2456 * \param sMesh - SMESH mesh to fill in
2457 * \param nodeVec - vector of nodes in which node index == netgen ID
2458 * \param comment - returns problem description
2459 * \param quadHelper - holder of medium nodes of sub-meshes
2460 * \retval int - error
2462 //================================================================================
2464 int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo,
2465 netgen::Mesh& ngMesh,
2466 const NETGENPlugin_ngMeshInfo& initState,
2468 std::vector<const SMDS_MeshNode*>& nodeVec,
2469 SMESH_Comment& comment,
2470 SMESH_MesherHelper* quadHelper)
2472 int nbNod = ngMesh.GetNP();
2473 int nbSeg = ngMesh.GetNSeg();
2474 int nbFac = ngMesh.GetNSE();
2475 int nbVol = ngMesh.GetNE();
2477 SMESHDS_Mesh* meshDS = sMesh.GetMeshDS();
2479 // quadHelper is used for either
2480 // 1) making quadratic elements when a lower dimension mesh is loaded
2481 // to SMESH before conversion to quadratic by NETGEN
2482 // 2) sewing of quadratic elements with quadratic elements of sub-meshes
2483 if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() )
2486 int ngID, nbInitNod = initState._nbNodes;
2487 if ( initState._elementsRemoved )
2489 // PAL23427. Update nodeVec to track removal of netgen free points as a result
2490 // of removal of faces in FillNgMesh() in the case of a shrunk sub-mesh
2491 size_t i, nodeVecSize = nodeVec.size();
2492 const double eps = std::numeric_limits<double>::min();
2493 for ( i = ngID = 1; i < nodeVecSize; ++ngID, ++i )
2495 gp_Pnt ngPnt( NGPOINT_COORDS( ngMesh.Point( ngID )));
2496 gp_Pnt node ( SMESH_NodeXYZ (nodeVec_ACCESS(i) ));
2497 if ( ngPnt.SquareDistance( node ) < eps )
2499 nodeVec[ ngID ] = nodeVec[ i ];
2506 nodeVec.resize( ngID );
2507 nbInitNod = ngID - 1;
2509 // -------------------------------------
2510 // Create and insert nodes into nodeVec
2511 // -------------------------------------
2513 if ( nbNod > nbInitNod )
2514 nodeVec.resize( nbNod + 1 );
2515 for ( int i = nbInitNod+1; i <= nbNod; ++i )
2517 const netgen::MeshPoint& ngPoint = ngMesh.Point(i);
2518 SMDS_MeshNode* node = NULL;
2519 TopoDS_Vertex aVert;
2520 // First, netgen creates nodes on vertices in occgeo.vmap,
2521 // so node index corresponds to vertex index
2522 // but (issue 0020776) netgen does not create nodes with equal coordinates
2523 if ( i-nbInitNod <= occgeo.vmap.Extent() )
2525 gp_Pnt p ( NGPOINT_COORDS(ngPoint) );
2526 for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV)
2528 aVert = TopoDS::Vertex( occgeo.vmap( iV ));
2529 gp_Pnt pV = BRep_Tool::Pnt( aVert );
2530 if ( p.SquareDistance( pV ) > 1e-20 )
2533 node = const_cast<SMDS_MeshNode*>( SMESH_Algo::VertexNode( aVert, meshDS ));
2536 if (!node) // node not found on vertex
2538 node = meshDS->AddNode( NGPOINT_COORDS( ngPoint ));
2539 if (!aVert.IsNull())
2540 meshDS->SetNodeOnVertex(node, aVert);
2545 // -------------------------------------------
2546 // Create mesh segments along geometric edges
2547 // -------------------------------------------
2549 int nbInitSeg = initState._nbSegments;
2550 for ( int i = nbInitSeg+1; i <= nbSeg; ++i )
2552 const netgen::Segment& seg = ngMesh.LineSegment(i);
2554 int pinds[3] = { seg.pnums[0], seg.pnums[1], seg.pnums[2] };
2557 for (int j=0; j < 3; ++j)
2559 int pind = pinds[j];
2560 if (pind <= 0 || !nodeVec_ACCESS(pind))
2568 int aGeomEdgeInd = seg.epgeominfo[j].edgenr;
2569 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
2570 aEdge = TopoDS::Edge(occgeo.emap(aGeomEdgeInd));
2572 param = seg.epgeominfo[j].dist;
2575 else // middle point
2577 param = param2 * 0.5;
2579 if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->GetShapeID() < 1)
2581 meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param);
2586 SMDS_MeshEdge* edge = 0;
2587 if (nbp == 2) // second order ?
2589 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1])))
2591 if ( quadHelper ) // final mesh must be quadratic
2592 edge = quadHelper->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2594 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]));
2598 if ( meshDS->FindEdge( nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2599 nodeVec_ACCESS(pinds[2])))
2601 edge = meshDS->AddEdge(nodeVec_ACCESS(pinds[0]), nodeVec_ACCESS(pinds[1]),
2602 nodeVec_ACCESS(pinds[2]));
2606 if ( comment.empty() ) comment << "Cannot create a mesh edge";
2607 MESSAGE("Cannot create a mesh edge");
2608 nbSeg = nbFac = nbVol = 0;
2611 if ( !aEdge.IsNull() && edge->GetShapeID() < 1 )
2612 meshDS->SetMeshElementOnShape(edge, aEdge);
2614 else if ( comment.empty() )
2616 comment << "Invalid netgen segment #" << i;
2620 // ----------------------------------------
2621 // Create mesh faces along geometric faces
2622 // ----------------------------------------
2624 int nbInitFac = initState._nbFaces;
2625 int quadFaceID = ngMesh.GetNFD() + 1;
2626 if ( nbInitFac < nbFac )
2627 // add a faces descriptor to exclude qudrangle elements generated by NETGEN
2628 // from computation of 3D mesh
2629 ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0));
2631 vector<const SMDS_MeshNode*> nodes;
2632 for ( int i = nbInitFac+1; i <= nbFac; ++i )
2634 const netgen::Element2d& elem = ngMesh.SurfaceElement(i);
2635 const int aGeomFaceInd = elem.GetIndex();
2637 if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent())
2638 aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd));
2640 for ( int j = 1; j <= elem.GetNP(); ++j )
2642 int pind = elem.PNum(j);
2643 if ( pind < 1 || pind >= (int) nodeVec.size() )
2645 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind))
2647 nodes.push_back( node );
2648 if (!aFace.IsNull() && node->GetShapeID() < 1)
2650 const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j);
2651 meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v);
2655 if ((int) nodes.size() != elem.GetNP() )
2657 if ( comment.empty() )
2658 comment << "Invalid netgen 2d element #" << i;
2659 continue; // bad node ids
2661 SMDS_MeshFace* face = NULL;
2662 switch (elem.GetType())
2665 if ( quadHelper ) // final mesh must be quadratic
2666 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2]);
2668 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2]);
2671 if ( quadHelper ) // final mesh must be quadratic
2672 face = quadHelper->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2674 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3]);
2675 // exclude qudrangle elements from computation of 3D mesh
2676 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2679 nodes[5] = mediumNode( nodes[0],nodes[1],nodes[5], quadHelper );
2680 nodes[3] = mediumNode( nodes[1],nodes[2],nodes[3], quadHelper );
2681 nodes[4] = mediumNode( nodes[2],nodes[0],nodes[4], quadHelper );
2682 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[5],nodes[3],nodes[4]);
2685 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2686 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2687 nodes[5] = mediumNode( nodes[2],nodes[3],nodes[5], quadHelper );
2688 nodes[6] = mediumNode( nodes[3],nodes[0],nodes[6], quadHelper );
2689 face = meshDS->AddFace(nodes[0],nodes[1],nodes[2],nodes[3],
2690 nodes[4],nodes[7],nodes[5],nodes[6]);
2691 // exclude qudrangle elements from computation of 3D mesh
2692 const_cast< netgen::Element2d& >( elem ).SetIndex( quadFaceID );
2695 MESSAGE("NETGEN created a face of unexpected type, ignoring");
2700 if ( comment.empty() ) comment << "Cannot create a mesh face";
2701 MESSAGE("Cannot create a mesh face");
2702 nbSeg = nbFac = nbVol = 0;
2705 if ( !aFace.IsNull() )
2706 meshDS->SetMeshElementOnShape( face, aFace );
2709 // ------------------
2710 // Create tetrahedra
2711 // ------------------
2713 for ( int i = 1; i <= nbVol; ++i )
2715 const netgen::Element& elem = ngMesh.VolumeElement(i);
2716 int aSolidInd = elem.GetIndex();
2717 TopoDS_Solid aSolid;
2718 if ( aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent() )
2719 aSolid = TopoDS::Solid(occgeo.somap(aSolidInd));
2721 for ( int j = 1; j <= elem.GetNP(); ++j )
2723 int pind = elem.PNum(j);
2724 if ( pind < 1 || pind >= (int)nodeVec.size() )
2726 if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) )
2728 nodes.push_back(node);
2729 if ( !aSolid.IsNull() && node->GetShapeID() < 1 )
2730 meshDS->SetNodeInVolume(node, aSolid);
2733 if ((int) nodes.size() != elem.GetNP() )
2735 if ( comment.empty() )
2736 comment << "Invalid netgen 3d element #" << i;
2739 SMDS_MeshVolume* vol = NULL;
2740 switch ( elem.GetType() )
2743 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]);
2746 nodes[4] = mediumNode( nodes[0],nodes[1],nodes[4], quadHelper );
2747 nodes[7] = mediumNode( nodes[1],nodes[2],nodes[7], quadHelper );
2748 nodes[5] = mediumNode( nodes[2],nodes[0],nodes[5], quadHelper );
2749 nodes[6] = mediumNode( nodes[0],nodes[3],nodes[6], quadHelper );
2750 nodes[8] = mediumNode( nodes[1],nodes[3],nodes[8], quadHelper );
2751 nodes[9] = mediumNode( nodes[2],nodes[3],nodes[9], quadHelper );
2752 vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3],
2753 nodes[4],nodes[7],nodes[5],nodes[6],nodes[8],nodes[9]);
2756 MESSAGE("NETGEN created a volume of unexpected type, ignoring");
2761 if ( comment.empty() ) comment << "Cannot create a mesh volume";
2762 MESSAGE("Cannot create a mesh volume");
2763 nbSeg = nbFac = nbVol = 0;
2766 if (!aSolid.IsNull())
2767 meshDS->SetMeshElementOnShape(vol, aSolid);
2769 return comment.empty() ? 0 : 1;
2774 //================================================================================
2776 * \brief Convert error into text
2778 //================================================================================
2780 std::string text(int err)
2785 SMESH_Comment("Error in netgen::OCCGenerateMesh() at ") << netgen::multithread.task;
2788 //================================================================================
2790 * \brief Convert exception into text
2792 //================================================================================
2794 std::string text(Standard_Failure& ex)
2796 SMESH_Comment str("Exception in netgen::OCCGenerateMesh()");
2797 str << " at " << netgen::multithread.task
2798 << ": " << ex.DynamicType()->Name();
2799 if ( ex.GetMessageString() && strlen( ex.GetMessageString() ))
2800 str << ": " << ex.GetMessageString();
2803 //================================================================================
2805 * \brief Convert exception into text
2807 //================================================================================
2809 std::string text(netgen::NgException& ex)
2811 SMESH_Comment str("NgException");
2812 if ( strlen( netgen::multithread.task ) > 0 )
2813 str << " at " << netgen::multithread.task;
2814 str << ": " << ex.What();
2818 //================================================================================
2820 * \brief Looks for triangles lying on a SOLID
2822 //================================================================================
2824 bool hasBadElemOnSolid( const list<const SMDS_MeshElement*>& elems,
2825 SMESH_subMesh* solidSM )
2827 TopTools_IndexedMapOfShape solidSubs;
2828 TopExp::MapShapes( solidSM->GetSubShape(), solidSubs );
2829 SMESHDS_Mesh* mesh = solidSM->GetFather()->GetMeshDS();
2831 list<const SMDS_MeshElement*>::const_iterator e = elems.begin();
2832 for ( ; e != elems.end(); ++e )
2834 const SMDS_MeshElement* elem = *e;
2835 // if ( elem->GetType() != SMDSAbs_Face ) -- 23047
2837 int nbNodesOnSolid = 0, nbNodes = elem->NbNodes();
2838 SMDS_NodeIteratorPtr nIt = elem->nodeIterator();
2839 while ( nIt->more() )
2841 const SMDS_MeshNode* n = nIt->next();
2842 const TopoDS_Shape& s = mesh->IndexToShape( n->GetShapeID() );
2843 nbNodesOnSolid += ( !s.IsNull() && solidSubs.Contains( s ));
2844 if ( nbNodesOnSolid > 2 ||
2845 nbNodesOnSolid == nbNodes)
2852 const double edgeMeshingTime = 0.001;
2853 const double faceMeshingTime = 0.019;
2854 const double edgeFaceMeshingTime = edgeMeshingTime + faceMeshingTime;
2855 const double faceOptimizTime = 0.06;
2856 const double voluMeshingTime = 0.15;
2857 const double volOptimizeTime = 0.77;
2860 //=============================================================================
2862 * Here we are going to use the NETGEN mesher
2864 //=============================================================================
2866 bool NETGENPlugin_Mesher::Compute()
2868 NETGENPlugin_NetgenLibWrapper ngLib;
2870 netgen::MeshingParameters& mparams = netgen::mparam;
2872 SMESH_ComputeErrorPtr error = SMESH_ComputeError::New();
2873 SMESH_MesherHelper quadHelper( *_mesh );
2874 quadHelper.SetIsQuadratic( mparams.secondorder );
2876 // -------------------------
2877 // Prepare OCC geometry
2878 // -------------------------
2880 netgen::OCCGeometry occgeo;
2881 list< SMESH_subMesh* > meshedSM[3]; // for 0-2 dimensions
2882 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
2883 PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals );
2886 _totalTime = edgeFaceMeshingTime;
2888 _totalTime += faceOptimizTime;
2890 _totalTime += voluMeshingTime + ( _optimize ? volOptimizeTime : 0 );
2891 double doneTime = 0;
2894 _curShapeIndex = -1;
2896 // -------------------------
2897 // Generate the mesh
2898 // -------------------------
2901 NETGENPlugin_ngMeshInfo initState; // it remembers size of ng mesh equal to size of Smesh
2903 SMESH_Comment comment;
2906 // vector of nodes in which node index == netgen ID
2907 vector< const SMDS_MeshNode* > nodeVec;
2915 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
2916 mparams.uselocalh = false;
2917 mparams.grading = 0.8; // not limitited size growth
2919 if ( _simpleHyp->GetNumberOfSegments() )
2921 mparams.maxh = occgeo.boundingbox.Diam();
2924 mparams.maxh = _simpleHyp->GetLocalLength();
2927 if ( mparams.maxh == 0.0 )
2928 mparams.maxh = occgeo.boundingbox.Diam();
2929 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
2930 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
2932 // Local size on faces
2933 occgeo.face_maxh = mparams.maxh;
2935 // Let netgen create _ngMesh and calculate element size on not meshed shapes
2936 int startWith = netgen::MESHCONST_ANALYSE;
2937 int endWith = netgen::MESHCONST_ANALYSE;
2942 err = ngLib.GenerateMesh(occgeo, startWith, endWith, _ngMesh);
2944 if(netgen::multithread.terminate)
2947 comment << text(err);
2949 catch (Standard_Failure& ex)
2951 comment << text(ex);
2953 catch (netgen::NgException & ex)
2955 comment << text(ex);
2957 bool hasSizeFile = !mparams.meshsizefilename.empty();
2959 bool hasSizeFile = mparams.meshsizefilename;
2962 throw SMESH_ComputeError(COMPERR_BAD_PARMETERS, comment );
2964 err = 0; //- MESHCONST_ANALYSE isn't so important step
2967 ngLib.setMesh(( Ng_Mesh*) _ngMesh );
2969 _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self
2971 if ( !mparams.uselocalh ) // mparams.grading is not taken into account yet
2972 _ngMesh->LocalHFunction().SetGrading( mparams.grading );
2976 // Pass 1D simple parameters to NETGEN
2977 // --------------------------------
2978 double nbSeg = (double) _simpleHyp->GetNumberOfSegments();
2979 double segSize = _simpleHyp->GetLocalLength();
2980 for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
2982 const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
2984 segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
2985 setLocalSize( e, segSize, *_ngMesh );
2988 else // if ( ! _simpleHyp )
2990 // Local size on shapes
2991 SetLocalSize( occgeo, *_ngMesh );
2992 SetLocalSizeForChordalError( occgeo, *_ngMesh );
2995 // Precompute internal edges (issue 0020676) in order to
2996 // add mesh on them correctly (twice) to netgen mesh
2997 if ( !err && internals.hasInternalEdges() )
2999 // load internal shapes into OCCGeometry
3000 netgen::OCCGeometry intOccgeo;
3001 internals.getInternalEdges( intOccgeo.fmap, intOccgeo.emap, intOccgeo.vmap, meshedSM );
3002 intOccgeo.boundingbox = occgeo.boundingbox;
3003 intOccgeo.shape = occgeo.shape;
3004 intOccgeo.face_maxh.SetSize(intOccgeo.fmap.Extent());
3005 intOccgeo.face_maxh = netgen::mparam.maxh;
3006 netgen::Mesh *tmpNgMesh = NULL;
3010 // compute local H on internal shapes in the main mesh
3011 //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH
3013 // let netgen create a temporary mesh
3014 ngLib.GenerateMesh(intOccgeo, startWith, endWith, tmpNgMesh);
3016 if ( netgen::multithread.terminate )
3019 // copy LocalH from the main to temporary mesh
3020 initState.transferLocalH( _ngMesh, tmpNgMesh );
3022 // compute mesh on internal edges
3023 startWith = endWith = netgen::MESHCONST_MESHEDGES;
3024 err = ngLib.GenerateMesh(intOccgeo, startWith, endWith, tmpNgMesh);
3026 comment << text(err);
3028 catch (Standard_Failure& ex)
3030 comment << text(ex);
3033 initState.restoreLocalH( tmpNgMesh );
3035 // fill SMESH by netgen mesh
3036 vector< const SMDS_MeshNode* > tmpNodeVec;
3037 FillSMesh( intOccgeo, *tmpNgMesh, initState, *_mesh, tmpNodeVec, comment );
3038 err = ( err || !comment.empty() );
3040 nglib::Ng_DeleteMesh((nglib::Ng_Mesh*)tmpNgMesh);
3043 // Fill _ngMesh with nodes and segments of computed submeshes
3046 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_0D ]) &&
3047 FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_1D ], &quadHelper));
3049 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3054 startWith = endWith = netgen::MESHCONST_MESHEDGES;
3059 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3061 if ( netgen::multithread.terminate )
3064 comment << text(err);
3066 catch (Standard_Failure& ex)
3068 comment << text(ex);
3073 _ticTime = ( doneTime += edgeMeshingTime ) / _totalTime / _progressTic;
3075 mparams.uselocalh = true; // restore as it is used at surface optimization
3077 // ---------------------
3078 // compute surface mesh
3079 // ---------------------
3082 // Pass 2D simple parameters to NETGEN
3084 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3086 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3087 mparams.grading = 0.4; // moderate size growth
3090 // length from edges
3091 if ( _ngMesh->GetNSeg() ) {
3092 double edgeLength = 0;
3093 TopTools_MapOfShape visitedEdges;
3094 for ( TopExp_Explorer exp( _shape, TopAbs_EDGE ); exp.More(); exp.Next() )
3095 if( visitedEdges.Add(exp.Current()) )
3096 edgeLength += SMESH_Algo::EdgeLength( TopoDS::Edge( exp.Current() ));
3097 // we have to multiply length by 2 since for each TopoDS_Edge there
3098 // are double set of NETGEN edges, in other words, we have to
3099 // divide _ngMesh->GetNSeg() by 2.
3100 mparams.maxh = 2*edgeLength / _ngMesh->GetNSeg();
3103 mparams.maxh = 1000;
3105 mparams.grading = 0.2; // slow size growth
3107 mparams.quad = _simpleHyp->GetAllowQuadrangles();
3108 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3109 _ngMesh->SetGlobalH (mparams.maxh);
3110 netgen::Box<3> bb = occgeo.GetBoundingBox();
3111 bb.Increase (bb.Diam()/20);
3112 _ngMesh->SetLocalH (bb.PMin(), bb.PMax(), mparams.grading);
3115 // Care of vertices internal in faces (issue 0020676)
3116 if ( internals.hasInternalVertexInFace() )
3118 // store computed segments in SMESH in order not to create SMESH
3119 // edges for ng segments added by AddIntVerticesInFaces()
3120 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
3121 // add segments to faces with internal vertices
3122 AddIntVerticesInFaces( occgeo, *_ngMesh, nodeVec, internals );
3123 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3126 // Build viscous layers
3127 if (( _isViscousLayers2D ) ||
3128 ( !occgeo.fmap.IsEmpty() &&
3129 StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( occgeo.fmap(1) ), *_mesh )))
3131 if ( !internals.hasInternalVertexInFace() ) {
3132 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment );
3133 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3135 SMESH_ProxyMesh::Ptr viscousMesh;
3136 SMESH_MesherHelper helper( *_mesh );
3137 for ( int faceID = 1; faceID <= occgeo.fmap.Extent(); ++faceID )
3139 const TopoDS_Face& F = TopoDS::Face( occgeo.fmap( faceID ));
3140 viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F );
3143 if ( viscousMesh->NbProxySubMeshes() == 0 )
3145 // exclude from computation ng segments built on EDGEs of F
3146 for (int i = 1; i <= _ngMesh->GetNSeg(); i++)
3148 netgen::Segment & seg = _ngMesh->LineSegment(i);
3149 if (seg.si == faceID)
3152 // add new segments to _ngMesh instead of excluded ones
3153 helper.SetSubShape( F );
3155 StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true,
3156 error, &helper, viscousMesh );
3157 error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec );
3159 if ( !error ) error = SMESH_ComputeError::New();
3161 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3164 // Let netgen compute 2D mesh
3165 startWith = netgen::MESHCONST_MESHSURFACE;
3166 endWith = _optimize ? netgen::MESHCONST_OPTSURFACE : netgen::MESHCONST_MESHSURFACE;
3171 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3173 if ( netgen::multithread.terminate )
3176 comment << text (err);
3178 catch (Standard_Failure& ex)
3180 comment << text(ex);
3181 //err = 1; -- try to make volumes anyway
3183 catch (netgen::NgException& exc)
3185 comment << text(exc);
3186 //err = 1; -- try to make volumes anyway
3191 doneTime += faceMeshingTime + ( _optimize ? faceOptimizTime : 0 );
3192 _ticTime = doneTime / _totalTime / _progressTic;
3194 // ---------------------
3195 // generate volume mesh
3196 // ---------------------
3197 // Fill _ngMesh with nodes and faces of computed 2D submeshes
3198 if ( !err && _isVolume &&
3199 ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad || _viscousLayersHyp ))
3201 // load SMESH with computed segments and faces
3202 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3204 // compute prismatic boundary volumes
3205 smIdType nbQuad = _mesh->NbQuadrangles();
3206 SMESH_ProxyMesh::Ptr viscousMesh;
3207 if ( _viscousLayersHyp )
3209 viscousMesh = _viscousLayersHyp->Compute( *_mesh, _shape );
3213 // compute pyramids on quadrangles
3214 vector<SMESH_ProxyMesh::Ptr> pyramidMeshes( occgeo.somap.Extent() );
3216 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
3218 StdMeshers_QuadToTriaAdaptor* adaptor = new StdMeshers_QuadToTriaAdaptor;
3219 pyramidMeshes[ iS-1 ].reset( adaptor );
3220 bool ok = adaptor->Compute( *_mesh, occgeo.somap(iS), viscousMesh.get() );
3224 // add proxy faces to NG mesh
3225 list< SMESH_subMesh* > viscousSM;
3226 for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS )
3228 list< SMESH_subMesh* > quadFaceSM;
3229 for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next())
3230 if ( pyramidMeshes[iS-1] && pyramidMeshes[iS-1]->GetProxySubMesh( face.Current() ))
3232 quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() ));
3233 meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() );
3235 else if ( viscousMesh && viscousMesh->GetProxySubMesh( face.Current() ))
3237 viscousSM.push_back( _mesh->GetSubMesh( face.Current() ));
3238 meshedSM[ MeshDim_2D ].remove( viscousSM.back() );
3240 if ( !quadFaceSM.empty() )
3241 FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, pyramidMeshes[iS-1]);
3243 if ( !viscousSM.empty() )
3244 FillNgMesh(occgeo, *_ngMesh, nodeVec, viscousSM, &quadHelper, viscousMesh );
3246 // fill _ngMesh with faces of sub-meshes
3247 err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper));
3248 initState = NETGENPlugin_ngMeshInfo(_ngMesh, /*checkRemovedElems=*/true);
3249 // toPython( _ngMesh )
3251 if (!err && _isVolume)
3253 // Pass 3D simple parameters to NETGEN
3254 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3255 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3257 _ngMesh->Compress();
3258 if ( double vol = simple3d->GetMaxElementVolume() ) {
3260 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3261 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3264 // length from faces
3265 mparams.maxh = _ngMesh->AverageH();
3267 _ngMesh->SetGlobalH (mparams.maxh);
3268 mparams.grading = 0.4;
3269 ngLib.CalcLocalH( ngLib._ngMesh );
3271 // Care of vertices internal in solids and internal faces (issue 0020676)
3272 if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() )
3274 // store computed faces in SMESH in order not to create SMESH
3275 // faces for ng faces added here
3276 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3277 // add ng faces to solids with internal vertices
3278 AddIntVerticesInSolids( occgeo, *_ngMesh, nodeVec, internals );
3279 // duplicate mesh faces on internal faces
3280 FixIntFaces( occgeo, *_ngMesh, internals );
3281 initState = NETGENPlugin_ngMeshInfo(_ngMesh);
3283 // Let netgen compute 3D mesh
3284 startWith = endWith = netgen::MESHCONST_MESHVOLUME;
3289 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3291 if ( netgen::multithread.terminate )
3294 if ( comment.empty() ) // do not overwrite a previous error
3295 comment << text(err);
3297 catch (Standard_Failure& ex)
3299 if ( comment.empty() ) // do not overwrite a previous error
3300 comment << text(ex);
3303 catch (netgen::NgException& exc)
3305 if ( comment.empty() ) // do not overwrite a previous error
3306 comment << text(exc);
3309 _ticTime = ( doneTime += voluMeshingTime ) / _totalTime / _progressTic;
3311 // Let netgen optimize 3D mesh
3312 if ( !err && _optimize )
3314 startWith = endWith = netgen::MESHCONST_OPTVOLUME;
3319 err = ngLib.GenerateMesh(occgeo, startWith, endWith);
3321 if ( netgen::multithread.terminate )
3324 if ( comment.empty() ) // do not overwrite a previous error
3325 comment << text(err);
3327 catch (Standard_Failure& ex)
3329 if ( comment.empty() ) // do not overwrite a previous error
3330 comment << text(ex);
3332 catch (netgen::NgException& exc)
3334 if ( comment.empty() ) // do not overwrite a previous error
3335 comment << text(exc);
3339 if (!err && mparams.secondorder > 0)
3344 if ( !meshedSM[ MeshDim_1D ].empty() )
3346 // remove segments not attached to geometry (IPAL0052479)
3347 for (int i = 1; i <= _ngMesh->GetNSeg(); ++i)
3349 const netgen::Segment & seg = _ngMesh->LineSegment (i);
3350 if ( seg.epgeominfo[ 0 ].edgenr == 0 )
3352 _ngMesh->DeleteSegment( i );
3353 initState._nbSegments--;
3356 _ngMesh->Compress();
3358 // convert to quadratic
3360 occgeo.GetRefinement().MakeSecondOrder(*_ngMesh);
3362 netgen::OCCRefinementSurfaces(occgeo).MakeSecondOrder(*_ngMesh);
3365 // care of elements already loaded to SMESH
3366 // if ( initState._nbSegments > 0 )
3367 // makeQuadratic( occgeo.emap, _mesh );
3368 // if ( initState._nbFaces > 0 )
3369 // makeQuadratic( occgeo.fmap, _mesh );
3371 catch (Standard_Failure& ex)
3373 if ( comment.empty() ) // do not overwrite a previous error
3374 comment << "Exception in netgen at passing to 2nd order ";
3376 catch (netgen::NgException& exc)
3378 if ( comment.empty() ) // do not overwrite a previous error
3379 comment << exc.What();
3384 _ticTime = 0.98 / _progressTic;
3386 //int nbNod = _ngMesh->GetNP();
3387 //int nbSeg = _ngMesh->GetNSeg();
3388 int nbFac = _ngMesh->GetNSE();
3389 int nbVol = _ngMesh->GetNE();
3390 bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) );
3392 // Feed back the SMESHDS with the generated Nodes and Elements
3393 if ( true /*isOK*/ ) // get whatever built
3395 FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper );
3397 if ( quadHelper.GetIsQuadratic() ) // remove free nodes
3399 for ( size_t i = 0; i < nodeVec.size(); ++i )
3400 if ( nodeVec[i] && nodeVec[i]->NbInverseElements() == 0 )
3402 _mesh->GetMeshDS()->RemoveFreeNode( nodeVec[i], 0, /*fromGroups=*/false );
3405 for ( size_t i = nodeVec.size()-1; i > 0; --i ) // remove trailing removed nodes
3407 nodeVec.resize( i );
3412 SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec);
3413 if ( readErr && readErr->HasBadElems() )
3416 if ( !comment.empty() && !readErr->myComment.empty() ) comment += "\n";
3417 comment += readErr->myComment;
3419 if ( error->IsOK() && ( !isOK || comment.size() > 0 ))
3420 error->myName = COMPERR_ALGO_FAILED;
3421 if ( !comment.empty() )
3422 error->myComment = comment;
3424 // SetIsAlwaysComputed( true ) to empty sub-meshes, which
3425 // appear if the geometry contains coincident sub-shape due
3426 // to bool merge_solids = 1; in netgen/libsrc/occ/occgenmesh.cpp
3427 const int nbMaps = 2;
3428 const TopTools_IndexedMapOfShape* geoMaps[nbMaps] =
3429 { & occgeo.vmap, & occgeo.emap/*, & occgeo.fmap*/ };
3430 for ( int iMap = 0; iMap < nbMaps; ++iMap )
3431 for (int i = 1; i <= geoMaps[iMap]->Extent(); i++)
3432 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( geoMaps[iMap]->FindKey(i)))
3433 if ( !sm->IsMeshComputed() )
3434 sm->SetIsAlwaysComputed( true );
3436 // set bad compute error to subshapes of all failed sub-shapes
3437 if ( !error->IsOK() )
3439 bool pb2D = false, pb3D = false;
3440 for (int i = 1; i <= occgeo.fmap.Extent(); i++) {
3441 int status = occgeo.facemeshstatus[i-1];
3442 if (status == netgen::FACE_MESHED_OK ) continue;
3443 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) {
3444 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3445 if ( !smError || smError->IsOK() ) {
3446 if ( status == netgen::FACE_FAILED )
3447 smError.reset( new SMESH_ComputeError( *error ));
3449 smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" ));
3450 if ( SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3451 smError->myName = COMPERR_WARNING;
3453 pb2D = pb2D || smError->IsKO();
3456 if ( !pb2D ) // all faces are OK
3457 for (int i = 1; i <= occgeo.somap.Extent(); i++)
3458 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.somap( i )))
3460 bool smComputed = nbVol && !sm->IsEmpty();
3461 if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() ))
3463 size_t nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size();
3464 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3465 smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > (smIdType) nbIntV );
3467 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
3468 if ( !smComputed && ( !smError || smError->IsOK() ))
3471 if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK )
3473 smError->myName = COMPERR_WARNING;
3475 else if ( smError->HasBadElems() ) // bad surface mesh
3477 if ( !hasBadElemOnSolid
3478 ( static_cast<SMESH_BadInputElements*>( smError.get() )->myBadElements, sm ))
3482 pb3D = pb3D || ( smError && smError->IsKO() );
3484 if ( !pb2D && !pb3D )
3485 err = 0; // no fatal errors, only warnings
3488 ngLib._isComputeOk = !err;
3493 //=============================================================================
3497 //=============================================================================
3498 bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap)
3500 netgen::MeshingParameters& mparams = netgen::mparam;
3503 // -------------------------
3504 // Prepare OCC geometry
3505 // -------------------------
3506 netgen::OCCGeometry occgeo;
3507 NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume );
3508 PrepareOCCgeometry( occgeo, _shape, *_mesh, 0, &internals );
3510 bool tooManyElems = false;
3511 const int hugeNb = std::numeric_limits<int>::max() / 100;
3516 // pass 1D simple parameters to NETGEN
3519 // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE
3520 mparams.uselocalh = false;
3521 mparams.grading = 0.8; // not limitited size growth
3523 if ( _simpleHyp->GetNumberOfSegments() )
3525 mparams.maxh = occgeo.boundingbox.Diam();
3528 mparams.maxh = _simpleHyp->GetLocalLength();
3531 if ( mparams.maxh == 0.0 )
3532 mparams.maxh = occgeo.boundingbox.Diam();
3533 if ( _simpleHyp || ( mparams.minh == 0.0 && _fineness != NETGENPlugin_Hypothesis::UserDefined))
3534 mparams.minh = GetDefaultMinSize( _shape, mparams.maxh );
3536 // let netgen create _ngMesh and calculate element size on not meshed shapes
3537 NETGENPlugin_NetgenLibWrapper ngLib;
3538 netgen::Mesh *ngMesh = NULL;
3539 int startWith = netgen::MESHCONST_ANALYSE;
3540 int endWith = netgen::MESHCONST_MESHEDGES;
3541 int err = ngLib.GenerateMesh(occgeo, startWith, endWith, ngMesh);
3543 if(netgen::multithread.terminate)
3546 ngLib.setMesh(( Ng_Mesh*) ngMesh );
3548 if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( _shape ))
3549 sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED ));
3552 // if ( _simpleHyp )
3554 // // Pass 1D simple parameters to NETGEN
3555 // // --------------------------------
3556 // int nbSeg = _simpleHyp->GetNumberOfSegments();
3557 // double segSize = _simpleHyp->GetLocalLength();
3558 // for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE )
3560 // const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE));
3562 // segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 );
3563 // setLocalSize( e, segSize, *ngMesh );
3566 // else // if ( ! _simpleHyp )
3568 // // Local size on shapes
3569 // SetLocalSize( occgeo, *ngMesh );
3571 // calculate total nb of segments and length of edges
3572 double fullLen = 0.0;
3573 smIdType fullNbSeg = 0;
3574 int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge;
3575 TopTools_DataMapOfShapeInteger Edge2NbSeg;
3576 for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next())
3578 TopoDS_Edge E = TopoDS::Edge( exp.Current() );
3579 if( !Edge2NbSeg.Bind(E,0) )
3582 double aLen = SMESH_Algo::EdgeLength(E);
3585 vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(E)];
3587 aVec.resize( SMDSEntity_Last, 0);
3589 fullNbSeg += aVec[ entity ];
3592 // store nb of segments computed by Netgen
3594 for (int i = 1; i <= ngMesh->GetNSeg(); ++i )
3596 const netgen::Segment& seg = ngMesh->LineSegment(i);
3597 Link link(seg[0], seg[1]);
3598 if ( !linkMap.Add( link )) continue;
3599 int aGeomEdgeInd = seg.epgeominfo[0].edgenr;
3600 if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent())
3602 vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))];
3606 // store nb of nodes on edges computed by Netgen
3607 TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg);
3608 for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next())
3610 vector<smIdType>& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())];
3611 if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 )
3612 aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1;
3614 fullNbSeg += aVec[ entity ];
3615 Edge2NbSeg( Edge2NbSegIt.Key() ) = (int) aVec[ entity ];
3617 if ( fullNbSeg == 0 )
3624 if ( double area = _simpleHyp->GetMaxElementArea() ) {
3626 mparams.maxh = sqrt(2. * area/sqrt(3.0));
3627 mparams.grading = 0.4; // moderate size growth
3630 // length from edges
3631 mparams.maxh = fullLen / double( fullNbSeg );
3632 mparams.grading = 0.2; // slow size growth
3635 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3636 mparams.maxh = min( mparams.maxh, fullLen / double( fullNbSeg ) * (1. + mparams.grading));
3638 for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next())
3640 TopoDS_Face F = TopoDS::Face( exp.Current() );
3641 SMESH_subMesh *sm = _mesh->GetSubMesh(F);
3643 BRepGProp::SurfaceProperties(F,G);
3644 double anArea = G.Mass();
3645 tooManyElems = tooManyElems || ( anArea/hugeNb > mparams.maxh*mparams.maxh );
3647 if ( !tooManyElems )
3649 TopTools_MapOfShape edges;
3650 for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next())
3651 if ( edges.Add( exp1.Current() ))
3652 nb1d += Edge2NbSeg.Find(exp1.Current());
3654 int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.)));
3655 int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 );
3657 vector<smIdType> aVec(SMDSEntity_Last, 0);
3658 if( mparams.secondorder > 0 ) {
3659 int nb1d_in = (nbFaces*3 - nb1d) / 2;
3660 aVec[SMDSEntity_Node] = nbNodes + nb1d_in;
3661 aVec[SMDSEntity_Quad_Triangle] = nbFaces;
3664 aVec[SMDSEntity_Node] = Max ( nbNodes, 0 );
3665 aVec[SMDSEntity_Triangle] = nbFaces;
3667 aResMap[sm].swap(aVec);
3674 // pass 3D simple parameters to NETGEN
3675 const NETGENPlugin_SimpleHypothesis_3D* simple3d =
3676 dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp );
3678 if ( double vol = simple3d->GetMaxElementVolume() ) {
3680 mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. );
3681 mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 );
3684 // using previous length from faces
3686 mparams.grading = 0.4;
3687 mparams.maxh = min( mparams.maxh, fullLen / double( fullNbSeg ) * (1. + mparams.grading));
3690 BRepGProp::VolumeProperties(_shape,G);
3691 double aVolume = G.Mass();
3692 double tetrVol = 0.1179*mparams.maxh*mparams.maxh*mparams.maxh;
3693 tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol );
3694 int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol);
3695 int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 );
3696 vector<smIdType> aVec(SMDSEntity_Last, 0 );
3697 if ( tooManyElems ) // avoid FPE
3699 aVec[SMDSEntity_Node] = hugeNb;
3700 aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb;
3704 if( mparams.secondorder > 0 ) {
3705 aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in;
3706 aVec[SMDSEntity_Quad_Tetra] = nbVols;
3709 aVec[SMDSEntity_Node] = nb1d_in/3 + 1;
3710 aVec[SMDSEntity_Tetra] = nbVols;
3713 SMESH_subMesh *sm = _mesh->GetSubMesh(_shape);
3714 aResMap[sm].swap(aVec);
3720 double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* /*holder*/,
3721 const int * algoProgressTic,
3722 const double * algoProgress) const
3724 ((int&) _progressTic ) = *algoProgressTic + 1;
3726 if ( !_occgeom ) return 0;
3728 double progress = -1;
3731 if ( _ticTime < 0 && netgen::multithread.task[0] == 'O'/*Optimizing surface*/ )
3733 ((double&) _ticTime ) = edgeFaceMeshingTime / _totalTime / _progressTic;
3735 else if ( !_optimize /*&& _occgeom->fmap.Extent() > 1*/ )
3737 int doneShapeIndex = -1;
3738 while ( doneShapeIndex+1 < _occgeom->facemeshstatus.Size() &&
3739 _occgeom->facemeshstatus[ doneShapeIndex+1 ])
3741 if ( doneShapeIndex+1 != _curShapeIndex )
3743 ((int&) _curShapeIndex) = doneShapeIndex+1;
3744 double doneShapeRate = _curShapeIndex / double( _occgeom->fmap.Extent() );
3745 double doneTime = edgeMeshingTime + doneShapeRate * faceMeshingTime;
3746 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3747 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3748 // << " " << doneTime / _totalTime / _progressTic << endl;
3752 else if ( !_optimize && _occgeom->somap.Extent() > 1 )
3754 int curShapeIndex = _curShapeIndex;
3755 if ( _ngMesh->GetNE() > 0 )
3757 netgen::Element el = (*_ngMesh)[netgen::ElementIndex( _ngMesh->GetNE()-1 )];
3758 curShapeIndex = el.GetIndex();
3760 if ( curShapeIndex != _curShapeIndex )
3762 ((int&) _curShapeIndex) = curShapeIndex;
3763 double doneShapeRate = _curShapeIndex / double( _occgeom->somap.Extent() );
3764 double doneTime = edgeFaceMeshingTime + doneShapeRate * voluMeshingTime;
3765 ((double&) _ticTime) = doneTime / _totalTime / _progressTic;
3766 // cout << "shape " << _curShapeIndex << " _ticTime " << _ticTime
3767 // << " " << doneTime / _totalTime / _progressTic << endl;
3772 progress = Max( *algoProgressTic * _ticTime, *algoProgress );
3777 netgen::multithread.task[0] == 'D'/*elaunay meshing*/ &&
3778 progress > voluMeshingTime )
3780 progress = voluMeshingTime;
3781 ((double&) _ticTime) = voluMeshingTime / _totalTime / _progressTic;
3783 ((int&) *algoProgressTic )++;
3784 ((double&) *algoProgress) = progress;
3786 //cout << progress << " " << *algoProgressTic << " " << netgen::multithread.task << " "<< _ticTime << endl;
3788 return Min( progress, 0.99 );
3791 //================================================================================
3793 * \brief Read mesh entities preventing successful computation from "test.out" file
3795 //================================================================================
3797 SMESH_ComputeErrorPtr
3798 NETGENPlugin_Mesher::ReadErrors(const vector<const SMDS_MeshNode* >& nodeVec)
3800 if ( nodeVec.size() < 2 ) return SMESH_ComputeErrorPtr();
3801 SMESH_BadInputElements* err =
3802 new SMESH_BadInputElements( nodeVec.back()->GetMesh(), COMPERR_BAD_INPUT_MESH,
3803 "Some edges multiple times in surface mesh");
3804 SMESH_File file("test.out");
3806 vector<int> three1(3), three2(3);
3807 const char* badEdgeStr = " multiple times in surface mesh";
3808 const int badEdgeStrLen = (int) strlen( badEdgeStr );
3809 const int nbNodes = (int) nodeVec.size();
3811 while( !file.eof() )
3813 if ( strncmp( file, "Edge ", 5 ) == 0 &&
3814 file.getInts( two ) &&
3815 strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 &&
3816 two[0] < nbNodes && two[1] < nbNodes )
3818 err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] ));
3819 file += (int) badEdgeStrLen;
3821 else if ( strncmp( file, "Intersecting: ", 14 ) == 0 )
3824 // openelement 18 with open element 126
3828 const char* pos = file;
3829 bool ok = ( strncmp( file, "openelement ", 12 ) == 0 );
3830 ok = ok && file.getInts( two );
3831 ok = ok && file.getInts( three1 );
3832 ok = ok && file.getInts( three2 );
3833 for ( int i = 0; ok && i < 3; ++i )
3834 ok = ( three1[i] < nbNodes && nodeVec[ three1[i]]);
3835 for ( int i = 0; ok && i < 3; ++i )
3836 ok = ( three2[i] < nbNodes && nodeVec[ three2[i]]);
3839 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]],
3840 nodeVec[ three1[1]],
3841 nodeVec[ three1[2]]));
3842 err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three2[0]],
3843 nodeVec[ three2[1]],
3844 nodeVec[ three2[2]]));
3845 err->myComment = "Intersecting triangles";
3859 size_t nbBadElems = err->myBadElements.size();
3860 if ( nbBadElems ) nbBadElems++; // avoid warning: variable set but not used
3863 return SMESH_ComputeErrorPtr( err );
3866 //================================================================================
3868 * \brief Write a python script creating an equivalent SALOME mesh.
3869 * This is useful to see what mesh is passed as input for the next step of mesh
3870 * generation (of mesh of higher dimension)
3872 //================================================================================
3874 void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh )
3876 const char* pyFile = "/tmp/ngMesh.py";
3877 ofstream outfile( pyFile, ios::out );
3878 if ( !outfile ) return;
3880 outfile << "import salome, SMESH" << std::endl
3881 << "from salome.smesh import smeshBuilder" << std::endl
3882 << "smesh = smeshBuilder.New()" << std::endl
3883 << "mesh = smesh.Mesh()" << std::endl << std::endl;
3885 using namespace netgen;
3889 for ( int i = 1; i <= ngMesh->GetNP(); i++)
3891 const Point3d & p = ngMesh->Point(i);
3892 outfile << "mesh.AddNode( ";
3893 outfile << p.X() << ", ";
3894 outfile << p.Y() << ", ";
3895 outfile << p.Z() << ") ## "<< i << std::endl;
3898 int nbDom = ngMesh->GetNDomains();
3899 for ( int i = 0; i < nbDom; ++i )
3900 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< std::endl;
3903 for (int i = 1; i <= ngMesh->GetNSE(); i++)
3905 outfile << "mesh.AddFace([ ";
3906 Element2d sel = ngMesh->SurfaceElement(i);
3907 for (int j = 1; j <= sel.GetNP(); j++)
3908 outfile << sel.PNum(j) << ( j < sel.GetNP() ? ", " : " ])");
3909 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3910 outfile << std::endl;
3911 nbDel += sel.IsDeleted();
3915 if ( int dom1 = ngMesh->GetFaceDescriptor(sel.GetIndex ()).DomainIn())
3916 outfile << "grp"<< dom1 <<".Add([ " << i - nbDel << " ])" << std::endl;
3917 if ( int dom2 = ngMesh->GetFaceDescriptor(sel.GetIndex ()).DomainOut())
3918 outfile << "grp"<< dom2 <<".Add([ " << i - nbDel << " ])" << std::endl;
3922 for (int i = 1; i <= ngMesh->GetNE(); i++)
3924 Element el = ngMesh->VolumeElement(i);
3925 outfile << "mesh.AddVolume([ ";
3926 for (int j = 1; j <= el.GetNP(); j++)
3927 outfile << el.PNum(j) << ( j < el.GetNP() ? ", " : " ])");
3928 outfile << std::endl;
3931 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3933 const Segment & seg = ngMesh->LineSegment (i);
3934 outfile << "mesh.AddEdge([ "
3936 << seg[1]+1 << " ])" << std::endl;
3942 for (pi = PointIndex::BASE;
3943 pi < ngMesh->GetNP()+PointIndex::BASE; pi++)
3945 outfile << "mesh.AddNode( ";
3946 outfile << (*ngMesh)[pi](0) << ", ";
3947 outfile << (*ngMesh)[pi](1) << ", ";
3948 outfile << (*ngMesh)[pi](2) << ") ## "<< pi << std::endl;
3951 int nbDom = ngMesh->GetNDomains();
3952 for ( int i = 0; i < nbDom; ++i )
3953 outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< std::endl;
3956 SurfaceElementIndex sei;
3957 for (sei = 0; sei < ngMesh->GetNSE(); sei++)
3959 outfile << "mesh.AddFace([ ";
3960 Element2d sel = (*ngMesh)[sei];
3961 for (int j = 0; j < sel.GetNP(); j++)
3962 outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])");
3963 if ( sel.IsDeleted() ) outfile << " ## IsDeleted ";
3964 outfile << std::endl;
3965 nbDel += sel.IsDeleted();
3967 if ((*ngMesh)[sei].GetIndex())
3969 if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn())
3970 outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 - nbDel << " ])" << std::endl;
3971 if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut())
3972 outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 - nbDel << " ])" << std::endl;
3976 for (ElementIndex ei = 0; ei < ngMesh->GetNE(); ei++)
3978 Element el = (*ngMesh)[ei];
3979 outfile << "mesh.AddVolume([ ";
3980 for (int j = 0; j < el.GetNP(); j++)
3981 outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])");
3982 outfile << std::endl;
3985 for (int i = 1; i <= ngMesh->GetNSeg(); i++)
3987 const Segment & seg = ngMesh->LineSegment (i);
3988 outfile << "mesh.AddEdge([ "
3990 << seg[1] << " ])" << std::endl;
3995 std::cout << "Write " << pyFile << std::endl;
3998 //================================================================================
4000 * \brief Constructor of NETGENPlugin_ngMeshInfo
4002 //================================================================================
4004 NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh,
4005 bool checkRemovedElems):
4006 _elementsRemoved( false ), _copyOfLocalH(0)
4010 _nbNodes = ngMesh->GetNP();
4011 _nbSegments = ngMesh->GetNSeg();
4012 _nbFaces = ngMesh->GetNSE();
4013 _nbVolumes = ngMesh->GetNE();
4015 if ( checkRemovedElems )
4016 for ( int i = 1; i <= ngMesh->GetNSE() && !_elementsRemoved; ++i )
4017 _elementsRemoved = ngMesh->SurfaceElement(i).IsDeleted();
4021 _nbNodes = _nbSegments = _nbFaces = _nbVolumes = 0;
4025 //================================================================================
4027 * \brief Copy LocalH member from one netgen mesh to another
4029 //================================================================================
4031 void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh,
4032 netgen::Mesh* toMesh )
4034 if ( !fromMesh->LocalHFunctionGenerated() ) return;
4035 if ( !toMesh->LocalHFunctionGenerated() )
4036 NETGENPlugin_NetgenLibWrapper::CalcLocalH( toMesh );
4038 const size_t size = sizeof( netgen::LocalH );
4039 _copyOfLocalH = new char[ size ];
4040 memcpy( (void*)_copyOfLocalH, (void*)&toMesh->LocalHFunction(), size );
4041 memcpy( (void*)&toMesh->LocalHFunction(), (void*)&fromMesh->LocalHFunction(), size );
4044 //================================================================================
4046 * \brief Restore LocalH member of a netgen mesh
4048 //================================================================================
4050 void NETGENPlugin_ngMeshInfo::restoreLocalH( netgen::Mesh* toMesh )
4052 if ( _copyOfLocalH )
4054 const size_t size = sizeof( netgen::LocalH );
4055 memcpy( (void*)&toMesh->LocalHFunction(), (void*)_copyOfLocalH, size );
4056 delete [] _copyOfLocalH;
4061 //================================================================================
4063 * \brief Find "internal" sub-shapes
4065 //================================================================================
4067 NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh,
4068 const TopoDS_Shape& shape,
4070 : _mesh( mesh ), _is3D( is3D )
4072 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
4074 TopExp_Explorer f,e;
4075 for ( f.Init( shape, TopAbs_FACE ); f.More(); f.Next() )
4077 int faceID = meshDS->ShapeToIndex( f.Current() );
4079 // find not computed internal edges
4081 for ( e.Init( f.Current().Oriented(TopAbs_FORWARD), TopAbs_EDGE ); e.More(); e.Next() )
4082 if ( e.Current().Orientation() == TopAbs_INTERNAL )
4084 SMESH_subMesh* eSM = mesh.GetSubMesh( e.Current() );
4085 if ( eSM->IsEmpty() )
4087 _e2face.insert( make_pair( eSM->GetId(), faceID ));
4088 for ( TopoDS_Iterator v(e.Current()); v.More(); v.Next() )
4089 _e2face.insert( make_pair( meshDS->ShapeToIndex( v.Value() ), faceID ));
4093 // find internal vertices in a face
4094 set<int> intVV; // issue 0020850 where same vertex is twice in a face
4095 for ( TopoDS_Iterator fSub( f.Current() ); fSub.More(); fSub.Next())
4096 if ( fSub.Value().ShapeType() == TopAbs_VERTEX )
4098 int vID = meshDS->ShapeToIndex( fSub.Value() );
4099 if ( intVV.insert( vID ).second )
4100 _f2v[ faceID ].push_back( vID );
4105 // find internal faces and their subshapes where nodes are to be doubled
4106 // to make a crack with non-sewed borders
4108 if ( f.Current().Orientation() == TopAbs_INTERNAL )
4110 _intShapes.insert( meshDS->ShapeToIndex( f.Current() ));
4113 list< TopoDS_Shape > edges;
4114 for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next())
4115 if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 )
4117 _intShapes.insert( meshDS->ShapeToIndex( e.Current() ));
4118 edges.push_back( e.Current() );
4119 // find border faces
4120 PShapeIteratorPtr fIt =
4121 SMESH_MesherHelper::GetAncestors( edges.back(),mesh,TopAbs_FACE );
4122 while ( const TopoDS_Shape* pFace = fIt->next() )
4123 if ( !pFace->IsSame( f.Current() ))
4124 _borderFaces.insert( meshDS->ShapeToIndex( *pFace ));
4127 // we consider vertex internal if it is shared by more than one internal edge
4128 list< TopoDS_Shape >::iterator edge = edges.begin();
4129 for ( ; edge != edges.end(); ++edge )
4130 for ( TopoDS_Iterator v( *edge ); v.More(); v.Next() )
4132 set<int> internalEdges;
4133 PShapeIteratorPtr eIt =
4134 SMESH_MesherHelper::GetAncestors( v.Value(),mesh,TopAbs_EDGE );
4135 while ( const TopoDS_Shape* pEdge = eIt->next() )
4137 int edgeID = meshDS->ShapeToIndex( *pEdge );
4138 if ( isInternalShape( edgeID ))
4139 internalEdges.insert( edgeID );
4141 if ( internalEdges.size() > 1 )
4142 _intShapes.insert( meshDS->ShapeToIndex( v.Value() ));
4146 } // loop on geom faces
4148 // find vertices internal in solids
4151 for ( TopExp_Explorer so(shape, TopAbs_SOLID); so.More(); so.Next())
4153 int soID = meshDS->ShapeToIndex( so.Current() );
4154 for ( TopoDS_Iterator soSub( so.Current() ); soSub.More(); soSub.Next())
4155 if ( soSub.Value().ShapeType() == TopAbs_VERTEX )
4156 _s2v[ soID ].push_back( meshDS->ShapeToIndex( soSub.Value() ));
4161 //================================================================================
4163 * \brief Find mesh faces on non-internal geom faces sharing internal edge
4164 * some nodes of which are to be doubled to make the second border of the "crack"
4166 //================================================================================
4168 void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems )
4170 if ( _intShapes.empty() ) return;
4172 SMESH_Mesh& mesh = const_cast<SMESH_Mesh&>(_mesh);
4173 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
4175 // loop on internal geom edges
4176 set<int>::const_iterator intShapeId = _intShapes.begin();
4177 for ( ; intShapeId != _intShapes.end(); ++intShapeId )
4179 const TopoDS_Shape& s = meshDS->IndexToShape( *intShapeId );
4180 if ( s.ShapeType() != TopAbs_EDGE ) continue;
4182 // get internal and non-internal geom faces sharing the internal edge <s>
4184 set<int>::iterator bordFace = _borderFaces.end();
4185 PShapeIteratorPtr faces = SMESH_MesherHelper::GetAncestors( s, _mesh, TopAbs_FACE );
4186 while ( const TopoDS_Shape* pFace = faces->next() )
4188 int faceID = meshDS->ShapeToIndex( *pFace );
4189 if ( isInternalShape( faceID ))
4192 bordFace = _borderFaces.insert( faceID ).first;
4194 if ( bordFace == _borderFaces.end() || !intFace ) continue;
4196 // get all links of mesh faces on internal geom face sharing nodes on edge <s>
4197 set< SMESH_OrientedLink > links; //!< links of faces on internal geom face
4198 list<const SMDS_MeshElement*> suspectFaces[2]; //!< mesh faces on border geom faces
4199 int nbSuspectFaces = 0;
4200 SMESHDS_SubMesh* intFaceSM = meshDS->MeshElements( intFace );
4201 if ( !intFaceSM || intFaceSM->NbElements() == 0 ) continue;
4202 SMESH_subMeshIteratorPtr smIt = mesh.GetSubMesh( s )->getDependsOnIterator(true,true);
4203 while ( smIt->more() )
4205 SMESHDS_SubMesh* sm = smIt->next()->GetSubMeshDS();
4206 if ( !sm ) continue;
4207 SMDS_NodeIteratorPtr nIt = sm->GetNodes();
4208 while ( nIt->more() )
4210 const SMDS_MeshNode* nOnEdge = nIt->next();
4211 SMDS_ElemIteratorPtr fIt = nOnEdge->GetInverseElementIterator(SMDSAbs_Face);
4212 while ( fIt->more() )
4214 const SMDS_MeshElement* f = fIt->next();
4215 const int nbNodes = f->NbCornerNodes();
4216 if ( intFaceSM->Contains( f ))
4218 for ( int i = 0; i < nbNodes; ++i )
4219 links.insert( SMESH_OrientedLink( f->GetNode(i), f->GetNode((i+1)%nbNodes)));
4224 for ( int i = 0; i < nbNodes; ++i )
4225 nbDblNodes += isInternalShape( f->GetNode(i)->GetShapeID() );
4227 suspectFaces[ nbDblNodes < 2 ].push_back( f );
4233 // suspectFaces[0] having link with same orientation as mesh faces on
4234 // the internal geom face are <borderElems>. suspectFaces[1] have
4235 // only one node on edge <s>, we decide on them later (at the 2nd loop)
4236 // by links of <borderElems> found at the 1st and 2nd loops
4237 set< SMESH_OrientedLink > borderLinks;
4238 for ( int isPostponed = 0; isPostponed < 2; ++isPostponed )
4240 list<const SMDS_MeshElement*>::iterator fIt = suspectFaces[isPostponed].begin();
4241 for ( int nbF = 0; fIt != suspectFaces[isPostponed].end(); ++fIt, ++nbF )
4243 const SMDS_MeshElement* f = *fIt;
4244 bool isBorder = false, linkFound = false, borderLinkFound = false;
4245 list< SMESH_OrientedLink > faceLinks;
4246 int nbNodes = f->NbCornerNodes();
4247 for ( int i = 0; i < nbNodes; ++i )
4249 SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes));
4250 faceLinks.push_back( link );
4253 set< SMESH_OrientedLink >::iterator foundLink = links.find( link );
4254 if ( foundLink != links.end() )
4257 isBorder = ( foundLink->_reversed == link._reversed );
4258 if ( !isBorder && !isPostponed ) break;
4259 faceLinks.pop_back();
4261 else if ( isPostponed && !borderLinkFound )
4263 foundLink = borderLinks.find( link );
4264 if ( foundLink != borderLinks.end() )
4266 borderLinkFound = true;
4267 isBorder = ( foundLink->_reversed != link._reversed );
4274 borderElems.insert( f );
4275 borderLinks.insert( faceLinks.begin(), faceLinks.end() );
4277 else if ( !linkFound && !borderLinkFound )
4279 suspectFaces[1].push_back( f );
4280 if ( nbF > 2 * nbSuspectFaces )
4281 break; // dead loop protection
4288 //================================================================================
4290 * \brief put internal shapes in maps and fill in submeshes to precompute
4292 //================================================================================
4294 void NETGENPlugin_Internals::getInternalEdges( TopTools_IndexedMapOfShape& fmap,
4295 TopTools_IndexedMapOfShape& emap,
4296 TopTools_IndexedMapOfShape& vmap,
4297 list< SMESH_subMesh* > smToPrecompute[])
4299 if ( !hasInternalEdges() ) return;
4300 map<int,int>::const_iterator ev_face = _e2face.begin();
4301 for ( ; ev_face != _e2face.end(); ++ev_face )
4303 const TopoDS_Shape& ev = _mesh.GetMeshDS()->IndexToShape( ev_face->first );
4304 const TopoDS_Shape& face = _mesh.GetMeshDS()->IndexToShape( ev_face->second );
4306 ( ev.ShapeType() == TopAbs_EDGE ? emap : vmap ).Add( ev );
4308 //cout<<"INTERNAL EDGE or VERTEX "<<ev_face->first<<" on face "<<ev_face->second<<endl;
4310 smToPrecompute[ MeshDim_1D ].push_back( _mesh.GetSubMeshContaining( ev_face->first ));
4314 //================================================================================
4316 * \brief return shapes and submeshes to be meshed and already meshed boundary submeshes
4318 //================================================================================
4320 void NETGENPlugin_Internals::getInternalFaces( TopTools_IndexedMapOfShape& fmap,
4321 TopTools_IndexedMapOfShape& emap,
4322 list< SMESH_subMesh* >& intFaceSM,
4323 list< SMESH_subMesh* >& boundarySM)
4325 if ( !hasInternalFaces() ) return;
4327 // <fmap> and <emap> are for not yet meshed shapes
4328 // <intFaceSM> is for submeshes of faces
4329 // <boundarySM> is for meshed edges and vertices
4334 set<int> shapeIDs ( _intShapes );
4335 if ( !_borderFaces.empty() )
4336 shapeIDs.insert( _borderFaces.begin(), _borderFaces.end() );
4338 set<int>::const_iterator intS = shapeIDs.begin();
4339 for ( ; intS != shapeIDs.end(); ++intS )
4341 SMESH_subMesh* sm = _mesh.GetSubMeshContaining( *intS );
4343 if ( sm->GetSubShape().ShapeType() != TopAbs_FACE ) continue;
4345 intFaceSM.push_back( sm );
4347 // add submeshes of not computed internal faces
4348 if ( !sm->IsEmpty() ) continue;
4350 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(true,true);
4351 while ( smIt->more() )
4354 const TopoDS_Shape& s = sm->GetSubShape();
4356 if ( sm->IsEmpty() )
4359 switch ( s.ShapeType() ) {
4360 case TopAbs_FACE: fmap.Add ( s ); break;
4361 case TopAbs_EDGE: emap.Add ( s ); break;
4367 if ( s.ShapeType() != TopAbs_FACE )
4368 boundarySM.push_back( sm );
4374 //================================================================================
4376 * \brief Return true if given shape is to be precomputed in order to be correctly
4377 * added to netgen mesh
4379 //================================================================================
4381 bool NETGENPlugin_Internals::isShapeToPrecompute(const TopoDS_Shape& s)
4383 int shapeID = _mesh.GetMeshDS()->ShapeToIndex( s );
4384 switch ( s.ShapeType() ) {
4385 case TopAbs_FACE : break; //return isInternalShape( shapeID ) || isBorderFace( shapeID );
4386 case TopAbs_EDGE : return isInternalEdge( shapeID );
4387 case TopAbs_VERTEX: break;
4393 //================================================================================
4395 * \brief Return SMESH
4397 //================================================================================
4399 SMESH_Mesh& NETGENPlugin_Internals::getMesh() const
4401 return const_cast<SMESH_Mesh&>( _mesh );
4404 //================================================================================
4406 * \brief Access to a counter of NETGENPlugin_NetgenLibWrapper instances
4408 //================================================================================
4410 int& NETGENPlugin_NetgenLibWrapper::instanceCounter()
4412 static int theCouner = 0;
4416 //================================================================================
4418 * \brief Initialize netgen library
4420 //================================================================================
4422 NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper():
4425 if ( instanceCounter() == 0 )
4428 if ( !netgen::testout )
4429 netgen::testout = new ofstream( "test.out" );
4432 ++instanceCounter();
4434 _isComputeOk = false;
4438 if ( !getenv( "KEEP_NETGEN_OUTPUT" ))
4440 // redirect all netgen output (mycout,myerr,cout) to _outputFileName
4441 _outputFileName = getOutputFileName();
4442 _ngcout = netgen::mycout;
4443 _ngcerr = netgen::myerr;
4444 netgen::mycout = new ofstream ( _outputFileName.c_str() );
4445 netgen::myerr = netgen::mycout;
4446 _coutBuffer = std::cout.rdbuf();
4448 std::cout << "NOTE: netgen output is redirected to file " << _outputFileName << std::endl;
4450 std::cout.rdbuf( netgen::mycout->rdbuf() );
4454 setMesh( Ng_NewMesh() );
4457 //================================================================================
4459 * \brief Finish using netgen library
4461 //================================================================================
4463 NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper()
4465 --instanceCounter();
4467 Ng_DeleteMesh( ngMesh() );
4471 std::cout.rdbuf( _coutBuffer );
4478 //================================================================================
4480 * \brief Set netgen mesh to delete at destruction
4482 //================================================================================
4484 void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh )
4487 Ng_DeleteMesh( ngMesh() );
4488 _ngMesh = (netgen::Mesh*) mesh;
4491 //================================================================================
4493 * \brief Perform a step of mesh generation
4494 * \param [inout] occgeo - geometry to mesh
4495 * \param [inout] startWith - start step
4496 * \param [inout] endWith - end step
4497 * \param [inout] ngMesh - netgen mesh
4498 * \return int - is error
4500 //================================================================================
4502 int NETGENPlugin_NetgenLibWrapper::GenerateMesh( netgen::OCCGeometry& occgeo,
4503 int startWith, int endWith,
4504 netgen::Mesh* & ngMesh )
4508 ngMesh = new netgen::Mesh;
4512 ngMesh->SetGeometry( shared_ptr<netgen::NetgenGeometry>( &occgeo, &NOOP_Deleter ));
4514 netgen::mparam.perfstepsstart = startWith;
4515 netgen::mparam.perfstepsend = endWith;
4516 std::shared_ptr<netgen::Mesh> meshPtr( ngMesh, &NOOP_Deleter );
4517 err = occgeo.GenerateMesh( meshPtr, netgen::mparam );
4522 err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith);
4527 err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr);
4534 //================================================================================
4536 * \brief Create a mesh size tree
4538 //================================================================================
4540 void NETGENPlugin_NetgenLibWrapper::CalcLocalH( netgen::Mesh * ngMesh )
4542 #if defined( NETGEN_V5 ) || defined( NETGEN_V6 )
4543 ngMesh->CalcLocalH(netgen::mparam.grading);
4545 ngMesh->CalcLocalH();
4549 //================================================================================
4551 * \brief Return a unique file name
4553 //================================================================================
4555 std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName()
4557 std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
4559 TCollection_AsciiString aGenericName = aTmpDir.c_str();
4560 aGenericName += "NETGEN_";
4562 aGenericName += getpid();
4564 aGenericName += _getpid();
4566 aGenericName += "_";
4567 aGenericName += Abs((Standard_Integer)(long) aGenericName.ToCString());
4568 aGenericName += ".out";
4570 return aGenericName.ToCString();
4573 //================================================================================
4575 * \brief Remove "test.out" and "problemfaces" files in current directory
4577 //================================================================================
4579 void NETGENPlugin_NetgenLibWrapper::RemoveTmpFiles()
4581 bool rm = SMESH_File("test.out").remove() ;
4583 if ( rm && netgen::testout && instanceCounter() == 0 )
4585 delete netgen::testout;
4586 netgen::testout = 0;
4589 SMESH_File("problemfaces").remove();
4590 SMESH_File("occmesh.rep").remove();
4593 //================================================================================
4595 * \brief Remove file with netgen output
4597 //================================================================================
4599 void NETGENPlugin_NetgenLibWrapper::removeOutputFile()
4601 if ( !_outputFileName.empty() )
4605 delete netgen::mycout;
4606 netgen::mycout = _ngcout;
4607 netgen::myerr = _ngcerr;
4610 string tmpDir = SALOMEDS_Tool::GetDirFromPath ( _outputFileName );
4611 string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out";
4612 SALOMEDS_Tool::ListOfFiles aFiles;
4614 aFiles.push_back(aFileName.c_str());
4616 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles, true );