X-Git-Url: http://git.salome-platform.org/gitweb/?a=blobdiff_plain;f=src%2FNETGENPlugin%2FNETGENPlugin_Mesher.cxx;h=5853a7e4a870a2cb051e71ad3c4cfd4196aada55;hb=a8606239fd767f5f572f411ddbefb24439d26ff7;hp=039c8f65d720d543f82ddcc41374540d84fab4c4;hpb=86f0b5ec0bf1b929201a35804393a23a4686ce2d;p=plugins%2Fnetgenplugin.git diff --git a/src/NETGENPlugin/NETGENPlugin_Mesher.cxx b/src/NETGENPlugin/NETGENPlugin_Mesher.cxx index 039c8f6..5853a7e 100644 --- a/src/NETGENPlugin/NETGENPlugin_Mesher.cxx +++ b/src/NETGENPlugin/NETGENPlugin_Mesher.cxx @@ -1,4 +1,4 @@ -// Copyright (C) 2007-2014 CEA/DEN, EDF R&D, OPEN CASCADE +// Copyright (C) 2007-2021 CEA/DEN, EDF R&D, OPEN CASCADE // // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS @@ -32,12 +32,14 @@ #include "NETGENPlugin_SimpleHypothesis_3D.hxx" #include +#include #include #include #include #include #include #include +#include #include #include #include @@ -50,22 +52,29 @@ #include +#include #include +#include +#include +#include #include #include +#include #include +#include #include #include +#include #include #include +#include #include #include #include #include #include #include -#include -#include +#include // Netgen include files #ifndef OCCGEOMETRY @@ -75,15 +84,21 @@ #include //#include namespace netgen { -#ifdef NETGEN_V5 - extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, MeshingParameters&, int, int); -#else - extern int OCCGenerateMesh (OCCGeometry&, Mesh*&, int, int, char*); -#endif - //extern void OCCSetLocalMeshSize(OCCGeometry & geom, Mesh & mesh); + + NETGENPLUGIN_DLL_HEADER extern MeshingParameters mparam; + + NETGENPLUGIN_DLL_HEADER extern volatile multithreadt multithread; + + NETGENPLUGIN_DLL_HEADER extern bool merge_solids; + + // values used for occgeo.facemeshstatus + enum EFaceMeshStatus { FACE_NOT_TREATED = 0, + FACE_FAILED = -1, + FACE_MESHED_OK = 1, + }; } #include @@ -103,15 +118,390 @@ using namespace std; #define NGPOINT_COORDS(p) p(0),p(1),p(2) +#ifdef _DEBUG_ // dump elements added to ng mesh //#define DUMP_SEGMENTS //#define DUMP_TRIANGLES //#define DUMP_TRIANGLES_SCRIPT "/tmp/trias.py" //!< debug AddIntVerticesInSolids() +#endif TopTools_IndexedMapOfShape ShapesWithLocalSize; std::map VertexId2LocalSize; std::map EdgeId2LocalSize; std::map FaceId2LocalSize; +std::map SolidId2LocalSize; + +std::vector ControlPoints; +std::set ShapesWithControlPoints; // <-- allows calling SetLocalSize() several times w/o recomputing ControlPoints + +namespace +{ + inline void NOOP_Deleter(void *) { ; } + + //============================================================================= + /*! + * Link - a pair of integer numbers + */ + //============================================================================= + struct Link + { + int n1, n2; + Link(int _n1, int _n2) : n1(_n1), n2(_n2) {} + Link() : n1(0), n2(0) {} + bool Contains( int n ) const { return n == n1 || n == n2; } + bool IsConnected( const Link& other ) const + { + return (( Contains( other.n1 ) || Contains( other.n2 )) && ( this != &other )); + } + static int HashCode(const Link& aLink, int aLimit) + { + return ::HashCode(aLink.n1 + aLink.n2, aLimit); + } + + static Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2) + { + return (( aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 ) || + ( aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1 )); + } + }; + + typedef NCollection_Map TLinkMap; + + //================================================================================ + /*! + * \brief return id of netgen point corresponding to SMDS node + */ + //================================================================================ + typedef map< const SMDS_MeshNode*, int > TNode2IdMap; + + int ngNodeId( const SMDS_MeshNode* node, + netgen::Mesh& ngMesh, + TNode2IdMap& nodeNgIdMap) + { + int newNgId = ngMesh.GetNP() + 1; + + TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first; + + if ( node_id->second == newNgId) + { +#if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES) + cout << "Ng " << newNgId << " - " << node; +#endif + netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) ); + ngMesh.AddPoint( p ); + } + return node_id->second; + } + + //================================================================================ + /*! + * \brief Return computed EDGEs connected to the given one + */ + //================================================================================ + + list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge& edge, + const TopoDS_Face& face, + const set< SMESH_subMesh* > & /*computedSM*/, + const SMESH_MesherHelper& helper, + map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces) + { + // get ordered EDGEs + list< TopoDS_Edge > edges; + list< int > nbEdgesInWire; + /*int nbWires =*/ SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire); + + // find within + list< TopoDS_Edge >::iterator eItFwd = edges.begin(); + for ( ; eItFwd != edges.end(); ++eItFwd ) + if ( edge.IsSame( *eItFwd )) + break; + if ( eItFwd == edges.end()) return list< TopoDS_Edge>(); + + if ( eItFwd->Orientation() >= TopAbs_INTERNAL ) + { + // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented + // so treat each INTERNAL edge separately + TopoDS_Edge e = *eItFwd; + edges.clear(); + edges.push_back( e ); + return edges; + } + + // get all computed EDGEs connected to + + list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev; + TopoDS_Vertex vCommon; + TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to + eAdded.Add( edge ); + + // put edges before to back + while ( edges.begin() != eItFwd ) + edges.splice( edges.end(), edges, edges.begin() ); + + // search forward + ePrev = eItFwd; + while ( ++eItFwd != edges.end() ) + { + SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd ); + + bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon ); + bool computed = !sm->IsEmpty(); + bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() ); + bool doubled = !eAdded.Add( *eItFwd ); + bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) == + ( eItFwd->Orientation() < TopAbs_INTERNAL ) ); + if ( !connected || !computed || !orientOK || added || doubled ) + { + // stop advancement; move edges from tail to head + while ( edges.back() != *ePrev ) + edges.splice( edges.begin(), edges, --edges.end() ); + break; + } + ePrev = eItFwd; + } + // search backward + while ( eItBack != edges.begin() ) + { + ePrev = eItBack; + --eItBack; + SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack ); + + bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon ); + bool computed = !sm->IsEmpty(); + bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() ); + bool doubled = !eAdded.Add( *eItBack ); + bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) == + ( eItBack->Orientation() < TopAbs_INTERNAL ) ); + if ( !connected || !computed || !orientOK || added || doubled) + { + // stop advancement + edges.erase( edges.begin(), ePrev ); + break; + } + } + if ( edges.front() != edges.back() ) + { + // assure that the 1st vertex is meshed + TopoDS_Edge eLast = edges.back(); + while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS()) + && + edges.front() != eLast ) + edges.splice( edges.end(), edges, edges.begin() ); + } + return edges; + } + + //================================================================================ + /*! + * \brief Make triangulation of a shape precise enough + */ + //================================================================================ + + void updateTriangulation( const TopoDS_Shape& shape ) + { + // static set< Poly_Triangulation* > updated; + + // TopLoc_Location loc; + // TopExp_Explorer fExp( shape, TopAbs_FACE ); + // for ( ; fExp.More(); fExp.Next() ) + // { + // Handle(Poly_Triangulation) triangulation = + // BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc); + // if ( triangulation.IsNull() || + // updated.insert( triangulation.operator->() ).second ) + // { + // BRepTools::Clean (shape); + try { + OCC_CATCH_SIGNALS; + BRepMesh_IncrementalMesh e(shape, 0.01, true); + } + catch (Standard_Failure&) + { + } + // updated.erase( triangulation.operator->() ); + // triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc); + // updated.insert( triangulation.operator->() ); + // } + // } + } + //================================================================================ + /*! + * \brief Returns a medium node either existing in SMESH of created by NETGEN + * \param [in] corner1 - corner node 1 + * \param [in] corner2 - corner node 2 + * \param [in] defaultMedium - the node created by NETGEN + * \param [in] helper - holder of medium nodes existing in SMESH + * \return const SMDS_MeshNode* - the result node + */ + //================================================================================ + + const SMDS_MeshNode* mediumNode( const SMDS_MeshNode* corner1, + const SMDS_MeshNode* corner2, + const SMDS_MeshNode* defaultMedium, + const SMESH_MesherHelper* helper) + { + if ( helper ) + { + TLinkNodeMap::const_iterator l2n = + helper->GetTLinkNodeMap().find( SMESH_TLink( corner1, corner2 )); + if ( l2n != helper->GetTLinkNodeMap().end() ) + defaultMedium = l2n->second; + } + return defaultMedium; + } + + //================================================================================ + /*! + * \brief Assure that mesh on given shapes is quadratic + */ + //================================================================================ + + // void makeQuadratic( const TopTools_IndexedMapOfShape& shapes, + // SMESH_Mesh* mesh ) + // { + // for ( int i = 1; i <= shapes.Extent(); ++i ) + // { + // SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) ); + // if ( !smDS ) continue; + // SMDS_ElemIteratorPtr elemIt = smDS->GetElements(); + // if ( !elemIt->more() ) continue; + // const SMDS_MeshElement* e = elemIt->next(); + // if ( !e || e->IsQuadratic() ) + // continue; + + // TIDSortedElemSet elems; + // elems.insert( e ); + // while ( elemIt->more() ) + // elems.insert( elems.end(), elemIt->next() ); + + // SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false ); + // } + // } + + //================================================================================ + /*! + * \brief Restrict size of elements on the given edge + */ + //================================================================================ + + void setLocalSize(const TopoDS_Edge& edge, + double size, + netgen::Mesh& mesh, + const bool overrideMinH = true) + { + if ( size <= std::numeric_limits::min() ) + return; + Standard_Real u1, u2; + Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2); + if ( curve.IsNull() ) + { + TopoDS_Iterator vIt( edge ); + if ( !vIt.More() ) return; + gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() )); + NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH ); + } + else + { + const int nb = (int)( 1.5 * SMESH_Algo::EdgeLength( edge ) / size ); + Standard_Real delta = (u2-u1)/nb; + for(int i=0; iValue(u); + NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size, overrideMinH ); + netgen::Point3d pi(p.X(), p.Y(), p.Z()); + double resultSize = mesh.GetH(pi); + if ( resultSize - size > 0.1*size ) + // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136) + NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201, overrideMinH ); + } + } + } + + //================================================================================ + /*! + * \brief Return triangle size for a given chordalError and radius of curvature + */ + //================================================================================ + + double elemSizeForChordalError( double chordalError, double radius ) + { + if ( 2 * radius < chordalError ) + return 1.5 * radius; + return Sqrt( 3 ) * Sqrt( chordalError * ( 2 * radius - chordalError )); + } + + //============================================================================= + /*! + * + */ + //============================================================================= + + void setLocalSize(const TopoDS_Shape& GeomShape, double LocalSize) + { + if ( GeomShape.IsNull() ) return; + TopAbs_ShapeEnum GeomType = GeomShape.ShapeType(); + if (GeomType == TopAbs_COMPOUND) { + for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) { + setLocalSize(it.Value(), LocalSize); + } + return; + } + int key; + if (! ShapesWithLocalSize.Contains(GeomShape)) + key = ShapesWithLocalSize.Add(GeomShape); + else + key = ShapesWithLocalSize.FindIndex(GeomShape); + if (GeomType == TopAbs_VERTEX) { + VertexId2LocalSize[key] = LocalSize; + } else if (GeomType == TopAbs_EDGE) { + EdgeId2LocalSize[key] = LocalSize; + } else if (GeomType == TopAbs_FACE) { + FaceId2LocalSize[key] = LocalSize; + } else if (GeomType == TopAbs_SOLID) { + SolidId2LocalSize[key] = LocalSize; + } + return; + } + + //================================================================================ + /*! + * \brief Return faceNgID or faceNgID-1 depending on side the given proxy face lies + * \param [in] f - proxy face + * \param [in] solidSMDSIDs - IDs of SOLIDs sharing the FACE on which face lies + * \param [in] faceNgID - NETGEN ID of the FACE + * \return int - NETGEN ID of the FACE + */ + //================================================================================ + + int getFaceNgID( const SMDS_MeshElement* face, + const int * solidSMDSIDs, + const int faceNgID ) + { + for ( int i = 0; i < 3; ++i ) + { + const SMDS_MeshNode* n = face->GetNode( i ); + const int shapeID = n->GetShapeID(); + if ( shapeID == solidSMDSIDs[0] ) + return faceNgID - 1; + if ( shapeID == solidSMDSIDs[1] ) + return faceNgID; + } + std::vector fNodes( face->begin_nodes(), face->end_nodes() ); + std::vector vols; + if ( SMDS_Mesh::GetElementsByNodes( fNodes, vols, SMDSAbs_Volume )) + for ( size_t i = 0; i < vols.size(); ++i ) + { + const int shapeID = vols[i]->GetShapeID(); + if ( shapeID == solidSMDSIDs[0] ) + return faceNgID - 1; + if ( shapeID == solidSMDSIDs[1] ) + return faceNgID; + } + return faceNgID; + } + +} // namespace //============================================================================= /*! @@ -128,12 +518,14 @@ NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh, _optimize(true), _fineness(NETGENPlugin_Hypothesis::GetDefaultFineness()), _isViscousLayers2D(false), + _chordalError(-1), // means disabled _ngMesh(NULL), _occgeom(NULL), _curShapeIndex(-1), _progressTic(1), _totalTime(1.0), _simpleHyp(NULL), + _viscousLayersHyp(NULL), _ptrToMe(NULL) { SetDefaultParameters(); @@ -141,11 +533,14 @@ NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh, VertexId2LocalSize.clear(); EdgeId2LocalSize.clear(); FaceId2LocalSize.clear(); + SolidId2LocalSize.clear(); + ControlPoints.clear(); + ShapesWithControlPoints.clear(); } //================================================================================ /*! - * Destuctor + * Destructor */ //================================================================================ @@ -184,6 +579,7 @@ void NETGENPlugin_Mesher::SetSelfPointer( NETGENPlugin_Mesher ** ptr ) void NETGENPlugin_Mesher::SetDefaultParameters() { netgen::MeshingParameters& mparams = netgen::mparam; + mparams = netgen::MeshingParameters(); // maximal mesh edge size mparams.maxh = 0;//NETGENPlugin_Hypothesis::GetDefaultMaxSize(); mparams.minh = 0; @@ -205,34 +601,6 @@ void NETGENPlugin_Mesher::SetDefaultParameters() netgen::merge_solids = NETGENPlugin_Hypothesis::GetDefaultFuseEdges(); } -//============================================================================= -/*! - * - */ -//============================================================================= -void SetLocalSize(TopoDS_Shape GeomShape, double LocalSize) -{ - TopAbs_ShapeEnum GeomType = GeomShape.ShapeType(); - if (GeomType == TopAbs_COMPOUND) { - for (TopoDS_Iterator it (GeomShape); it.More(); it.Next()) { - SetLocalSize(it.Value(), LocalSize); - } - return; - } - int key; - if (! ShapesWithLocalSize.Contains(GeomShape)) - key = ShapesWithLocalSize.Add(GeomShape); - else - key = ShapesWithLocalSize.FindIndex(GeomShape); - if (GeomType == TopAbs_VERTEX) { - VertexId2LocalSize[key] = LocalSize; - } else if (GeomType == TopAbs_EDGE) { - EdgeId2LocalSize[key] = LocalSize; - } else if (GeomType == TopAbs_FACE) { - FaceId2LocalSize[key] = LocalSize; - } -} - //============================================================================= /*! * Pass parameters to NETGEN @@ -245,53 +613,68 @@ void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_Hypothesis* hyp) netgen::MeshingParameters& mparams = netgen::mparam; // Initialize global NETGEN parameters: // maximal mesh segment size - mparams.maxh = hyp->GetMaxSize(); + mparams.maxh = hyp->GetMaxSize(); // maximal mesh element linear size - mparams.minh = hyp->GetMinSize(); + mparams.minh = hyp->GetMinSize(); // minimal number of segments per edge - mparams.segmentsperedge = hyp->GetNbSegPerEdge(); + mparams.segmentsperedge = hyp->GetNbSegPerEdge(); // rate of growth of size between elements - mparams.grading = hyp->GetGrowthRate(); + mparams.grading = hyp->GetGrowthRate(); // safety factor for curvatures (elements per radius) - mparams.curvaturesafety = hyp->GetNbSegPerRadius(); + mparams.curvaturesafety = hyp->GetNbSegPerRadius(); // create elements of second order - mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0; + mparams.secondorder = hyp->GetSecondOrder() ? 1 : 0; // quad-dominated surface meshing - // only triangles are allowed for volumic mesh (before realizing IMP 0021676) - //if (!_isVolume) - mparams.quad = hyp->GetQuadAllowed() ? 1 : 0; - _optimize = hyp->GetOptimize(); - _fineness = hyp->GetFineness(); - mparams.uselocalh = hyp->GetSurfaceCurvature(); - netgen::merge_solids = hyp->GetFuseEdges(); - _simpleHyp = NULL; - - SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen(); - CORBA::Object_var anObject = smeshGen_i->GetNS()->Resolve("/myStudyManager"); - SALOMEDS::StudyManager_var aStudyMgr = SALOMEDS::StudyManager::_narrow(anObject); - SALOMEDS::Study_var myStudy = aStudyMgr->GetStudyByID(hyp->GetStudyId()); - - const NETGENPlugin_Hypothesis::TLocalSize localSizes = hyp->GetLocalSizesAndEntries(); - NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin(); - for (it ; it != localSizes.end() ; it++) + mparams.quad = hyp->GetQuadAllowed() ? 1 : 0; + _optimize = hyp->GetOptimize(); + _fineness = hyp->GetFineness(); + mparams.uselocalh = hyp->GetSurfaceCurvature(); + netgen::merge_solids = hyp->GetFuseEdges(); + _chordalError = hyp->GetChordalErrorEnabled() ? hyp->GetChordalError() : -1.; + mparams.optsteps2d = _optimize ? hyp->GetNbSurfOptSteps() : 0; + mparams.optsteps3d = _optimize ? hyp->GetNbVolOptSteps() : 0; + mparams.elsizeweight = hyp->GetElemSizeWeight(); + mparams.opterrpow = hyp->GetWorstElemMeasure(); + mparams.delaunay = hyp->GetUseDelauney(); + mparams.checkoverlap = hyp->GetCheckOverlapping(); + mparams.checkchartboundary = hyp->GetCheckChartBoundary(); + _simpleHyp = NULL; + // mesh size file +#ifdef NETGEN_V6 + // std::string + mparams.meshsizefilename = hyp->GetMeshSizeFile(); +#else + // const char* + mparams.meshsizefilename= hyp->GetMeshSizeFile().empty() ? 0 : hyp->GetMeshSizeFile().c_str(); +#endif + const NETGENPlugin_Hypothesis::TLocalSize& localSizes = hyp->GetLocalSizesAndEntries(); + if ( !localSizes.empty() ) + { + SMESH_Gen_i* smeshGen_i = SMESH_Gen_i::GetSMESHGen(); + NETGENPlugin_Hypothesis::TLocalSize::const_iterator it = localSizes.begin(); + for ( ; it != localSizes.end() ; it++) { std::string entry = (*it).first; - double val = (*it).second; + double val = (*it).second; // -- GEOM::GEOM_Object_var aGeomObj; - TopoDS_Shape S = TopoDS_Shape(); - SALOMEDS::SObject_var aSObj = myStudy->FindObjectID( entry.c_str() ); - if (!aSObj->_is_nil()) { + SALOMEDS::SObject_var aSObj = SMESH_Gen_i::GetSMESHGen()->getStudyServant()->FindObjectID( entry.c_str() ); + if ( !aSObj->_is_nil() ) { CORBA::Object_var obj = aSObj->GetObject(); aGeomObj = GEOM::GEOM_Object::_narrow(obj); aSObj->UnRegister(); } - if ( !aGeomObj->_is_nil() ) - S = smeshGen_i->GeomObjectToShape( aGeomObj.in() ); - // -- - SetLocalSize(S, val); + TopoDS_Shape S = smeshGen_i->GeomObjectToShape( aGeomObj.in() ); + setLocalSize(S, val); } + } } + +#ifdef NETGEN_V6 + + netgen::mparam.closeedgefac = 2; + +#endif } //============================================================================= @@ -307,242 +690,229 @@ void NETGENPlugin_Mesher::SetParameters(const NETGENPlugin_SimpleHypothesis_2D* SetDefaultParameters(); } -//============================================================================= +//================================================================================ /*! - * Link - a pair of integer numbers + * \brief Store a Viscous Layers hypothesis */ -//============================================================================= -struct Link -{ - int n1, n2; - Link(int _n1, int _n2) : n1(_n1), n2(_n2) {} - Link() : n1(0), n2(0) {} -}; - -int HashCode(const Link& aLink, int aLimit) -{ - return HashCode(aLink.n1 + aLink.n2, aLimit); -} +//================================================================================ -Standard_Boolean IsEqual(const Link& aLink1, const Link& aLink2) +void NETGENPlugin_Mesher::SetParameters(const StdMeshers_ViscousLayers* hyp ) { - return (aLink1.n1 == aLink2.n1 && aLink1.n2 == aLink2.n2 || - aLink1.n1 == aLink2.n2 && aLink1.n2 == aLink2.n1); + _viscousLayersHyp = hyp; } -namespace -{ - //================================================================================ - /*! - * \brief return id of netgen point corresponding to SMDS node - */ - //================================================================================ - typedef map< const SMDS_MeshNode*, int > TNode2IdMap; - - int ngNodeId( const SMDS_MeshNode* node, - netgen::Mesh& ngMesh, - TNode2IdMap& nodeNgIdMap) - { - int newNgId = ngMesh.GetNP() + 1; - - TNode2IdMap::iterator node_id = nodeNgIdMap.insert( make_pair( node, newNgId )).first; - - if ( node_id->second == newNgId) - { -#if defined(DUMP_SEGMENTS) || defined(DUMP_TRIANGLES) - cout << "Ng " << newNgId << " - " << node; -#endif - netgen::MeshPoint p( netgen::Point<3> (node->X(), node->Y(), node->Z()) ); - ngMesh.AddPoint( p ); - } - return node_id->second; - } - - //================================================================================ - /*! - * \brief Return computed EDGEs connected to the given one - */ - //================================================================================ - - list< TopoDS_Edge > getConnectedEdges( const TopoDS_Edge& edge, - const TopoDS_Face& face, - const set< SMESH_subMesh* > & computedSM, - const SMESH_MesherHelper& helper, - map< SMESH_subMesh*, set< int > >& addedEdgeSM2Faces) - { - // get ordered EDGEs - list< TopoDS_Edge > edges; - list< int > nbEdgesInWire; - int nbWires = SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire); - - // find within - list< TopoDS_Edge >::iterator eItFwd = edges.begin(); - for ( ; eItFwd != edges.end(); ++eItFwd ) - if ( edge.IsSame( *eItFwd )) - break; - if ( eItFwd == edges.end()) return list< TopoDS_Edge>(); - - if ( eItFwd->Orientation() >= TopAbs_INTERNAL ) - { - // connected INTERNAL edges returned from GetOrderedEdges() are wrongly oriented - // so treat each INTERNAL edge separately - TopoDS_Edge e = *eItFwd; - edges.clear(); - edges.push_back( e ); - return edges; - } - - // get all computed EDGEs connected to - - list< TopoDS_Edge >::iterator eItBack = eItFwd, ePrev; - TopoDS_Vertex vCommon; - TopTools_MapOfShape eAdded; // map used not to add a seam edge twice to - eAdded.Add( edge ); - - // put edges before to back - while ( edges.begin() != eItFwd ) - edges.splice( edges.end(), edges, edges.begin() ); - - // search forward - ePrev = eItFwd; - while ( ++eItFwd != edges.end() ) - { - SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItFwd ); +//================================================================================ +/*! + * \brief Set local size on shapes defined by SetParameters() + */ +//================================================================================ - bool connected = TopExp::CommonVertex( *ePrev, *eItFwd, vCommon ); - bool computed = sm->IsMeshComputed(); - bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() ); - bool doubled = !eAdded.Add( *eItFwd ); - bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) == - ( eItFwd->Orientation() < TopAbs_INTERNAL ) ); - if ( !connected || !computed || !orientOK || added || doubled ) - { - // stop advancement; move edges from tail to head - while ( edges.back() != *ePrev ) - edges.splice( edges.begin(), edges, --edges.end() ); - break; - } - ePrev = eItFwd; +void NETGENPlugin_Mesher::SetLocalSize( netgen::OCCGeometry& occgeo, + netgen::Mesh& ngMesh) +{ + // edges + std::map::const_iterator it; + for( it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++) + { + int key = (*it).first; + double hi = (*it).second; + const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key); + setLocalSize( TopoDS::Edge(shape), hi, ngMesh ); + } + // vertices + for(it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++) + { + int key = (*it).first; + double hi = (*it).second; + const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key); + gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex(shape) ); + NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, p.XYZ(), hi ); + } + // faces + for(it=FaceId2LocalSize.begin(); it!=FaceId2LocalSize.end(); it++) + { + int key = (*it).first; + double val = (*it).second; + const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key); + int faceNgID = occgeo.fmap.FindIndex(shape); + if ( faceNgID >= 1 ) + { +#ifdef NETGEN_V6 + occgeo.SetFaceMaxH(faceNgID-1, val, netgen::mparam); +#else + occgeo.SetFaceMaxH(faceNgID, val); +#endif + for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() ) + setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, ngMesh ); } - // search backward - while ( eItBack != edges.begin() ) + else if ( !ShapesWithControlPoints.count( key )) { - ePrev = eItBack; - --eItBack; - SMESH_subMesh* sm = helper.GetMesh()->GetSubMesh( *eItBack ); - - bool connected = TopExp::CommonVertex( *ePrev, *eItBack, vCommon ); - bool computed = sm->IsMeshComputed(); - bool added = addedEdgeSM2Faces[ sm ].count( helper.GetSubShapeID() ); - bool doubled = !eAdded.Add( *eItBack ); - bool orientOK = (( ePrev ->Orientation() < TopAbs_INTERNAL ) == - ( eItBack->Orientation() < TopAbs_INTERNAL ) ); - if ( !connected || !computed || !orientOK || added || doubled) - { - // stop advancement - edges.erase( edges.begin(), ePrev ); - break; - } + SMESHUtils::createPointsSampleFromFace( TopoDS::Face( shape ), val, ControlPoints ); + ShapesWithControlPoints.insert( key ); } - if ( edges.front() != edges.back() ) + } + //solids + for(it=SolidId2LocalSize.begin(); it!=SolidId2LocalSize.end(); it++) + { + int key = (*it).first; + double val = (*it).second; + if ( !ShapesWithControlPoints.count( key )) { - // assure that the 1st vertex is meshed - TopoDS_Edge eLast = edges.back(); - while ( !SMESH_Algo::VertexNode( SMESH_MesherHelper::IthVertex( 0, edges.front()), helper.GetMeshDS()) - && - edges.front() != eLast ) - edges.splice( edges.end(), edges, edges.begin() ); + const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key); + SMESHUtils::createPointsSampleFromSolid( TopoDS::Solid( shape ), val, ControlPoints ); + ShapesWithControlPoints.insert( key ); } - return edges; } - //================================================================================ - /*! - * \brief Make triangulation of a shape precise enough - */ - //================================================================================ - - void updateTriangulation( const TopoDS_Shape& shape ) + if ( !ControlPoints.empty() ) { - // static set< Poly_Triangulation* > updated; - - // TopLoc_Location loc; - // TopExp_Explorer fExp( shape, TopAbs_FACE ); - // for ( ; fExp.More(); fExp.Next() ) - // { - // Handle(Poly_Triangulation) triangulation = - // BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc); - // if ( triangulation.IsNull() || - // updated.insert( triangulation.operator->() ).second ) - // { - // BRepTools::Clean (shape); - try { - OCC_CATCH_SIGNALS; - BRepMesh_IncrementalMesh e(shape, 0.01, true); - } - catch (Standard_Failure) - { - } - // updated.erase( triangulation.operator->() ); - // triangulation = BRep_Tool::Triangulation ( TopoDS::Face( fExp.Current() ), loc); - // updated.insert( triangulation.operator->() ); - // } - // } + for ( size_t i = 0; i < ControlPoints.size(); ++i ) + NETGENPlugin_Mesher::RestrictLocalSize( ngMesh, ControlPoints[i].XYZ(), ControlPoints[i].Size() ); } - //================================================================================ - /*! - * \brief Returns a medium node either existing in SMESH of created by NETGEN - * \param [in] corner1 - corner node 1 - * \param [in] corner2 - corner node 2 - * \param [in] defaultMedium - the node created by NETGEN - * \param [in] helper - holder of medium nodes existing in SMESH - * \return const SMDS_MeshNode* - the result node - */ - //================================================================================ + return; +} - const SMDS_MeshNode* mediumNode( const SMDS_MeshNode* corner1, - const SMDS_MeshNode* corner2, - const SMDS_MeshNode* defaultMedium, - const SMESH_MesherHelper* helper) +//================================================================================ +/*! + * \brief Restrict local size to achieve a required _chordalError + */ +//================================================================================ + +void NETGENPlugin_Mesher::SetLocalSizeForChordalError( netgen::OCCGeometry& occgeo, + netgen::Mesh& ngMesh) +{ + if ( _chordalError <= 0. ) + return; + + TopLoc_Location loc; + BRepLProp_SLProps surfProp( 2, 1e-6 ); + const double sizeCoef = 0.95; + + // find non-planar FACEs with non-constant curvature + std::vector fInd; + for ( int i = 1; i <= occgeo.fmap.Extent(); ++i ) { - if ( helper ) + const TopoDS_Face& face = TopoDS::Face( occgeo.fmap( i )); + BRepAdaptor_Surface surfAd( face, false ); + switch ( surfAd.GetType() ) { - TLinkNodeMap::const_iterator l2n = - helper->GetTLinkNodeMap().find( SMESH_TLink( corner1, corner2 )); - if ( l2n != helper->GetTLinkNodeMap().end() ) - defaultMedium = l2n->second; + case GeomAbs_Plane: + continue; + case GeomAbs_Cylinder: + case GeomAbs_Sphere: + case GeomAbs_Torus: // constant curvature + { + surfProp.SetSurface( surfAd ); + surfProp.SetParameters( 0, 0 ); + double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() )); + double size = elemSizeForChordalError( _chordalError, 1 / maxCurv ); +#ifdef NETGEN_V6 + occgeo.SetFaceMaxH( i-1, size * sizeCoef, netgen::mparam ); +#else + occgeo.SetFaceMaxH( i, size * sizeCoef ); +#endif + // limit size one edges + TopTools_MapOfShape edgeMap; + for ( TopExp_Explorer eExp( face, TopAbs_EDGE ); eExp.More(); eExp.Next() ) + if ( edgeMap.Add( eExp.Current() )) + setLocalSize( TopoDS::Edge( eExp.Current() ), size, ngMesh, /*overrideMinH=*/false ); + break; + } + default: + Handle(Geom_Surface) surf = BRep_Tool::Surface( face, loc ); + if ( GeomLib_IsPlanarSurface( surf ).IsPlanar() ) + continue; + fInd.push_back( i ); } - return defaultMedium; } - - //================================================================================ - /*! - * \brief Assure that mesh on given shapes is quadratic - */ - //================================================================================ - - void makeQuadratic( const TopTools_IndexedMapOfShape& shapes, - SMESH_Mesh* mesh ) + // set local size + if ( !fInd.empty() ) { - for ( int i = 1; i <= shapes.Extent(); ++i ) + BRep_Builder b; + TopoDS_Compound allFacesComp; + b.MakeCompound( allFacesComp ); + for ( size_t i = 0; i < fInd.size(); ++i ) + b.Add( allFacesComp, occgeo.fmap( fInd[i] )); + + // copy the shape to avoid spoiling its triangulation + TopoDS_Shape allFacesCompCopy = BRepBuilderAPI_Copy( allFacesComp ); + + // create triangulation with desired chordal error + BRepMesh_IncrementalMesh( allFacesCompCopy, + _chordalError, + /*isRelative = */Standard_False, + /*theAngDeflection = */ 0.5, + /*isInParallel = */Standard_True); + + // loop on FACEs + for ( TopExp_Explorer fExp( allFacesCompCopy, TopAbs_FACE ); fExp.More(); fExp.Next() ) { - SMESHDS_SubMesh* smDS = mesh->GetMeshDS()->MeshElements( shapes(i) ); - if ( !smDS ) continue; - SMDS_ElemIteratorPtr elemIt = smDS->GetElements(); - if ( !elemIt->more() ) continue; - const SMDS_MeshElement* e = elemIt->next(); - if ( !e || e->IsQuadratic() ) - continue; + const TopoDS_Face& face = TopoDS::Face( fExp.Current() ); + Handle(Poly_Triangulation) triangulation = BRep_Tool::Triangulation ( face, loc ); + if ( triangulation.IsNull() ) continue; + + BRepAdaptor_Surface surf( face, false ); + surfProp.SetSurface( surf ); + + gp_XY uv[3]; + gp_XYZ p[3]; + double size[3]; + for ( int i = 1; i <= triangulation->NbTriangles(); ++i ) + { + Standard_Integer n1,n2,n3; + triangulation->Triangles()(i).Get( n1,n2,n3 ); + p [0] = triangulation->Nodes()(n1).Transformed(loc).XYZ(); + p [1] = triangulation->Nodes()(n2).Transformed(loc).XYZ(); + p [2] = triangulation->Nodes()(n3).Transformed(loc).XYZ(); + uv[0] = triangulation->UVNodes()(n1).XY(); + uv[1] = triangulation->UVNodes()(n2).XY(); + uv[2] = triangulation->UVNodes()(n3).XY(); + surfProp.SetParameters( uv[0].X(), uv[0].Y() ); + if ( !surfProp.IsCurvatureDefined() ) + break; + + for ( int n = 0; n < 3; ++n ) // get size at triangle nodes + { + surfProp.SetParameters( uv[n].X(), uv[n].Y() ); + double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() )); + size[n] = elemSizeForChordalError( _chordalError, 1 / maxCurv ); + } + for ( int n1 = 0; n1 < 3; ++n1 ) // limit size along each triangle edge + { + int n2 = ( n1 + 1 ) % 3; + double minSize = size[n1], maxSize = size[n2]; + if ( size[n1] > size[n2] ) + minSize = size[n2], maxSize = size[n1]; - TIDSortedElemSet elems; - elems.insert( e ); - while ( elemIt->more() ) - elems.insert( elems.end(), elemIt->next() ); + if ( maxSize / minSize < 1.2 ) // netgen ignores size difference < 1.2 + { + ngMesh.RestrictLocalHLine ( netgen::Point3d( p[n1].X(), p[n1].Y(), p[n1].Z() ), + netgen::Point3d( p[n2].X(), p[n2].Y(), p[n2].Z() ), + sizeCoef * minSize ); + } + else + { + gp_XY uvVec( uv[n2] - uv[n1] ); + double len = ( p[n1] - p[n2] ).Modulus(); + int nb = int( len / minSize ) + 1; + for ( int j = 0; j <= nb; ++j ) + { + double r = double( j ) / nb; + gp_XY uvj = uv[n1] + r * uvVec; + + surfProp.SetParameters( uvj.X(), uvj.Y() ); + double maxCurv = Max( Abs( surfProp.MaxCurvature()), Abs( surfProp.MinCurvature() )); + double h = elemSizeForChordalError( _chordalError, 1 / maxCurv ); - SMESH_MeshEditor( mesh ).ConvertToQuadratic( /*3d=*/false, elems, /*biQuad=*/false ); + const gp_Pnt& pj = surfProp.Value(); + netgen::Point3d ngP( pj.X(), pj.Y(), pj.Z()); + ngMesh.RestrictLocalH( ngP, h * sizeCoef ); + } + } + } + } } } - } //================================================================================ @@ -563,9 +933,6 @@ void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo, BRepBndLib::Add (shape, bb); double x1,y1,z1,x2,y2,z2; bb.Get (x1,y1,z1,x2,y2,z2); - MESSAGE("shape bounding box:\n" << - "(" << x1 << " " << y1 << " " << z1 << ") " << - "(" << x2 << " " << y2 << " " << z2 << ")"); netgen::Point<3> p1 = netgen::Point<3> (x1,y1,z1); netgen::Point<3> p2 = netgen::Point<3> (x2,y2,z2); occgeo.boundingbox = netgen::Box<3> (p1,p2); @@ -586,6 +953,8 @@ void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo, rootSM.push_back( mesh.GetSubMesh( it.Value() )); } + int totNbFaces = 0; + // add subshapes of empty submeshes list< SMESH_subMesh* >::iterator rootIt = rootSM.begin(), rootEnd = rootSM.end(); for ( ; rootIt != rootEnd; ++rootIt ) { @@ -597,8 +966,9 @@ void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo, TopExp::MapShapes(root->GetSubShape(), subShapes); while ( smIt->more() ) { - SMESH_subMesh* sm = smIt->next(); + SMESH_subMesh* sm = smIt->next(); TopoDS_Shape shape = sm->GetSubShape(); + totNbFaces += ( shape.ShapeType() == TopAbs_FACE ); if ( intern && intern->isShapeToPrecompute( shape )) continue; if ( !meshedSM || sm->IsEmpty() ) @@ -606,7 +976,7 @@ void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo, if ( shape.ShapeType() != TopAbs_VERTEX ) shape = subShapes( subShapes.FindIndex( shape ));// shape -> index -> oriented shape if ( shape.Orientation() >= TopAbs_INTERNAL ) - shape.Orientation( TopAbs_FORWARD ); // isuue 0020676 + shape.Orientation( TopAbs_FORWARD ); // issue 0020676 switch ( shape.ShapeType() ) { case TopAbs_FACE : occgeo.fmap.Add( shape ); break; case TopAbs_EDGE : occgeo.emap.Add( shape ); break; @@ -623,11 +993,11 @@ void NETGENPlugin_Mesher::PrepareOCCgeometry(netgen::OCCGeometry& occgeo, } } } - occgeo.facemeshstatus.SetSize (occgeo.fmap.Extent()); + occgeo.facemeshstatus.SetSize (totNbFaces); occgeo.facemeshstatus = 0; - occgeo.face_maxh_modified.SetSize(occgeo.fmap.Extent()); + occgeo.face_maxh_modified.SetSize(totNbFaces); occgeo.face_maxh_modified = 0; - occgeo.face_maxh.SetSize(occgeo.fmap.Extent()); + occgeo.face_maxh.SetSize(totNbFaces); occgeo.face_maxh = netgen::mparam.maxh; } @@ -675,7 +1045,7 @@ double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom, } else { - minh = 3 * sqrt( minh ); // triangulation for visualization is rather fine + minh = sqrt( minh ); // triangulation for visualization is rather fine //cout << "TRIANGULATION minh = " < 0.5 * maxSize ) @@ -690,12 +1060,24 @@ double NETGENPlugin_Mesher::GetDefaultMinSize(const TopoDS_Shape& geom, */ //================================================================================ -void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh, const gp_XYZ& p, const double size) +void NETGENPlugin_Mesher::RestrictLocalSize(netgen::Mesh& ngMesh, + const gp_XYZ& p, + double size, + const bool overrideMinH) { + if ( size <= std::numeric_limits::min() ) + return; if ( netgen::mparam.minh > size ) { - ngMesh.SetMinimalH( size ); - netgen::mparam.minh = size; + if ( overrideMinH ) + { + ngMesh.SetMinimalH( size ); + netgen::mparam.minh = size; + } + else + { + size = netgen::mparam.minh; + } } netgen::Point3d pi(p.X(), p.Y(), p.Z()); ngMesh.RestrictLocalH( pi, size ); @@ -715,7 +1097,7 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom, SMESH_ProxyMesh::Ptr proxyMesh) { TNode2IdMap nodeNgIdMap; - for ( int i = 1; i < nodeVec.size(); ++i ) + for ( size_t i = 1; i < nodeVec.size(); ++i ) nodeNgIdMap.insert( make_pair( nodeVec[i], i )); TopTools_MapOfShape visitedShapes; @@ -723,6 +1105,7 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom, set< SMESH_subMesh* > computedSM( meshedSM.begin(), meshedSM.end() ); SMESH_MesherHelper helper (*_mesh); + SMESHDS_Mesh* meshDS = _mesh->GetMeshDS(); int faceNgID = ngMesh.GetNFD(); @@ -752,7 +1135,7 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom, if ( faceNgID < 1 ) continue; // meshed face - int faceSMDSId = helper.GetMeshDS()->ShapeToIndex( *anc ); + int faceSMDSId = meshDS->ShapeToIndex( *anc ); if ( visitedEdgeSM2Faces[ sm ].count( faceSMDSId )) continue; // already treated EDGE @@ -780,10 +1163,12 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom, bool isForwad = ( fOri == eNotSeam.Orientation() || fOri >= TopAbs_INTERNAL ); // get all nodes from connected - bool isQuad = smDS->NbElements() ? smDS->GetElements()->next()->IsQuadratic() : false; - StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, isQuad ); + const bool skipMedium = netgen::mparam.secondorder;//smDS->IsQuadratic(); + StdMeshers_FaceSide fSide( face, edges, _mesh, isForwad, skipMedium, &helper ); const vector& points = fSide.GetUVPtStruct(); - int i, nbSeg = fSide.NbSegments(); + if ( points.empty() ) + return false; // invalid node params? + smIdType i, nbSeg = fSide.NbSegments(); // remember EDGEs of fSide to treat only once for ( int iE = 0; iE < fSide.NbEdges(); ++iE ) @@ -804,7 +1189,7 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom, if ( p1.node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ) //an EDGE begins { isSeam = false; - if ( helper.IsRealSeam( p1.node->getshapeId() )) + if ( helper.IsRealSeam( p1.node->GetShapeID() )) { TopoDS_Edge e = fSide.Edge( fSide.EdgeIndex( 0.5 * ( p1.normParam + p2.normParam ))); isSeam = helper.IsRealSeam( e ); @@ -839,7 +1224,7 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom, RestrictLocalSize( ngMesh, 0.5*(np1+np2), (np1-np2).Modulus() ); #ifdef DUMP_SEGMENTS - cout << "Segment: " << seg.edgenr << " on SMESH face " << helper.GetMeshDS()->ShapeToIndex( face ) << endl + cout << "Segment: " << seg.edgenr << " on SMESH face " << meshDS->ShapeToIndex( face ) << endl << "\tface index: " << seg.si << endl << "\tp1: " << seg[0] << endl << "\tp2: " << seg[1] << endl @@ -861,10 +1246,10 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom, seg.epgeominfo[ 1 ].v = otherSeamParam; swap (seg.epgeominfo[0].u, seg.epgeominfo[1].u); } - swap (seg[0], seg[1]); - swap (seg.epgeominfo[0].dist, seg.epgeominfo[1].dist); + swap( seg[0], seg[1] ); + swap( seg.epgeominfo[0].dist, seg.epgeominfo[1].dist ); seg.edgenr = ngMesh.GetNSeg() + 1; // segment id - ngMesh.AddSegment (seg); + ngMesh.AddSegment( seg ); #ifdef DUMP_SEGMENTS cout << "Segment: " << seg.edgenr << endl << "\t is SEAM (reverse) of the previous. " @@ -874,10 +1259,10 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom, } else if ( fOri == TopAbs_INTERNAL ) { - swap (seg[0], seg[1]); + swap( seg[0], seg[1] ); swap( seg.epgeominfo[0], seg.epgeominfo[1] ); seg.edgenr = ngMesh.GetNSeg() + 1; // segment id - ngMesh.AddSegment (seg); + ngMesh.AddSegment( seg ); #ifdef DUMP_SEGMENTS cout << "Segment: " << seg.edgenr << endl << "\t is REVERSE of the previous" << endl; #endif @@ -906,37 +1291,132 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom, bool isInternalFace = ( geomFace.Orientation() == TopAbs_INTERNAL ); // Find solids the geomFace bounds - int solidID1 = 0, solidID2 = 0; - StdMeshers_QuadToTriaAdaptor* quadAdaptor = - dynamic_cast( proxyMesh.get() ); - if ( quadAdaptor ) + int solidID1 = 0, solidID2 = 0; // ng IDs + int solidSMDSIDs[2] = { 0,0 }; // smds IDs { - solidID1 = occgeom.somap.FindIndex( quadAdaptor->GetShape() ); - } - else - { PShapeIteratorPtr solidIt = helper.GetAncestors( geomFace, *sm->GetFather(), TopAbs_SOLID); while ( const TopoDS_Shape * solid = solidIt->next() ) { int id = occgeom.somap.FindIndex ( *solid ); if ( solidID1 && id != solidID1 ) solidID2 = id; else solidID1 = id; + if ( id ) solidSMDSIDs[ bool( solidSMDSIDs[0] )] = meshDS->ShapeToIndex( *solid ); + } + } + if ( proxyMesh && proxyMesh->GetProxySubMesh( geomFace )) + { + // if a proxy sub-mesh contains temporary faces, then these faces + // should be used to mesh only one SOLID + bool hasTmp = false; + smDS = proxyMesh->GetSubMesh( geomFace ); + SMDS_ElemIteratorPtr faces = smDS->GetElements(); + while ( faces->more() ) + { + const SMDS_MeshElement* f = faces->next(); + if ( proxyMesh->IsTemporary( f )) + { + hasTmp = true; + if ( solidSMDSIDs[1] && proxyMesh->HasPrismsOnTwoSides( meshDS->MeshElements( geomFace ))) + break; + else + solidSMDSIDs[1] = 0; + std::vector fNodes( f->begin_nodes(), f->end_nodes() ); + std::vector vols; + if ( meshDS->GetElementsByNodes( fNodes, vols, SMDSAbs_Volume ) == 1 ) + { + int geomID = vols[0]->GetShapeID(); + const TopoDS_Shape& solid = meshDS->IndexToShape( geomID ); + if ( !solid.IsNull() ) + solidID1 = occgeom.somap.FindIndex ( solid ); + solidID2 = 0; + break; + } + } + } + const int fID = occgeom.fmap.FindIndex( geomFace ); + if ( !hasTmp ) // shrunk mesh + { + // move netgen points according to moved nodes + SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(/*includeSelf=*/true); + while ( smIt->more() ) + { + SMESH_subMesh* sub = smIt->next(); + if ( !sub->GetSubMeshDS() ) continue; + SMDS_NodeIteratorPtr nodeIt = sub->GetSubMeshDS()->GetNodes(); + while ( nodeIt->more() ) + { + const SMDS_MeshNode* n = nodeIt->next(); + int ngID = ngNodeId( n, ngMesh, nodeNgIdMap ); + netgen::MeshPoint& ngPoint = ngMesh.Point( ngID ); + ngPoint(0) = n->X(); + ngPoint(1) = n->Y(); + ngPoint(2) = n->Z(); + } + } + // remove faces near boundary to avoid their overlapping + // with shrunk faces + for ( int i = 1; i <= ngMesh.GetNSE(); ++i ) + { + const netgen::Element2d& elem = ngMesh.SurfaceElement(i); + if ( elem.GetIndex() == fID ) + { + for ( int iN = 0; iN < elem.GetNP(); ++iN ) + if ( ngMesh[ elem[ iN ]].Type() != netgen::SURFACEPOINT ) + { + ngMesh.DeleteSurfaceElement( i ); + break; + } + } + } + } + // exclude faces generated by NETGEN from computation of 3D mesh + //if ( hasTmp ) + { + faceNgID++; + ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID,/*solid1=*/0,/*solid2=*/0,0 )); + for (int i = 1; i <= ngMesh.GetNSE(); ++i ) + { + const netgen::Element2d& elem = ngMesh.SurfaceElement(i); + if ( elem.GetIndex() == fID ) + const_cast< netgen::Element2d& >( elem ).SetIndex( faceNgID ); + } } + } // if proxy + else + { + solidSMDSIDs[1] = 0; } + const bool hasVLOn2Sides = ( solidSMDSIDs[1] > 0 ); + // Add ng face descriptors of meshed faces faceNgID++; - ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(faceNgID, solidID1, solidID2, 0)); - + if ( hasVLOn2Sides ) + { + // viscous layers are on two sides of the FACE + ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, 0, 0 )); + faceNgID++; + ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, 0, solidID2, 0 )); + } + else + { + ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceNgID, solidID1, solidID2, 0 )); + } // if second oreder is required, even already meshed faces must be passed to NETGEN int fID = occgeom.fmap.Add( geomFace ); + if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID ); + occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK; while ( fID < faceNgID ) // geomFace is already in occgeom.fmap, add a copy + { fID = occgeom.fmap.Add( BRepBuilderAPI_Copy( geomFace, /*copyGeom=*/false )); + if ( occgeom.facemeshstatus.Size() < fID ) occgeom.facemeshstatus.SetSize( fID ); + occgeom.facemeshstatus[ fID-1 ] = netgen::FACE_MESHED_OK; + } // Problem with the second order in a quadrangular mesh remains. // 1) All quadrangles generated by NETGEN are moved to an inexistent face // by FillSMesh() (find "AddFaceDescriptor") // 2) Temporary triangles generated by StdMeshers_QuadToTriaAdaptor // are on faces where quadrangles were. - // Due to these 2 points, wrong geom faces are used while conversion to qudratic + // Due to these 2 points, wrong geom faces are used while conversion to quadratic // of the mentioned above quadrangles and triangles // Orient the face correctly in solidID1 (issue 0020206) @@ -952,15 +1432,13 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom, // Add surface elements netgen::Element2d tri(3); - tri.SetIndex ( faceNgID ); - + tri.SetIndex( faceNgID ); + SMESH_TNodeXYZ xyz[3]; #ifdef DUMP_TRIANGLES - cout << "SMESH face " << helper.GetMeshDS()->ShapeToIndex( geomFace ) + cout << "SMESH face " << meshDS->ShapeToIndex( geomFace ) << " internal="<GetSubMesh( geomFace ); SMDS_ElemIteratorPtr faces = smDS->GetElements(); while ( faces->more() ) @@ -971,23 +1449,30 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom, PShapeIteratorPtr solidIt=helper.GetAncestors(geomFace,*sm->GetFather(),TopAbs_SOLID); if ( const TopoDS_Shape * solid = solidIt->next() ) sm = _mesh->GetSubMesh( *solid ); - SMESH_ComputeErrorPtr& smError = sm->GetComputeError(); - smError.reset( new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH,"Not triangle submesh")); - smError->myBadElements.push_back( f ); + SMESH_BadInputElements* badElems = + new SMESH_BadInputElements( meshDS, COMPERR_BAD_INPUT_MESH, "Not triangle sub-mesh"); + badElems->add( f ); + sm->GetComputeError().reset( badElems ); return false; } + if ( hasVLOn2Sides ) + tri.SetIndex( getFaceNgID( f, solidSMDSIDs, faceNgID )); + for ( int i = 0; i < 3; ++i ) { const SMDS_MeshNode* node = f->GetNode( i ), * inFaceNode=0; + xyz[i].Set( node ); // get node UV on face - int shapeID = node->getshapeId(); + int shapeID = node->GetShapeID(); if ( helper.IsSeamShape( shapeID )) - if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->getshapeId() )) + { + if ( helper.IsSeamShape( f->GetNodeWrap( i+1 )->GetShapeID() )) inFaceNode = f->GetNodeWrap( i-1 ); else inFaceNode = f->GetNodeWrap( i+1 ); + } gp_XY uv = helper.GetNodeUV( geomFace, node, inFaceNode ); int ind = reverse ? 3-i : i+1; @@ -996,6 +1481,13 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom, tri.PNum (ind) = ngNodeId( node, ngMesh, nodeNgIdMap ); } + // pass a triangle size to NG size-map + double size = ( ( xyz[0] - xyz[1] ).Modulus() + + ( xyz[1] - xyz[2] ).Modulus() + + ( xyz[2] - xyz[0] ).Modulus() ) / 3; + gp_XYZ gc = ( xyz[0] + xyz[1] + xyz[2] ) / 3; + RestrictLocalSize( ngMesh, gc, size, /*overrideMinH=*/false ); + ngMesh.AddSurfaceElement (tri); #ifdef DUMP_TRIANGLES cout << tri << endl; @@ -1009,7 +1501,7 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom, cout << tri << endl; #endif } - } + } // loop on sub-mesh faces if ( quadHelper ) // remember medium nodes of sub-meshes { @@ -1036,7 +1528,8 @@ bool NETGENPlugin_Mesher::FillNgMesh(netgen::OCCGeometry& occgeom, while ( const TopoDS_Shape* e = ansIt->next() ) { SMESH_subMesh* eSub = helper.GetMesh()->GetSubMesh( *e ); - if (( toAdd = eSub->IsEmpty() )) break; + if (( toAdd = ( eSub->IsEmpty() && !SMESH_Algo::isDegenerated( TopoDS::Edge( *e ))))) + break; } if ( toAdd ) { @@ -1083,7 +1576,7 @@ void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom, { // duplicate faces int i, nbFaces = ngMesh.GetNSE(); - for (int i = 1; i <= nbFaces; ++i) + for ( i = 1; i <= nbFaces; ++i) { netgen::Element2d elem = ngMesh.SurfaceElement(i); if ( ngFaceIds.count( elem.GetIndex() )) @@ -1095,6 +1588,115 @@ void NETGENPlugin_Mesher::FixIntFaces(const netgen::OCCGeometry& occgeom, } } +//================================================================================ +/*! + * \brief Tries to heal the mesh on a FACE. The FACE is supposed to be partially + * meshed due to NETGEN failure + * \param [in] occgeom - geometry + * \param [in,out] ngMesh - the mesh to fix + * \param [inout] faceID - ID of the FACE to fix the mesh on + * \return bool - is mesh is or becomes OK + */ +//================================================================================ + +bool NETGENPlugin_Mesher::FixFaceMesh(const netgen::OCCGeometry& occgeom, + netgen::Mesh& ngMesh, + const int faceID) +{ + // we address a case where the FACE is almost fully meshed except small holes + // of usually triangular shape at FACE boundary (IPAL52861) + + // The case appeared to be not simple: holes only look triangular but + // indeed are a self intersecting polygon. A reason of the bug was in coincident + // NG points on a seam edge. But the code below is very nice, leave it for + // another case. + return false; + + + if ( occgeom.fmap.Extent() < faceID ) + return false; + //const TopoDS_Face& face = TopoDS::Face( occgeom.fmap( faceID )); + + // find free links on the FACE + TLinkMap linkMap; + for ( int iF = 1; iF <= ngMesh.GetNSE(); ++iF ) + { + const netgen::Element2d& elem = ngMesh.SurfaceElement(iF); + if ( faceID != elem.GetIndex() ) + continue; + int n0 = elem[ elem.GetNP() - 1 ]; + for ( int i = 0; i < elem.GetNP(); ++i ) + { + int n1 = elem[i]; + Link link( n0, n1 ); + if ( !linkMap.Add( link )) + linkMap.Remove( link ); + n0 = n1; + } + } + // add/remove boundary links + for ( int iSeg = 1; iSeg <= ngMesh.GetNSeg(); ++iSeg ) + { + const netgen::Segment& seg = ngMesh.LineSegment( iSeg ); + if ( seg.si != faceID ) // !edgeIDs.Contains( seg.edgenr )) + continue; + Link link( seg[1], seg[0] ); // reverse!!! + if ( !linkMap.Add( link )) + linkMap.Remove( link ); + } + if ( linkMap.IsEmpty() ) + return true; + if ( linkMap.Extent() < 3 ) + return false; + + // make triangles of the links + + netgen::Element2d tri(3); + tri.SetIndex ( faceID ); + + TLinkMap::Iterator linkIt( linkMap ); + Link link1 = linkIt.Value(); + // look for a link connected to link1 + TLinkMap::Iterator linkIt2 = linkIt; + for ( linkIt2.Next(); linkIt2.More(); linkIt2.Next() ) + { + const Link& link2 = linkIt2.Value(); + if ( link2.IsConnected( link1 )) + { + // look for a link connected to both link1 and link2 + TLinkMap::Iterator linkIt3 = linkIt2; + for ( linkIt3.Next(); linkIt3.More(); linkIt3.Next() ) + { + const Link& link3 = linkIt3.Value(); + if ( link3.IsConnected( link1 ) && + link3.IsConnected( link2 ) ) + { + // add a triangle + tri[0] = link1.n2; + tri[1] = link1.n1; + tri[2] = ( link2.Contains( link1.n1 ) ? link2.n1 : link3.n1 ); + if ( tri[0] == tri[2] || tri[1] == tri[2] ) + return false; + ngMesh.AddSurfaceElement( tri ); + + // prepare for the next tria search + if ( linkMap.Extent() == 3 ) + return true; + linkMap.Remove( link3 ); + linkMap.Remove( link2 ); + linkIt.Next(); + linkMap.Remove( link1 ); + link1 = linkIt.Value(); + linkIt2 = linkIt; + break; + } + } + } + } + return false; + +} // FixFaceMesh() + namespace { //================================================================================ @@ -1123,7 +1725,7 @@ namespace return dist3D; // start recursion if necessary - double dist2D = SMESH_MesherHelper::applyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus(); + double dist2D = SMESH_MesherHelper::ApplyIn2D(surf, uv1, uv2, gp_XY_Subtracted, 0).Modulus(); if ( fabs( dist3D - dist2D ) < dist2D * 1e-10 ) return dist3D; // equal parametrization of a planar surface @@ -1139,7 +1741,7 @@ namespace struct TIntVData { gp_XY uv; //!< UV in face parametric space - int ngId; //!< ng id of corrsponding node + int ngId; //!< ng id of corresponding node gp_XY uvClose; //!< UV of closest boundary node int ngIdClose; //!< ng id of closest boundary node }; @@ -1157,10 +1759,15 @@ namespace int ngIdCloseN; //!< ng id of closest node of the closest 2d mesh element }; - inline double dist2(const netgen::MeshPoint& p1, const netgen::MeshPoint& p2) + inline double dist2( const netgen::MeshPoint& p1, const netgen::MeshPoint& p2 ) { return gp_Pnt( NGPOINT_COORDS(p1)).SquareDistance( gp_Pnt( NGPOINT_COORDS(p2))); } + + // inline double dist2(const netgen::MeshPoint& p, const SMDS_MeshNode* n ) + // { + // return gp_Pnt( NGPOINT_COORDS(p)).SquareDistance( SMESH_NodeXYZ(n)); + // } } //================================================================================ @@ -1177,7 +1784,7 @@ void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& o vector& nodeVec, NETGENPlugin_Internals& internalShapes) { - if ( nodeVec.size() < ngMesh.GetNP() ) + if ((int) nodeVec.size() < ngMesh.GetNP() ) nodeVec.resize( ngMesh.GetNP(), 0 ); SMESHDS_Mesh* meshDS = internalShapes.getMesh().GetMeshDS(); @@ -1230,7 +1837,7 @@ void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& o nodeVec.push_back( nV ); // get node UV - bool uvOK = false; + bool uvOK = true; vData.uv = helper.GetNodeUV( face, nV, 0, &uvOK ); if ( !uvOK ) helper.CheckNodeUV( face, nV, vData.uv, BRep_Tool::Tolerance(V),/*force=*/1); @@ -1247,14 +1854,14 @@ void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& o { uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v ); if ( ngIdLast == seg[ iEnd ] ) continue; - dist2 = helper.applyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus(); + dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus(); if ( dist2 < closeDist2 ) vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2; ngIdLast = seg[ iEnd ]; } if ( !nbV ) { - totSegLen2D += helper.applyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus(); + totSegLen2D += helper.ApplyIn2D(surf, uv[0], uv[1], gp_XY_Subtracted, false).Modulus(); totNbSeg++; } } @@ -1281,7 +1888,7 @@ void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& o for ( int iEnd = 0; iEnd < 2; ++iEnd) { uv[iEnd].SetCoord( seg.epgeominfo[iEnd].u, seg.epgeominfo[iEnd].v ); - dist2 = helper.applyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus(); + dist2 = helper.ApplyIn2D(surf, uv[iEnd], vData.uv, gp_XY_Subtracted,0).SquareModulus(); if ( dist2 < closeDist2 ) vData.ngIdClose = seg[ iEnd ], vData.uvClose = uv[iEnd], closeDist2 = dist2; } @@ -1304,7 +1911,7 @@ void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& o // how far from V double r = min( 0.5, ( hintLenOK ? segLenHint/nodeDist3D : avgSegLen2d/nodeDist2D )); // direction from V to closet node in 2D - gp_Dir2d v2n( helper.applyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false )); + gp_Dir2d v2n( helper.ApplyIn2D(surf, uvP, uvV, gp_XY_Subtracted, false )); // new point uvP = vData.uv + r * nodeDist2D * v2n.XY(); gp_Pnt P = surf->Value( uvP.X(), uvP.Y() ).Transformed( loc ); @@ -1340,13 +1947,14 @@ void NETGENPlugin_Mesher::AddIntVerticesInFaces(const netgen::OCCGeometry& o ngMesh.AddSegment (seg); // add reverse segment - swap (seg[0], seg[1]); + swap( seg[0], seg[1] ); swap( seg.epgeominfo[0], seg.epgeominfo[1] ); seg.edgenr = ngMesh.GetNSeg() + 1; // segment id ngMesh.AddSegment (seg); } } + ngMesh.CalcSurfacesOfNode(); } //================================================================================ @@ -1368,10 +1976,10 @@ void NETGENPlugin_Mesher::AddIntVerticesInSolids(const netgen::OCCGeometry& ofstream py(DUMP_TRIANGLES_SCRIPT); py << "import SMESH"<< endl << "from salome.smesh import smeshBuilder"< & nodeVec) + vector< const SMDS_MeshNode* > & nodeVec, + const bool overrideMinH) { // ---------------------------- // Check wires and count nodes // ---------------------------- - int nbNodes = 0; - for ( int iW = 0; iW < wires.size(); ++iW ) + smIdType nbNodes = 0; + for ( size_t iW = 0; iW < wires.size(); ++iW ) { StdMeshers_FaceSidePtr wire = wires[ iW ]; if ( wire->MissVertexNode() ) @@ -1611,7 +2220,7 @@ NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh, // (new SMESH_ComputeError(COMPERR_BAD_INPUT_MESH, "Missing nodes on vertices")); } const vector& uvPtVec = wire->GetUVPtStruct(); - if ( uvPtVec.size() != wire->NbPoints() ) + if ((int) uvPtVec.size() != wire->NbPoints() ) return SMESH_ComputeError::New(COMPERR_BAD_INPUT_MESH, SMESH_Comment("Unexpected nb of points on wire ") << iW << ": " << uvPtVec.size()<<" != "<NbPoints()); @@ -1634,7 +2243,7 @@ NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh, if ( !wasNgMeshEmpty ) // fill node2ngID with nodes built by NETGEN { set< int > subIDs; // ids of sub-shapes of the FACE - for ( int iW = 0; iW < wires.size(); ++iW ) + for ( size_t iW = 0; iW < wires.size(); ++iW ) { StdMeshers_FaceSidePtr wire = wires[ iW ]; for ( int iE = 0, nbE = wire->NbEdges(); iE < nbE; ++iE ) @@ -1644,19 +2253,19 @@ NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh, } } for ( size_t ngID = 1; ngID < nodeVec.size(); ++ngID ) - if ( subIDs.count( nodeVec[ngID]->getshapeId() )) + if ( subIDs.count( nodeVec[ngID]->GetShapeID() )) node2ngID.insert( make_pair( nodeVec[ngID], ngID )); } const int solidID = 0, faceID = geom.fmap.FindIndex( helper.GetSubShape() ); if ( ngMesh.GetNFD() < 1 ) - ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(faceID, solidID, solidID, 0)); + ngMesh.AddFaceDescriptor( netgen::FaceDescriptor( faceID, solidID, solidID, 0 )); - for ( int iW = 0; iW < wires.size(); ++iW ) + for ( size_t iW = 0; iW < wires.size(); ++iW ) { - StdMeshers_FaceSidePtr wire = wires[ iW ]; + StdMeshers_FaceSidePtr wire = wires[ iW ]; const vector& uvPtVec = wire->GetUVPtStruct(); - const int nbSegments = wire->NbPoints() - 1; + const smIdType nbSegments = wire->NbPoints() - 1; // assure the 1st node to be in node2ngID, which is needed to correctly // "close chain of segments" (see below) in case if the 1st node is not @@ -1677,17 +2286,17 @@ NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh, // Add the first point of a segment const SMDS_MeshNode * n = uvPtVec[ i ].node; - const int posShapeID = n->getshapeId(); + const int posShapeID = n->GetShapeID(); bool onVertex = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX ); bool onEdge = ( n->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE ); // skip nodes on degenerated edges if ( helper.IsDegenShape( posShapeID ) && - helper.IsDegenShape( uvPtVec[ i+1 ].node->getshapeId() )) + helper.IsDegenShape( uvPtVec[ i+1 ].node->GetShapeID() )) continue; int ngID1 = ngMesh.GetNP() + 1, ngID2 = ngID1+1; - if ( onVertex || ( !wasNgMeshEmpty && onEdge )) + if ( onVertex || ( !wasNgMeshEmpty && onEdge ) || helper.IsRealSeam( posShapeID )) ngID1 = node2ngID.insert( make_pair( n, ngID1 )).first->second; if ( ngID1 > ngMesh.GetNP() ) { @@ -1748,14 +2357,14 @@ NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh, SMESH_TNodeXYZ np1( n ), np2( uvPtVec[ i+1 ].node ); // get an average size of adjacent segments to avoid sharp change of // element size (regression on issue 0020452, note 0010898) - int iPrev = SMESH_MesherHelper::WrapIndex( i-1, nbSegments ); - int iNext = SMESH_MesherHelper::WrapIndex( i+1, nbSegments ); + int iPrev = SMESH_MesherHelper::WrapIndex( i-1, (int) nbSegments ); + int iNext = SMESH_MesherHelper::WrapIndex( i+1, (int) nbSegments ); double sumH = segLen[ iPrev ] + segLen[ i ] + segLen[ iNext ]; int nbSeg = ( int( segLen[ iPrev ] > sumH / 100.) + int( segLen[ i ] > sumH / 100.) + int( segLen[ iNext ] > sumH / 100.)); if ( nbSeg > 0 ) - RestrictLocalSize( ngMesh, 0.5*(np1+np2), sumH / nbSeg ); + RestrictLocalSize( ngMesh, 0.5*(np1+np2), sumH / nbSeg, overrideMinH ); } if ( isInternalWire ) { @@ -1769,7 +2378,7 @@ NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh, // close chain of segments if ( nbSegments > 0 ) { - netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire)); + netgen::Segment& lastSeg = ngMesh.LineSegment( ngMesh.GetNSeg() - int( isInternalWire )); const SMDS_MeshNode * lastNode = uvPtVec.back().node; lastSeg[1] = node2ngID.insert( make_pair( lastNode, lastSeg[1] )).first->second; if ( lastSeg[1] > ngMesh.GetNP() ) @@ -1794,13 +2403,13 @@ NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh, netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 ); if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] ) { - cout << "Segment: " << seg.edgenr << endl << "\tis REVRESE of the previous one" << endl; + cout << "Segment: " << seg.edgenr << endl << "\tis REVERSE of the previous one" << endl; continue; } } cout << "Segment: " << seg.edgenr << endl - << "\tp1: " << seg[0] << endl - << "\tp2: " << seg[1] << endl + << "\tp1: " << seg[0] << " n" << nodeVec[ seg[0]]->GetID() << endl + << "\tp2: " << seg[1] << " n" << nodeVec[ seg[1]]->GetID() << endl << "\tp0 param: " << seg.epgeominfo[ 0 ].dist << endl << "\tp0 uv: " << seg.epgeominfo[ 0 ].u <<", "<< seg.epgeominfo[ 0 ].v << endl << "\tp0 edge: " << seg.epgeominfo[ 0 ].edgenr << endl @@ -1809,6 +2418,8 @@ NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh, << "\tp1 edge: " << seg.epgeominfo[ 1 ].edgenr << endl; } cout << "--END WIRE " << iW << endl; +#else + SMESH_Comment __not_unused_variable( prevNbNGSeg ); #endif } // loop on WIREs of a FACE @@ -1854,19 +2465,42 @@ int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo, SMESHDS_Mesh* meshDS = sMesh.GetMeshDS(); // quadHelper is used for either - // 1) making quadratic elements when a lower dimention mesh is loaded - // to SMESH before convertion to quadratic by NETGEN + // 1) making quadratic elements when a lower dimension mesh is loaded + // to SMESH before conversion to quadratic by NETGEN // 2) sewing of quadratic elements with quadratic elements of sub-meshes if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() ) quadHelper = 0; + int ngID, nbInitNod = initState._nbNodes; + if ( initState._elementsRemoved ) + { + // PAL23427. Update nodeVec to track removal of netgen free points as a result + // of removal of faces in FillNgMesh() in the case of a shrunk sub-mesh + size_t i, nodeVecSize = nodeVec.size(); + const double eps = std::numeric_limits::min(); + for ( i = ngID = 1; i < nodeVecSize; ++ngID, ++i ) + { + gp_Pnt ngPnt( NGPOINT_COORDS( ngMesh.Point( ngID ))); + gp_Pnt node ( SMESH_NodeXYZ (nodeVec_ACCESS(i) )); + if ( ngPnt.SquareDistance( node ) < eps ) + { + nodeVec[ ngID ] = nodeVec[ i ]; + } + else + { + --ngID; + } + } + nodeVec.resize( ngID ); + nbInitNod = ngID - 1; + } // ------------------------------------- // Create and insert nodes into nodeVec // ------------------------------------- - nodeVec.resize( nbNod + 1 ); - int i, nbInitNod = initState._nbNodes; - for (i = nbInitNod+1; i <= nbNod; ++i ) + if ( nbNod > nbInitNod ) + nodeVec.resize( nbNod + 1 ); + for ( int i = nbInitNod+1; i <= nbNod; ++i ) { const netgen::MeshPoint& ngPoint = ngMesh.Point(i); SMDS_MeshNode* node = NULL; @@ -1879,7 +2513,7 @@ int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo, gp_Pnt p ( NGPOINT_COORDS(ngPoint) ); for (int iV = i-nbInitNod; aVert.IsNull() && iV <= occgeo.vmap.Extent(); ++iV) { - aVert = TopoDS::Vertex( occgeo.vmap( iV ) ); + aVert = TopoDS::Vertex( occgeo.vmap( iV )); gp_Pnt pV = BRep_Tool::Pnt( aVert ); if ( p.SquareDistance( pV ) > 1e-20 ) aVert.Nullify(); @@ -1901,7 +2535,7 @@ int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo, // ------------------------------------------- int nbInitSeg = initState._nbSegments; - for (i = nbInitSeg+1; i <= nbSeg; ++i ) + for ( int i = nbInitSeg+1; i <= nbSeg; ++i ) { const netgen::Segment& seg = ngMesh.LineSegment(i); TopoDS_Edge aEdge; @@ -1930,7 +2564,7 @@ int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo, { param = param2 * 0.5; } - if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->getshapeId() < 1) + if (!aEdge.IsNull() && nodeVec_ACCESS(pind)->GetShapeID() < 1) { meshDS->SetNodeOnEdge(nodeVec_ACCESS(pind), aEdge, param); } @@ -1962,7 +2596,7 @@ int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo, nbSeg = nbFac = nbVol = 0; break; } - if ( !aEdge.IsNull() && edge->getshapeId() < 1 ) + if ( !aEdge.IsNull() && edge->GetShapeID() < 1 ) meshDS->SetMeshElementOnShape(edge, aEdge); } else if ( comment.empty() ) @@ -1983,30 +2617,30 @@ int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo, ngMesh.AddFaceDescriptor (netgen::FaceDescriptor(quadFaceID, /*solid1=*/0, /*solid2=*/0, 0)); vector nodes; - for (i = nbInitFac+1; i <= nbFac; ++i ) + for ( int i = nbInitFac+1; i <= nbFac; ++i ) { const netgen::Element2d& elem = ngMesh.SurfaceElement(i); - int aGeomFaceInd = elem.GetIndex(); + const int aGeomFaceInd = elem.GetIndex(); TopoDS_Face aFace; if (aGeomFaceInd > 0 && aGeomFaceInd <= occgeo.fmap.Extent()) aFace = TopoDS::Face(occgeo.fmap(aGeomFaceInd)); nodes.clear(); - for (int j=1; j <= elem.GetNP(); ++j) + for ( int j = 1; j <= elem.GetNP(); ++j ) { int pind = elem.PNum(j); - if ( pind < 1 || pind >= nodeVec.size() ) + if ( pind < 1 || pind >= (int) nodeVec.size() ) break; if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind)) { nodes.push_back( node ); - if (!aFace.IsNull() && node->getshapeId() < 1) + if (!aFace.IsNull() && node->GetShapeID() < 1) { const netgen::PointGeomInfo& pgi = elem.GeomInfoPi(j); meshDS->SetNodeOnFace(node, aFace, pgi.u, pgi.v); } } } - if ( nodes.size() != elem.GetNP() ) + if ((int) nodes.size() != elem.GetNP() ) { if ( comment.empty() ) comment << "Invalid netgen 2d element #" << i; @@ -2049,49 +2683,49 @@ int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo, MESSAGE("NETGEN created a face of unexpected type, ignoring"); continue; } - if (!face) + if ( !face ) { if ( comment.empty() ) comment << "Cannot create a mesh face"; MESSAGE("Cannot create a mesh face"); nbSeg = nbFac = nbVol = 0; break; } - if (!aFace.IsNull()) - meshDS->SetMeshElementOnShape(face, aFace); + if ( !aFace.IsNull() ) + meshDS->SetMeshElementOnShape( face, aFace ); } // ------------------ // Create tetrahedra // ------------------ - for (i = 1; i <= nbVol; ++i) + for ( int i = 1; i <= nbVol; ++i ) { const netgen::Element& elem = ngMesh.VolumeElement(i); int aSolidInd = elem.GetIndex(); TopoDS_Solid aSolid; - if (aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent()) + if ( aSolidInd > 0 && aSolidInd <= occgeo.somap.Extent() ) aSolid = TopoDS::Solid(occgeo.somap(aSolidInd)); nodes.clear(); - for (int j=1; j <= elem.GetNP(); ++j) + for ( int j = 1; j <= elem.GetNP(); ++j ) { int pind = elem.PNum(j); - if ( pind < 1 || pind >= nodeVec.size() ) + if ( pind < 1 || pind >= (int)nodeVec.size() ) break; if ( SMDS_MeshNode* node = nodeVec_ACCESS(pind) ) { nodes.push_back(node); - if ( !aSolid.IsNull() && node->getshapeId() < 1 ) + if ( !aSolid.IsNull() && node->GetShapeID() < 1 ) meshDS->SetNodeInVolume(node, aSolid); } } - if ( nodes.size() != elem.GetNP() ) + if ((int) nodes.size() != elem.GetNP() ) { if ( comment.empty() ) comment << "Invalid netgen 3d element #" << i; continue; } SMDS_MeshVolume* vol = NULL; - switch (elem.GetType()) + switch ( elem.GetType() ) { case netgen::TET: vol = meshDS->AddVolume(nodes[0],nodes[1],nodes[2],nodes[3]); @@ -2125,43 +2759,6 @@ int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo, namespace { - //================================================================================ - /*! - * \brief Restrict size of elements on the given edge - */ - //================================================================================ - - void setLocalSize(const TopoDS_Edge& edge, - double size, - netgen::Mesh& mesh) - { - const int nb = 1000; - Standard_Real u1, u2; - Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, u1, u2); - if ( curve.IsNull() ) - { - TopoDS_Iterator vIt( edge ); - if ( !vIt.More() ) return; - gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vIt.Value() )); - NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size ); - } - else - { - Standard_Real delta = (u2-u1)/nb; - for(int i=0; iValue(u); - NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), size ); - netgen::Point3d pi(p.X(), p.Y(), p.Z()); - double resultSize = mesh.GetH(pi); - if ( resultSize - size > 0.1*size ) - // netgen does restriction iff oldH/newH > 1.2 (localh.cpp:136) - NETGENPlugin_Mesher::RestrictLocalSize( mesh, p.XYZ(), resultSize/1.201 ); - } - } - } - //================================================================================ /*! * \brief Convert error into text @@ -2223,16 +2820,17 @@ namespace for ( ; e != elems.end(); ++e ) { const SMDS_MeshElement* elem = *e; - if ( elem->GetType() != SMDSAbs_Face ) - continue; - int nbNodesOnSolid = 0; + // if ( elem->GetType() != SMDSAbs_Face ) -- 23047 + // continue; + int nbNodesOnSolid = 0, nbNodes = elem->NbNodes(); SMDS_NodeIteratorPtr nIt = elem->nodeIterator(); while ( nIt->more() ) { const SMDS_MeshNode* n = nIt->next(); - const TopoDS_Shape& s = mesh->IndexToShape( n->getshapeId() ); + const TopoDS_Shape& s = mesh->IndexToShape( n->GetShapeID() ); nbNodesOnSolid += ( !s.IsNull() && solidSubs.Contains( s )); - if ( nbNodesOnSolid > 2 ) + if ( nbNodesOnSolid > 2 || + nbNodesOnSolid == nbNodes) return true; } } @@ -2258,23 +2856,11 @@ bool NETGENPlugin_Mesher::Compute() NETGENPlugin_NetgenLibWrapper ngLib; netgen::MeshingParameters& mparams = netgen::mparam; - MESSAGE("Compute with:\n" - " max size = " << mparams.maxh << "\n" - " segments per edge = " << mparams.segmentsperedge); - MESSAGE("\n" - " growth rate = " << mparams.grading << "\n" - " elements per radius = " << mparams.curvaturesafety << "\n" - " second order = " << mparams.secondorder << "\n" - " quad allowed = " << mparams.quad << "\n" - " surface curvature = " << mparams.uselocalh << "\n" - " fuse edges = " << netgen::merge_solids); SMESH_ComputeErrorPtr error = SMESH_ComputeError::New(); SMESH_MesherHelper quadHelper( *_mesh ); quadHelper.SetIsQuadratic( mparams.secondorder ); - static string debugFile = "/tmp/ngMesh.py"; /* to call toPython( ngMesh, debugFile ) - while debugging netgen */ // ------------------------- // Prepare OCC geometry // ------------------------- @@ -2335,19 +2921,14 @@ bool NETGENPlugin_Mesher::Compute() occgeo.face_maxh = mparams.maxh; // Let netgen create _ngMesh and calculate element size on not meshed shapes -#ifndef NETGEN_V5 - char *optstr = 0; -#endif int startWith = netgen::MESHCONST_ANALYSE; int endWith = netgen::MESHCONST_ANALYSE; try { OCC_CATCH_SIGNALS; -#ifdef NETGEN_V5 - err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith); -#else - err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr); -#endif + + err = ngLib.GenerateMesh(occgeo, startWith, endWith, _ngMesh); + if(netgen::multithread.terminate) return false; @@ -2357,6 +2938,17 @@ bool NETGENPlugin_Mesher::Compute() { comment << text(ex); } + catch (netgen::NgException & ex) + { + comment << text(ex); +#ifdef NETGEN_V6 + bool hasSizeFile = !mparams.meshsizefilename.empty(); +#else + bool hasSizeFile = mparams.meshsizefilename; +#endif + if ( hasSizeFile ) + throw SMESH_ComputeError(COMPERR_BAD_PARMETERS, comment ); + } err = 0; //- MESHCONST_ANALYSE isn't so important step if ( !_ngMesh ) return false; @@ -2364,11 +2956,14 @@ bool NETGENPlugin_Mesher::Compute() _ngMesh->ClearFaceDescriptors(); // we make descriptors our-self + if ( !mparams.uselocalh ) // mparams.grading is not taken into account yet + _ngMesh->LocalHFunction().SetGrading( mparams.grading ); + if ( _simpleHyp ) { // Pass 1D simple parameters to NETGEN // -------------------------------- - int nbSeg = _simpleHyp->GetNumberOfSegments(); + double nbSeg = (double) _simpleHyp->GetNumberOfSegments(); double segSize = _simpleHyp->GetLocalLength(); for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE ) { @@ -2380,36 +2975,9 @@ bool NETGENPlugin_Mesher::Compute() } else // if ( ! _simpleHyp ) { - // Local size on vertices and edges - // -------------------------------- - for(std::map::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++) - { - int key = (*it).first; - double hi = (*it).second; - const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key); - const TopoDS_Edge& e = TopoDS::Edge(shape); - setLocalSize( e, hi, *_ngMesh ); - } - for(std::map::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++) - { - int key = (*it).first; - double hi = (*it).second; - const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key); - const TopoDS_Vertex& v = TopoDS::Vertex(shape); - gp_Pnt p = BRep_Tool::Pnt(v); - NETGENPlugin_Mesher::RestrictLocalSize( *_ngMesh, p.XYZ(), hi ); - } - for(map::const_iterator it=FaceId2LocalSize.begin(); - it!=FaceId2LocalSize.end(); it++) - { - int key = (*it).first; - double val = (*it).second; - const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key); - int faceNgID = occgeo.fmap.FindIndex(shape); - occgeo.SetFaceMaxH(faceNgID, val); - for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() ) - setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *_ngMesh ); - } + // Local size on shapes + SetLocalSize( occgeo, *_ngMesh ); + SetLocalSizeForChordalError( occgeo, *_ngMesh ); } // Precompute internal edges (issue 0020676) in order to @@ -2431,12 +2999,9 @@ bool NETGENPlugin_Mesher::Compute() //OCCSetLocalMeshSize(intOccgeo, *_ngMesh); it deletes _ngMesh->localH // let netgen create a temporary mesh -#ifdef NETGEN_V5 - netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith); -#else - netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr); -#endif - if(netgen::multithread.terminate) + ngLib.GenerateMesh(intOccgeo, startWith, endWith, tmpNgMesh); + + if ( netgen::multithread.terminate ) return false; // copy LocalH from the main to temporary mesh @@ -2444,11 +3009,8 @@ bool NETGENPlugin_Mesher::Compute() // compute mesh on internal edges startWith = endWith = netgen::MESHCONST_MESHEDGES; -#ifdef NETGEN_V5 - err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, mparams, startWith, endWith); -#else - err = netgen::OCCGenerateMesh(intOccgeo, tmpNgMesh, startWith, endWith, optstr); -#endif + err = ngLib.GenerateMesh(intOccgeo, startWith, endWith, tmpNgMesh); + comment << text(err); } catch (Standard_Failure& ex) @@ -2481,12 +3043,10 @@ bool NETGENPlugin_Mesher::Compute() try { OCC_CATCH_SIGNALS; -#ifdef NETGEN_V5 - err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith); -#else - err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr); -#endif - if(netgen::multithread.terminate) + + err = ngLib.GenerateMesh(occgeo, startWith, endWith); + + if ( netgen::multithread.terminate ) return false; comment << text(err); @@ -2552,7 +3112,9 @@ bool NETGENPlugin_Mesher::Compute() } // Build viscous layers - if ( _isViscousLayers2D ) + if (( _isViscousLayers2D ) || + ( !occgeo.fmap.IsEmpty() && + StdMeshers_ViscousLayers2D::HasProxyMesh( TopoDS::Face( occgeo.fmap(1) ), *_mesh ))) { if ( !internals.hasInternalVertexInFace() ) { FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment ); @@ -2566,6 +3128,8 @@ bool NETGENPlugin_Mesher::Compute() viscousMesh = StdMeshers_ViscousLayers2D::Compute( *_mesh, F ); if ( !viscousMesh ) return false; + if ( viscousMesh->NbProxySubMeshes() == 0 ) + continue; // exclude from computation ng segments built on EDGEs of F for (int i = 1; i <= _ngMesh->GetNSeg(); i++) { @@ -2577,7 +3141,7 @@ bool NETGENPlugin_Mesher::Compute() helper.SetSubShape( F ); TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *_mesh, /*skipMediumNodes=*/true, - error, viscousMesh ); + error, &helper, viscousMesh ); error = AddSegmentsToMesh( *_ngMesh, occgeo, wires, helper, nodeVec ); if ( !error ) error = SMESH_ComputeError::New(); @@ -2591,12 +3155,10 @@ bool NETGENPlugin_Mesher::Compute() try { OCC_CATCH_SIGNALS; -#ifdef NETGEN_V5 - err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith); -#else - err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr); -#endif - if(netgen::multithread.terminate) + + err = ngLib.GenerateMesh(occgeo, startWith, endWith); + + if ( netgen::multithread.terminate ) return false; comment << text (err); @@ -2606,7 +3168,7 @@ bool NETGENPlugin_Mesher::Compute() comment << text(ex); //err = 1; -- try to make volumes anyway } - catch (netgen::NgException exc) + catch (netgen::NgException& exc) { comment << text(exc); //err = 1; -- try to make volumes anyway @@ -2621,37 +3183,58 @@ bool NETGENPlugin_Mesher::Compute() // generate volume mesh // --------------------- // Fill _ngMesh with nodes and faces of computed 2D submeshes - if ( !err && _isVolume && ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad )) + if ( !err && _isVolume && + ( !meshedSM[ MeshDim_2D ].empty() || mparams.quad || _viscousLayersHyp )) { // load SMESH with computed segments and faces FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper ); + // compute prismatic boundary volumes + smIdType nbQuad = _mesh->NbQuadrangles(); + SMESH_ProxyMesh::Ptr viscousMesh; + if ( _viscousLayersHyp ) + { + viscousMesh = _viscousLayersHyp->Compute( *_mesh, _shape ); + if ( !viscousMesh ) + return false; + } // compute pyramids on quadrangles - SMESH_ProxyMesh::Ptr proxyMesh; - if ( _mesh->NbQuadrangles() > 0 ) + vector pyramidMeshes( occgeo.somap.Extent() ); + if ( nbQuad > 0 ) for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS ) { - StdMeshers_QuadToTriaAdaptor* Adaptor = new StdMeshers_QuadToTriaAdaptor; - proxyMesh.reset( Adaptor ); - - int nbPyrams = _mesh->NbPyramids(); - Adaptor->Compute( *_mesh, occgeo.somap(iS) ); - if ( nbPyrams != _mesh->NbPyramids() ) + StdMeshers_QuadToTriaAdaptor* adaptor = new StdMeshers_QuadToTriaAdaptor; + pyramidMeshes[ iS-1 ].reset( adaptor ); + bool ok = adaptor->Compute( *_mesh, occgeo.somap(iS), viscousMesh.get() ); + if ( !ok ) + return false; + } + // add proxy faces to NG mesh + list< SMESH_subMesh* > viscousSM; + for ( int iS = 1; iS <= occgeo.somap.Extent(); ++iS ) + { + list< SMESH_subMesh* > quadFaceSM; + for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next()) + if ( pyramidMeshes[iS-1] && pyramidMeshes[iS-1]->GetProxySubMesh( face.Current() )) { - list< SMESH_subMesh* > quadFaceSM; - for (TopExp_Explorer face(occgeo.somap(iS), TopAbs_FACE); face.More(); face.Next()) - if ( Adaptor->GetProxySubMesh( face.Current() )) - { - quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() )); - meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() ); - } - FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, proxyMesh); + quadFaceSM.push_back( _mesh->GetSubMesh( face.Current() )); + meshedSM[ MeshDim_2D ].remove( quadFaceSM.back() ); } - } + else if ( viscousMesh && viscousMesh->GetProxySubMesh( face.Current() )) + { + viscousSM.push_back( _mesh->GetSubMesh( face.Current() )); + meshedSM[ MeshDim_2D ].remove( viscousSM.back() ); + } + if ( !quadFaceSM.empty() ) + FillNgMesh(occgeo, *_ngMesh, nodeVec, quadFaceSM, &quadHelper, pyramidMeshes[iS-1]); + } + if ( !viscousSM.empty() ) + FillNgMesh(occgeo, *_ngMesh, nodeVec, viscousSM, &quadHelper, viscousMesh ); + // fill _ngMesh with faces of sub-meshes err = ! ( FillNgMesh(occgeo, *_ngMesh, nodeVec, meshedSM[ MeshDim_2D ], &quadHelper)); - initState = NETGENPlugin_ngMeshInfo(_ngMesh); - //toPython( _ngMesh, "/tmp/ngPython.py"); + initState = NETGENPlugin_ngMeshInfo(_ngMesh, /*checkRemovedElems=*/true); + // toPython( _ngMesh ); } if (!err && _isVolume) { @@ -2659,6 +3242,7 @@ bool NETGENPlugin_Mesher::Compute() const NETGENPlugin_SimpleHypothesis_3D* simple3d = dynamic_cast< const NETGENPlugin_SimpleHypothesis_3D* > ( _simpleHyp ); if ( simple3d ) { + _ngMesh->Compress(); if ( double vol = simple3d->GetMaxElementVolume() ) { // max volume mparams.maxh = pow( 72, 1/6. ) * pow( vol, 1/3. ); @@ -2670,11 +3254,7 @@ bool NETGENPlugin_Mesher::Compute() } _ngMesh->SetGlobalH (mparams.maxh); mparams.grading = 0.4; -#ifdef NETGEN_V5 - _ngMesh->CalcLocalH(mparams.grading); -#else - _ngMesh->CalcLocalH(); -#endif + ngLib.CalcLocalH( ngLib._ngMesh ); } // Care of vertices internal in solids and internal faces (issue 0020676) if ( internals.hasInternalVertexInSolid() || internals.hasInternalFaces() ) @@ -2693,26 +3273,24 @@ bool NETGENPlugin_Mesher::Compute() try { OCC_CATCH_SIGNALS; -#ifdef NETGEN_V5 - err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith); -#else - err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr); -#endif - if(netgen::multithread.terminate) + + err = ngLib.GenerateMesh(occgeo, startWith, endWith); + + if ( netgen::multithread.terminate ) return false; - if ( comment.empty() ) // do not overwrite a previos error + if ( comment.empty() ) // do not overwrite a previous error comment << text(err); } catch (Standard_Failure& ex) { - if ( comment.empty() ) // do not overwrite a previos error + if ( comment.empty() ) // do not overwrite a previous error comment << text(ex); err = 1; } - catch (netgen::NgException exc) + catch (netgen::NgException& exc) { - if ( comment.empty() ) // do not overwrite a previos error + if ( comment.empty() ) // do not overwrite a previous error comment << text(exc); err = 1; } @@ -2725,25 +3303,23 @@ bool NETGENPlugin_Mesher::Compute() try { OCC_CATCH_SIGNALS; -#ifdef NETGEN_V5 - err = netgen::OCCGenerateMesh(occgeo, _ngMesh, mparams, startWith, endWith); -#else - err = netgen::OCCGenerateMesh(occgeo, _ngMesh, startWith, endWith, optstr); -#endif - if(netgen::multithread.terminate) + + err = ngLib.GenerateMesh(occgeo, startWith, endWith); + + if ( netgen::multithread.terminate ) return false; - if ( comment.empty() ) // do not overwrite a previos error + if ( comment.empty() ) // do not overwrite a previous error comment << text(err); } catch (Standard_Failure& ex) { - if ( comment.empty() ) // do not overwrite a previos error + if ( comment.empty() ) // do not overwrite a previous error comment << text(ex); } - catch (netgen::NgException exc) + catch (netgen::NgException& exc) { - if ( comment.empty() ) // do not overwrite a previos error + if ( comment.empty() ) // do not overwrite a previous error comment << text(exc); } } @@ -2760,13 +3336,19 @@ bool NETGENPlugin_Mesher::Compute() { const netgen::Segment & seg = _ngMesh->LineSegment (i); if ( seg.epgeominfo[ 0 ].edgenr == 0 ) + { _ngMesh->DeleteSegment( i ); + initState._nbSegments--; + } } _ngMesh->Compress(); } // convert to quadratic - netgen::OCCRefinementSurfaces ref (occgeo); - ref.MakeSecondOrder (*_ngMesh); +#ifdef NETGEN_V6 + occgeo.GetRefinement().MakeSecondOrder(*_ngMesh); +#else + netgen::OCCRefinementSurfaces(occgeo).MakeSecondOrder(*_ngMesh); +#endif // care of elements already loaded to SMESH // if ( initState._nbSegments > 0 ) @@ -2776,12 +3358,12 @@ bool NETGENPlugin_Mesher::Compute() } catch (Standard_Failure& ex) { - if ( comment.empty() ) // do not overwrite a previos error + if ( comment.empty() ) // do not overwrite a previous error comment << "Exception in netgen at passing to 2nd order "; } - catch (netgen::NgException exc) + catch (netgen::NgException& exc) { - if ( comment.empty() ) // do not overwrite a previos error + if ( comment.empty() ) // do not overwrite a previous error comment << exc.What(); } } @@ -2789,32 +3371,39 @@ bool NETGENPlugin_Mesher::Compute() _ticTime = 0.98 / _progressTic; - int nbNod = _ngMesh->GetNP(); - int nbSeg = _ngMesh->GetNSeg(); + //int nbNod = _ngMesh->GetNP(); + //int nbSeg = _ngMesh->GetNSeg(); int nbFac = _ngMesh->GetNSE(); int nbVol = _ngMesh->GetNE(); bool isOK = ( !err && (_isVolume ? (nbVol > 0) : (nbFac > 0)) ); - MESSAGE((err ? "Mesh Generation failure" : "End of Mesh Generation") << - ", nb nodes: " << nbNod << - ", nb segments: " << nbSeg << - ", nb faces: " << nbFac << - ", nb volumes: " << nbVol); - // Feed back the SMESHDS with the generated Nodes and Elements if ( true /*isOK*/ ) // get whatever built { FillSMesh( occgeo, *_ngMesh, initState, *_mesh, nodeVec, comment, &quadHelper ); if ( quadHelper.GetIsQuadratic() ) // remove free nodes + { for ( size_t i = 0; i < nodeVec.size(); ++i ) if ( nodeVec[i] && nodeVec[i]->NbInverseElements() == 0 ) + { _mesh->GetMeshDS()->RemoveFreeNode( nodeVec[i], 0, /*fromGroups=*/false ); + nodeVec[i]=0; + } + for ( size_t i = nodeVec.size()-1; i > 0; --i ) // remove trailing removed nodes + if ( !nodeVec[i] ) + nodeVec.resize( i ); + else + break; + } } SMESH_ComputeErrorPtr readErr = ReadErrors(nodeVec); - if ( readErr && !readErr->myBadElements.empty() ) + if ( readErr && readErr->HasBadElems() ) + { error = readErr; - + if ( !comment.empty() && !readErr->myComment.empty() ) comment += "\n"; + comment += readErr->myComment; + } if ( error->IsOK() && ( !isOK || comment.size() > 0 )) error->myName = COMPERR_ALGO_FAILED; if ( !comment.empty() ) @@ -2838,11 +3427,11 @@ bool NETGENPlugin_Mesher::Compute() bool pb2D = false, pb3D = false; for (int i = 1; i <= occgeo.fmap.Extent(); i++) { int status = occgeo.facemeshstatus[i-1]; - if (status == 1 ) continue; + if (status == netgen::FACE_MESHED_OK ) continue; if ( SMESH_subMesh* sm = _mesh->GetSubMeshContaining( occgeo.fmap( i ))) { SMESH_ComputeErrorPtr& smError = sm->GetComputeError(); if ( !smError || smError->IsOK() ) { - if ( status == -1 ) + if ( status == netgen::FACE_FAILED ) smError.reset( new SMESH_ComputeError( *error )); else smError.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED, "Ignored" )); @@ -2859,21 +3448,22 @@ bool NETGENPlugin_Mesher::Compute() bool smComputed = nbVol && !sm->IsEmpty(); if ( smComputed && internals.hasInternalVertexInSolid( sm->GetId() )) { - int nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size(); + size_t nbIntV = internals.getSolidsWithVertices().find( sm->GetId() )->second.size(); SMESHDS_SubMesh* smDS = sm->GetSubMeshDS(); - smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > nbIntV ); + smComputed = ( smDS->NbElements() > 0 || smDS->NbNodes() > (smIdType) nbIntV ); } SMESH_ComputeErrorPtr& smError = sm->GetComputeError(); if ( !smComputed && ( !smError || smError->IsOK() )) { - smError.reset( new SMESH_ComputeError( *error )); + smError = error; if ( nbVol && SMESH_Algo::GetMeshError( sm ) == SMESH_Algo::MEr_OK ) { smError->myName = COMPERR_WARNING; } - else if ( !smError->myBadElements.empty() ) // bad surface mesh + else if ( smError->HasBadElems() ) // bad surface mesh { - if ( !hasBadElemOnSolid( smError->myBadElements, sm )) + if ( !hasBadElemOnSolid + ( static_cast( smError.get() )->myBadElements, sm )) smError.reset(); } } @@ -2902,9 +3492,8 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) // Prepare OCC geometry // ------------------------- netgen::OCCGeometry occgeo; - list< SMESH_subMesh* > meshedSM[4]; // for 0-3 dimensions NETGENPlugin_Internals internals( *_mesh, _shape, _isVolume ); - PrepareOCCgeometry( occgeo, _shape, *_mesh, meshedSM, &internals ); + PrepareOCCgeometry( occgeo, _shape, *_mesh, 0, &internals ); bool tooManyElems = false; const int hugeNb = std::numeric_limits::max() / 100; @@ -2935,16 +3524,9 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) // let netgen create _ngMesh and calculate element size on not meshed shapes NETGENPlugin_NetgenLibWrapper ngLib; netgen::Mesh *ngMesh = NULL; -#ifndef NETGEN_V5 - char *optstr = 0; -#endif int startWith = netgen::MESHCONST_ANALYSE; int endWith = netgen::MESHCONST_MESHEDGES; -#ifdef NETGEN_V5 - int err = netgen::OCCGenerateMesh(occgeo, ngMesh, mparams, startWith, endWith); -#else - int err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr); -#endif + int err = ngLib.GenerateMesh(occgeo, startWith, endWith, ngMesh); if(netgen::multithread.terminate) return false; @@ -2955,56 +3537,28 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) sm->GetComputeError().reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED )); return false; } - if ( _simpleHyp ) - { - // Pass 1D simple parameters to NETGEN - // -------------------------------- - int nbSeg = _simpleHyp->GetNumberOfSegments(); - double segSize = _simpleHyp->GetLocalLength(); - for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE ) - { - const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE)); - if ( nbSeg ) - segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 ); - setLocalSize( e, segSize, *ngMesh ); - } - } - else // if ( ! _simpleHyp ) - { - // Local size on vertices and edges - // -------------------------------- - for(std::map::const_iterator it=EdgeId2LocalSize.begin(); it!=EdgeId2LocalSize.end(); it++) - { - int key = (*it).first; - double hi = (*it).second; - const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key); - const TopoDS_Edge& e = TopoDS::Edge(shape); - setLocalSize( e, hi, *ngMesh ); - } - for(std::map::const_iterator it=VertexId2LocalSize.begin(); it!=VertexId2LocalSize.end(); it++) - { - int key = (*it).first; - double hi = (*it).second; - const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key); - const TopoDS_Vertex& v = TopoDS::Vertex(shape); - gp_Pnt p = BRep_Tool::Pnt(v); - NETGENPlugin_Mesher::RestrictLocalSize( *ngMesh, p.XYZ(), hi ); - } - for(map::const_iterator it=FaceId2LocalSize.begin(); - it!=FaceId2LocalSize.end(); it++) - { - int key = (*it).first; - double val = (*it).second; - const TopoDS_Shape& shape = ShapesWithLocalSize.FindKey(key); - int faceNgID = occgeo.fmap.FindIndex(shape); - occgeo.SetFaceMaxH(faceNgID, val); - for ( TopExp_Explorer edgeExp( shape, TopAbs_EDGE ); edgeExp.More(); edgeExp.Next() ) - setLocalSize( TopoDS::Edge( edgeExp.Current() ), val, *ngMesh ); - } - } + // if ( _simpleHyp ) + // { + // // Pass 1D simple parameters to NETGEN + // // -------------------------------- + // int nbSeg = _simpleHyp->GetNumberOfSegments(); + // double segSize = _simpleHyp->GetLocalLength(); + // for ( int iE = 1; iE <= occgeo.emap.Extent(); ++iE ) + // { + // const TopoDS_Edge& e = TopoDS::Edge( occgeo.emap(iE)); + // if ( nbSeg ) + // segSize = SMESH_Algo::EdgeLength( e ) / ( nbSeg - 0.4 ); + // setLocalSize( e, segSize, *ngMesh ); + // } + // } + // else // if ( ! _simpleHyp ) + // { + // // Local size on shapes + // SetLocalSize( occgeo, *ngMesh ); + // } // calculate total nb of segments and length of edges double fullLen = 0.0; - int fullNbSeg = 0; + smIdType fullNbSeg = 0; int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge; TopTools_DataMapOfShapeInteger Edge2NbSeg; for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next()) @@ -3016,7 +3570,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) double aLen = SMESH_Algo::EdgeLength(E); fullLen += aLen; - vector& aVec = aResMap[_mesh->GetSubMesh(E)]; + vector& aVec = aResMap[_mesh->GetSubMesh(E)]; if ( aVec.empty() ) aVec.resize( SMDSEntity_Last, 0); else @@ -3024,7 +3578,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) } // store nb of segments computed by Netgen - NCollection_Map linkMap; + TLinkMap linkMap; for (int i = 1; i <= ngMesh->GetNSeg(); ++i ) { const netgen::Segment& seg = ngMesh->LineSegment(i); @@ -3033,7 +3587,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) int aGeomEdgeInd = seg.epgeominfo[0].edgenr; if (aGeomEdgeInd > 0 && aGeomEdgeInd <= occgeo.emap.Extent()) { - vector& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))]; + vector& aVec = aResMap[_mesh->GetSubMesh(occgeo.emap(aGeomEdgeInd))]; aVec[ entity ]++; } } @@ -3041,12 +3595,12 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) TopTools_DataMapIteratorOfDataMapOfShapeInteger Edge2NbSegIt(Edge2NbSeg); for (; Edge2NbSegIt.More(); Edge2NbSegIt.Next()) { - vector& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())]; + vector& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())]; if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 ) aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1; fullNbSeg += aVec[ entity ]; - Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ]; + Edge2NbSeg( Edge2NbSegIt.Key() ) = (int) aVec[ entity ]; } if ( fullNbSeg == 0 ) return false; @@ -3062,12 +3616,12 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) } else { // length from edges - mparams.maxh = fullLen/fullNbSeg; + mparams.maxh = fullLen / double( fullNbSeg ); mparams.grading = 0.2; // slow size growth } } mparams.maxh = min( mparams.maxh, occgeo.boundingbox.Diam()/2 ); - mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading)); + mparams.maxh = min( mparams.maxh, fullLen / double( fullNbSeg ) * (1. + mparams.grading)); for (TopExp_Explorer exp(_shape, TopAbs_FACE); exp.More(); exp.Next()) { @@ -3080,15 +3634,15 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) int nb1d = 0; if ( !tooManyElems ) { - TopTools_MapOfShape egdes; + TopTools_MapOfShape edges; for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) - if ( egdes.Add( exp1.Current() )) + if ( edges.Add( exp1.Current() )) nb1d += Edge2NbSeg.Find(exp1.Current()); } int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.))); int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 ); - vector aVec(SMDSEntity_Last, 0); + vector aVec(SMDSEntity_Last, 0); if( mparams.secondorder > 0 ) { int nb1d_in = (nbFaces*3 - nb1d) / 2; aVec[SMDSEntity_Node] = nbNodes + nb1d_in; @@ -3118,7 +3672,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) // using previous length from faces } mparams.grading = 0.4; - mparams.maxh = min( mparams.maxh, fullLen/fullNbSeg * (1. + mparams.grading)); + mparams.maxh = min( mparams.maxh, fullLen / double( fullNbSeg ) * (1. + mparams.grading)); } GProp_GProps G; BRepGProp::VolumeProperties(_shape,G); @@ -3127,7 +3681,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) tooManyElems = tooManyElems || ( aVolume/hugeNb > tetrVol ); int nbVols = tooManyElems ? hugeNb : int(aVolume/tetrVol); int nb1d_in = int(( nbVols*6 - fullNbSeg ) / 6 ); - vector aVec(SMDSEntity_Last, 0 ); + vector aVec(SMDSEntity_Last, 0 ); if ( tooManyElems ) // avoid FPE { aVec[SMDSEntity_Node] = hugeNb; @@ -3151,7 +3705,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) return true; } -double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder, +double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* /*holder*/, const int * algoProgressTic, const double * algoProgress) const { @@ -3201,10 +3755,19 @@ double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder, // << " " << doneTime / _totalTime / _progressTic << endl; } } + if ( _ticTime > 0 ) progress = Max( *algoProgressTic * _ticTime, *algoProgress ); + if ( progress > 0 ) { + if ( _isVolume && + netgen::multithread.task[0] == 'D'/*elaunay meshing*/ && + progress > voluMeshingTime ) + { + progress = voluMeshingTime; + ((double&) _ticTime) = voluMeshingTime / _totalTime / _progressTic; + } ((int&) *algoProgressTic )++; ((double&) *algoProgress) = progress; } @@ -3213,26 +3776,6 @@ double NETGENPlugin_Mesher::GetProgress(const SMESH_Algo* holder, return Min( progress, 0.99 ); } -//================================================================================ -/*! - * \brief Remove "test.out" and "problemfaces" files in current directory - */ -//================================================================================ - -void NETGENPlugin_Mesher::RemoveTmpFiles() -{ - bool rm = SMESH_File("test.out").remove() ; -#ifndef WIN32 - if (rm && netgen::testout) - { - delete netgen::testout; - netgen::testout = 0; - } -#endif - SMESH_File("problemfaces").remove(); - SMESH_File("occmesh.rep").remove(); -} - //================================================================================ /*! * \brief Read mesh entities preventing successful computation from "test.out" file @@ -3242,21 +3785,26 @@ void NETGENPlugin_Mesher::RemoveTmpFiles() SMESH_ComputeErrorPtr NETGENPlugin_Mesher::ReadErrors(const vector& nodeVec) { - SMESH_ComputeErrorPtr err = SMESH_ComputeError::New - (COMPERR_BAD_INPUT_MESH, "Some edges multiple times in surface mesh"); + if ( nodeVec.size() < 2 ) return SMESH_ComputeErrorPtr(); + SMESH_BadInputElements* err = + new SMESH_BadInputElements( nodeVec.back()->GetMesh(), COMPERR_BAD_INPUT_MESH, + "Some edges multiple times in surface mesh"); SMESH_File file("test.out"); vector two(2); + vector three1(3), three2(3); const char* badEdgeStr = " multiple times in surface mesh"; - const int badEdgeStrLen = strlen( badEdgeStr ); + const int badEdgeStrLen = (int) strlen( badEdgeStr ); + const int nbNodes = (int) nodeVec.size(); + while( !file.eof() ) { if ( strncmp( file, "Edge ", 5 ) == 0 && file.getInts( two ) && strncmp( file, badEdgeStr, badEdgeStrLen ) == 0 && - two[0] < nodeVec.size() && two[1] < nodeVec.size()) + two[0] < nbNodes && two[1] < nbNodes ) { err->myBadElements.push_back( new SMDS_LinearEdge( nodeVec[ two[0]], nodeVec[ two[1]] )); - file += badEdgeStrLen; + file += (int) badEdgeStrLen; } else if ( strncmp( file, "Intersecting: ", 14 ) == 0 ) { @@ -3264,7 +3812,6 @@ NETGENPlugin_Mesher::ReadErrors(const vector& nodeVec) // openelement 18 with open element 126 // 41 36 38 // 69 70 72 - vector three1(3), three2(3); file.getLine(); const char* pos = file; bool ok = ( strncmp( file, "openelement ", 12 ) == 0 ); @@ -3272,9 +3819,9 @@ NETGENPlugin_Mesher::ReadErrors(const vector& nodeVec) ok = ok && file.getInts( three1 ); ok = ok && file.getInts( three2 ); for ( int i = 0; ok && i < 3; ++i ) - ok = ( three1[i] < nodeVec.size() && nodeVec[ three1[i]]); - for ( int i = 0; ok && i < 3; ++i ) - ok = ( three2[i] < nodeVec.size() && nodeVec[ three2[i]]); + ok = ( three1[i] < nbNodes && nodeVec[ three1[i]]); + for ( int i = 0; ok && i < 3; ++i ) + ok = ( three2[i] < nbNodes && nodeVec[ three2[i]]); if ( ok ) { err->myBadElements.push_back( new SMDS_FaceOfNodes( nodeVec[ three1[0]], @@ -3295,7 +3842,13 @@ NETGENPlugin_Mesher::ReadErrors(const vector& nodeVec) ++file; } } - return err; + +#ifdef _DEBUG_ + size_t nbBadElems = err->myBadElements.size(); + if ( nbBadElems ) nbBadElems++; // avoid warning: variable set but not used +#endif + + return SMESH_ComputeErrorPtr( err ); } //================================================================================ @@ -3306,18 +3859,71 @@ NETGENPlugin_Mesher::ReadErrors(const vector& nodeVec) */ //================================================================================ -void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh, - const std::string& pyFile) +void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh ) { - ofstream outfile(pyFile.c_str(), ios::out); + const char* pyFile = "/tmp/ngMesh.py"; + ofstream outfile( pyFile, ios::out ); if ( !outfile ) return; - outfile << "import SMESH" << endl - << "from salome.smesh import smeshBuilder" << endl - << "smesh = smeshBuilder.New(salome.myStudy)" << endl - << "mesh = smesh.Mesh()" << endl << endl; + outfile << "import salome, SMESH" << std::endl + << "from salome.smesh import smeshBuilder" << std::endl + << "smesh = smeshBuilder.New()" << std::endl + << "mesh = smesh.Mesh()" << std::endl << std::endl; using namespace netgen; + +#ifdef NETGEN_V6 + + for ( int i = 1; i <= ngMesh->GetNP(); i++) + { + const Point3d & p = ngMesh->Point(i); + outfile << "mesh.AddNode( "; + outfile << p.X() << ", "; + outfile << p.Y() << ", "; + outfile << p.Z() << ") ## "<< i << std::endl; + } + + int nbDom = ngMesh->GetNDomains(); + for ( int i = 0; i < nbDom; ++i ) + outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< std::endl; + + for (int i = 1; i <= ngMesh->GetNSE(); i++) + { + outfile << "mesh.AddFace([ "; + Element2d sel = ngMesh->SurfaceElement(i); + for (int j = 1; j <= sel.GetNP(); j++) + outfile << sel.PNum(j) << ( j < sel.GetNP() ? ", " : " ])"); + if ( sel.IsDeleted() ) outfile << " ## IsDeleted "; + outfile << std::endl; + + if (sel.GetIndex()) + { + if ( int dom1 = ngMesh->GetFaceDescriptor(sel.GetIndex ()).DomainIn()) + outfile << "grp"<< dom1 <<".Add([ " << i << " ])" << std::endl; + if ( int dom2 = ngMesh->GetFaceDescriptor(sel.GetIndex ()).DomainOut()) + outfile << "grp"<< dom2 <<".Add([ " << i << " ])" << std::endl; + } + } + + for (int i = 1; i <= ngMesh->GetNE(); i++) + { + Element el = ngMesh->VolumeElement(i); + outfile << "mesh.AddVolume([ "; + for (int j = 1; j <= el.GetNP(); j++) + outfile << el.PNum(j) << ( j < el.GetNP() ? ", " : " ])"); + outfile << std::endl; + } + + for (int i = 1; i <= ngMesh->GetNSeg(); i++) + { + const Segment & seg = ngMesh->LineSegment (i); + outfile << "mesh.AddEdge([ " + << seg[0]+1 << ", " + << seg[1]+1 << " ])" << std::endl; + } + +#else //////// V 5 + PointIndex pi; for (pi = PointIndex::BASE; pi < ngMesh->GetNP()+PointIndex::BASE; pi++) @@ -3325,12 +3931,12 @@ void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh, outfile << "mesh.AddNode( "; outfile << (*ngMesh)[pi](0) << ", "; outfile << (*ngMesh)[pi](1) << ", "; - outfile << (*ngMesh)[pi](2) << ") ## "<< pi << endl; + outfile << (*ngMesh)[pi](2) << ") ## "<< pi << std::endl; } int nbDom = ngMesh->GetNDomains(); for ( int i = 0; i < nbDom; ++i ) - outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< endl; + outfile<< "grp" << i+1 << " = mesh.CreateEmptyGroup( SMESH.FACE, 'domain"<< i+1 << "')"<< std::endl; SurfaceElementIndex sei; for (sei = 0; sei < ngMesh->GetNSE(); sei++) @@ -3340,14 +3946,14 @@ void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh, for (int j = 0; j < sel.GetNP(); j++) outfile << sel[j] << ( j+1 < sel.GetNP() ? ", " : " ])"); if ( sel.IsDeleted() ) outfile << " ## IsDeleted "; - outfile << endl; + outfile << std::endl; if ((*ngMesh)[sei].GetIndex()) { if ( int dom1 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainIn()) - outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << endl; + outfile << "grp"<< dom1 <<".Add([ " << (int)sei+1 << " ])" << std::endl; if ( int dom2 = ngMesh->GetFaceDescriptor((*ngMesh)[sei].GetIndex ()).DomainOut()) - outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << endl; + outfile << "grp"<< dom2 <<".Add([ " << (int)sei+1 << " ])" << std::endl; } } @@ -3357,7 +3963,7 @@ void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh, outfile << "mesh.AddVolume([ "; for (int j = 0; j < el.GetNP(); j++) outfile << el[j] << ( j+1 < el.GetNP() ? ", " : " ])"); - outfile << endl; + outfile << std::endl; } for (int i = 1; i <= ngMesh->GetNSeg(); i++) @@ -3365,9 +3971,12 @@ void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh, const Segment & seg = ngMesh->LineSegment (i); outfile << "mesh.AddEdge([ " << seg[0] << ", " - << seg[1] << " ])" << endl; + << seg[1] << " ])" << std::endl; } - cout << "Write " << pyFile << endl; + +#endif + + std::cout << "Write " << pyFile << std::endl; } //================================================================================ @@ -3376,8 +3985,9 @@ void NETGENPlugin_Mesher::toPython( const netgen::Mesh* ngMesh, */ //================================================================================ -NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh): - _copyOfLocalH(0) +NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh, + bool checkRemovedElems): + _elementsRemoved( false ), _copyOfLocalH(0) { if ( ngMesh ) { @@ -3385,6 +3995,10 @@ NETGENPlugin_ngMeshInfo::NETGENPlugin_ngMeshInfo( netgen::Mesh* ngMesh): _nbSegments = ngMesh->GetNSeg(); _nbFaces = ngMesh->GetNSE(); _nbVolumes = ngMesh->GetNE(); + + if ( checkRemovedElems ) + for ( int i = 1; i <= ngMesh->GetNSE() && !_elementsRemoved; ++i ) + _elementsRemoved = ngMesh->SurfaceElement(i).IsDeleted(); } else { @@ -3403,11 +4017,7 @@ void NETGENPlugin_ngMeshInfo::transferLocalH( netgen::Mesh* fromMesh, { if ( !fromMesh->LocalHFunctionGenerated() ) return; if ( !toMesh->LocalHFunctionGenerated() ) -#ifdef NETGEN_V5 - toMesh->CalcLocalH(netgen::mparam.grading); -#else - toMesh->CalcLocalH(); -#endif + NETGENPlugin_NetgenLibWrapper::CalcLocalH( toMesh ); const size_t size = sizeof( netgen::LocalH ); _copyOfLocalH = new char[ size ]; @@ -3483,7 +4093,7 @@ NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh, { _intShapes.insert( meshDS->ShapeToIndex( f.Current() )); - // egdes + // edges list< TopoDS_Shape > edges; for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next()) if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 ) @@ -3586,7 +4196,7 @@ void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems while ( fIt->more() ) { const SMDS_MeshElement* f = fIt->next(); - int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 ); + const int nbNodes = f->NbCornerNodes(); if ( intFaceSM->Contains( f )) { for ( int i = 0; i < nbNodes; ++i ) @@ -3596,7 +4206,7 @@ void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems { int nbDblNodes = 0; for ( int i = 0; i < nbNodes; ++i ) - nbDblNodes += isInternalShape( f->GetNode(i)->getshapeId() ); + nbDblNodes += isInternalShape( f->GetNode(i)->GetShapeID() ); if ( nbDblNodes ) suspectFaces[ nbDblNodes < 2 ].push_back( f ); nbSuspectFaces++; @@ -3617,7 +4227,7 @@ void NETGENPlugin_Internals::findBorderElements( TIDSortedElemSet & borderElems const SMDS_MeshElement* f = *fIt; bool isBorder = false, linkFound = false, borderLinkFound = false; list< SMESH_OrientedLink > faceLinks; - int nbNodes = f->NbNodes() / ( f->IsQuadratic() ? 2 : 1 ); + int nbNodes = f->NbCornerNodes(); for ( int i = 0; i < nbNodes; ++i ) { SMESH_OrientedLink link( f->GetNode(i), f->GetNode((i+1)%nbNodes)); @@ -3775,33 +4385,57 @@ SMESH_Mesh& NETGENPlugin_Internals::getMesh() const return const_cast( _mesh ); } +//================================================================================ +/*! + * \brief Access to a counter of NETGENPlugin_NetgenLibWrapper instances + */ +//================================================================================ + +int& NETGENPlugin_NetgenLibWrapper::instanceCounter() +{ + static int theCouner = 0; + return theCouner; +} + //================================================================================ /*! * \brief Initialize netgen library */ //================================================================================ -NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper() +NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper(): + _ngMesh(0) { - Ng_Init(); + if ( instanceCounter() == 0 ) + { + Ng_Init(); + if ( !netgen::testout ) + netgen::testout = new ofstream( "test.out" ); + } + + ++instanceCounter(); _isComputeOk = false; _coutBuffer = NULL; + _ngcout = NULL; + _ngcerr = NULL; if ( !getenv( "KEEP_NETGEN_OUTPUT" )) { // redirect all netgen output (mycout,myerr,cout) to _outputFileName _outputFileName = getOutputFileName(); + _ngcout = netgen::mycout; + _ngcerr = netgen::myerr; netgen::mycout = new ofstream ( _outputFileName.c_str() ); netgen::myerr = netgen::mycout; _coutBuffer = std::cout.rdbuf(); #ifdef _DEBUG_ - cout << "NOTE: netgen output is redirected to file " << _outputFileName << endl; + std::cout << "NOTE: netgen output is redirected to file " << _outputFileName << std::endl; #else std::cout.rdbuf( netgen::mycout->rdbuf() ); #endif } - _ngMesh = Ng_NewMesh(); + setMesh( Ng_NewMesh() ); } //================================================================================ @@ -3812,9 +4446,11 @@ NETGENPlugin_NetgenLibWrapper::NETGENPlugin_NetgenLibWrapper() NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper() { - Ng_DeleteMesh( _ngMesh ); + --instanceCounter(); + + Ng_DeleteMesh( ngMesh() ); Ng_Exit(); - NETGENPlugin_Mesher::RemoveTmpFiles(); + RemoveTmpFiles(); if ( _coutBuffer ) std::cout.rdbuf( _coutBuffer ); #ifdef _DEBUG_ @@ -3832,8 +4468,65 @@ NETGENPlugin_NetgenLibWrapper::~NETGENPlugin_NetgenLibWrapper() void NETGENPlugin_NetgenLibWrapper::setMesh( Ng_Mesh* mesh ) { if ( _ngMesh ) - Ng_DeleteMesh( _ngMesh ); - _ngMesh = mesh; + Ng_DeleteMesh( ngMesh() ); + _ngMesh = (netgen::Mesh*) mesh; +} + +//================================================================================ +/*! + * \brief Perform a step of mesh generation + * \param [inout] occgeo - geometry to mesh + * \param [inout] startWith - start step + * \param [inout] endWith - end step + * \param [inout] ngMesh - netgen mesh + * \return int - is error + */ +//================================================================================ + +int NETGENPlugin_NetgenLibWrapper::GenerateMesh( netgen::OCCGeometry& occgeo, + int startWith, int endWith, + netgen::Mesh* & ngMesh ) +{ + int err = 0; +#ifdef NETGEN_V6 + + if ( !ngMesh ) + ngMesh = new netgen::Mesh; + ngMesh->SetGeometry( shared_ptr( &occgeo, &NOOP_Deleter )); + + netgen::mparam.perfstepsstart = startWith; + netgen::mparam.perfstepsend = endWith; + std::shared_ptr meshPtr( ngMesh, &NOOP_Deleter ); + err = occgeo.GenerateMesh( meshPtr, netgen::mparam ); + +#else + #ifdef NETGEN_V5 + + err = netgen::OCCGenerateMesh(occgeo, ngMesh, netgen::mparam, startWith, endWith); + + #else + + char *optstr = 0; + err = netgen::OCCGenerateMesh(occgeo, ngMesh, startWith, endWith, optstr); + + #endif +#endif + return err; +} + +//================================================================================ +/*! + * \brief Create a mesh size tree + */ +//================================================================================ + +void NETGENPlugin_NetgenLibWrapper::CalcLocalH( netgen::Mesh * ngMesh ) +{ +#if defined( NETGEN_V5 ) || defined( NETGEN_V6 ) + ngMesh->CalcLocalH(netgen::mparam.grading); +#else + ngMesh->CalcLocalH(); +#endif } //================================================================================ @@ -3846,7 +4539,7 @@ std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName() { std::string aTmpDir = SALOMEDS_Tool::GetTmpDir(); - TCollection_AsciiString aGenericName = (char*)aTmpDir.c_str(); + TCollection_AsciiString aGenericName = aTmpDir.c_str(); aGenericName += "NETGEN_"; #ifndef WIN32 aGenericName += getpid(); @@ -3860,6 +4553,26 @@ std::string NETGENPlugin_NetgenLibWrapper::getOutputFileName() return aGenericName.ToCString(); } +//================================================================================ +/*! + * \brief Remove "test.out" and "problemfaces" files in current directory + */ +//================================================================================ + +void NETGENPlugin_NetgenLibWrapper::RemoveTmpFiles() +{ + bool rm = SMESH_File("test.out").remove() ; +#ifndef WIN32 + if ( rm && netgen::testout && instanceCounter() == 0 ) + { + delete netgen::testout; + netgen::testout = 0; + } +#endif + SMESH_File("problemfaces").remove(); + SMESH_File("occmesh.rep").remove(); +} + //================================================================================ /*! * \brief Remove file with netgen output @@ -3870,18 +4583,19 @@ void NETGENPlugin_NetgenLibWrapper::removeOutputFile() { if ( !_outputFileName.empty() ) { - if ( netgen::mycout ) + if ( _ngcout ) { delete netgen::mycout; - netgen::mycout = 0; - netgen::myerr = 0; + netgen::mycout = _ngcout; + netgen::myerr = _ngcerr; + _ngcout = 0; } string tmpDir = SALOMEDS_Tool::GetDirFromPath ( _outputFileName ); string aFileName = SALOMEDS_Tool::GetNameFromPath( _outputFileName ) + ".out"; - SALOMEDS::ListOfFileNames_var aFiles = new SALOMEDS::ListOfFileNames; - aFiles->length(1); - aFiles[0] = aFileName.c_str(); + SALOMEDS_Tool::ListOfFiles aFiles; + aFiles.reserve(1); + aFiles.push_back(aFileName.c_str()); - SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles.in(), true ); + SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.c_str(), aFiles, true ); } }